@needle-tools/engine 6.0.0-alpha.4 → 6.0.0-alpha.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/README.md +11 -1
  3. package/dist/{gltf-progressive-CcSfG2Ja.js → gltf-progressive-B7lOWdLe.js} +117 -115
  4. package/dist/gltf-progressive-BpT9M5Mt.umd.cjs +10 -0
  5. package/dist/gltf-progressive-D0rzvhNG.min.js +10 -0
  6. package/dist/{needle-engine.bundle-0tD9EcNs.js → needle-engine.bundle-4xlWxOTF.js} +592 -581
  7. package/dist/{needle-engine.bundle-BuUj9B4K.umd.cjs → needle-engine.bundle-D3nBMgfk.umd.cjs} +9 -9
  8. package/dist/{needle-engine.bundle-Bmcb5t3w.min.js → needle-engine.bundle-_kAszB-k.min.js} +27 -27
  9. package/dist/needle-engine.d.ts +13 -13
  10. package/dist/needle-engine.js +575 -575
  11. package/dist/needle-engine.min.js +1 -1
  12. package/dist/needle-engine.umd.cjs +1 -1
  13. package/lib/engine/api.d.ts +1 -1
  14. package/lib/engine/api.js +1 -1
  15. package/lib/engine/api.js.map +1 -1
  16. package/lib/engine/engine_init.js +2 -2
  17. package/lib/engine/engine_license.d.ts +7 -7
  18. package/lib/engine/engine_license.js +98 -78
  19. package/lib/engine/engine_license.js.map +1 -1
  20. package/lib/engine/engine_networking_blob.js +3 -3
  21. package/lib/engine/engine_networking_blob.js.map +1 -1
  22. package/lib/engine/engine_utils_qrcode.js +2 -2
  23. package/lib/engine/engine_utils_qrcode.js.map +1 -1
  24. package/lib/engine/webcomponents/needle menu/needle-menu-spatial.js +2 -2
  25. package/lib/engine/webcomponents/needle menu/needle-menu-spatial.js.map +1 -1
  26. package/lib/engine/webcomponents/needle menu/needle-menu.js +5 -5
  27. package/lib/engine/webcomponents/needle menu/needle-menu.js.map +1 -1
  28. package/lib/engine/webcomponents/needle-engine.js +2 -2
  29. package/lib/engine/webcomponents/needle-engine.js.map +1 -1
  30. package/lib/engine/webcomponents/needle-engine.loading.js +2 -2
  31. package/lib/engine/webcomponents/needle-engine.loading.js.map +1 -1
  32. package/lib/engine/xr/TempXRContext.js +2 -2
  33. package/lib/engine/xr/TempXRContext.js.map +1 -1
  34. package/lib/engine-components/export/usdz/USDZExporter.js +4 -4
  35. package/lib/engine-components/export/usdz/USDZExporter.js.map +1 -1
  36. package/package.json +5 -2
  37. package/plugins/common/license.js +4 -4
  38. package/plugins/license/README.md +38 -0
  39. package/plugins/license/cli.js +43 -0
  40. package/plugins/license/index.js +24 -0
  41. package/plugins/vite/license.js +4 -4
  42. package/src/engine/api.ts +1 -1
  43. package/src/engine/engine_init.ts +2 -2
  44. package/src/engine/engine_license.ts +93 -76
  45. package/src/engine/engine_networking_blob.ts +3 -3
  46. package/src/engine/engine_utils_qrcode.ts +2 -2
  47. package/src/engine/webcomponents/needle menu/needle-menu-spatial.ts +2 -2
  48. package/src/engine/webcomponents/needle menu/needle-menu.ts +5 -5
  49. package/src/engine/webcomponents/needle-engine.loading.ts +2 -2
  50. package/src/engine/webcomponents/needle-engine.ts +2 -2
  51. package/src/engine/xr/TempXRContext.ts +2 -2
  52. package/src/engine-components/export/usdz/USDZExporter.ts +4 -4
  53. package/dist/gltf-progressive-BYG9UH7O.min.js +0 -10
  54. package/dist/gltf-progressive-sK--FWg7.umd.cjs +0 -10
@@ -1,4 +1,4 @@
1
- "use strict";var dP=Object.defineProperty;var uP=(s,e,t)=>e in s?dP(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var Vb=(s,e,t)=>uP(s,typeof e!="symbol"?e+"":e,t);const c=require("./three-core.umd.cjs"),re=require("./gltf-progressive-sK--FWg7.umd.cjs"),V=require("./three-examples.umd.cjs"),ee=require("./vendor-BJviq-Oq.umd.cjs"),le=require("./three-mesh-ui-CzHaC-a-.umd.cjs");var Ha=typeof document<"u"?document.currentScript:null;const Wb=typeof window<"u"?window.location.search.includes("debugcontext"):!1;var ae=(s=>(s.ContextRegistered="ContextRegistered",s.ContextCreationStart="ContextCreationStart",s.ContextCreated="ContextCreated",s.ContextFirstFrameRendered="ContextFirstFrameRendered",s.ContextDestroying="ContextDestroying",s.ContextDestroyed="ContextDestroyed",s.MissingCamera="MissingCamera",s.ContextClearing="ContextClearing",s.ContextCleared="ContextCleared",s))(ae||{});class se{static get Current(){return globalThis["NeedleEngine.Context.Current"]}static set Current(e){globalThis["NeedleEngine.Context.Current"]=e}static get All(){return this.Registered}static Registered=[];static register(e){this.Registered.indexOf(e)===-1&&(Wb&&console.warn("Registering context"),this.Registered.push(e),this.dispatchCallback("ContextRegistered",e))}static unregister(e){const t=this.Registered.indexOf(e);t!==-1&&(Wb&&console.warn("Unregistering context"),this.Registered.splice(t,1))}static _callbacks={};static registerCallback(e,t){return this._callbacks[e]||(this._callbacks[e]=[]),this._callbacks[e].indexOf(t)!==-1?()=>this.unregisterCallback(e,t):(this._callbacks[e].push(t),()=>this.unregisterCallback(e,t))}static unregisterCallback(e,t){if(!this._callbacks[e])return;const i=this._callbacks[e].indexOf(t);i!==-1&&this._callbacks[e].splice(i,1)}static dispatchCallback(e,t,i){if(!this._callbacks[e])return!0;const n={event:e,context:t};if(i)for(const r in i)n[r]=i[r];const o=new Array;return this._callbacks[e].forEach(r=>{const a=r(n);a instanceof Promise&&o.push(a)}),Promise.all(o)}static addContextCreatedCallback(e){this.registerCallback("ContextCreated",e)}static addContextDestroyedCallback(e){this.registerCallback("ContextDestroyed",e)}}const Hp=new Map;function ki(s=globalThis.location?.hostname){if(Hp.has(s))return Hp.get(s);const e=/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})|localhost/.test(s);return Hp.set(s,e),e===!0}function Rw(){return window.location.hostname.includes("glitch.me")}const Tw=()=>s=>s;function fP(s){return Tw()(s)}function pP(){return!!x("debug")}class Mi{_factory;_cache=[];_maxSize;_index=0;constructor(e,t){this._factory=e,this._maxSize=t}get(){const e=this._index%this._maxSize;return this._index++,this._cache.length<=e&&(this._cache[e]=this._factory()),this._cache[e]}}let lr=!1;const lg=new Array;typeof window<"u"&&setTimeout(()=>{if(lr){const s={},e=new URL(window.location.href),t=new URL(e);t.searchParams.append("console","");const i=t.toString().replace(/=$|=(?=&)/g,"");for(const o of lg){const r=new URL(e);r.searchParams.append(o,""),s[o]=r.toString().replace(/=$|=(?=&)/g,"")}console.log(`🌵 ?help: Debug Options for Needle Engine.
1
+ "use strict";var dP=Object.defineProperty;var uP=(s,e,t)=>e in s?dP(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var Vb=(s,e,t)=>uP(s,typeof e!="symbol"?e+"":e,t);const c=require("./three-core.umd.cjs"),re=require("./gltf-progressive-BpT9M5Mt.umd.cjs"),V=require("./three-examples.umd.cjs"),ee=require("./vendor-BJviq-Oq.umd.cjs"),le=require("./three-mesh-ui-CzHaC-a-.umd.cjs");var Ha=typeof document<"u"?document.currentScript:null;const Wb=typeof window<"u"?window.location.search.includes("debugcontext"):!1;var ae=(s=>(s.ContextRegistered="ContextRegistered",s.ContextCreationStart="ContextCreationStart",s.ContextCreated="ContextCreated",s.ContextFirstFrameRendered="ContextFirstFrameRendered",s.ContextDestroying="ContextDestroying",s.ContextDestroyed="ContextDestroyed",s.MissingCamera="MissingCamera",s.ContextClearing="ContextClearing",s.ContextCleared="ContextCleared",s))(ae||{});class se{static get Current(){return globalThis["NeedleEngine.Context.Current"]}static set Current(e){globalThis["NeedleEngine.Context.Current"]=e}static get All(){return this.Registered}static Registered=[];static register(e){this.Registered.indexOf(e)===-1&&(Wb&&console.warn("Registering context"),this.Registered.push(e),this.dispatchCallback("ContextRegistered",e))}static unregister(e){const t=this.Registered.indexOf(e);t!==-1&&(Wb&&console.warn("Unregistering context"),this.Registered.splice(t,1))}static _callbacks={};static registerCallback(e,t){return this._callbacks[e]||(this._callbacks[e]=[]),this._callbacks[e].indexOf(t)!==-1?()=>this.unregisterCallback(e,t):(this._callbacks[e].push(t),()=>this.unregisterCallback(e,t))}static unregisterCallback(e,t){if(!this._callbacks[e])return;const i=this._callbacks[e].indexOf(t);i!==-1&&this._callbacks[e].splice(i,1)}static dispatchCallback(e,t,i){if(!this._callbacks[e])return!0;const n={event:e,context:t};if(i)for(const r in i)n[r]=i[r];const o=new Array;return this._callbacks[e].forEach(r=>{const a=r(n);a instanceof Promise&&o.push(a)}),Promise.all(o)}static addContextCreatedCallback(e){this.registerCallback("ContextCreated",e)}static addContextDestroyedCallback(e){this.registerCallback("ContextDestroyed",e)}}const Hp=new Map;function ki(s=globalThis.location?.hostname){if(Hp.has(s))return Hp.get(s);const e=/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})|localhost/.test(s);return Hp.set(s,e),e===!0}function Rw(){return window.location.hostname.includes("glitch.me")}const Tw=()=>s=>s;function fP(s){return Tw()(s)}function pP(){return!!x("debug")}class Mi{_factory;_cache=[];_maxSize;_index=0;constructor(e,t){this._factory=e,this._maxSize=t}get(){const e=this._index%this._maxSize;return this._index++,this._cache.length<=e&&(this._cache[e]=this._factory()),this._cache[e]}}let lr=!1;const lg=new Array;typeof window<"u"&&setTimeout(()=>{if(lr){const s={},e=new URL(window.location.href),t=new URL(e);t.searchParams.append("console","");const i=t.toString().replace(/=$|=(?=&)/g,"");for(const o of lg){const r=new URL(e);r.searchParams.append(o,""),s[o]=r.toString().replace(/=$|=(?=&)/g,"")}console.log(`🌵 ?help: Debug Options for Needle Engine.
2
2
  Append any of these parameters to the URL to enable specific debug options.
3
3
  Example: ${i} will show an onscreen console window.`);const n=lr===!0?"":` (containing "${lr}")`;console.group("Available URL parameters:"+n);for(const o of Object.keys(s).sort())typeof lr=="string"&&!o.toLowerCase().includes(lr.toLowerCase())||(console.groupCollapsed(o),console.log("Reload with this flag enabled:"),console.log(s[o]),console.groupEnd());console.groupEnd()}},100);function xh(){return new URLSearchParams(globalThis.location?.search)}function x(s){lr&&!lg.includes(s)&&lg.push(s);const e=xh();if(e.has(s)){const t=e.get(s);if(t){const i=Number(t);return isNaN(i)?t:i}else return!0}return!1}lr=x("help");function mP(s,e){const t=xh();t.has(s)?t.set(s,e):t.append(s,e),document.location.search=t.toString()}function Yc(s,e,t=!0){const i=xh();i.has(s)?e===null?i.delete(s):i.set(s,e):e!==null&&i.append(s,e),t?Aw(s,i):Sy(s,i)}function cg(s,e,t){s.has(e)?s.set(e,t.toString()):s.append(e,t.toString())}function Aw(s,e,t){window.history.pushState(t,s,"?"+e.toString()+window.location.hash)}function Sy(s,e,t){window.history.replaceState(t,s,"?"+e.toString()+window.location.hash)}function gP(s){for(var e="",t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",i=t.length,n=0;n<s;n++)e+=t.charAt(Math.floor(Math.random()*i));return e}function yP(s,e){return Math.floor(Math.random()*(e-s+1))+s}const Gb=["smol","tiny","giant","interesting","smart","bright","dull","extreme","beautiful","pretty","dark","epic","salty","silly","funny","lame","lazy","loud","lucky","mad","mean","mighty","mysterious","nasty","odd","old","powerful","quiet","rapid","scary","shiny","shy","silly","smooth","sour","spicy","stupid","sweet","tasty","terrible","ugly","unusual","vast","wet","wild","witty","wrong","zany","zealous","zippy","zombie","zorro"],Hb=["cat","dog","mouse","pig","cow","horse","sheep","chicken","duck","goat","panda","tiger","lion","elephant","monkey","bird","fish","snake","frog","turtle","hamster","penguin","kangaroo","whale","dolphin","crocodile","snail","ant","bee","beetle","butterfly","dragon","eagle","fish","giraffe","lizard","panda","penguin","rabbit","snake","spider","tiger","zebra"];function Dw(){const s=Gb[Math.floor(Math.random()*Gb.length)],e=Hb[Math.floor(Math.random()*Hb.length)];return s+"_"+e}function Iw(s){return s=s.replace(/[^a-z0-9áéíóúñü \.,_-]/gim,""),s.trim()}function Kc(s,e,t=!0,i=!1){if(e==null)return null;if(e.userData&&e.userData.guid===s)return e;if(e.guid==s)return e;if(i&&e.userData?.components){for(const n of e.userData.components)if(n.guid===s)return n}if(t){if(e.scenes)for(const n in e.scenes){const o=e.scenes[n],r=Kc(s,o,t,i);if(r)return r}if(e.children)for(const n in e.children){const o=e.children[n],r=Kc(s,o,t,i);if(r)return r}}}function _P(s){return!!(typeof EventTarget<"u"&&s instanceof EventTarget||s instanceof Date||s instanceof RegExp||s instanceof Map||s instanceof Set||s instanceof WeakMap||s instanceof WeakSet||s instanceof Promise||typeof ArrayBuffer<"u"&&s instanceof ArrayBuffer||ArrayBuffer.isView(s))}function Sh(s,e,t){if(s!=null&&typeof s=="object"){if(t||(t=new WeakSet),t.has(s)||(t.add(s),_P(s)))return s;let i;if(Array.isArray(s))i=[];else{i=Object.create(Object.getPrototypeOf(s));const n=Object.getOwnPropertyDescriptors(s);for(const o in n){const r=n[o];if(r.set||r.writable!==!1)try{i[o]=s[o]}catch{}}}for(const n of Object.keys(s)){const o=s[n];e&&!e(s,n,o)?i[n]=o:o?.clone!==void 0&&typeof o.clone=="function"?i[n]=o.clone():i[n]=Sh(o,e,t)}return i}return s}function Ds(s){return new Promise((e,t)=>{setTimeout(e,s)})}function kf(s,e){if(s<=0)return Promise.resolve();if(e||(e=se.Current),!e)return Promise.reject("No context");const t=e.time.frameCount+s;return new Promise((i,n)=>{if(!e)return n("No context");const o=()=>{e.time.frameCount>=t&&(e.pre_update_callbacks.splice(e.pre_update_callbacks.indexOf(o),1),i())};e.pre_update_callbacks.push(o)})}const md=x("debugresolveurl"),Lw="rel:";function bP(s,e){return cs(s,e)}function cs(s,e){if(e===void 0)return md&&console.warn("getPath: uri is undefined, returning uri",e),e;if(e.startsWith("./"))return e;if(e.startsWith("http"))return md&&console.warn("getPath: uri is absolute, returning uri",e),e;if(s===void 0)return md&&console.warn("getPath: source is undefined, returning uri",e),e;e.startsWith(Lw)&&(e=e.substring(4));const t=s.lastIndexOf("/");if(t>=0){const i=s.substring(0,t+1);for(;i.endsWith("/")&&e.startsWith("/");)e=e.substring(1);const n=i+e;return md&&console.log("source:",s,`changed uri
4
4
  from`,e,`
@@ -140,7 +140,7 @@ void main(){
140
140
  #__vconsole .vc-mask {
141
141
  overflow: hidden;
142
142
  }
143
- `,Yo?.prepend(n),s===!0&&jw()<=0&&sx(),console.log("🌵 Debug console has loaded")}},e.onerror=()=>{console.warn("🌵 Debug console failed to load."+(window.crossOriginIsolated?"This page is using cross-origin isolation, so external scripts can't be loaded.":"")),ic=!1,ai=null},e.src="https://cdn.jsdelivr.net/npm/vconsole@3.15.1/dist/vconsole.min.js",document.body.appendChild(e)}function Sk(){if(!globalThis.VConsole)return;const s=new VConsole.VConsolePlugin("needle-console","🌵 Inspect glTF"),e=()=>document.querySelector("#__vc_plug_"+s._id+" iframe");return s.on("renderTab",function(t){const i=globalThis["needle:codegen_files"];if(!i||i.length===0)return;let n=globalThis["needle:codegen_files"][0];const o=n.indexOf("?");o>-1&&(n=n.substring(0,o));const a=location.protocol+"//"+location.host+location.pathname+"/"+n,l=encodeURIComponent(a);s.fullUrl="https://viewer.needle.tools?inspect&file="+l;var h='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';t(h)}),s.on("show",function(){const t=e();t&&t.src!==s.fullUrl&&(t.src=s.fullUrl)}),s.on("hide",function(){const t=e();t&&(t.src="")}),s.on("addTopBar",function(t){var i=new Array;i.push({name:"Open in new window ↗",onClick:function(n){window.open(s.fullUrl,"_blank"),ai?.hide()}}),i.push({name:"Reload",onClick:function(n){const o=e();o&&(o.src=s.fullUrl)}}),i.push({name:"Fullscreen",onClick:function(n){const o=e();o.requestFullscreen?o.requestFullscreen():o.webkitRequestFullscreen instanceof Function&&o.webkitRequestFullscreen()}}),t(i)}),s}const gg="padding: 10px; font-family: monospace;",ov="margin-bottom: 10px;",Ko="margin-bottom: 10px; margin-top: 15px;",Ck="width: 100%; border-collapse: collapse; border: 1px solid rgba(0,0,0,0.1); table-layout: fixed;",ox="border: 1px solid rgba(0,0,0,0.1); padding: 5px;",Pk=ox,kk=ox+" word-break: break-all;";function zn(s,e=!1){e&&s.sort((i,n)=>(n.value?1:0)-(i.value?1:0));let t=`<table style='${Ck}'>`;t+="<tbody>";for(const i of s){const n=typeof i.value=="boolean"?i.value?"✅":"❌":i.value;t+=`<tr><td style='${Pk}'>${i.label}</td><td style='${kk}'>${n}</td></tr>`}return t+="</tbody></table>",t}function rx(){try{if(Ef())return"✅"}catch{}return"❌"}function Mk(){if(!globalThis.VConsole)return;const s=new VConsole.VConsolePlugin("device-utilities","📱 Device Info");return s.on("renderTab",function(e){let t=`<div style='${gg}'>`;const i=Fk();t+=`<h3 style='${ov}'>Device: ${i}</h3>`,t+=zn([{label:"💻 Desktop",value:exports.DeviceUtilities.isDesktop()},{label:"📱 Mobile Device",value:exports.DeviceUtilities.isMobileDevice()},{label:"🍎 iOS",value:exports.DeviceUtilities.isiOS()},{label:"📱 iPad",value:exports.DeviceUtilities.isiPad()},{label:"🤖 Android",value:exports.DeviceUtilities.isAndroidDevice()},{label:"🦊 Mozilla XR",value:exports.DeviceUtilities.isMozillaXR()},{label:"🌵 Needle App Clip",value:exports.DeviceUtilities.isNeedleAppClip()},{label:"🍏 macOS",value:exports.DeviceUtilities.isMacOS()},{label:"👓 VisionOS",value:exports.DeviceUtilities.isVisionOS()},{label:"🧭 Safari",value:exports.DeviceUtilities.isSafari()},{label:"🕶️ Meta Quest",value:exports.DeviceUtilities.isQuest()},{label:"🔗 QuickLook AR Support",value:exports.DeviceUtilities.supportsQuickLookAR()}],!0);const n=[],o=exports.DeviceUtilities.getiOSVersion();o&&n.push({label:"🍎 iOS Version",value:o});const r=exports.DeviceUtilities.getChromeVersion();r&&n.push({label:"🌐 Chrome Version",value:r});const a=exports.DeviceUtilities.getSafariVersion();a&&n.push({label:"🧭 Safari Version",value:a}),n.length>0&&(t+=zn(n,!1)),t+="</div>",t+=`<div style='${gg} margin-top: 20px;'>`,t+=`<h3 style='${ov}'>User Agent Info</h3>`;const l=[{label:"User Agent",value:navigator.userAgent},{label:"Platform",value:navigator.platform},{label:"App Version",value:navigator.appVersion},{label:"User Agent Data",value:navigator.userAgentData?`Platform: ${navigator.userAgentData.platform}, Mobile: ${navigator.userAgentData.mobile}`:"Not supported"},{label:"WebXR",value:"xr"in navigator?"✅":"❌"},{label:"WebGPU",value:"gpu"in navigator?"✅":"❌"},{label:"WebGL 2",value:rx()}];t+=zn(l,!1),t+="</div>",e(t)}),s}function Ok(){if(!globalThis.VConsole)return;const s=new VConsole.VConsolePlugin("graphics-info","🎨 Graphics Info");return s.on("renderTab",async function(e){let t=`<div style='${gg}'>`;const i=Ek();i.length>0&&(t+=`<h3 style='${Ko}'>General GPU Info</h3>`,t+=zn(i,!1));const n=Tk();n.length>0&&(t+=`<h3 style='${Ko}'>WebGL</h3>`,t+=zn(n,!1));const o=Ak();o.length>0&&(t+=`<h3 style='${Ko}'>WebGL 2 Features</h3>`,t+=zn(o,!1));const r=Dk();r.length>0&&(t+=`<h3 style='${Ko}'>WebGL Limits</h3>`,t+=zn(r,!1));const a=Ik();a.length>0&&(t+=`<h3 style='${Ko}'>Texture Formats</h3>`,t+=zn(a,!1));const l=await Lk();if(l.length>0&&(t+=`<h3 style='${Ko}'>WebGPU</h3>`,t+=zn(l,!1)),exports.DeviceUtilities.isSafari()){const h=Bk();h.length>0&&(t+=`<h3 style='${Ko}'>Safari GPU Info</h3>`,t+=zn(h,!1))}t+="</div>",e(t)}),s}function Ek(){const s=[],e=window.devicePixelRatio;s.push({label:"Device Pixel Ratio",value:e.toString()}),s.push({label:"Width (px)",value:(window.innerWidth*e).toString()}),s.push({label:"Height (px)",value:(window.innerHeight*e).toString()});const i=exports.DeviceUtilities.isMobileDevice()?150:96,n=screen.width/i,o=screen.height/i,r=n*2.54,a=o*2.54;s.push({label:"Estimated Width (cm)",value:r.toFixed(1)}),s.push({label:"Estimated Height (cm)",value:a.toFixed(1)});const l=ax();if(l){s.push({label:"GPU",value:l.renderer}),s.push({label:"Driver",value:l.vendor}),s.push({label:"ANGLE",value:l.angle||"Not detected"});const h=Rk(l.renderer);h&&(h.manufacturer&&s.push({label:"Manufacturer",value:h.manufacturer}),h.cardVersion&&s.push({label:"Card Version",value:h.cardVersion}),h.brand&&s.push({label:"Brand",value:h.brand}),s.push({label:"Integrated",value:h.integrated?"Yes":"No"}),h.layer&&s.push({label:"WebGL Layer",value:h.layer}))}return s}function Rk(s){if(!s)return null;const e=(h,d)=>{const u=d.match(h);return u&&u[0]},t=e(/(ANGLE)/g,s)||void 0,i=e(/((NVIDIA|AMD|Intel)[^\d]*[^\s]+)/,s)||s,n=i.split(" ");n.shift();const o=e(/(NVIDIA|AMD|Intel)/g,i)||void 0,r=n.length>0?n.pop():void 0,a=n.length>0?n.join(" "):void 0;return{manufacturer:o,cardVersion:r,brand:a,integrated:o==="Intel",layer:t,card:i}}function Tk(){const s=[],e=ax();return e&&(s.push({label:"📊 WebGL Version",value:e.version}),s.push({label:"🎮 WebGL 2 Available",value:rx()})),s}function Ak(){const s=[];try{const e=Ef();if(!e)return s;s.push({label:"Float Color Buffer",value:e.getExtension("EXT_color_buffer_float")?"✅":"❌"}),s.push({label:"Anisotropic Filtering",value:e.getExtension("EXT_texture_filter_anisotropic")?"✅":"❌"}),s.push({label:"Float Texture Linear",value:e.getExtension("OES_texture_float_linear")?"✅":"❌"}),s.push({label:"S3TC Compression",value:e.getExtension("WEBGL_compressed_texture_s3tc")?"✅":"❌"}),s.push({label:"ETC Compression",value:e.getExtension("WEBGL_compressed_texture_etc")?"✅":"❌"}),s.push({label:"PVRTC Compression",value:e.getExtension("WEBGL_compressed_texture_pvrtc")?"✅":"❌"}),s.push({label:"ASTC Compression",value:e.getExtension("WEBGL_compressed_texture_astc")?"✅":"❌"})}catch{}return s}function Dk(){const s=[];try{const e=nx();if(!e)return s;const t=e instanceof WebGL2RenderingContext;s.push({label:"📏 Max Texture Size",value:e.getParameter(e.MAX_TEXTURE_SIZE).toString()}),s.push({label:"🎨 Max Renderbuffer Size",value:e.getParameter(e.MAX_RENDERBUFFER_SIZE).toString()}),s.push({label:"🔗 Max Vertex Attribs",value:e.getParameter(e.MAX_VERTEX_ATTRIBS).toString()}),s.push({label:"🎯 Max Texture Units",value:e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS).toString()}),t&&(s.push({label:"⚡ Max Samples",value:e.getParameter(e.MAX_SAMPLES).toString()}),s.push({label:"🔄 Max Uniform Buffer Bindings",value:e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS).toString()}),s.push({label:"📐 Max 3D Texture Size",value:e.getParameter(e.MAX_3D_TEXTURE_SIZE).toString()}))}catch{}return s}function Ik(){const s=[];try{Wu()&&(s.push({label:"WebGL 1 RGBA",value:"✅"}),s.push({label:"WebGL 1 RGB",value:"✅"}));const t=Ef();t&&(s.push({label:"WebGL 2 RGBA32F",value:t.getExtension("EXT_color_buffer_float")?"✅":"❌"}),s.push({label:"WebGL 2 RGB32F",value:t.getExtension("EXT_color_buffer_float")?"✅":"❌"}),s.push({label:"WebGL 2 R11F_G11F_B10F",value:"✅"}),s.push({label:"WebGL 2 RGB565",value:"✅"}),s.push({label:"WebGL 2 RGB5_A1",value:"✅"}),s.push({label:"WebGL 2 RGBA4444",value:"✅"}))}catch{}return s}async function Lk(){const s=[];if(!("gpu"in navigator))return s.push({label:"🚀 WebGPU Support",value:"❌ Not supported"}),s;s.push({label:"🚀 WebGPU Support",value:"✅ Supported"});try{const e=await navigator.gpu.requestAdapter();if(!e)return s.push({label:"🎯 Adapter",value:"No adapter available"}),s;s.push({label:"🎯 Adapter",value:e.name||"Unknown Adapter"});const t=await e.requestDevice();s.push({label:"🔧 Device",value:t.label||"WebGPU Device"}),s.push({label:"📏 Max Texture 2D",value:t.limits.maxTextureDimension2D.toString()}),s.push({label:"📐 Max Texture 3D",value:t.limits.maxTextureDimension3D.toString()}),s.push({label:"📊 Max Texture Array Layers",value:t.limits.maxTextureArrayLayers.toString()}),s.push({label:"💾 Max Buffer Size",value:`${(t.limits.maxBufferSize/1024/1024).toFixed(1)}MB`}),s.push({label:"🔗 Max Bind Groups",value:t.limits.maxBindGroups.toString()})}catch(e){s.push({label:"❌ Error",value:e.message})}return s}function ax(){try{const s=nx();if(!s)return null;const e=s.getExtension("WEBGL_debug_renderer_info"),t=e?s.getParameter(e.UNMASKED_RENDERER_WEBGL):s.getParameter(s.RENDERER),i=e?s.getParameter(e.UNMASKED_VENDOR_WEBGL):s.getParameter(s.VENDOR),n=s.getParameter(s.VERSION);let o;if(t&&t.includes("ANGLE")){const r=t.match(/ANGLE \(([^)]+)\)/);r&&(o=r[1])}return{renderer:t,vendor:i,version:n,angle:o}}catch{return null}}function Bk(){const s=[];try{const e=Wu();if(e){const t=e.getExtension("WEBGL_debug_renderer_info");if(t){const i=e.getParameter(t.UNMASKED_RENDERER_WEBGL);i&&i.includes("Apple")&&s.push({label:"🍎 Apple GPU",value:i})}}}catch{}try{const e=Wu();e&&(e.getSupportedExtensions()||[]).includes("WEBGL_compressed_texture_pvrtc")&&s.push({label:"🗜️ PVRTC Support",value:"✅"})}catch{}return s}function Fk(){return exports.DeviceUtilities.isQuest()?"Meta Quest":exports.DeviceUtilities.isVisionOS()?"Vision Pro":exports.DeviceUtilities.isiOS()?exports.DeviceUtilities.isiPad()?"iPad":"iPhone/iPod":exports.DeviceUtilities.isAndroidDevice()?"Android Device":exports.DeviceUtilities.isMozillaXR()?"Mozilla XR Browser":exports.DeviceUtilities.isNeedleAppClip()?"Needle App Clip":exports.DeviceUtilities.isMacOS()?"Mac":exports.DeviceUtilities.isDesktop()?"Desktop PC":"Unknown Device"}function jk(){const s=document.querySelector("#__vconsole .vc-switch");return s||null}function Uk(){const s=document.querySelector("#__vconsole");return s||null}const bd=x("debugtypes");class zk{_types=new Map;_reverseTypes=new Map;_lazyLoaders=new Map;constructor(){bd&&console.warn("TypeStore: Created",this)}add(e,t){bd&&console.warn("ADD TYPE",e);const i=this._types.get(e);i?bd&&i!==t&&console.warn("Type name exists multiple times in your project and may lead to runtime errors:",e):(this._types.set(e,t),this._reverseTypes.set(t,e))}addLazy(e,t){this._types.has(e)||this._lazyLoaders.set(e,t)}get(e){return this._types.get(e)||null}async getAsync(e){const t=this._types.get(e);if(t)return t;const i=this._lazyLoaders.get(e);if(i){bd&&console.warn("LAZY LOAD TYPE",e);const n=await i();return this.add(e,n),this._lazyLoaders.delete(e),n}return null}getKey(e){return this._reverseTypes.get(e)||null}get types(){return this._types}}const Nk=Symbol("BuiltInType"),M=new zk,Ly=function(s){M.get(s.name)||M.add(s.name,s)};class $k{context;mixers=[];constructor(e){this.context=e}onDestroy(){this.mixers.forEach(e=>e.stopAllAction()),this.mixers.length=0}registerAnimationMixer(e){if(!e){console.warn("AnimationsRegistry.registerAnimationMixer called with null or undefined mixer");return}this.mixers.includes(e)||this.mixers.push(e)}unregisterAnimationMixer(e){if(!e){console.warn("AnimationsRegistry.unregisterAnimationMixer called with null or undefined mixer");return}const t=this.mixers.indexOf(e);t!==-1&&this.mixers.splice(t,1)}}exports.AnimationUtils=void 0;(s=>{function e(d,u){const f=d.getRoot();return f&&(f.userData.static||f.matrixAutoUpdate===!1||f.matrixWorldAutoUpdate===!1)?((u===!0||u===void 0&&E())&&console.warn(`AnimationUtils: The root object (${f.name||f.type}) of this AnimationAction has matrixAutoUpdate or matrixWorldAutoUpdate set to false. This may prevent the animation from working correctly. If the object is marked as static, try to change it to dynamic.`,{static:f.userData.static,name:f.userData.name,tag:f.userData.tag,matrixAutoUpdate:f.matrixAutoUpdate,matrixWorldAutoUpdate:f.matrixWorldAutoUpdate}),!1):!0}s.testIfRootCanAnimate=e;function t(d){const u=d._actions;return u||null}s.tryGetActionsFromMixer=t;function i(d,u){if(u||(u=new Array),d)d.animations&&u.push(...d.animations);else return u;if(d.children)for(const f of d.children)i(f,u);return u}s.tryGetAnimationClipsFromObjectHierarchy=i;const n=Symbol("objectIsAnimatedData");function o(d,u,f){if(!d)return;if(d[n]===void 0){if(!f)return;d[n]=new Set}const m=d[n];f?m.add(u):m.has(u)&&m.delete(u)}s.setObjectAnimated=o;function r(d){if(!d)return!1;const u=d[n];return u!==void 0&&u.size>0}s.getObjectAnimated=r;function a(d){if(!d||!d.animations)return console.debug("No animations found in file"),null;const u="scene"in d?d.scene:d,f=new Array;for(let g=0;g<d.animations.length;g++){const v=d.animations[g];if(!v.tracks||v.tracks.length<=0){console.warn("Animation has no tracks");continue}for(const _ in v.tracks){const y=v.tracks[_],b=c.PropertyBinding.parseTrackName(y.name);let w=c.PropertyBinding.findNode(u,b.nodeName);if(!w){const k=y.__objectName??y.name.substring(0,y.name.indexOf("."));if(w=u.getObjectByProperty("uuid",k)??null,!w)continue}let C=m(w)||m(u);if(!C){const k=M.get("Animation");if(C=u.addComponent(k),!C){console.error("Failed creating Animation component: No 'Animation' component found in TypeStore");break}}f.push(C),C.addClip&&C.addClip(v)}}return f;function m(g){if(!g)return null;const v=g.userData?.components;if(v&&v.length>0)for(let _=0;_<v.length;_++){const y=v[_];if(y.isAnimationComponent===!0)return y}return m(g.parent)}}s.autoplayAnimations=a;function l(){return new c.AnimationClip("empty",0,[])}s.emptyClip=l;function h(d){const u=d?.duration??.3;let f={x:1,y:1,z:1};d?.scale!==void 0&&(typeof d.scale=="number"?f={x:d.scale,y:d.scale,z:d.scale}:f=d.scale);const m=d?.type??"linear",g=d?.scaleFactor??1.2,v=new Array,_=new Array;switch(m){case"linear":v.push(0,u),_.push(f.x,f.y,f.z,f.x*g,f.y*g,f.z*g);break;case"spring":v.push(0,u*.3,u*.5,u*.7,u*.9,u),_.push(f.x,f.y,f.z,f.x*g,f.y*g,f.z*g,f.x*.9,f.y*.9,f.z*.9,f.x*1.05,f.y*1.05,f.z*1.05,f.x*.98,f.y*.98,f.z*.98,f.x,f.y,f.z);break}const y=new c.KeyframeTrack(".scale",v,_);return new c.AnimationClip("scale",v[v.length-1],[y])}s.createScaleClip=h})(exports.AnimationUtils||(exports.AnimationUtils={}));const Qe=function(s){return p(s)},p=function(s){if(s===void 0&&(s=null),!Array.isArray(s))s=rv(s);else for(let e=0;e<s.length;e++){const t=s[e];s[e]=rv(t)}return function(e,t){if(!e){const n=typeof t=="string"?t:t.name;console.warn(`@serializable without a target at '${n}'.`);return}typeof t!="string"&&(t=t.name),Object.getOwnPropertyDescriptor(e,"$serializedTypes")||(e.$serializedTypes={});const i=e.$serializedTypes=e.$serializedTypes||{};i[t]=s}};function rv(s){switch(s?.prototype?.constructor?.name){case"Number":case"String":case"Boolean":return null}return s}const av=x("debugcomponentevents");class Rf{static eventListeners=new Map;static addComponentLifecylceEventListener(e,t){this.eventListeners.has(e)&&this.eventListeners.set(e,[]);let i=this.eventListeners.get(e);i||(i=[]),i.push(t),this.eventListeners.set(e,i),av&&console.log("Added event listener for "+e,this.eventListeners)}static removeComponentLifecylceEventListener(e,t){const i=this.eventListeners.get(e);if(!i)return;const n=i.indexOf(t);n<0||i.splice(n,1)}static dispatchComponentLifecycleEvent(e,t){const i=this.eventListeners.get(e);if(av&&console.log("Dispatching event "+e,i),!!i)for(const n of i)n(t)}}const lx=x("debugdefines");Bo('if(!globalThis["NEEDLE_ENGINE_VERSION"]) globalThis["NEEDLE_ENGINE_VERSION"] = "0.0.0";');Bo('if(!globalThis["NEEDLE_ENGINE_GENERATOR"]) globalThis["NEEDLE_ENGINE_GENERATOR"] = "unknown";');Bo('if(!globalThis["NEEDLE_PROJECT_BUILD_TIME"]) globalThis["NEEDLE_PROJECT_BUILD_TIME"] = "unknown";');Bo('if(!globalThis["NEEDLE_PUBLIC_KEY"]) globalThis["NEEDLE_PUBLIC_KEY"] = "unknown";');Bo('globalThis["__NEEDLE_ENGINE_VERSION__"] = "6.0.0-alpha.4";');Bo('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";');Bo('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Fri Oct 02 2026 09:12:34 GMT+0000 (Coordinated Universal Time)";');Bo('globalThis["__NEEDLE_PUBLIC_KEY__"] = "'+NEEDLE_PUBLIC_KEY+'";');const Zt="6.0.0-alpha.4",al="undefined",Zc="Fri Oct 02 2026 09:12:34 GMT+0000 (Coordinated Universal Time)";lx&&console.log(`Engine version: ${Zt} (generator: ${al})
143
+ `,Yo?.prepend(n),s===!0&&jw()<=0&&sx(),console.log("🌵 Debug console has loaded")}},e.onerror=()=>{console.warn("🌵 Debug console failed to load."+(window.crossOriginIsolated?"This page is using cross-origin isolation, so external scripts can't be loaded.":"")),ic=!1,ai=null},e.src="https://cdn.jsdelivr.net/npm/vconsole@3.15.1/dist/vconsole.min.js",document.body.appendChild(e)}function Sk(){if(!globalThis.VConsole)return;const s=new VConsole.VConsolePlugin("needle-console","🌵 Inspect glTF"),e=()=>document.querySelector("#__vc_plug_"+s._id+" iframe");return s.on("renderTab",function(t){const i=globalThis["needle:codegen_files"];if(!i||i.length===0)return;let n=globalThis["needle:codegen_files"][0];const o=n.indexOf("?");o>-1&&(n=n.substring(0,o));const a=location.protocol+"//"+location.host+location.pathname+"/"+n,l=encodeURIComponent(a);s.fullUrl="https://viewer.needle.tools?inspect&file="+l;var h='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';t(h)}),s.on("show",function(){const t=e();t&&t.src!==s.fullUrl&&(t.src=s.fullUrl)}),s.on("hide",function(){const t=e();t&&(t.src="")}),s.on("addTopBar",function(t){var i=new Array;i.push({name:"Open in new window ↗",onClick:function(n){window.open(s.fullUrl,"_blank"),ai?.hide()}}),i.push({name:"Reload",onClick:function(n){const o=e();o&&(o.src=s.fullUrl)}}),i.push({name:"Fullscreen",onClick:function(n){const o=e();o.requestFullscreen?o.requestFullscreen():o.webkitRequestFullscreen instanceof Function&&o.webkitRequestFullscreen()}}),t(i)}),s}const gg="padding: 10px; font-family: monospace;",ov="margin-bottom: 10px;",Ko="margin-bottom: 10px; margin-top: 15px;",Ck="width: 100%; border-collapse: collapse; border: 1px solid rgba(0,0,0,0.1); table-layout: fixed;",ox="border: 1px solid rgba(0,0,0,0.1); padding: 5px;",Pk=ox,kk=ox+" word-break: break-all;";function zn(s,e=!1){e&&s.sort((i,n)=>(n.value?1:0)-(i.value?1:0));let t=`<table style='${Ck}'>`;t+="<tbody>";for(const i of s){const n=typeof i.value=="boolean"?i.value?"✅":"❌":i.value;t+=`<tr><td style='${Pk}'>${i.label}</td><td style='${kk}'>${n}</td></tr>`}return t+="</tbody></table>",t}function rx(){try{if(Ef())return"✅"}catch{}return"❌"}function Mk(){if(!globalThis.VConsole)return;const s=new VConsole.VConsolePlugin("device-utilities","📱 Device Info");return s.on("renderTab",function(e){let t=`<div style='${gg}'>`;const i=Fk();t+=`<h3 style='${ov}'>Device: ${i}</h3>`,t+=zn([{label:"💻 Desktop",value:exports.DeviceUtilities.isDesktop()},{label:"📱 Mobile Device",value:exports.DeviceUtilities.isMobileDevice()},{label:"🍎 iOS",value:exports.DeviceUtilities.isiOS()},{label:"📱 iPad",value:exports.DeviceUtilities.isiPad()},{label:"🤖 Android",value:exports.DeviceUtilities.isAndroidDevice()},{label:"🦊 Mozilla XR",value:exports.DeviceUtilities.isMozillaXR()},{label:"🌵 Needle App Clip",value:exports.DeviceUtilities.isNeedleAppClip()},{label:"🍏 macOS",value:exports.DeviceUtilities.isMacOS()},{label:"👓 VisionOS",value:exports.DeviceUtilities.isVisionOS()},{label:"🧭 Safari",value:exports.DeviceUtilities.isSafari()},{label:"🕶️ Meta Quest",value:exports.DeviceUtilities.isQuest()},{label:"🔗 QuickLook AR Support",value:exports.DeviceUtilities.supportsQuickLookAR()}],!0);const n=[],o=exports.DeviceUtilities.getiOSVersion();o&&n.push({label:"🍎 iOS Version",value:o});const r=exports.DeviceUtilities.getChromeVersion();r&&n.push({label:"🌐 Chrome Version",value:r});const a=exports.DeviceUtilities.getSafariVersion();a&&n.push({label:"🧭 Safari Version",value:a}),n.length>0&&(t+=zn(n,!1)),t+="</div>",t+=`<div style='${gg} margin-top: 20px;'>`,t+=`<h3 style='${ov}'>User Agent Info</h3>`;const l=[{label:"User Agent",value:navigator.userAgent},{label:"Platform",value:navigator.platform},{label:"App Version",value:navigator.appVersion},{label:"User Agent Data",value:navigator.userAgentData?`Platform: ${navigator.userAgentData.platform}, Mobile: ${navigator.userAgentData.mobile}`:"Not supported"},{label:"WebXR",value:"xr"in navigator?"✅":"❌"},{label:"WebGPU",value:"gpu"in navigator?"✅":"❌"},{label:"WebGL 2",value:rx()}];t+=zn(l,!1),t+="</div>",e(t)}),s}function Ok(){if(!globalThis.VConsole)return;const s=new VConsole.VConsolePlugin("graphics-info","🎨 Graphics Info");return s.on("renderTab",async function(e){let t=`<div style='${gg}'>`;const i=Ek();i.length>0&&(t+=`<h3 style='${Ko}'>General GPU Info</h3>`,t+=zn(i,!1));const n=Tk();n.length>0&&(t+=`<h3 style='${Ko}'>WebGL</h3>`,t+=zn(n,!1));const o=Ak();o.length>0&&(t+=`<h3 style='${Ko}'>WebGL 2 Features</h3>`,t+=zn(o,!1));const r=Dk();r.length>0&&(t+=`<h3 style='${Ko}'>WebGL Limits</h3>`,t+=zn(r,!1));const a=Ik();a.length>0&&(t+=`<h3 style='${Ko}'>Texture Formats</h3>`,t+=zn(a,!1));const l=await Lk();if(l.length>0&&(t+=`<h3 style='${Ko}'>WebGPU</h3>`,t+=zn(l,!1)),exports.DeviceUtilities.isSafari()){const h=Bk();h.length>0&&(t+=`<h3 style='${Ko}'>Safari GPU Info</h3>`,t+=zn(h,!1))}t+="</div>",e(t)}),s}function Ek(){const s=[],e=window.devicePixelRatio;s.push({label:"Device Pixel Ratio",value:e.toString()}),s.push({label:"Width (px)",value:(window.innerWidth*e).toString()}),s.push({label:"Height (px)",value:(window.innerHeight*e).toString()});const i=exports.DeviceUtilities.isMobileDevice()?150:96,n=screen.width/i,o=screen.height/i,r=n*2.54,a=o*2.54;s.push({label:"Estimated Width (cm)",value:r.toFixed(1)}),s.push({label:"Estimated Height (cm)",value:a.toFixed(1)});const l=ax();if(l){s.push({label:"GPU",value:l.renderer}),s.push({label:"Driver",value:l.vendor}),s.push({label:"ANGLE",value:l.angle||"Not detected"});const h=Rk(l.renderer);h&&(h.manufacturer&&s.push({label:"Manufacturer",value:h.manufacturer}),h.cardVersion&&s.push({label:"Card Version",value:h.cardVersion}),h.brand&&s.push({label:"Brand",value:h.brand}),s.push({label:"Integrated",value:h.integrated?"Yes":"No"}),h.layer&&s.push({label:"WebGL Layer",value:h.layer}))}return s}function Rk(s){if(!s)return null;const e=(h,d)=>{const u=d.match(h);return u&&u[0]},t=e(/(ANGLE)/g,s)||void 0,i=e(/((NVIDIA|AMD|Intel)[^\d]*[^\s]+)/,s)||s,n=i.split(" ");n.shift();const o=e(/(NVIDIA|AMD|Intel)/g,i)||void 0,r=n.length>0?n.pop():void 0,a=n.length>0?n.join(" "):void 0;return{manufacturer:o,cardVersion:r,brand:a,integrated:o==="Intel",layer:t,card:i}}function Tk(){const s=[],e=ax();return e&&(s.push({label:"📊 WebGL Version",value:e.version}),s.push({label:"🎮 WebGL 2 Available",value:rx()})),s}function Ak(){const s=[];try{const e=Ef();if(!e)return s;s.push({label:"Float Color Buffer",value:e.getExtension("EXT_color_buffer_float")?"✅":"❌"}),s.push({label:"Anisotropic Filtering",value:e.getExtension("EXT_texture_filter_anisotropic")?"✅":"❌"}),s.push({label:"Float Texture Linear",value:e.getExtension("OES_texture_float_linear")?"✅":"❌"}),s.push({label:"S3TC Compression",value:e.getExtension("WEBGL_compressed_texture_s3tc")?"✅":"❌"}),s.push({label:"ETC Compression",value:e.getExtension("WEBGL_compressed_texture_etc")?"✅":"❌"}),s.push({label:"PVRTC Compression",value:e.getExtension("WEBGL_compressed_texture_pvrtc")?"✅":"❌"}),s.push({label:"ASTC Compression",value:e.getExtension("WEBGL_compressed_texture_astc")?"✅":"❌"})}catch{}return s}function Dk(){const s=[];try{const e=nx();if(!e)return s;const t=e instanceof WebGL2RenderingContext;s.push({label:"📏 Max Texture Size",value:e.getParameter(e.MAX_TEXTURE_SIZE).toString()}),s.push({label:"🎨 Max Renderbuffer Size",value:e.getParameter(e.MAX_RENDERBUFFER_SIZE).toString()}),s.push({label:"🔗 Max Vertex Attribs",value:e.getParameter(e.MAX_VERTEX_ATTRIBS).toString()}),s.push({label:"🎯 Max Texture Units",value:e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS).toString()}),t&&(s.push({label:"⚡ Max Samples",value:e.getParameter(e.MAX_SAMPLES).toString()}),s.push({label:"🔄 Max Uniform Buffer Bindings",value:e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS).toString()}),s.push({label:"📐 Max 3D Texture Size",value:e.getParameter(e.MAX_3D_TEXTURE_SIZE).toString()}))}catch{}return s}function Ik(){const s=[];try{Wu()&&(s.push({label:"WebGL 1 RGBA",value:"✅"}),s.push({label:"WebGL 1 RGB",value:"✅"}));const t=Ef();t&&(s.push({label:"WebGL 2 RGBA32F",value:t.getExtension("EXT_color_buffer_float")?"✅":"❌"}),s.push({label:"WebGL 2 RGB32F",value:t.getExtension("EXT_color_buffer_float")?"✅":"❌"}),s.push({label:"WebGL 2 R11F_G11F_B10F",value:"✅"}),s.push({label:"WebGL 2 RGB565",value:"✅"}),s.push({label:"WebGL 2 RGB5_A1",value:"✅"}),s.push({label:"WebGL 2 RGBA4444",value:"✅"}))}catch{}return s}async function Lk(){const s=[];if(!("gpu"in navigator))return s.push({label:"🚀 WebGPU Support",value:"❌ Not supported"}),s;s.push({label:"🚀 WebGPU Support",value:"✅ Supported"});try{const e=await navigator.gpu.requestAdapter();if(!e)return s.push({label:"🎯 Adapter",value:"No adapter available"}),s;s.push({label:"🎯 Adapter",value:e.name||"Unknown Adapter"});const t=await e.requestDevice();s.push({label:"🔧 Device",value:t.label||"WebGPU Device"}),s.push({label:"📏 Max Texture 2D",value:t.limits.maxTextureDimension2D.toString()}),s.push({label:"📐 Max Texture 3D",value:t.limits.maxTextureDimension3D.toString()}),s.push({label:"📊 Max Texture Array Layers",value:t.limits.maxTextureArrayLayers.toString()}),s.push({label:"💾 Max Buffer Size",value:`${(t.limits.maxBufferSize/1024/1024).toFixed(1)}MB`}),s.push({label:"🔗 Max Bind Groups",value:t.limits.maxBindGroups.toString()})}catch(e){s.push({label:"❌ Error",value:e.message})}return s}function ax(){try{const s=nx();if(!s)return null;const e=s.getExtension("WEBGL_debug_renderer_info"),t=e?s.getParameter(e.UNMASKED_RENDERER_WEBGL):s.getParameter(s.RENDERER),i=e?s.getParameter(e.UNMASKED_VENDOR_WEBGL):s.getParameter(s.VENDOR),n=s.getParameter(s.VERSION);let o;if(t&&t.includes("ANGLE")){const r=t.match(/ANGLE \(([^)]+)\)/);r&&(o=r[1])}return{renderer:t,vendor:i,version:n,angle:o}}catch{return null}}function Bk(){const s=[];try{const e=Wu();if(e){const t=e.getExtension("WEBGL_debug_renderer_info");if(t){const i=e.getParameter(t.UNMASKED_RENDERER_WEBGL);i&&i.includes("Apple")&&s.push({label:"🍎 Apple GPU",value:i})}}}catch{}try{const e=Wu();e&&(e.getSupportedExtensions()||[]).includes("WEBGL_compressed_texture_pvrtc")&&s.push({label:"🗜️ PVRTC Support",value:"✅"})}catch{}return s}function Fk(){return exports.DeviceUtilities.isQuest()?"Meta Quest":exports.DeviceUtilities.isVisionOS()?"Vision Pro":exports.DeviceUtilities.isiOS()?exports.DeviceUtilities.isiPad()?"iPad":"iPhone/iPod":exports.DeviceUtilities.isAndroidDevice()?"Android Device":exports.DeviceUtilities.isMozillaXR()?"Mozilla XR Browser":exports.DeviceUtilities.isNeedleAppClip()?"Needle App Clip":exports.DeviceUtilities.isMacOS()?"Mac":exports.DeviceUtilities.isDesktop()?"Desktop PC":"Unknown Device"}function jk(){const s=document.querySelector("#__vconsole .vc-switch");return s||null}function Uk(){const s=document.querySelector("#__vconsole");return s||null}const bd=x("debugtypes");class zk{_types=new Map;_reverseTypes=new Map;_lazyLoaders=new Map;constructor(){bd&&console.warn("TypeStore: Created",this)}add(e,t){bd&&console.warn("ADD TYPE",e);const i=this._types.get(e);i?bd&&i!==t&&console.warn("Type name exists multiple times in your project and may lead to runtime errors:",e):(this._types.set(e,t),this._reverseTypes.set(t,e))}addLazy(e,t){this._types.has(e)||this._lazyLoaders.set(e,t)}get(e){return this._types.get(e)||null}async getAsync(e){const t=this._types.get(e);if(t)return t;const i=this._lazyLoaders.get(e);if(i){bd&&console.warn("LAZY LOAD TYPE",e);const n=await i();return this.add(e,n),this._lazyLoaders.delete(e),n}return null}getKey(e){return this._reverseTypes.get(e)||null}get types(){return this._types}}const Nk=Symbol("BuiltInType"),M=new zk,Ly=function(s){M.get(s.name)||M.add(s.name,s)};class $k{context;mixers=[];constructor(e){this.context=e}onDestroy(){this.mixers.forEach(e=>e.stopAllAction()),this.mixers.length=0}registerAnimationMixer(e){if(!e){console.warn("AnimationsRegistry.registerAnimationMixer called with null or undefined mixer");return}this.mixers.includes(e)||this.mixers.push(e)}unregisterAnimationMixer(e){if(!e){console.warn("AnimationsRegistry.unregisterAnimationMixer called with null or undefined mixer");return}const t=this.mixers.indexOf(e);t!==-1&&this.mixers.splice(t,1)}}exports.AnimationUtils=void 0;(s=>{function e(d,u){const f=d.getRoot();return f&&(f.userData.static||f.matrixAutoUpdate===!1||f.matrixWorldAutoUpdate===!1)?((u===!0||u===void 0&&E())&&console.warn(`AnimationUtils: The root object (${f.name||f.type}) of this AnimationAction has matrixAutoUpdate or matrixWorldAutoUpdate set to false. This may prevent the animation from working correctly. If the object is marked as static, try to change it to dynamic.`,{static:f.userData.static,name:f.userData.name,tag:f.userData.tag,matrixAutoUpdate:f.matrixAutoUpdate,matrixWorldAutoUpdate:f.matrixWorldAutoUpdate}),!1):!0}s.testIfRootCanAnimate=e;function t(d){const u=d._actions;return u||null}s.tryGetActionsFromMixer=t;function i(d,u){if(u||(u=new Array),d)d.animations&&u.push(...d.animations);else return u;if(d.children)for(const f of d.children)i(f,u);return u}s.tryGetAnimationClipsFromObjectHierarchy=i;const n=Symbol("objectIsAnimatedData");function o(d,u,f){if(!d)return;if(d[n]===void 0){if(!f)return;d[n]=new Set}const m=d[n];f?m.add(u):m.has(u)&&m.delete(u)}s.setObjectAnimated=o;function r(d){if(!d)return!1;const u=d[n];return u!==void 0&&u.size>0}s.getObjectAnimated=r;function a(d){if(!d||!d.animations)return console.debug("No animations found in file"),null;const u="scene"in d?d.scene:d,f=new Array;for(let g=0;g<d.animations.length;g++){const v=d.animations[g];if(!v.tracks||v.tracks.length<=0){console.warn("Animation has no tracks");continue}for(const _ in v.tracks){const y=v.tracks[_],b=c.PropertyBinding.parseTrackName(y.name);let w=c.PropertyBinding.findNode(u,b.nodeName);if(!w){const k=y.__objectName??y.name.substring(0,y.name.indexOf("."));if(w=u.getObjectByProperty("uuid",k)??null,!w)continue}let C=m(w)||m(u);if(!C){const k=M.get("Animation");if(C=u.addComponent(k),!C){console.error("Failed creating Animation component: No 'Animation' component found in TypeStore");break}}f.push(C),C.addClip&&C.addClip(v)}}return f;function m(g){if(!g)return null;const v=g.userData?.components;if(v&&v.length>0)for(let _=0;_<v.length;_++){const y=v[_];if(y.isAnimationComponent===!0)return y}return m(g.parent)}}s.autoplayAnimations=a;function l(){return new c.AnimationClip("empty",0,[])}s.emptyClip=l;function h(d){const u=d?.duration??.3;let f={x:1,y:1,z:1};d?.scale!==void 0&&(typeof d.scale=="number"?f={x:d.scale,y:d.scale,z:d.scale}:f=d.scale);const m=d?.type??"linear",g=d?.scaleFactor??1.2,v=new Array,_=new Array;switch(m){case"linear":v.push(0,u),_.push(f.x,f.y,f.z,f.x*g,f.y*g,f.z*g);break;case"spring":v.push(0,u*.3,u*.5,u*.7,u*.9,u),_.push(f.x,f.y,f.z,f.x*g,f.y*g,f.z*g,f.x*.9,f.y*.9,f.z*.9,f.x*1.05,f.y*1.05,f.z*1.05,f.x*.98,f.y*.98,f.z*.98,f.x,f.y,f.z);break}const y=new c.KeyframeTrack(".scale",v,_);return new c.AnimationClip("scale",v[v.length-1],[y])}s.createScaleClip=h})(exports.AnimationUtils||(exports.AnimationUtils={}));const Qe=function(s){return p(s)},p=function(s){if(s===void 0&&(s=null),!Array.isArray(s))s=rv(s);else for(let e=0;e<s.length;e++){const t=s[e];s[e]=rv(t)}return function(e,t){if(!e){const n=typeof t=="string"?t:t.name;console.warn(`@serializable without a target at '${n}'.`);return}typeof t!="string"&&(t=t.name),Object.getOwnPropertyDescriptor(e,"$serializedTypes")||(e.$serializedTypes={});const i=e.$serializedTypes=e.$serializedTypes||{};i[t]=s}};function rv(s){switch(s?.prototype?.constructor?.name){case"Number":case"String":case"Boolean":return null}return s}const av=x("debugcomponentevents");class Rf{static eventListeners=new Map;static addComponentLifecylceEventListener(e,t){this.eventListeners.has(e)&&this.eventListeners.set(e,[]);let i=this.eventListeners.get(e);i||(i=[]),i.push(t),this.eventListeners.set(e,i),av&&console.log("Added event listener for "+e,this.eventListeners)}static removeComponentLifecylceEventListener(e,t){const i=this.eventListeners.get(e);if(!i)return;const n=i.indexOf(t);n<0||i.splice(n,1)}static dispatchComponentLifecycleEvent(e,t){const i=this.eventListeners.get(e);if(av&&console.log("Dispatching event "+e,i),!!i)for(const n of i)n(t)}}const lx=x("debugdefines");Bo('if(!globalThis["NEEDLE_ENGINE_VERSION"]) globalThis["NEEDLE_ENGINE_VERSION"] = "0.0.0";');Bo('if(!globalThis["NEEDLE_ENGINE_GENERATOR"]) globalThis["NEEDLE_ENGINE_GENERATOR"] = "unknown";');Bo('if(!globalThis["NEEDLE_PROJECT_BUILD_TIME"]) globalThis["NEEDLE_PROJECT_BUILD_TIME"] = "unknown";');Bo('if(!globalThis["NEEDLE_PUBLIC_KEY"]) globalThis["NEEDLE_PUBLIC_KEY"] = "unknown";');Bo('globalThis["__NEEDLE_ENGINE_VERSION__"] = "6.0.0-alpha.5";');Bo('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";');Bo('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Mon Oct 05 2026 13:00:42 GMT+0000 (Coordinated Universal Time)";');Bo('globalThis["__NEEDLE_PUBLIC_KEY__"] = "'+NEEDLE_PUBLIC_KEY+'";');const Zt="6.0.0-alpha.5",al="undefined",Zc="Mon Oct 05 2026 13:00:42 GMT+0000 (Coordinated Universal Time)";lx&&console.log(`Engine version: ${Zt} (generator: ${al})
144
144
  Project built at ${Zc}`);const wo=NEEDLE_PUBLIC_KEY,Zn="needle_isActiveInHierarchy",cr="builtin_components",Rs="needle_editor_guid";function Bo(s){try{(0,eval)(s)}catch(e){lx&&console.error(e)}}globalThis.NEEDLE_USE_RAPIER=globalThis.NEEDLE_USE_RAPIER!==void 0?globalThis.NEEDLE_USE_RAPIER:!0;globalThis.NEEDLE_USE_POSTPROCESSING=globalThis.NEEDLE_USE_POSTPROCESSING!==void 0?globalThis.NEEDLE_USE_POSTPROCESSING:!0;const By={experimentalSmartHierarchyUpdate:!1},xi=Symbol("shadowDomOwner"),Vk=x("debugpatch");function Tf(s,e,t,i){const n=Vk===e;if(!t&&!i)return;const o=e+"___needle";Gk(s,e,t,i);const r=Object.getOwnPropertyDescriptor(s,e),a=s[e];n&&console.log("Patch",s.constructor.name,e,r,a),r?(n&&console.log("Apply patch with existing descriptor",s.constructor.name,e,r),typeof r.value=="function"&&(s[e]=cv(r.value,s,e))):(n&&console.log("Create patch with new property",s.constructor.name,e,r),Object.defineProperty(s,e,{set:function(l){if(typeof l=="function")this[o]=cv(l,s,e);else{const h=this[o];cx(s,e,this,h,l),this[o]=l,hx(s,e,this,h,l)}},get:function(){const l=this[o];return typeof l=="function"&&l[o]?l[o]:l}}))}function Wk(s,e,t){const i=Fy(s,e);if(i)for(let n=i.length-1;n>=0;n--){const o=i[n];o.prefix===t&&(o.prefix=null),o.postfix===t&&(o.postfix=null),!o.prefix&&!o.postfix&&i.splice(n,1)}}const lv=Symbol("Needle:Patches:WrappedFunction");function cv(s,e,t){if(s[lv])return s;const i=function(...n){cx(e,t,this,...n);const o=s.apply(this,n);return hx(e,t,this,o,...n),o};return i[lv]=!0,i}const gu="Needle:Patches";function yg(){return globalThis[gu]||(globalThis[gu]=new WeakMap),globalThis[gu]}function Fy(s,e){const t=yg().get(s);return t?t.get(e):null}function Gk(s,e,t,i){let n=yg().get(s);n||(n=new Map,yg().set(s,n));let o=n.get(e);o||(o=[],n.set(e,o)),o.push({prefix:t,postfix:i})}function cx(s,e,t,...i){if(!t)return;const n=Fy(s,e);if(n)for(const o of n)o.prefix?.call(t,...i)}function hx(s,e,t,i,...n){if(!t)return;const o=Fy(s,e);if(o)for(const r of o)r.postfix?.call(t,i,...n)}function Hk(s,e){if(typeof window!==void 0&&window.SPECTOR){console.log(window.SPECTOR);const t=new URLSearchParams(window.location.search);if(t.has("spector")){let i=function(){if(n>s.time.frame)return window.requestAnimationFrame(()=>i());const r=o.captureCanvas(e);r&&r instanceof Promise?r.then(()=>o.displayUI()):o.displayUI()};const n=Number.parseInt(t.get("spector")||"0")||0;console.log("Scheduled Spector capture at frame #"+n);const o=new window.SPECTOR.Spector;o.spyCanvases=!0,i();return}else E()&&console.debug("Spector available: Add '?spector=<frame>' to the URL to enable it and capture a frame.")}}function dx(s){const e=s;return!!(e.parser&&e.parser.json)}var as=(s=>(s[s.None=0]="None",s[s.DontExport=1]="DontExport",s[s.DontInstantiate=2]="DontInstantiate",s))(as||{});const Gu=Symbol("component-name");function Af(s){return s&&typeof s=="object"&&s.isComponent}const qk=Symbol("object"),Zp=new Mi(()=>new c.Vector3,20);class ux{_point;_normal;_tangentVelocity;distance;impulse;friction;get point(){return Zp.get().set(this._point.x,this._point.y,this._point.z)}get normal(){return Zp.get().set(this._normal.x,this._normal.y,this._normal.z)}get tangentVelocity(){return Zp.get().set(this._tangentVelocity.x,this._tangentVelocity.y,this._tangentVelocity.z)}constructor(e,t,i,n,o,r){this._point=e,this.distance=t,this._normal=i,this.impulse=n,this.friction=o,this._tangentVelocity=r}}class fx{contacts;constructor(e,t,i){this.me=e,this._collider=t,this._gameObject=t.gameObject,this.contacts=i}me;_collider;get collider(){return this._collider}_gameObject;get gameObject(){return this._gameObject}get rigidBody(){return this.collider?.attachedRigidbody}}class px{object;collider;constructor(e,t){this.object=e,this.collider=t}}class Hu{constructor(e){this.context=e,this.root.style.cssText=`
145
145
  position: absolute;
146
146
  width: 1px; height: 1px;
@@ -158,7 +158,7 @@ To unregister you can call the function returned by your event hook (e.g.const u
158
158
 
159
159
  or by using the once option like onStart(()=>{}, { once:true }).
160
160
 
161
- See https://engine.needle.tools/docs/scripting.html#special-lifecycle-hooks for more information.`))}}function Fo(s,e){const t=Ua.get(e);if(t){for(let n=0;n<t.length;n++)if(t[n].method===s){t.splice(n,1);return}}const i=Xa.get(e);if(i){for(let n=0;n<i.length;n++)if(i[n].method===s){i.splice(n,1);return}}}function An(s,e){e===ae.ContextCreated&&_g.delete(s),yx(s,e)}function yx(s,e){e===Ce.Start&&Xa.get(ae.ContextCreated)&&yx(s,ae.ContextCreated);const t=e===Ce.Start||e===ae.ContextCreated,i=Ua.get(e);i&&i.length>0&&fv(s,i,t);const n=Xa.get(e);if(n&&n.length>0){const o=[...n];n.length=0,fv(s,o,t),o.length>0&&(Ua.has(e)||Ua.set(e,new Array),Ua.get(e).push(...o))}}const uv=[];let vd=0;const wd={context:null};function fv(s,e,t){const i=uv[vd]??(uv[vd]=[]);vd++;try{Yk(s,e,t,i)}finally{i.length=0,vd--}}function Yk(s,e,t,i){for(let o=0;o<e.length;o++)i.push(e[o]);let n=_g.get(s);for(let o=0;o<i.length;o++){const r=i[o];let a=!0;if(n&&n.has(r)&&(a=!1),a){const l=wd.context;try{wd.context=s,r.method?.call(wd,s)}catch(h){console.error("Error in lifecycle method",h)}finally{wd.context=l}}if(r.options?.once){for(let l=0;l<e.length;l++)if(e[l]===r){e.splice(l,1);break}}else t&&(n||(n=new Set,_g.set(s,n)),n.add(r))}}const _g=new WeakMap;function Uy(s,e){return Us(s,ae.ContextCreated,e),()=>Fo(s,ae.ContextCreated)}function Kk(s,e){return Us(s,ae.ContextClearing,e),()=>Fo(s,ae.ContextClearing)}function Zk(s,e){return Us(s,ae.ContextDestroying,e),()=>Fo(s,ae.ContextDestroying)}function If(s,e){return Us(s,Ce.Start,e),()=>Fo(s,Ce.Start)}function _x(s,e){return Us(s,Ce.Update,e),()=>Fo(s,Ce.Update)}function Jk(s,e){return Us(s,Ce.OnBeforeRender,e),()=>Fo(s,Ce.OnBeforeRender)}function eM(s,e){return Us(s,Ce.OnAfterRender,e),()=>Fo(s,Ce.OnAfterRender)}const we=x("__debuglic__"),qu=new WeakMap,Xu=new WeakMap,zy=new WeakSet;se.registerCallback(ae.ContextDestroying,({context:s})=>{zy.add(s);for(const e of qu.get(s)??[])clearInterval(e);qu.delete(s);for(const e of Xu.get(s)??[])clearTimeout(e);Xu.delete(s)});function bg(s,e,t){if(zy.has(s))return;let i=qu.get(s);i||qu.set(s,i=new Set);const n=setInterval(e,t);return i.add(n),n}function yu(s,e,t){if(zy.has(s))return;let i=Xu.get(s);i||Xu.set(s,i=new Set);const n=setTimeout(()=>{i.delete(n),e()},t);return i.add(n),n}const _u=[];let Pi="",Fc="";if(we)if(console.log("License Type: "+Pi),Fc){console.log("License JWT: "+Fc);try{const s=JSON.parse(atob(Fc.split(".")[1].replace(/-/g,"+").replace(/_/g,"/")));console.log("License JWT payload:",s)}catch{console.log("License JWT payload: (failed to decode)")}}else console.log("License JWT: (none)");function ns(){switch(Pi){case"pro":case"enterprise":return!0}return!1}function kh(){return Pi==="indie"}function Ny(){return Pi==="edu"}function Yi(){return ns()||kh()||Ny()}function tM(s){return ns()||kh()||Ny()?(s(!0),()=>{}):(_u.push(s),()=>{const e=_u.indexOf(s);e>=0&&_u.splice(e,1)})}function wc(s){for(const e of _u)try{e(s)}catch{}}const iM={kty:"EC",crv:"P-256",x:"A34nyKMjhQYVgzeE4tyLUYdx34TAKogDa7v7PRaO9Lg",y:"JZI9IQavGCpGjEG_-pa0J-MHQYWJYINUM-MnvSu0TmE"};function pv(s){const e=s.replace(/-/g,"+").replace(/_/g,"/"),t=e+"=".repeat((4-e.length%4)%4),i=atob(t),n=new Uint8Array(i.length);for(let o=0;o<i.length;o++)n[o]=i.charCodeAt(o);return n}async function nM(s){if(!s)return null;try{const e=s.split(".");if(e.length!==3)return null;const[t,i,n]=e,o=await crypto.subtle.importKey("jwk",iM,{name:"ECDSA",namedCurve:"P-256"},!1,["verify"]),r=new TextEncoder().encode(`${t}.${i}`),a=pv(n);if(!await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},o,a.buffer,r))return we&&console.warn("JWT: signature verification failed"),null;const h=new TextDecoder().decode(pv(i)),d=JSON.parse(h);if(typeof d.type!="string"||d.type.length===0)return we&&console.warn("JWT: missing or invalid 'type' claim"),null;if(typeof d.exp=="number"){const u=Math.floor(Date.now()/1e3);if(u>d.exp)return we&&console.warn("JWT: token has expired (exp="+d.exp+", now="+u+")"),null}if(d.aud){const u=typeof window<"u"?window.location.hostname:void 0;if(u){const f=Array.isArray(d.aud)?d.aud:[d.aud];if(!f.some(m=>u===m||u.endsWith("."+m)))return we&&console.warn("JWT: domain '"+u+"' not in allowed audience: "+f.join(", ")),null}}return we&&console.log("JWT: verified license type: "+d.type),d.type}catch(e){return we&&console.error("JWT: verification error",e),null}}let vg;async function sM(){const s=Fc;Fc="";const e=await nM(s);e?(Pi=e,we&&console.log("License type set from verified JWT: "+e),wc(Yi())):(Pi="basic",we&&s&&console.warn("JWT verification failed — license reset to basic"))}var st;(s=>{typeof window<"u"&&(window.addEventListener("error",y=>{h(X.Current,"unhandled_error",y)}),window.addEventListener("unhandledrejection",y=>{t(y)}));function e(y,b){if(y==="AbortError")return!0;const w=(b||"").toLowerCase();return w.includes("load failed")||w.includes("failed to fetch")||w.includes("networkerror")||w.includes("network connection was lost")||w.includes("the operation was aborted")||w.includes("load cancelled")}function t(y){const b=y?.reason,w=typeof b?.name=="string"?b.name:void 0,C=typeof b?.message=="string"?b.message:typeof b=="string"?b:void 0,k=X.Current,O=typeof document<"u"?document.visibilityState:void 0,D=typeof navigator<"u"?navigator.onLine:void 0;if(e(w,C)){l(k,"network_rejection",{message:C,name:w,visibility:O,online:D});return}h(k,"unhandled_promise_rejection",{name:w,message:C,stack:b?.stack,url:typeof b?.url=="string"?b.url:void 0,visibility:O,online:D,version:Zt,timestamp:Date.now()})}function i(){jy||Uy((y=>n(y)),{once:!0})}s.init=i;function n(y){if(!o(y)){we&&console.debug("Telemetry is disabled via no-telemetry attribute");return}return _({site_id:"dabb8317376f",type:"pageview",pathname:window.location.pathname,hostname:window.location.hostname,page_title:document.title,referrer:document.referrer,user_agent:navigator.userAgent,querystring:window.location.search,language:navigator.language,screenWidth:window.screen.width,screenHeight:window.screen.height,event_name:"page_view"}).then(b=>{if(b instanceof Response&&b.ok&&ki()){const C=(y.domElement?.getAttribute("src")||"")+Zt+al+Zc+wo;window.sessionStorage.getItem("session_key")!==C&&(window.sessionStorage.setItem("session_key",C),l(y,"info",{src:y.domElement?.getAttribute("src")||"",version:Zt,generator:al,build_time:Zc,public_key:wo}))}})}function o(y){let b=y?.domElement;if(b||(b=document.querySelector("needle-engine")),!b&&!y)return!1;const w=b?.getAttribute("no-telemetry");return ns()&&(w===""||w==="true"||w==="1")?(we&&console.debug("Telemetry is disabled via no-telemetry attribute"),!1):r()?(we&&console.debug("Telemetry is disabled via Do Not Track / Global Privacy Control"),!1):typeof window<"u"&&window.crossOriginIsolated?(we&&console.debug("Telemetry is disabled on cross-origin-isolated pages"),!1):!0}s.isAllowed=o;function r(){if(typeof navigator>"u")return!1;const y=navigator;if(y.globalPrivacyControl===!0)return!0;const b=y.doNotTrack??y.msDoNotTrack??(typeof window<"u"?window.doNotTrack:null);return b==="1"||b==="yes"}const a="dabb8317376f";async function l(y,b,w){if(!o(y)){we&&console.debug("Telemetry is disabled");return}const C={site_id:a,type:"custom_event",pathname:window.location.pathname,event_name:b,properties:w?JSON.stringify(w):void 0};return _(C)}s.sendEvent=l;async function h(y,b,w){if(!o(y)){we&&console.debug("Telemetry is disabled");return}w instanceof ErrorEvent?w={message:w.message,stack:w.error?.stack,filename:w.filename,lineno:w.lineno,colno:w.colno,timestamp:w.timeStamp||Date.now()}:w instanceof Error&&(w={message:w.message,stack:w.stack,timestamp:Date.now()});const C={site_id:a,type:"error",event_name:b||"error",properties:JSON.stringify({error_name:b,message:w.message,stack:w.stack,filename:w.filename,lineno:w.lineno,colno:w.colno,timestamp:w.timestamp,name:w.name,visibility:w.visibility,online:w.online,url:w.url,version:w.version})};return _(C)}s.sendError=h;function d(y,b){if(!o(y))return;const w={action:"load",success:b.success,files:b.files,is_reload:b.is_reload,load_ms:Math.round(b.load_ms)};b.error&&(w.error=b.error),b.first_frame_ms!==void 0&&(w.first_frame_ms=Math.round(b.first_frame_ms)),b.since_navigation_ms!==void 0&&(w.since_navigation_ms=Math.round(b.since_navigation_ms)),b.success&&u(y,w),l(y,"engine",w)}s.reportLoad=d;function u(y,b){const w=y?.renderer;if(w)try{if(w.isWebGPURenderer===!0)b.api="webgpu";else{const C=w.getContext();if(C){const k=typeof WebGL2RenderingContext<"u"&&C instanceof WebGL2RenderingContext;b.api=k?"webgl2":"webgl",b.max_texture_size=C.getParameter(C.MAX_TEXTURE_SIZE),k&&(b.max_samples=C.getParameter(C.MAX_SAMPLES));const O=[];C.getExtension("WEBGL_compressed_texture_astc")&&O.push("astc"),C.getExtension("WEBGL_compressed_texture_etc")&&O.push("etc"),C.getExtension("WEBGL_compressed_texture_s3tc")&&O.push("s3tc"),C.getExtension("WEBGL_compressed_texture_pvrtc")&&O.push("pvrtc"),O.length&&(b.compression=O.join(","))}}if(b.dpr=w.getPixelRatio(),b.is_mobile=exports.DeviceUtilities.isMobileDevice(),typeof navigator<"u"){navigator.hardwareConcurrency&&(b.cores=navigator.hardwareConcurrency);const C=navigator.deviceMemory;typeof C=="number"&&(b.device_memory=C)}}catch(C){we&&console.warn("Telemetry: capability probe failed",C)}}const f=new WeakSet;function m(y){const b=y?.renderer?.domElement;if(!b||f.has(b))return;f.add(b);let w=0;b.addEventListener("webglcontextlost",()=>{w=performance.now(),l(y,"engine",{action:"context_lost",since_navigation_ms:Math.round(performance.now()),during_xr:y?.isInXR===!0})}),b.addEventListener("webglcontextrestored",()=>{l(y,"engine",{action:"context_restored",downtime_ms:w?Math.round(performance.now()-w):void 0})})}s.attachContextLossMonitor=m;const g=new WeakSet;function v(y){if(!y||typeof document>"u"||g.has(y)||!o(y))return;g.add(y);let b=0,w=0,C=0,k=0,O=0;const D=()=>{const R=y.time.deltaTimeUnscaled;if(R<=0)return;b++,w+=R*1e3,R>C&&(C=R);const U=y.renderer?.info?.render;U&&(U.calls>k&&(k=U.calls),U.triangles>O&&(O=U.triangles))};y.post_render_callbacks.push(D);const I=()=>{b=0,w=0,C=0,k=0,O=0},j=()=>{b<=0||(l(y,"engine",{action:"performance",frames:b,duration_ms:Math.round(w),avg_fps:Math.round(1e3*b/w),min_fps:C>0?Math.round(1/C):0,avg_frame_ms:Math.round(w/b*10)/10,max_frame_ms:Math.round(C*1e3*10)/10,peak_draw_calls:k,peak_triangles:O}),I())},$=()=>{document.visibilityState==="hidden"&&j()};document.addEventListener("visibilitychange",$),window.addEventListener("pagehide",j);const W=se.registerCallback(ae.ContextDestroyed,R=>{if(R.context!==y)return;j(),document.removeEventListener("visibilitychange",$),window.removeEventListener("pagehide",j);const U=y.post_render_callbacks.indexOf(D);U>=0&&y.post_render_callbacks.splice(U,1),g.delete(y),W()})}s.attachPerformanceMonitor=v;function _(y){try{return fetch("https://needle.tools/api/v1/rum/t",{method:"POST",body:JSON.stringify(y),headers:{"Content-Type":"application/json"},keepalive:!0,mode:"cors",priority:"low"}).catch(w=>{we&&console.error("Failed to send telemetry",w)})}catch(b){we&&console.error(b)}return Promise.resolve()}})(st||(st={}));function oM(){Pi===""&&(Pi="basic"),vg=sM(),st.init(),se.registerCallback(ae.ContextRegistered,s=>{lM(s.context),aM(s.context),yu(s.context,()=>hM(s.context),2e3)}),se.registerCallback(ae.ContextCreated,s=>{st.attachContextLossMonitor(s.context),st.attachPerformanceMonitor(s.context)})}let Qu,wg=!1,xg="";async function rM(){if(Qu)return Qu;if(vg&&await vg,Pi==="basic")try{const s="https://needle.tools/api/v1/needle-engine/check?location="+encodeURIComponent(window.location.href)+"&version="+Zt+"&generator="+encodeURIComponent(al),e=await fetch(s,{method:"GET"}).catch(t=>{we&&console.error("License check failed",t)});e?.status===200?(wg=!1,we&&console.log("License check succeeded"),Pi="pro",wc(!0)):e?.status===403?(wc(!1),wg=!0,xg=await e.text()):(wc(!1),we&&console.log("License check failed with status "+e?.status))}catch(s){wc(!1),we&&console.error("License check failed",s)}else we&&console.log('Runtime license check is skipped because license is already applied as "'+Pi+'"')}Qu=rM();async function aM(s){function e(){const n=document.createElement("div");n.className="needle-forbidden",n.style.cssText=`
161
+ See https://engine.needle.tools/docs/scripting.html#special-lifecycle-hooks for more information.`))}}function Fo(s,e){const t=Ua.get(e);if(t){for(let n=0;n<t.length;n++)if(t[n].method===s){t.splice(n,1);return}}const i=Xa.get(e);if(i){for(let n=0;n<i.length;n++)if(i[n].method===s){i.splice(n,1);return}}}function An(s,e){e===ae.ContextCreated&&_g.delete(s),yx(s,e)}function yx(s,e){e===Ce.Start&&Xa.get(ae.ContextCreated)&&yx(s,ae.ContextCreated);const t=e===Ce.Start||e===ae.ContextCreated,i=Ua.get(e);i&&i.length>0&&fv(s,i,t);const n=Xa.get(e);if(n&&n.length>0){const o=[...n];n.length=0,fv(s,o,t),o.length>0&&(Ua.has(e)||Ua.set(e,new Array),Ua.get(e).push(...o))}}const uv=[];let vd=0;const wd={context:null};function fv(s,e,t){const i=uv[vd]??(uv[vd]=[]);vd++;try{Yk(s,e,t,i)}finally{i.length=0,vd--}}function Yk(s,e,t,i){for(let o=0;o<e.length;o++)i.push(e[o]);let n=_g.get(s);for(let o=0;o<i.length;o++){const r=i[o];let a=!0;if(n&&n.has(r)&&(a=!1),a){const l=wd.context;try{wd.context=s,r.method?.call(wd,s)}catch(h){console.error("Error in lifecycle method",h)}finally{wd.context=l}}if(r.options?.once){for(let l=0;l<e.length;l++)if(e[l]===r){e.splice(l,1);break}}else t&&(n||(n=new Set,_g.set(s,n)),n.add(r))}}const _g=new WeakMap;function Uy(s,e){return Us(s,ae.ContextCreated,e),()=>Fo(s,ae.ContextCreated)}function Kk(s,e){return Us(s,ae.ContextClearing,e),()=>Fo(s,ae.ContextClearing)}function Zk(s,e){return Us(s,ae.ContextDestroying,e),()=>Fo(s,ae.ContextDestroying)}function If(s,e){return Us(s,Ce.Start,e),()=>Fo(s,Ce.Start)}function _x(s,e){return Us(s,Ce.Update,e),()=>Fo(s,Ce.Update)}function Jk(s,e){return Us(s,Ce.OnBeforeRender,e),()=>Fo(s,Ce.OnBeforeRender)}function eM(s,e){return Us(s,Ce.OnAfterRender,e),()=>Fo(s,Ce.OnAfterRender)}const be=x("__debuglic__"),qu=new WeakMap,Xu=new WeakMap,zy=new WeakSet;se.registerCallback(ae.ContextDestroying,({context:s})=>{zy.add(s);for(const e of qu.get(s)??[])clearInterval(e);qu.delete(s);for(const e of Xu.get(s)??[])clearTimeout(e);Xu.delete(s)});function bg(s,e,t){if(zy.has(s))return;let i=qu.get(s);i||qu.set(s,i=new Set);const n=setInterval(e,t);return i.add(n),n}function yu(s,e,t){if(zy.has(s))return;let i=Xu.get(s);i||Xu.set(s,i=new Set);const n=setTimeout(()=>{i.delete(n),e()},t);return i.add(n),n}const _u=[];let Pi="",Fc="";if(be)if(console.log("License Type: "+Pi),Fc){console.log("License JWT: "+Fc);try{const s=JSON.parse(atob(Fc.split(".")[1].replace(/-/g,"+").replace(/_/g,"/")));console.log("License JWT payload:",s)}catch{console.log("License JWT payload: (failed to decode)")}}else console.log("License JWT: (none)");function ns(){switch(Pi){case"pro":case"enterprise":return!0}return!1}function kh(){return Pi==="indie"}function Ny(){return Pi==="edu"}function Yi(){return ns()||kh()||Ny()}function tM(s){return ns()||kh()||Ny()?(s(!0),()=>{}):(_u.push(s),()=>{const e=_u.indexOf(s);e>=0&&_u.splice(e,1)})}function wc(s){for(const e of _u)try{e(s)}catch{}}const iM={kty:"EC",crv:"P-256",x:"A34nyKMjhQYVgzeE4tyLUYdx34TAKogDa7v7PRaO9Lg",y:"JZI9IQavGCpGjEG_-pa0J-MHQYWJYINUM-MnvSu0TmE"};function pv(s){const e=s.replace(/-/g,"+").replace(/_/g,"/"),t=e+"=".repeat((4-e.length%4)%4),i=atob(t),n=new Uint8Array(i.length);for(let o=0;o<i.length;o++)n[o]=i.charCodeAt(o);return n}async function nM(s){if(!s)return null;try{const e=s.split(".");if(e.length!==3)return null;const[t,i,n]=e,o=await crypto.subtle.importKey("jwk",iM,{name:"ECDSA",namedCurve:"P-256"},!1,["verify"]),r=new TextEncoder().encode(`${t}.${i}`),a=pv(n);if(!await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},o,a.buffer,r))return be&&console.warn("JWT: signature verification failed"),null;const h=new TextDecoder().decode(pv(i)),d=JSON.parse(h);if(typeof d.type!="string"||d.type.length===0)return be&&console.warn("JWT: missing or invalid 'type' claim"),null;if(typeof d.exp=="number"){const u=Math.floor(Date.now()/1e3);if(u>d.exp)return be&&console.warn("JWT: token has expired (exp="+d.exp+", now="+u+")"),null}if(d.aud){const u=typeof window<"u"?window.location.hostname:void 0;if(u){const f=Array.isArray(d.aud)?d.aud:[d.aud];if(!f.some(m=>u===m||u.endsWith("."+m)))return be&&console.warn("JWT: domain '"+u+"' not in allowed audience: "+f.join(", ")),null}}return be&&console.log("JWT: verified license type: "+d.type),d.type}catch(e){return be&&console.error("JWT: verification error",e),null}}let vg;async function sM(){let s=Fc;if(Fc="",!s&&typeof document<"u"){const t=document.querySelector('meta[name="needle-license"]')?.getAttribute("content");if(t)try{const i=new URL(t,document.baseURI),n=await fetch(i,{cache:"no-store"});if(n.ok){const o=await n.json();typeof o?.jwt=="string"&&(s=o.jwt)}}catch(i){be&&console.warn("Could not load signed license file",i)}}const e=await nM(s);e?(Pi=e,be&&console.log("License type set from verified JWT: "+e),wc(Yi())):(Pi="basic",be&&s&&console.warn("JWT verification failed — license reset to basic"))}var st;(s=>{typeof window<"u"&&(window.addEventListener("error",y=>{h(X.Current,"unhandled_error",y)}),window.addEventListener("unhandledrejection",y=>{t(y)}));function e(y,b){if(y==="AbortError")return!0;const w=(b||"").toLowerCase();return w.includes("load failed")||w.includes("failed to fetch")||w.includes("networkerror")||w.includes("network connection was lost")||w.includes("the operation was aborted")||w.includes("load cancelled")}function t(y){const b=y?.reason,w=typeof b?.name=="string"?b.name:void 0,C=typeof b?.message=="string"?b.message:typeof b=="string"?b:void 0,k=X.Current,O=typeof document<"u"?document.visibilityState:void 0,D=typeof navigator<"u"?navigator.onLine:void 0;if(e(w,C)){l(k,"network_rejection",{message:C,name:w,visibility:O,online:D});return}h(k,"unhandled_promise_rejection",{name:w,message:C,stack:b?.stack,url:typeof b?.url=="string"?b.url:void 0,visibility:O,online:D,version:Zt,timestamp:Date.now()})}function i(){jy||Uy((y=>n(y)),{once:!0})}s.init=i;function n(y){if(!o(y)){be&&console.debug("Telemetry is disabled via no-telemetry attribute");return}return _({site_id:"dabb8317376f",type:"pageview",pathname:window.location.pathname,hostname:window.location.hostname,page_title:document.title,referrer:document.referrer,user_agent:navigator.userAgent,querystring:window.location.search,language:navigator.language,screenWidth:window.screen.width,screenHeight:window.screen.height,event_name:"page_view"}).then(b=>{if(b instanceof Response&&b.ok&&ki()){const C=(y.domElement?.getAttribute("src")||"")+Zt+al+Zc+wo;window.sessionStorage.getItem("session_key")!==C&&(window.sessionStorage.setItem("session_key",C),l(y,"info",{src:y.domElement?.getAttribute("src")||"",version:Zt,generator:al,build_time:Zc,public_key:wo}))}})}function o(y){let b=y?.domElement;if(b||(b=document.querySelector("needle-engine")),!b&&!y)return!1;const w=b?.getAttribute("no-telemetry");return ns()&&(w===""||w==="true"||w==="1")?(be&&console.debug("Telemetry is disabled via no-telemetry attribute"),!1):r()?(be&&console.debug("Telemetry is disabled via Do Not Track / Global Privacy Control"),!1):typeof window<"u"&&window.crossOriginIsolated?(be&&console.debug("Telemetry is disabled on cross-origin-isolated pages"),!1):!0}s.isAllowed=o;function r(){if(typeof navigator>"u")return!1;const y=navigator;if(y.globalPrivacyControl===!0)return!0;const b=y.doNotTrack??y.msDoNotTrack??(typeof window<"u"?window.doNotTrack:null);return b==="1"||b==="yes"}const a="dabb8317376f";async function l(y,b,w){if(!o(y)){be&&console.debug("Telemetry is disabled");return}const C={site_id:a,type:"custom_event",pathname:window.location.pathname,event_name:b,properties:w?JSON.stringify(w):void 0};return _(C)}s.sendEvent=l;async function h(y,b,w){if(!o(y)){be&&console.debug("Telemetry is disabled");return}w instanceof ErrorEvent?w={message:w.message,stack:w.error?.stack,filename:w.filename,lineno:w.lineno,colno:w.colno,timestamp:w.timeStamp||Date.now()}:w instanceof Error&&(w={message:w.message,stack:w.stack,timestamp:Date.now()});const C={site_id:a,type:"error",event_name:b||"error",properties:JSON.stringify({error_name:b,message:w.message,stack:w.stack,filename:w.filename,lineno:w.lineno,colno:w.colno,timestamp:w.timestamp,name:w.name,visibility:w.visibility,online:w.online,url:w.url,version:w.version})};return _(C)}s.sendError=h;function d(y,b){if(!o(y))return;const w={action:"load",success:b.success,files:b.files,is_reload:b.is_reload,load_ms:Math.round(b.load_ms)};b.error&&(w.error=b.error),b.first_frame_ms!==void 0&&(w.first_frame_ms=Math.round(b.first_frame_ms)),b.since_navigation_ms!==void 0&&(w.since_navigation_ms=Math.round(b.since_navigation_ms)),b.success&&u(y,w),l(y,"engine",w)}s.reportLoad=d;function u(y,b){const w=y?.renderer;if(w)try{if(w.isWebGPURenderer===!0)b.api="webgpu";else{const C=w.getContext();if(C){const k=typeof WebGL2RenderingContext<"u"&&C instanceof WebGL2RenderingContext;b.api=k?"webgl2":"webgl",b.max_texture_size=C.getParameter(C.MAX_TEXTURE_SIZE),k&&(b.max_samples=C.getParameter(C.MAX_SAMPLES));const O=[];C.getExtension("WEBGL_compressed_texture_astc")&&O.push("astc"),C.getExtension("WEBGL_compressed_texture_etc")&&O.push("etc"),C.getExtension("WEBGL_compressed_texture_s3tc")&&O.push("s3tc"),C.getExtension("WEBGL_compressed_texture_pvrtc")&&O.push("pvrtc"),O.length&&(b.compression=O.join(","))}}if(b.dpr=w.getPixelRatio(),b.is_mobile=exports.DeviceUtilities.isMobileDevice(),typeof navigator<"u"){navigator.hardwareConcurrency&&(b.cores=navigator.hardwareConcurrency);const C=navigator.deviceMemory;typeof C=="number"&&(b.device_memory=C)}}catch(C){be&&console.warn("Telemetry: capability probe failed",C)}}const f=new WeakSet;function m(y){const b=y?.renderer?.domElement;if(!b||f.has(b))return;f.add(b);let w=0;b.addEventListener("webglcontextlost",()=>{w=performance.now(),l(y,"engine",{action:"context_lost",since_navigation_ms:Math.round(performance.now()),during_xr:y?.isInXR===!0})}),b.addEventListener("webglcontextrestored",()=>{l(y,"engine",{action:"context_restored",downtime_ms:w?Math.round(performance.now()-w):void 0})})}s.attachContextLossMonitor=m;const g=new WeakSet;function v(y){if(!y||typeof document>"u"||g.has(y)||!o(y))return;g.add(y);let b=0,w=0,C=0,k=0,O=0;const D=()=>{const R=y.time.deltaTimeUnscaled;if(R<=0)return;b++,w+=R*1e3,R>C&&(C=R);const U=y.renderer?.info?.render;U&&(U.calls>k&&(k=U.calls),U.triangles>O&&(O=U.triangles))};y.post_render_callbacks.push(D);const I=()=>{b=0,w=0,C=0,k=0,O=0},j=()=>{b<=0||(l(y,"engine",{action:"performance",frames:b,duration_ms:Math.round(w),avg_fps:Math.round(1e3*b/w),min_fps:C>0?Math.round(1/C):0,avg_frame_ms:Math.round(w/b*10)/10,max_frame_ms:Math.round(C*1e3*10)/10,peak_draw_calls:k,peak_triangles:O}),I())},$=()=>{document.visibilityState==="hidden"&&j()};document.addEventListener("visibilitychange",$),window.addEventListener("pagehide",j);const W=se.registerCallback(ae.ContextDestroyed,R=>{if(R.context!==y)return;j(),document.removeEventListener("visibilitychange",$),window.removeEventListener("pagehide",j);const U=y.post_render_callbacks.indexOf(D);U>=0&&y.post_render_callbacks.splice(U,1),g.delete(y),W()})}s.attachPerformanceMonitor=v;function _(y){try{return fetch("https://needle.tools/api/v1/rum/t",{method:"POST",body:JSON.stringify(y),headers:{"Content-Type":"application/json"},keepalive:!0,mode:"cors",priority:"low"}).catch(w=>{be&&console.error("Failed to send telemetry",w)})}catch(b){be&&console.error(b)}return Promise.resolve()}})(st||(st={}));function oM(){Pi===""&&(Pi="basic"),vg=sM(),Qu=rM(),st.init(),se.registerCallback(ae.ContextRegistered,s=>{lM(s.context),aM(s.context),yu(s.context,()=>hM(s.context),2e3)}),se.registerCallback(ae.ContextCreated,s=>{st.attachContextLossMonitor(s.context),st.attachPerformanceMonitor(s.context)})}let Qu,wg=!1,xg="";async function rM(){if(Qu)return Qu;if(vg&&await vg,Pi==="basic")try{const s="https://needle.tools/api/v1/needle-engine/check?location="+encodeURIComponent(window.location.href)+"&version="+Zt+"&generator="+encodeURIComponent(al),e=await fetch(s,{method:"GET"}).catch(t=>{be&&console.error("License check failed",t)});e?.status===200?(wg=!1,be&&console.log("License check succeeded"),Pi="pro",wc(!0)):e?.status===403?(wc(!1),wg=!0,xg=await e.text()):(wc(!1),be&&console.log("License check failed with status "+e?.status))}catch(s){wc(!1),be&&console.error("License check failed",s)}else be&&console.log('Runtime license check is skipped because license is already applied as "'+Pi+'"')}async function aM(s){function e(){const n=document.createElement("div");n.className="needle-forbidden",n.style.cssText=`
162
162
  position: fixed;
163
163
  top: 0;
164
164
  left: 0;
@@ -186,7 +186,7 @@ See https://engine.needle.tools/docs/scripting.html#special-lifecycle-hooks for
186
186
  align-items: center;
187
187
  background-color: rgba(0,0,0,.3);
188
188
  text-shadow: 0 0 2px black;
189
- `;const a=r.style.cssText,l=xg?.length>1?xg:"This web application has been paused.<br/>You might be in violation of the Needle Engine terms of use.<br/>Please contact the Needle support if you think this is a mistake.";return r.innerHTML=l,bg(s,()=>{r.innerHTML!==l&&(r.innerHTML=l),r.parentNode!==n&&n.appendChild(r),n.style.cssText!==o&&(n.style.cssText=o),r.style.cssText!==a&&(r.style.cssText=a)},500),n}let t=e();const i=t.style.cssText;bg(s,()=>{wg===!0&&(t.style.cssText!==i&&(t=e()),s.domElement.shadowRoot?t.parentNode!==s.domElement.shadowRoot&&s.domElement.shadowRoot?.appendChild(t):t.parentNode!=document.body&&document.body.appendChild(t))},500)}async function lM(s){try{if(!ns()&&!kh())return Jp(s)}catch(e){return we&&console.log("License check failed",e),Jp(s)}we&&Jp(s)}async function Jp(s){let e=!1;s.domElement.addEventListener("ready",()=>e=!0),await Qu?.catch(()=>{}),!(ns()||kh())&&(Yi()===!1&&cM(),e?Sg(s):s.domElement.addEventListener("ready",()=>{Sg(s)}))}function Sg(s){const e=`
189
+ `;const a=r.style.cssText,l=xg?.length>1?xg:"This web application has been paused.<br/>You might be in violation of the Needle Engine terms of use.<br/>Please contact the Needle support if you think this is a mistake.";return r.innerHTML=l,bg(s,()=>{r.innerHTML!==l&&(r.innerHTML=l),r.parentNode!==n&&n.appendChild(r),n.style.cssText!==o&&(n.style.cssText=o),r.style.cssText!==a&&(r.style.cssText=a)},500),n}let t=e();const i=t.style.cssText;bg(s,()=>{wg===!0&&(t.style.cssText!==i&&(t=e()),s.domElement.shadowRoot?t.parentNode!==s.domElement.shadowRoot&&s.domElement.shadowRoot?.appendChild(t):t.parentNode!=document.body&&document.body.appendChild(t))},500)}async function lM(s){try{if(!ns()&&!kh())return Jp(s)}catch(e){return be&&console.log("License check failed",e),Jp(s)}be&&Jp(s)}async function Jp(s){let e=!1;s.domElement.addEventListener("ready",()=>e=!0),await Qu?.catch(()=>{}),!(ns()||kh())&&(Yi()===!1&&cM(),e?Sg(s):s.domElement.addEventListener("ready",()=>{Sg(s)}))}function Sg(s){const e=`
190
190
  position: relative;
191
191
  display: block;
192
192
  background-size: 20px;
@@ -229,7 +229,7 @@ See https://engine.needle.tools/docs/scripting.html#special-lifecycle-hooks for
229
229
  padding-left: 25px;
230
230
  border-radius: .5em;
231
231
  border: 2px solid rgba(160,160,160,.3);
232
- `,n=`Needle Engine — No license active, commercial use is not allowed. Visit https://needle.tools/pricing for more information and licensing options! v${Zt}`;X.Current?.xr||navigator.webdriver?console.log(n):console.log("%c "+n,t)}async function hM(s){if(!st.isAllowed(s)){we&&console.debug("Telemetry is disabled");return}try{const e="https://needle.tools/api/v1/needle-engine/ping";if(e){const t=window.location.href.split("?")[0],n={license:Pi,url:t,hostname:window.location.hostname,pathname:window.location.pathname,version:Zt,generator:al,build_time:Zc,public_key:wo},o=navigator.sendBeacon?.(e,JSON.stringify(n));we&&console.debug("Sent beacon: "+o)}}catch(e){we&&console.log("Failed to send non-commercial usage message to analytics backend",e)}}function vx(s){function e(_,y){const b=(_&65535)+(y&65535);return(_>>16)+(y>>16)+(b>>16)<<16|b&65535}function t(_,y){return _<<y|_>>>32-y}function i(_,y,b,w,C,k){return e(t(e(e(y,_),e(w,k)),C),b)}function n(_,y,b,w,C,k,O){return i(y&b|~y&w,_,y,C,k,O)}function o(_,y,b,w,C,k,O){return i(y&w|b&~w,_,y,C,k,O)}function r(_,y,b,w,C,k,O){return i(y^b^w,_,y,C,k,O)}function a(_,y,b,w,C,k,O){return i(b^(y|~w),_,y,C,k,O)}const l=s.length,h=new Uint8Array(Math.ceil((l+9)/64)*64);h.set(s),h[l]=128;const d=new DataView(h.buffer);d.setUint32(h.length-8,l<<3,!0),d.setUint32(h.length-4,l/536870912|0,!0);let u=1732584193,f=4023233417,m=2562383102,g=271733878;for(let _=0;_<h.length>>2;_+=16){const y=O=>d.getInt32((_+O)*4,!0),[b,w,C,k]=[u,f,m,g];u=n(u,f,m,g,y(0),7,-680876936),g=n(g,u,f,m,y(1),12,-389564586),m=n(m,g,u,f,y(2),17,606105819),f=n(f,m,g,u,y(3),22,-1044525330),u=n(u,f,m,g,y(4),7,-176418897),g=n(g,u,f,m,y(5),12,1200080426),m=n(m,g,u,f,y(6),17,-1473231341),f=n(f,m,g,u,y(7),22,-45705983),u=n(u,f,m,g,y(8),7,1770035416),g=n(g,u,f,m,y(9),12,-1958414417),m=n(m,g,u,f,y(10),17,-42063),f=n(f,m,g,u,y(11),22,-1990404162),u=n(u,f,m,g,y(12),7,1804603682),g=n(g,u,f,m,y(13),12,-40341101),m=n(m,g,u,f,y(14),17,-1502002290),f=n(f,m,g,u,y(15),22,1236535329),u=o(u,f,m,g,y(1),5,-165796510),g=o(g,u,f,m,y(6),9,-1069501632),m=o(m,g,u,f,y(11),14,643717713),f=o(f,m,g,u,y(0),20,-373897302),u=o(u,f,m,g,y(5),5,-701558691),g=o(g,u,f,m,y(10),9,38016083),m=o(m,g,u,f,y(15),14,-660478335),f=o(f,m,g,u,y(4),20,-405537848),u=o(u,f,m,g,y(9),5,568446438),g=o(g,u,f,m,y(14),9,-1019803690),m=o(m,g,u,f,y(3),14,-187363961),f=o(f,m,g,u,y(8),20,1163531501),u=o(u,f,m,g,y(13),5,-1444681467),g=o(g,u,f,m,y(2),9,-51403784),m=o(m,g,u,f,y(7),14,1735328473),f=o(f,m,g,u,y(12),20,-1926607734),u=r(u,f,m,g,y(5),4,-378558),g=r(g,u,f,m,y(8),11,-2022574463),m=r(m,g,u,f,y(11),16,1839030562),f=r(f,m,g,u,y(14),23,-35309556),u=r(u,f,m,g,y(1),4,-1530992060),g=r(g,u,f,m,y(4),11,1272893353),m=r(m,g,u,f,y(7),16,-155497632),f=r(f,m,g,u,y(10),23,-1094730640),u=r(u,f,m,g,y(13),4,681279174),g=r(g,u,f,m,y(0),11,-358537222),m=r(m,g,u,f,y(3),16,-722521979),f=r(f,m,g,u,y(6),23,76029189),u=r(u,f,m,g,y(9),4,-640364487),g=r(g,u,f,m,y(12),11,-421815835),m=r(m,g,u,f,y(15),16,530742520),f=r(f,m,g,u,y(2),23,-995338651),u=a(u,f,m,g,y(0),6,-198630844),g=a(g,u,f,m,y(7),10,1126891415),m=a(m,g,u,f,y(14),15,-1416354905),f=a(f,m,g,u,y(5),21,-57434055),u=a(u,f,m,g,y(12),6,1700485571),g=a(g,u,f,m,y(3),10,-1894986606),m=a(m,g,u,f,y(10),15,-1051523),f=a(f,m,g,u,y(1),21,-2054922799),u=a(u,f,m,g,y(8),6,1873313359),g=a(g,u,f,m,y(15),10,-30611744),m=a(m,g,u,f,y(6),15,-1560198380),f=a(f,m,g,u,y(13),21,1309151649),u=a(u,f,m,g,y(4),6,-145523070),g=a(g,u,f,m,y(11),10,-1120210379),m=a(m,g,u,f,y(2),15,718787259),f=a(f,m,g,u,y(9),21,-343485551),u=e(u,b),f=e(f,w),m=e(m,C),g=e(g,k)}const v=new DataView(new ArrayBuffer(16));return v.setUint32(0,u,!0),v.setUint32(4,f,!0),v.setUint32(8,m,!0),v.setUint32(12,g,!0),Array.from(new Uint8Array(v.buffer))}function dM(s){return vx(s).map(e=>e.toString(16).padStart(2,"0")).join("")}function uM(s){return vx(s)}function fM(s){return crypto.subtle.digest("SHA-256",new Uint8Array(s)).then(e=>btoa(String.fromCharCode(...new Uint8Array(e))))}exports.BlobStorage=void 0;(s=>{s.baseUrl="https://networking.needle.tools";function i(d){return dM(new Uint8Array(d))}s.hashMD5=i;function n(d){const u=uM(new Uint8Array(d));return btoa(String.fromCharCode(...u))}s.hashMD5_Base64=n;function o(d){return fM(d)}s.hashSha256=o;function r(d){const u=d.filesize/1024/1024;return Yi()?u<50:u<5}s.canUpload=r;async function a(d,u){const f=s.baseUrl;if(f){if(!d.name)return console.error("Upload: file name is missing"),null}else return console.error("Blob storage base url is not set"),null;let m=null;d instanceof File?m=await d.arrayBuffer():m=d.data;const g=m.byteLength,v=g/1024/1024;if(v>50)return u?.silent!==!0&&de(`File (${v.toFixed(1)}MB) is too large for uploading (see console for details)`),console.warn(`Your file is too large for uploading (${v.toFixed(1)}MB). Max allowed size is 50MB`),null;if(!Yi()&&v>5)return u?.silent!==!0&&de('File is too large for uploading. Please get a <a href="https://needle.tools/pricing" target="_blank">commercial license</a> to upload files larger than 5MB'),console.warn(`Your file is too large for uploading (${v.toFixed(1)}MB). Max size is 5MB for non-commercial users. Please get a commercial license at https://needle.tools/pricing for larger files (up to 50MB)`),null;if(g<1)return console.warn(`Your file is too small for uploading (${v.toFixed(1)}MB). Min size is 1 byte`),null;const _=n(m),y={filename:d.name,"Content-Md5":_,"Content-Type":d.type||"application/octet-stream",FileSize:g.toString(),"Content-Disposition":`attachment; filename="${d.name}"`,"x-amz-server-side-encryption":"AES256"},b=await fetch(f+"/api/needle/blob",{method:"POST",headers:y,signal:u?.abort}).then(w=>w.json()).catch(w=>(console.error(w),null));if(b==null)return console.warn("Upload failed..."),null;if("error"in b)return console.error(b.error),null;if("upload"in b&&b.upload){let w=function(O){return u?.onProgress?.call(null,{progress01:0,state:"inprogress"}),fetch(O,{method:"PUT",headers:y,body:m,signal:u?.abort}).then(I=>(u?.onProgress?.call(null,{progress01:1,state:"finished"}),I)).catch(I=>I)};console.debug("Uploading file",b.upload);let C=!1,k=null;for(let O=0;O<3;O++)try{if(C)break;if(u?.abort?.aborted)return console.debug("Aborted upload"),null;const D=await w(b.upload);D instanceof Error?(k=D,await Ds(1e3*O)):D.ok&&(console.debug("File uploaded successfully"),C=!0)}catch(D){console.error(D)}if(!C)return console.error(k?.message||"Failed to upload file"),null}if("download"in b){const w=f+b.download;return console.debug("File found in blob storage",w),{key:b.key,success:!0,download_url:w}}return null}s.upload=a;function l(d){return`${s.baseUrl}/api/needle/blob/${d}`}s.getBlobUrlForKey=l;async function h(d,u){const f=new c.FileLoader;f.setResponseType("arraybuffer");const m=await f.loadAsync(d,g=>{u&&u.call(null,g)});return m instanceof ArrayBuffer?new Uint8Array(m):(console.error("Download failed, no arraybuffer returned"),null)}s.download=h})(exports.BlobStorage||(exports.BlobStorage={}));var yn=(s=>(s[s.OnConnection=0]="OnConnection",s[s.OnRoomJoin=1]="OnRoomJoin",s[s.Queued=2]="Queued",s[s.Immediate=3]="Immediate",s))(yn||{});const nc={},ll={register(s,e){nc[s]=e},unregister(s){delete nc[s]},list(){return Object.keys(nc)},has(s){return s in nc},async resolve(s){const e=nc[s];return e?e(s):null}};se.registerCallback(ae.ContextCreated,s=>{const e=s.context;kx(e),xx(e)});const Yu=x("debugcomponents"),gv="eff8ba80-635d-11ec-90d6-0242ac120003";class ot{get seed(){return this._seed}set seed(e){this._seed=e}_originalSeed;_seed;constructor(e){typeof e=="string"&&(e=ot.hash(e)),this._originalSeed=e,this._seed=e}reset(){this._seed=this._originalSeed}generateUUID(e){if(typeof e=="string")return ee.v5(e,gv);const t=this._seed;return this._seed-=1,ee.v5(t.toString(),gv)}initialize(e){typeof e=="string"?this._seed=ot.hash(e):this._seed=e}static createFromString(e){return new ot(this.hash(e))}static hash(e){let t=0;for(let i=0;i<e.length;i++)t=e.charCodeAt(i)+((t<<5)-t);return t}}var wx=(s=>(s.NewInstanceCreated="new-instance-created",s.InstanceDestroyed="instance-destroyed",s))(wx||{});class pM{guid;dontSave;constructor(e){this.guid=e}}function Mh(s,e,t=!0,i){if(!s)return;const n=s;if(fi(s,t),!e){console.warn("Can not send destroy: No networking connection provided",s.guid);return}if(!e.isConnected){E()&&console.debug("Can not send destroy: not connected",s.guid);return}let o=s.guid;if(!o&&n.uuid&&(o=n.uuid),!o){console.warn("Can not send destroy: failed to find guid",s);return}$y(o,e,i)}function $y(s,e,t){const i=new pM(s);t?.saveInRoom===!1&&(i.dontSave=!0),e.send("instance-destroyed",i,yn.Queued)}const bu=[];function mM(s){return bu.push(s),()=>{const e=bu.indexOf(s);e>=0&&bu.splice(e,1)}}function xx(s){s.connection.beginListen("instance-destroyed",e=>{Yu&&console.log("[Remote] Destroyed",s.scene,e);const t=l_(e.guid,s.scene);if(t){for(const i of bu)try{i(e.guid,t)}catch(n){console.error("Error in onSyncDestroy callback",n)}fi(t)}})}class gM{filename;hash;size;constructor(e,t,i){this.filename=e,this.hash=t,this.size=i}}class Sx{guid;originalGuid;seed;visible;hostData;dontSave;parent;position;rotation;scale;preventCreation=void 0;deleteStateOnDisconnect;constructor(e,t){this.originalGuid=e,this.guid=t}}const vu=[];function Cx(s){return vu.push(s),()=>{const e=vu.indexOf(s);e>=0&&vu.splice(e,1)}}function Vy(s,e,t,i){const n=s;if(!n.guid)if(n.name)n.guid=n.name;else return console.error("[syncInstantiate] Can not instantiate: a 'guid' is required. For runtime-created objects, either set a name (`obj.name = 'my-prefab'`) or a guid (`obj.guid = 'my-prefab-id'`). The identifier must be the same on all clients.",n),null;if(ll.has(n.guid)||ll.register(n.guid,async()=>n),e.context||(e.context=X.Current),!e.context)return console.error("[syncInstantiate] Missing network instantiate options / reference to network connection in sync instantiate. Please pass in the Needle Engine context."),null;const o=e?{...e}:null,{instance:r,seed:a}=yM(n,e);if(r){const l=r;if(l.guid){Yu&&console.log("[Local] new instance","gameobject:",r?.guid);const h=new Sx(n.guid,l.guid);h.seed=a,e.deleteOnDisconnect===!0&&(h.deleteStateOnDisconnect=!0),o&&(o.position&&(Array.isArray(o.position)?h.position={x:o.position[0],y:o.position[1],z:o.position[2]}:h.position={x:o.position.x,y:o.position.y,z:o.position.z}),o.rotation&&(o.rotation instanceof c.Euler?o.rotation=new c.Quaternion().setFromEuler(o.rotation):o.rotation instanceof Array&&(o.rotation=new c.Quaternion().fromArray(o.rotation)),h.rotation={x:o.rotation.x,y:o.rotation.y,z:o.rotation.z,w:o.rotation.w}),o.scale&&(Array.isArray(o.scale)?h.scale={x:o.scale[0],y:o.scale[1],z:o.scale[2]}:h.scale={x:o.scale.x,y:o.scale.y,z:o.scale.z})),h.position||(h.position={x:l.position.x,y:l.position.y,z:l.position.z}),h.rotation||(h.rotation={x:l.quaternion.x,y:l.quaternion.y,z:l.quaternion.z,w:l.quaternion.w}),h.scale||(h.scale={x:l.scale.x,y:l.scale.y,z:l.scale.z}),h.visible=n.visible,o?.parent&&(typeof o.parent=="string"?h.parent=o.parent:o.parent?.guid?h.parent=o.parent.guid:o.parent instanceof c.Scene?h.parent="scene":console.warn("Unsupported parent type in sync instantiate options: "+o.parent?.name)),h.hostData=t,i===!1&&(h.dontSave=!0),!e?.context?.connection&&E()&&console.debug("Object will be instantiated but it will not be synced: not connected",n.guid),e.context.connection.isInRoom&&Ma.push(new WeakRef(l)),e?.context?.connection.send("new-instance-created",h)}else console.warn("Missing guid, can not send new instance event",l)}return r}function Px(){return Math.random()*9999999}const Ma=new Array;function kx(s){const e=s.connection.beginListen("new-instance-created",async i=>{const n=await bM(i.originalGuid,s.scene);if(i.preventCreation===!0)return;if(!n){console.warn("could not find object that was instantiated: "+i.guid);return}const o=new hs;i.position&&(o.position=new c.Vector3(i.position.x,i.position.y,i.position.z)),i.rotation&&(o.rotation=new c.Quaternion(i.rotation.x,i.rotation.y,i.rotation.z,i.rotation.w)),i.scale&&(o.scale=new c.Vector3(i.scale.x,i.scale.y,i.scale.z)),o.parent=i.parent,i.seed&&(o.idProvider=new ot(i.seed)),o.visible=i.visible,o.context=s,Yu&&s.alias&&console.log("[Remote] instantiate in: "+s.alias);const r=Ls(n,o);if(Ma.push(new WeakRef(r)),r){i.parent==="scene"&&s.scene.add(r),Yu&&console.log("[Remote] new instance","gameobject:",r?.guid,n);for(const a of vu)try{a(r,i,s)}catch(l){console.error("Error in onSyncInstantiate callback",l)}}}),t=s.connection.beginListen("left-room",()=>{Ma.length>0&&console.debug(`Left networking room, cleaning up ${Ma.length} instantiated objects`);for(const i of Ma){const n=i.deref();n&&n.destroy()}Ma.length=0});return()=>{e(),t()}}function yM(s,e){const t=Px(),i=e??new hs;i.idProvider=new ot(t);const n=Ls(s,i);return{seed:t,instance:n}}function Mx(s,e){ll.register(s,e)}function _M(s){ll.unregister(s)}async function bM(s,e){const t=await ll.resolve(s);return t||Ox(s,e)}function Ox(s,e){if(e===null||!s)return null;if(e.guid===s)return e;if(e.children)for(const t of e.children){const i=Ox(s,t);if(i)return i}return null}const Oh=x("gizmos"),_t=x("debugextension"),Wy=x("debugresolvedependencies"),vM=["/extensions/","extensions/"],wM=[{prefix:"/nodes/",dependencyName:"node"},{prefix:"/meshes/",dependencyName:"mesh"},{prefix:"/materials/",dependencyName:"material"},{prefix:"/textures/",dependencyName:"texture"},{prefix:"/animations/",dependencyName:"animation"},{prefix:"nodes/",dependencyName:"node"},{prefix:"meshes/",dependencyName:"mesh"},{prefix:"materials/",dependencyName:"material"},{prefix:"textures/",dependencyName:"texture"},{prefix:"animations/",dependencyName:"animation"}];async function Gy(s,e){Wy&&console.log(s,e);const t=[];Cg(wM,s,e,t);const i=await Promise.all(t);return typeof e=="string"&&i.length===1?i[0]:i}function Ex(s,e){return!s||!e?!1:s["needle:identifier"]!=null&&e["needle:identifier"]!=null?s["needle:identifier"]===e["needle:identifier"]:!1}function xM(s,e){s["needle:identifier"]=e}function Cg(s,e,t,i){if(typeof t=="object"&&t!==void 0&&t!==null)for(const n of Object.keys(t)){const o=t[n];if(typeof o=="string"){const r=yv(e,o);if(r!=null)typeof r.then=="function"?i.push(r.then(a=>t[n]=a)):t[n]=r;else{const a=_v(s,e,o);if(a){i.push(a.then(l=>(t[n]=l,l)));continue}}}else if(Array.isArray(o))for(let r=0;r<o.length;r++){const a=o[r],l=yv(e,a);if(l!=null){typeof l.then=="function"?i.push(l.then(h=>o[r]=h)):o[r]=l;continue}for(const h of s){const d=Rx(h.prefix,a);if(d>=0){Wy&&console.log(h,d,h.dependencyName),i.push(e.getDependency(h.dependencyName,d).then(u=>o[r]=u));break}}typeof a=="object"&&Cg(s,e,a,i)}else typeof o=="object"&&Cg(s,e,o,i)}else if(typeof t=="string"){const n=_v(s,e,t);n&&i.push(n)}}function yv(s,e){if(s&&s.plugins&&typeof e=="string"){for(const t of vM)if(e.startsWith(t)){let i=e.substring(t.length);const n=i.indexOf("/");n>=0&&(i=i.substring(0,n));const o=s.plugins[i];if(_t&&console.log(i,o),typeof o?.resolve=="function"){const r=e.substring(t.length+i.length+1);return o.resolve(s,r)}break}}return null}function _v(s,e,t){for(const i of s){const n=Rx(i.prefix,t);if(n>=0)return Wy&&console.warn("GET DEPENDENCY",i,n,i.dependencyName),e.getDependency(i.dependencyName,n)}return null}function Rx(s,e){if(typeof e=="string"&&e.startsWith(s)){const t=e.substring(s.length),i=Number.parseInt(t);if(i>=0)return i}return-1}const em="NEEDLE_persistent_assets";function SM(s){return s?.___persistentAsset===!0}class CM{get name(){return em}parser;constructor(e){this.parser=e}async afterRoot(e){if(!this.parser?.json?.extensions)return;const t=this.parser.json.extensions[em];if(!t)return;_t&&console.log(t);const i=new Array;for(const n of t?.assets){const o=Gy(this.parser,n);o&&i.push(o)}await Promise.all(i)}resolve(e,t){const i=Number.parseInt(t);if(i>=0){_t&&console.log(t);const n=e.json.extensions[em];if(n){const o=n?.assets[i];if(o&&typeof o=="object"){o.___persistentAsset=!0;const r=o.__type;r&&M.get(r)}return o}}return null}}const Nn=x("debugserializer");class PM{register(e,t){if(this.typeMap.has(e)){const i=this.typeMap.get(e);if(i===t)return;Nn&&console.warn("Type: "+e+" is already registered",t,i)}Nn&&console.log("Register type serializer",t.name,t,e),this.typeMap.set(e,t)}typeMap=new Map;getSerializer(e){if(e)return this.typeMap.get(e)}getSerializerForConstructor(e,t=0){if(t>20)return;if(!e||!e.constructor){Nn&&console.log("invalid type");return}const i=e.name,n=this.getSerializer(e);if(n!==void 0)return Nn&&console.log("FOUND SERIALIZER",n?.name,e.name,e.constructor.name,"for type: "+i,n,e,this.typeMap),n;const o=Object.getPrototypeOf(e);if(o&&o!==e){const r=this.getSerializerForConstructor(o,++t);if(r){const a=o.constructor||o.prototype;Nn&&console.log("FOUND SERIALIZER(in constructor) "+a.constructor.name,a.name,a,r),this.register(a,r)}if(r)return r}if(t===0&&typeof i=="string"&&i.length>0){for(const[r,a]of this.typeMap)if(r.name===i)return this.register(e,a),a}Nn&&console.warn("No serializer found for "+i,e,e.name,e.constructor.name)}}const Ku=new PM;class Ai{name;constructor(e,t){if(this.name=t,Array.isArray(e))for(const i of e)Ku.register(i,this);else Ku.register(e,this)}}class Tx{isDevMode=ki();cache={};registerDefinedKeys(e,t){if(this.isDevMode&&this.cache[e]===void 0){this.cache[e]=Object.keys(t);const i=t;i.$serializedTypes&&Object.keys(i.$serializedTypes)&&this.cache[e].push(...Object.keys(i.$serializedTypes)),Nn&&console.log("registerDefinedKeys for "+e,this.cache[e],t)}}getDefinedKey(e,t){return this.cache[e]===void 0?!1:this.cache[e].includes(t)}}class Eh{root;gltf;gltfId;object;target;nodeId;nodeToObject;objectToNode;context;path;type;serializable;implementationInformation;objectToDocumentReference;constructor(e){this.root=e}}function kM(s){return s&&typeof s=="object"&&(typeof s.$serializedTypes=="object"||typeof s.onBeforeDeserialize=="function"||typeof s.onBeforeDeserializeMember=="function"||typeof s.onAfterDeserializeMember=="function"||typeof s.onAfterDeserialize=="function")}function Ax(s,e){const t=s.$serializedTypes;if(t===void 0)return null;const i={};for(const o in t){const r=s[o];if(r!=null&&typeof r=="object"){const a=Ku.getSerializerForConstructor(r.constructor);if(a){i[o]=a.onSerialize(r,e);continue}}if(typeof r=="number"&&!Number.isFinite(r)){i[o]=String(r);continue}i[o]=r}function n(o){return M.getKey(s.constructor)||o.__name||o.constructor.name}return i.name=n(s),typeof s.guid=="string"&&(i.guid=s.guid),s.enabled===!1&&(i.enabled=!1),i}const wu=[];function Dx(s,e){if(!s)return e;typeof s.$serializedTypes=="object"&&(e||(e={}),Object.assign(e,s.$serializedTypes));const t=Object.getPrototypeOf(s);return Dx(t,e)}function Jc(s,e,t){if(!s)return!1;if(t.target=s,s.onBeforeDeserialize!==void 0){const n=s.onBeforeDeserialize(e,t);if(typeof n=="boolean")return n}const i=Dx(s);if(e){if(typeof e.guid=="string"&&(s.guid=e.guid),i)for(const n in i){let o=function(l){const d=l.type;return d?Pg(a,d,t,void 0,s[n]):Pg(a,l,t,void 0,s[n])};const r=i[n],a=e[n];if(Nn&&console.log(n,a,s,r),!(s[n]!==void 0&&a===void 0)){{const l=Ix(a,s[n]);if(l!==a){s[n]=l;continue}}if(t.type=void 0,t.path=n,t.serializable=r,!(s.onBeforeDeserializeMember!==void 0&&s.onBeforeDeserializeMember(n,a,t)===!0)){if(r===null)s[n]=a;else{if(Array.isArray(r))for(let l=0;l<r.length;l++){const h=r[l],d=o(h);if(d!==void 0||l===r.length-1){s[n]=d;break}}else s[n]=o(r);wu.length=0}s.onAfterDeserializeMember!==void 0&&s.onAfterDeserializeMember(n,a,t)}}}EM(s,e)}return OM(s,e,t.implementationInformation),s.onAfterDeserialize!==void 0&&s.onAfterDeserialize(e,t),!0}const MM=x("noerrors");function OM(s,e,t){if(MM||!e||!ki()||!s||s.constructor&&s.constructor[Nk]===!0)return;const i=s.constructor?.name,n=Object.getOwnPropertyNames(e);for(const o of n){if(o==="sourceId")continue;const r=s[o];if(r==null)continue;const a=e[o];if(t?.getDefinedKey(i,o)===!1){const l=o.charAt(0).toUpperCase()+o.slice(1);t.getDefinedKey(i,l)&&(fr(Ci.Warn,'<strong>Please rename</strong> "'+l+'" to "'+o+'" in '+i),console.warn('Please use lowercase for field: "'+l+'" in '+i,a,s));continue}if(a!=null){if(typeof a=="object"&&(r===void 0||!r.isObject3D)){if(typeof a.node=="number"||typeof a.guid=="string"){if(a.could_not_resolve)continue;if(!(r!==void 0&&Object.keys(r).length>1)){fr(Ci.Warn,`<strong>Missing serialization for object reference!</strong>
232
+ `,n=`Needle Engine — No license active, commercial use is not allowed. Visit https://needle.tools/pricing for more information and licensing options! v${Zt}`;X.Current?.xr||navigator.webdriver?console.log(n):console.log("%c "+n,t)}async function hM(s){if(!st.isAllowed(s)){be&&console.debug("Telemetry is disabled");return}try{const e="https://needle.tools/api/v1/needle-engine/ping";if(e){const t=window.location.href.split("?")[0],n={license:Pi,url:t,hostname:window.location.hostname,pathname:window.location.pathname,version:Zt,generator:al,build_time:Zc,public_key:wo},o=navigator.sendBeacon?.(e,JSON.stringify(n));be&&console.debug("Sent beacon: "+o)}}catch(e){be&&console.log("Failed to send non-commercial usage message to analytics backend",e)}}function vx(s){function e(_,y){const b=(_&65535)+(y&65535);return(_>>16)+(y>>16)+(b>>16)<<16|b&65535}function t(_,y){return _<<y|_>>>32-y}function i(_,y,b,w,C,k){return e(t(e(e(y,_),e(w,k)),C),b)}function n(_,y,b,w,C,k,O){return i(y&b|~y&w,_,y,C,k,O)}function o(_,y,b,w,C,k,O){return i(y&w|b&~w,_,y,C,k,O)}function r(_,y,b,w,C,k,O){return i(y^b^w,_,y,C,k,O)}function a(_,y,b,w,C,k,O){return i(b^(y|~w),_,y,C,k,O)}const l=s.length,h=new Uint8Array(Math.ceil((l+9)/64)*64);h.set(s),h[l]=128;const d=new DataView(h.buffer);d.setUint32(h.length-8,l<<3,!0),d.setUint32(h.length-4,l/536870912|0,!0);let u=1732584193,f=4023233417,m=2562383102,g=271733878;for(let _=0;_<h.length>>2;_+=16){const y=O=>d.getInt32((_+O)*4,!0),[b,w,C,k]=[u,f,m,g];u=n(u,f,m,g,y(0),7,-680876936),g=n(g,u,f,m,y(1),12,-389564586),m=n(m,g,u,f,y(2),17,606105819),f=n(f,m,g,u,y(3),22,-1044525330),u=n(u,f,m,g,y(4),7,-176418897),g=n(g,u,f,m,y(5),12,1200080426),m=n(m,g,u,f,y(6),17,-1473231341),f=n(f,m,g,u,y(7),22,-45705983),u=n(u,f,m,g,y(8),7,1770035416),g=n(g,u,f,m,y(9),12,-1958414417),m=n(m,g,u,f,y(10),17,-42063),f=n(f,m,g,u,y(11),22,-1990404162),u=n(u,f,m,g,y(12),7,1804603682),g=n(g,u,f,m,y(13),12,-40341101),m=n(m,g,u,f,y(14),17,-1502002290),f=n(f,m,g,u,y(15),22,1236535329),u=o(u,f,m,g,y(1),5,-165796510),g=o(g,u,f,m,y(6),9,-1069501632),m=o(m,g,u,f,y(11),14,643717713),f=o(f,m,g,u,y(0),20,-373897302),u=o(u,f,m,g,y(5),5,-701558691),g=o(g,u,f,m,y(10),9,38016083),m=o(m,g,u,f,y(15),14,-660478335),f=o(f,m,g,u,y(4),20,-405537848),u=o(u,f,m,g,y(9),5,568446438),g=o(g,u,f,m,y(14),9,-1019803690),m=o(m,g,u,f,y(3),14,-187363961),f=o(f,m,g,u,y(8),20,1163531501),u=o(u,f,m,g,y(13),5,-1444681467),g=o(g,u,f,m,y(2),9,-51403784),m=o(m,g,u,f,y(7),14,1735328473),f=o(f,m,g,u,y(12),20,-1926607734),u=r(u,f,m,g,y(5),4,-378558),g=r(g,u,f,m,y(8),11,-2022574463),m=r(m,g,u,f,y(11),16,1839030562),f=r(f,m,g,u,y(14),23,-35309556),u=r(u,f,m,g,y(1),4,-1530992060),g=r(g,u,f,m,y(4),11,1272893353),m=r(m,g,u,f,y(7),16,-155497632),f=r(f,m,g,u,y(10),23,-1094730640),u=r(u,f,m,g,y(13),4,681279174),g=r(g,u,f,m,y(0),11,-358537222),m=r(m,g,u,f,y(3),16,-722521979),f=r(f,m,g,u,y(6),23,76029189),u=r(u,f,m,g,y(9),4,-640364487),g=r(g,u,f,m,y(12),11,-421815835),m=r(m,g,u,f,y(15),16,530742520),f=r(f,m,g,u,y(2),23,-995338651),u=a(u,f,m,g,y(0),6,-198630844),g=a(g,u,f,m,y(7),10,1126891415),m=a(m,g,u,f,y(14),15,-1416354905),f=a(f,m,g,u,y(5),21,-57434055),u=a(u,f,m,g,y(12),6,1700485571),g=a(g,u,f,m,y(3),10,-1894986606),m=a(m,g,u,f,y(10),15,-1051523),f=a(f,m,g,u,y(1),21,-2054922799),u=a(u,f,m,g,y(8),6,1873313359),g=a(g,u,f,m,y(15),10,-30611744),m=a(m,g,u,f,y(6),15,-1560198380),f=a(f,m,g,u,y(13),21,1309151649),u=a(u,f,m,g,y(4),6,-145523070),g=a(g,u,f,m,y(11),10,-1120210379),m=a(m,g,u,f,y(2),15,718787259),f=a(f,m,g,u,y(9),21,-343485551),u=e(u,b),f=e(f,w),m=e(m,C),g=e(g,k)}const v=new DataView(new ArrayBuffer(16));return v.setUint32(0,u,!0),v.setUint32(4,f,!0),v.setUint32(8,m,!0),v.setUint32(12,g,!0),Array.from(new Uint8Array(v.buffer))}function dM(s){return vx(s).map(e=>e.toString(16).padStart(2,"0")).join("")}function uM(s){return vx(s)}function fM(s){return crypto.subtle.digest("SHA-256",new Uint8Array(s)).then(e=>btoa(String.fromCharCode(...new Uint8Array(e))))}exports.BlobStorage=void 0;(s=>{s.baseUrl="https://networking.needle.tools";function i(d){return dM(new Uint8Array(d))}s.hashMD5=i;function n(d){const u=uM(new Uint8Array(d));return btoa(String.fromCharCode(...u))}s.hashMD5_Base64=n;function o(d){return fM(d)}s.hashSha256=o;function r(d){const u=d.filesize/1024/1024;return Yi()?u<50:u<5}s.canUpload=r;async function a(d,u){const f=s.baseUrl;if(f){if(!d.name)return console.error("Upload: file name is missing"),null}else return console.error("Blob storage base url is not set"),null;let m=null;d instanceof File?m=await d.arrayBuffer():m=d.data;const g=m.byteLength,v=g/1024/1024;if(v>50)return u?.silent!==!0&&de(`File (${v.toFixed(1)}MB) is too large for uploading (see console for details)`),console.warn(`Your file is too large for uploading (${v.toFixed(1)}MB). Max allowed size is 50MB`),null;if(!Yi()&&v>5)return u?.silent!==!0&&de('File is too large for uploading. Please get a <a href="https://needle.tools/pricing" target="_blank">commercial license</a> to upload files larger than 5MB'),console.warn(`Your file is too large for uploading (${v.toFixed(1)}MB). Max size is 5MB for non-commercial users. Please get a commercial license at https://needle.tools/pricing for larger files (up to 50MB)`),null;if(g<1)return console.warn(`Your file is too small for uploading (${v.toFixed(1)}MB). Min size is 1 byte`),null;const _=n(m),y={filename:d.name,"Content-Md5":_,"Content-Type":d.type||"application/octet-stream",FileSize:g.toString(),"Content-Disposition":`attachment; filename="${d.name}"`,"x-amz-server-side-encryption":"AES256"},b=await fetch(f+"/api/needle/blob",{method:"POST",headers:y,signal:u?.abort}).then(w=>w.json()).catch(w=>(console.error(w),null));if(b==null)return console.warn("Upload failed..."),null;if("error"in b)return console.error(b.error),null;if("upload"in b&&b.upload){let w=function(O){return u?.onProgress?.call(null,{progress01:0,state:"inprogress"}),fetch(O,{method:"PUT",headers:y,body:m,signal:u?.abort}).then(I=>(u?.onProgress?.call(null,{progress01:1,state:"finished"}),I)).catch(I=>I)};console.debug("Uploading file",b.upload);let C=!1,k=null;for(let O=0;O<3;O++)try{if(C)break;if(u?.abort?.aborted)return console.debug("Aborted upload"),null;const D=await w(b.upload);D instanceof Error?(k=D,await Ds(1e3*O)):D.ok&&(console.debug("File uploaded successfully"),C=!0)}catch(D){console.error(D)}if(!C)return console.error(k?.message||"Failed to upload file"),null}if("download"in b){const w=f+b.download;return console.debug("File found in blob storage",w),{key:b.key,success:!0,download_url:w}}return null}s.upload=a;function l(d){return`${s.baseUrl}/api/needle/blob/${d}`}s.getBlobUrlForKey=l;async function h(d,u){const f=new c.FileLoader;f.setResponseType("arraybuffer");const m=await f.loadAsync(d,g=>{u&&u.call(null,g)});return m instanceof ArrayBuffer?new Uint8Array(m):(console.error("Download failed, no arraybuffer returned"),null)}s.download=h})(exports.BlobStorage||(exports.BlobStorage={}));var yn=(s=>(s[s.OnConnection=0]="OnConnection",s[s.OnRoomJoin=1]="OnRoomJoin",s[s.Queued=2]="Queued",s[s.Immediate=3]="Immediate",s))(yn||{});const nc={},ll={register(s,e){nc[s]=e},unregister(s){delete nc[s]},list(){return Object.keys(nc)},has(s){return s in nc},async resolve(s){const e=nc[s];return e?e(s):null}};se.registerCallback(ae.ContextCreated,s=>{const e=s.context;kx(e),xx(e)});const Yu=x("debugcomponents"),gv="eff8ba80-635d-11ec-90d6-0242ac120003";class ot{get seed(){return this._seed}set seed(e){this._seed=e}_originalSeed;_seed;constructor(e){typeof e=="string"&&(e=ot.hash(e)),this._originalSeed=e,this._seed=e}reset(){this._seed=this._originalSeed}generateUUID(e){if(typeof e=="string")return ee.v5(e,gv);const t=this._seed;return this._seed-=1,ee.v5(t.toString(),gv)}initialize(e){typeof e=="string"?this._seed=ot.hash(e):this._seed=e}static createFromString(e){return new ot(this.hash(e))}static hash(e){let t=0;for(let i=0;i<e.length;i++)t=e.charCodeAt(i)+((t<<5)-t);return t}}var wx=(s=>(s.NewInstanceCreated="new-instance-created",s.InstanceDestroyed="instance-destroyed",s))(wx||{});class pM{guid;dontSave;constructor(e){this.guid=e}}function Mh(s,e,t=!0,i){if(!s)return;const n=s;if(fi(s,t),!e){console.warn("Can not send destroy: No networking connection provided",s.guid);return}if(!e.isConnected){E()&&console.debug("Can not send destroy: not connected",s.guid);return}let o=s.guid;if(!o&&n.uuid&&(o=n.uuid),!o){console.warn("Can not send destroy: failed to find guid",s);return}$y(o,e,i)}function $y(s,e,t){const i=new pM(s);t?.saveInRoom===!1&&(i.dontSave=!0),e.send("instance-destroyed",i,yn.Queued)}const bu=[];function mM(s){return bu.push(s),()=>{const e=bu.indexOf(s);e>=0&&bu.splice(e,1)}}function xx(s){s.connection.beginListen("instance-destroyed",e=>{Yu&&console.log("[Remote] Destroyed",s.scene,e);const t=l_(e.guid,s.scene);if(t){for(const i of bu)try{i(e.guid,t)}catch(n){console.error("Error in onSyncDestroy callback",n)}fi(t)}})}class gM{filename;hash;size;constructor(e,t,i){this.filename=e,this.hash=t,this.size=i}}class Sx{guid;originalGuid;seed;visible;hostData;dontSave;parent;position;rotation;scale;preventCreation=void 0;deleteStateOnDisconnect;constructor(e,t){this.originalGuid=e,this.guid=t}}const vu=[];function Cx(s){return vu.push(s),()=>{const e=vu.indexOf(s);e>=0&&vu.splice(e,1)}}function Vy(s,e,t,i){const n=s;if(!n.guid)if(n.name)n.guid=n.name;else return console.error("[syncInstantiate] Can not instantiate: a 'guid' is required. For runtime-created objects, either set a name (`obj.name = 'my-prefab'`) or a guid (`obj.guid = 'my-prefab-id'`). The identifier must be the same on all clients.",n),null;if(ll.has(n.guid)||ll.register(n.guid,async()=>n),e.context||(e.context=X.Current),!e.context)return console.error("[syncInstantiate] Missing network instantiate options / reference to network connection in sync instantiate. Please pass in the Needle Engine context."),null;const o=e?{...e}:null,{instance:r,seed:a}=yM(n,e);if(r){const l=r;if(l.guid){Yu&&console.log("[Local] new instance","gameobject:",r?.guid);const h=new Sx(n.guid,l.guid);h.seed=a,e.deleteOnDisconnect===!0&&(h.deleteStateOnDisconnect=!0),o&&(o.position&&(Array.isArray(o.position)?h.position={x:o.position[0],y:o.position[1],z:o.position[2]}:h.position={x:o.position.x,y:o.position.y,z:o.position.z}),o.rotation&&(o.rotation instanceof c.Euler?o.rotation=new c.Quaternion().setFromEuler(o.rotation):o.rotation instanceof Array&&(o.rotation=new c.Quaternion().fromArray(o.rotation)),h.rotation={x:o.rotation.x,y:o.rotation.y,z:o.rotation.z,w:o.rotation.w}),o.scale&&(Array.isArray(o.scale)?h.scale={x:o.scale[0],y:o.scale[1],z:o.scale[2]}:h.scale={x:o.scale.x,y:o.scale.y,z:o.scale.z})),h.position||(h.position={x:l.position.x,y:l.position.y,z:l.position.z}),h.rotation||(h.rotation={x:l.quaternion.x,y:l.quaternion.y,z:l.quaternion.z,w:l.quaternion.w}),h.scale||(h.scale={x:l.scale.x,y:l.scale.y,z:l.scale.z}),h.visible=n.visible,o?.parent&&(typeof o.parent=="string"?h.parent=o.parent:o.parent?.guid?h.parent=o.parent.guid:o.parent instanceof c.Scene?h.parent="scene":console.warn("Unsupported parent type in sync instantiate options: "+o.parent?.name)),h.hostData=t,i===!1&&(h.dontSave=!0),!e?.context?.connection&&E()&&console.debug("Object will be instantiated but it will not be synced: not connected",n.guid),e.context.connection.isInRoom&&Ma.push(new WeakRef(l)),e?.context?.connection.send("new-instance-created",h)}else console.warn("Missing guid, can not send new instance event",l)}return r}function Px(){return Math.random()*9999999}const Ma=new Array;function kx(s){const e=s.connection.beginListen("new-instance-created",async i=>{const n=await bM(i.originalGuid,s.scene);if(i.preventCreation===!0)return;if(!n){console.warn("could not find object that was instantiated: "+i.guid);return}const o=new hs;i.position&&(o.position=new c.Vector3(i.position.x,i.position.y,i.position.z)),i.rotation&&(o.rotation=new c.Quaternion(i.rotation.x,i.rotation.y,i.rotation.z,i.rotation.w)),i.scale&&(o.scale=new c.Vector3(i.scale.x,i.scale.y,i.scale.z)),o.parent=i.parent,i.seed&&(o.idProvider=new ot(i.seed)),o.visible=i.visible,o.context=s,Yu&&s.alias&&console.log("[Remote] instantiate in: "+s.alias);const r=Ls(n,o);if(Ma.push(new WeakRef(r)),r){i.parent==="scene"&&s.scene.add(r),Yu&&console.log("[Remote] new instance","gameobject:",r?.guid,n);for(const a of vu)try{a(r,i,s)}catch(l){console.error("Error in onSyncInstantiate callback",l)}}}),t=s.connection.beginListen("left-room",()=>{Ma.length>0&&console.debug(`Left networking room, cleaning up ${Ma.length} instantiated objects`);for(const i of Ma){const n=i.deref();n&&n.destroy()}Ma.length=0});return()=>{e(),t()}}function yM(s,e){const t=Px(),i=e??new hs;i.idProvider=new ot(t);const n=Ls(s,i);return{seed:t,instance:n}}function Mx(s,e){ll.register(s,e)}function _M(s){ll.unregister(s)}async function bM(s,e){const t=await ll.resolve(s);return t||Ox(s,e)}function Ox(s,e){if(e===null||!s)return null;if(e.guid===s)return e;if(e.children)for(const t of e.children){const i=Ox(s,t);if(i)return i}return null}const Oh=x("gizmos"),_t=x("debugextension"),Wy=x("debugresolvedependencies"),vM=["/extensions/","extensions/"],wM=[{prefix:"/nodes/",dependencyName:"node"},{prefix:"/meshes/",dependencyName:"mesh"},{prefix:"/materials/",dependencyName:"material"},{prefix:"/textures/",dependencyName:"texture"},{prefix:"/animations/",dependencyName:"animation"},{prefix:"nodes/",dependencyName:"node"},{prefix:"meshes/",dependencyName:"mesh"},{prefix:"materials/",dependencyName:"material"},{prefix:"textures/",dependencyName:"texture"},{prefix:"animations/",dependencyName:"animation"}];async function Gy(s,e){Wy&&console.log(s,e);const t=[];Cg(wM,s,e,t);const i=await Promise.all(t);return typeof e=="string"&&i.length===1?i[0]:i}function Ex(s,e){return!s||!e?!1:s["needle:identifier"]!=null&&e["needle:identifier"]!=null?s["needle:identifier"]===e["needle:identifier"]:!1}function xM(s,e){s["needle:identifier"]=e}function Cg(s,e,t,i){if(typeof t=="object"&&t!==void 0&&t!==null)for(const n of Object.keys(t)){const o=t[n];if(typeof o=="string"){const r=yv(e,o);if(r!=null)typeof r.then=="function"?i.push(r.then(a=>t[n]=a)):t[n]=r;else{const a=_v(s,e,o);if(a){i.push(a.then(l=>(t[n]=l,l)));continue}}}else if(Array.isArray(o))for(let r=0;r<o.length;r++){const a=o[r],l=yv(e,a);if(l!=null){typeof l.then=="function"?i.push(l.then(h=>o[r]=h)):o[r]=l;continue}for(const h of s){const d=Rx(h.prefix,a);if(d>=0){Wy&&console.log(h,d,h.dependencyName),i.push(e.getDependency(h.dependencyName,d).then(u=>o[r]=u));break}}typeof a=="object"&&Cg(s,e,a,i)}else typeof o=="object"&&Cg(s,e,o,i)}else if(typeof t=="string"){const n=_v(s,e,t);n&&i.push(n)}}function yv(s,e){if(s&&s.plugins&&typeof e=="string"){for(const t of vM)if(e.startsWith(t)){let i=e.substring(t.length);const n=i.indexOf("/");n>=0&&(i=i.substring(0,n));const o=s.plugins[i];if(_t&&console.log(i,o),typeof o?.resolve=="function"){const r=e.substring(t.length+i.length+1);return o.resolve(s,r)}break}}return null}function _v(s,e,t){for(const i of s){const n=Rx(i.prefix,t);if(n>=0)return Wy&&console.warn("GET DEPENDENCY",i,n,i.dependencyName),e.getDependency(i.dependencyName,n)}return null}function Rx(s,e){if(typeof e=="string"&&e.startsWith(s)){const t=e.substring(s.length),i=Number.parseInt(t);if(i>=0)return i}return-1}const em="NEEDLE_persistent_assets";function SM(s){return s?.___persistentAsset===!0}class CM{get name(){return em}parser;constructor(e){this.parser=e}async afterRoot(e){if(!this.parser?.json?.extensions)return;const t=this.parser.json.extensions[em];if(!t)return;_t&&console.log(t);const i=new Array;for(const n of t?.assets){const o=Gy(this.parser,n);o&&i.push(o)}await Promise.all(i)}resolve(e,t){const i=Number.parseInt(t);if(i>=0){_t&&console.log(t);const n=e.json.extensions[em];if(n){const o=n?.assets[i];if(o&&typeof o=="object"){o.___persistentAsset=!0;const r=o.__type;r&&M.get(r)}return o}}return null}}const Nn=x("debugserializer");class PM{register(e,t){if(this.typeMap.has(e)){const i=this.typeMap.get(e);if(i===t)return;Nn&&console.warn("Type: "+e+" is already registered",t,i)}Nn&&console.log("Register type serializer",t.name,t,e),this.typeMap.set(e,t)}typeMap=new Map;getSerializer(e){if(e)return this.typeMap.get(e)}getSerializerForConstructor(e,t=0){if(t>20)return;if(!e||!e.constructor){Nn&&console.log("invalid type");return}const i=e.name,n=this.getSerializer(e);if(n!==void 0)return Nn&&console.log("FOUND SERIALIZER",n?.name,e.name,e.constructor.name,"for type: "+i,n,e,this.typeMap),n;const o=Object.getPrototypeOf(e);if(o&&o!==e){const r=this.getSerializerForConstructor(o,++t);if(r){const a=o.constructor||o.prototype;Nn&&console.log("FOUND SERIALIZER(in constructor) "+a.constructor.name,a.name,a,r),this.register(a,r)}if(r)return r}if(t===0&&typeof i=="string"&&i.length>0){for(const[r,a]of this.typeMap)if(r.name===i)return this.register(e,a),a}Nn&&console.warn("No serializer found for "+i,e,e.name,e.constructor.name)}}const Ku=new PM;class Ai{name;constructor(e,t){if(this.name=t,Array.isArray(e))for(const i of e)Ku.register(i,this);else Ku.register(e,this)}}class Tx{isDevMode=ki();cache={};registerDefinedKeys(e,t){if(this.isDevMode&&this.cache[e]===void 0){this.cache[e]=Object.keys(t);const i=t;i.$serializedTypes&&Object.keys(i.$serializedTypes)&&this.cache[e].push(...Object.keys(i.$serializedTypes)),Nn&&console.log("registerDefinedKeys for "+e,this.cache[e],t)}}getDefinedKey(e,t){return this.cache[e]===void 0?!1:this.cache[e].includes(t)}}class Eh{root;gltf;gltfId;object;target;nodeId;nodeToObject;objectToNode;context;path;type;serializable;implementationInformation;objectToDocumentReference;constructor(e){this.root=e}}function kM(s){return s&&typeof s=="object"&&(typeof s.$serializedTypes=="object"||typeof s.onBeforeDeserialize=="function"||typeof s.onBeforeDeserializeMember=="function"||typeof s.onAfterDeserializeMember=="function"||typeof s.onAfterDeserialize=="function")}function Ax(s,e){const t=s.$serializedTypes;if(t===void 0)return null;const i={};for(const o in t){const r=s[o];if(r!=null&&typeof r=="object"){const a=Ku.getSerializerForConstructor(r.constructor);if(a){i[o]=a.onSerialize(r,e);continue}}if(typeof r=="number"&&!Number.isFinite(r)){i[o]=String(r);continue}i[o]=r}function n(o){return M.getKey(s.constructor)||o.__name||o.constructor.name}return i.name=n(s),typeof s.guid=="string"&&(i.guid=s.guid),s.enabled===!1&&(i.enabled=!1),i}const wu=[];function Dx(s,e){if(!s)return e;typeof s.$serializedTypes=="object"&&(e||(e={}),Object.assign(e,s.$serializedTypes));const t=Object.getPrototypeOf(s);return Dx(t,e)}function Jc(s,e,t){if(!s)return!1;if(t.target=s,s.onBeforeDeserialize!==void 0){const n=s.onBeforeDeserialize(e,t);if(typeof n=="boolean")return n}const i=Dx(s);if(e){if(typeof e.guid=="string"&&(s.guid=e.guid),i)for(const n in i){let o=function(l){const d=l.type;return d?Pg(a,d,t,void 0,s[n]):Pg(a,l,t,void 0,s[n])};const r=i[n],a=e[n];if(Nn&&console.log(n,a,s,r),!(s[n]!==void 0&&a===void 0)){{const l=Ix(a,s[n]);if(l!==a){s[n]=l;continue}}if(t.type=void 0,t.path=n,t.serializable=r,!(s.onBeforeDeserializeMember!==void 0&&s.onBeforeDeserializeMember(n,a,t)===!0)){if(r===null)s[n]=a;else{if(Array.isArray(r))for(let l=0;l<r.length;l++){const h=r[l],d=o(h);if(d!==void 0||l===r.length-1){s[n]=d;break}}else s[n]=o(r);wu.length=0}s.onAfterDeserializeMember!==void 0&&s.onAfterDeserializeMember(n,a,t)}}}EM(s,e)}return OM(s,e,t.implementationInformation),s.onAfterDeserialize!==void 0&&s.onAfterDeserialize(e,t),!0}const MM=x("noerrors");function OM(s,e,t){if(MM||!e||!ki()||!s||s.constructor&&s.constructor[Nk]===!0)return;const i=s.constructor?.name,n=Object.getOwnPropertyNames(e);for(const o of n){if(o==="sourceId")continue;const r=s[o];if(r==null)continue;const a=e[o];if(t?.getDefinedKey(i,o)===!1){const l=o.charAt(0).toUpperCase()+o.slice(1);t.getDefinedKey(i,l)&&(fr(Ci.Warn,'<strong>Please rename</strong> "'+l+'" to "'+o+'" in '+i),console.warn('Please use lowercase for field: "'+l+'" in '+i,a,s));continue}if(a!=null){if(typeof a=="object"&&(r===void 0||!r.isObject3D)){if(typeof a.node=="number"||typeof a.guid=="string"){if(a.could_not_resolve)continue;if(!(r!==void 0&&Object.keys(r).length>1)){fr(Ci.Warn,`<strong>Missing serialization for object reference!</strong>
233
233
 
234
234
  Please change to:
235
235
  @serializable(Object3D)
@@ -879,7 +879,7 @@ Possible solutions:
879
879
  Render:`,{shaders:this.renderer.info.programs?.length,...this.renderer.info.render},`
880
880
  Memory:`,{usedMemory:t,...this.renderer.info.memory},`
881
881
  Renderer:`,{dpr:this.renderer.getPixelRatio(),windowDpr:window.devicePixelRatio,antialias:i.getContextAttributes()?.antialias,samples:i.getParameter(i.SAMPLES),resolution:`${this.renderer.domElement.width}x${this.renderer.domElement.height}`},`
882
- Target Framerate: `+this.targetFrameRate)}}this._dispatchReadyAfterFrame&&(this._dispatchReadyAfterFrame=!1,this.domElement.dispatchEvent(new CustomEvent("ready")),se.dispatchCallback(ae.ContextFirstFrameRendered,this))}_tempClearColor=new c.Color;_tempClearColor2=new c.Color;renderNow(e){if(!e&&(e=this.mainCamera,!e))return!1;if(this.handleRendererContextLost(),this._isRendering=!0,this.renderRequiredTextures(),this.renderer.toneMapping!==c.NoToneMapping&&nS(),this.postprocessing.update(),this.composer&&!this.isInXR){e&&"setMainCamera"in this.composer&&this.composer.passes[0]?.mainCamera!=e&&this.composer.setMainCamera(e);const t=this.renderer.getClearColor(this._tempClearColor),i=this.renderer.getClearAlpha();this._tempClearColor2.copy(t),this.renderer.setClearColor(t.convertSRGBToLinear(),this.renderer.getClearAlpha()),this.composer.render(this.time.deltaTime),this.renderer.setClearColor(this._tempClearColor2,i)}else e&&(this.isInXR&&exports.DeviceUtilities.isMacOS()&&this.renderer.clearDepth(),this.renderer.render(this.scene,e));return this._isRendering=!1,!0}_contextRestoreTries=0;handleRendererContextLost(){this.time.frame%10&&this.renderer.getContext().isContextLost()&&this._contextRestoreTries++<100&&(console.warn("Attempting to recover WebGL context..."),this.renderer.forceContextRestore())}_wasPaused=!1;onHandlePaused(){const e=this.evaluatePaused();if(this._wasPaused!==e){aE&&console.log("Paused?",e,"context:"+this.alias);for(let t=0;t<this.scripts_pausedChanged.length;t++){const i=this.scripts_pausedChanged[t];i.activeAndEnabled&&i.onPausedChanged!==void 0&&(_e.Current=this,i.onPausedChanged(e,this._wasPaused))}}return this._wasPaused=e,e}evaluatePaused(){return this.isInXR?!1:this.isPaused?!0:this.runInBackground?!1:!this.isVisibleToUser}renderRequiredTextures(){if(!this.mainCamera||!this._requireDepthTexture&&!this._requireColorTexture)return;if(!this._renderTarget){if(this._renderTarget=new c.WebGLRenderTarget(this.domWidth,this.domHeight),this._requireDepthTexture){const i=new c.DepthTexture(this.domWidth,this.domHeight);this._renderTarget.depthTexture=i}this._requireColorTexture&&(this._renderTarget.texture=new c.Texture,this._renderTarget.texture.generateMipmaps=!1,this._renderTarget.texture.minFilter=c.NearestFilter,this._renderTarget.texture.magFilter=c.NearestFilter,this._renderTarget.texture.format=c.RGBAFormat)}const e=this._renderTarget;e.texture&&(e.texture.colorSpace=this.renderer.outputColorSpace);const t=this.renderer.getRenderTarget();this.renderer.setRenderTarget(e),this.renderer.render(this.scene,this.mainCamera),this.renderer.setRenderTarget(t)}executeCoroutines(e){if(this.coroutines[e]){const i=this.coroutines[e];for(let n=0;n<i.length;n++)try{const o=i[n];if(!o.comp||o.comp.destroyed||!o.main||o.comp.enabled===!1){cE&&console.log("Removing coroutine",o.comp,o.comp.enabled),i.splice(n,1),--n;continue}const a=o.chained;if(a&&a.length>0){const u=a[a.length-1].next();if(u.done&&a.pop(),t(u)&&(o.chained||(o.chained=[]),o.chained.push(u.value)),!u.done)continue}const l=o.main.next();if(l.done===!0){i.splice(n,1),--n;continue}const h=l.value;if(t(h)){if(h.next().done)continue;o.chained||(o.chained=[]),o.chained.push(h)}else if(h instanceof Promise){const d=h;o.chained||(o.chained=[]);const u=zx(d);o.chained?.push(u);continue}}catch(o){console.error(o)}}function t(i){return!!(i&&i.next&&i.return)}}};ye([ge()],me.prototype,"scripts");ye([ge()],me.prototype,"scripts_pausedChanged");ye([ge()],me.prototype,"scripts_earlyUpdate");ye([ge()],me.prototype,"scripts_update");ye([ge()],me.prototype,"scripts_lateUpdate");ye([ge()],me.prototype,"scripts_onBeforeRender");ye([ge()],me.prototype,"scripts_onAfterRender");ye([ge()],me.prototype,"scripts_WithCorroutines");ye([ge()],me.prototype,"scripts_immersive_vr");ye([ge()],me.prototype,"scripts_immersive_ar");ye([ge()],me.prototype,"coroutines");ye([ge("keep")],me.prototype,"post_setup_callbacks");ye([ge("keep")],me.prototype,"pre_update_callbacks");ye([ge("keep")],me.prototype,"pre_render_callbacks");ye([ge("keep")],me.prototype,"post_render_callbacks");ye([ge()],me.prototype,"pre_update_oneshot_callbacks");ye([ge()],me.prototype,"new_scripts");ye([ge()],me.prototype,"new_script_start");ye([ge()],me.prototype,"new_scripts_pre_setup_callbacks");ye([ge()],me.prototype,"new_scripts_post_setup_callbacks");ye([ge()],me.prototype,"new_scripts_xr");ye([ge("undefined")],me.prototype,"mainCameraComponent");ye([ge("null")],me.prototype,"_mainCamera");ye([ge("null")],me.prototype,"_fallbackCamera");ye([ge("custom")],me.prototype,"_events");ye([ge("custom")],me.prototype,"lights");ye([ge("keep")],me.prototype,"_disposeCallbacks");ye([ge()],me.prototype,"_cameraStack");ye([ge("custom")],me.prototype,"_onBeforeRenderListeners");ye([ge("custom")],me.prototype,"_onAfterRenderListeners");ye([ge("keep")],me.prototype,"rootSceneSourceIdentifiers");let X=me;const um=x("debugwebxr");class wS{static tryFindAvatarObjects(e,t,i){if(i.head&&i.leftHand&&i.rightHand)return;const n=e.name.toLocaleLowerCase();!i.head&&n.includes("head")&&(um&&console.log("FOUND AVATAR HEAD",e.name),i.head=new J("",t,e)),n.includes("hand")&&(!i.leftHand&&n.includes("left")&&(um&&console.log("FOUND AVATAR LEFT HAND",e.name),i.leftHand=new J("",t,e)),!i.rightHand&&n.includes("right")&&(um&&console.log("FOUND AVATAR RIGHT HAND",e.name),i.rightHand=new J("",t,e)));for(let o=0;o<e.children.length;o++){if(i.head&&i.leftHand&&i.rightHand)return;const r=e.children[o];this.tryFindAvatarObjects(r,t,i)}}}class oe extends c.Color{alpha=1;get isRGBAColor(){return!0}set a(e){this.alpha=e}get a(){return this.alpha}constructor(e,t,i,n){super(),typeof e=="number"&&typeof t=="number"&&typeof i=="number"?(this.setRGB(Number.isFinite(e)?e:0,Number.isFinite(t)?t:0,Number.isFinite(i)?i:0),this.alpha=typeof n=="number"&&Number.isFinite(n)?n:1):e!==void 0&&(this.set(e),this.alpha=1)}clone(){const e=super.clone();return e.alpha=this.alpha,e}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,"alpha"in e&&typeof e.alpha=="number"?this.alpha=e.alpha:typeof e.a=="number"&&(this.alpha=e.a),this}lerp(e,t){const i=e;return i.alpha!=null&&(this.alpha=L.lerp(this.alpha,i.alpha,t)),super.lerp(e,t)}lerpColors(e,t,i){const n=e,o=t;return n.alpha!=null&&o.alpha!=null&&(this.alpha=L.lerp(n.alpha,o.alpha,i)),super.lerpColors(e,t,i)}multiply(e){const t=e;return t.alpha!=null&&(this.alpha=this.alpha*t.alpha),super.multiply(e)}fromArray(e,t=0){return this.alpha=e[t+3],super.fromArray(e,t)}static fromColorRepresentation(e){if(typeof e=="string"){if(e.trim()==="transparent")return new oe(0,0,0,0);if(e.startsWith("#")&&e.length===9){const t=parseInt(e.slice(1,9),16),i=t>>24&255,n=t>>16&255,o=t>>8&255,r=t>>0&255;return new oe(i/255,n/255,o/255,r/255)}else if(e.startsWith("#")){const t=parseInt(e.slice(1),16),i=t>>16&255,n=t>>8&255,o=t>>0&255;return new oe(i/255,n/255,o/255,1)}else if(e.startsWith("rgba")){const t=e.slice(5,-1).split(",").map(Number);return new oe(t[0]/255,t[1]/255,t[2]/255,t[3])}else if(e.startsWith("rgb")){const t=e.slice(4,-1).split(",").map(Number);return new oe(t[0]/255,t[1]/255,t[2]/255,1)}}else if(Array.isArray(e)){if(e.length===4)return new oe(e[0],e[1],e[2],e[3]);if(e.length===3)return new oe(e[0],e[1],e[2],1);console.error("Invalid color array length. Expected 3 or 4, got "+e.length)}return new oe(e)}}const Bt=new c.Vector3,Vv=new c.Vector3,Wv=new c.Quaternion,uE=x("debuggizmos"),un=8947848,fm=32;class B{constructor(){}static enabled=!0;static isGizmo(e){return e[Lg]!==void 0}static setVisible(e){for(const t of ri.timedObjectsBuffer)t.visible=e}static DrawLabel(e,t,i=.05,n=0,o,r,a,l=!0){if(!B.enabled)return null;o||(o=un);const h=N.active?.rigScale??1,d=ri.getTextLabel(n,t,i*h,o,r);return d[xS]=l===!1,a instanceof c.Object3D&&a.add(d),d.position.x=e.x,d.position.y=e.y,d.position.z=e.z,d}static DrawRay(e,t,i=un,n=0,o=!0){if(!B.enabled)return;const r=ri.getLine(n),a=r.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),Bt.set(t.x,t.y,t.z).multiplyScalar(999999999),a.setXYZ(1,e.x+Bt.x,e.y+Bt.y,e.z+Bt.z),a.needsUpdate=!0,r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1,mn(r.material,i)}static DrawDirection(e,t,i=un,n=0,o=!0,r=1){if(!B.enabled)return;const a=ri.getLine(n),l=a.geometry.getAttribute("position");l.setXYZ(0,e.x,e.y,e.z),t.w!==void 0?(Bt.set(0,0,-r),Wv.set(t.x,t.y,t.z,t.w),Bt.applyQuaternion(Wv)):(Bt.set(t.x,t.y,t.z),Bt.multiplyScalar(r)),l.setXYZ(1,e.x+Bt.x,e.y+Bt.y,e.z+Bt.z),l.needsUpdate=!0,a.material.depthTest=o,a.material.depthWrite=!1,mn(a.material,i)}static DrawLine(e,t,i=un,n=0,o=!0){if(!B.enabled)return;const r=ri.getLine(n),a=r.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),a.setXYZ(1,t.x,t.y,t.z),a.needsUpdate=!0,r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1,mn(r.material,i)}static DrawCircle(e,t,i,n=un,o=0,r=!0){if(!B.enabled)return;const a=ri.getCircle(o);a.position.set(e.x,e.y,e.z),a.scale.set(i,i,i),a.quaternion.setFromUnitVectors(this._up,Bt.set(t.x,t.y,t.z).normalize()),a.material.depthTest=r,a.material.depthWrite=!1,a.material.fog=!1,mn(a.material,n)}static DrawWireSphere(e,t,i=un,n=0,o=!0){if(!B.enabled)return;const r=ri.getSphere(t,n,!0);Ar(r,e.x,e.y,e.z),r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1,mn(r.material,i)}static DrawSphere(e,t,i=un,n=0,o=!0){if(!B.enabled)return;const r=ri.getSphere(t,n,!1);Ar(r,e.x,e.y,e.z),r.material.depthTest=o,r.material.depthWrite=!1,mn(r.material,i)}static DrawWireBox(e,t,i=un,n=0,o=!0,r=void 0){if(!B.enabled)return;const a=ri.getBox(n);a.position.set(e.x,e.y,e.z),a.scale.set(t.x,t.y,t.z),r?a.quaternion.copy(r):a.quaternion.identity(),a.material.depthTest=o,a.material.wireframe=!0,a.material.depthWrite=!1,a.material.fog=!1,mn(a.material,i)}static DrawWireBox3(e,t=un,i=0,n=!0){if(!B.enabled)return;const o=ri.getBox(i);o.position.copy(e.getCenter(Bt)),o.scale.copy(e.getSize(Bt)),o.material.depthTest=n,o.material.wireframe=!0,o.material.depthWrite=!1,o.material.fog=!1,mn(o.material,t)}static _up=new c.Vector3(0,1,0);static DrawArrow(e,t,i=un,n=0,o=!0,r=!1){if(!B.enabled)return;const a=ri.getArrowHead(n);a.position.set(t.x,t.y,t.z),a.quaternion.setFromUnitVectors(this._up.set(0,1,0),Bt.set(t.x,t.y,t.z).sub(Vv.set(e.x,e.y,e.z)).normalize());const h=Bt.set(t.x,t.y,t.z).sub(Vv.set(e.x,e.y,e.z)).length()*.1;a.scale.set(h,h,h),a.material.depthTest=o,a.material.wireframe=r,mn(a.material,i),this.DrawLine(e,t,i,n,o)}static DrawWireMesh(e){const t=ri.getMesh(e.duration??0);"mesh"in e?(t.geometry=e.mesh.geometry,t.matrixWorld.copy(e.mesh.matrixWorld)):(t.geometry=e.geometry,t.matrixWorld.copy(e.matrix)),t.matrixAutoUpdate=!1,t.matrixWorldAutoUpdate=!1,t.material.depthTest=e.depthTest??!0,t.material.wireframe=!0,mn(t.material,e.color??un)}}const fE=new c.BoxGeometry(1,1,1);function s_(s=null){const e=new c.Color(s??14540253),t=new c.EdgesGeometry(fE);return new c.LineSegments(t,new c.LineBasicMaterial({color:e}))}function mn(s,e){if(Array.isArray(s)){for(const i of s)mn(i,e);return}const t=e instanceof oe?e.a:1;s.color.set(e),s.opacity=t,s.transparent=t<1}const Lg=Symbol("GizmoCache"),xS=Symbol("GizmoLabelOnTop");class ri{static familyName="needle-gizmos";static ensureFont(){let e=le.__webpack_exports__default.FontLibrary.getFontFamily(this.familyName);e||(e=le.__webpack_exports__default.FontLibrary.addFontFamily(this.familyName),e.addVariant("normal","normal","https://cdn.needle.tools/static/fonts/msdf/arial/arial-msdf.json","https://cdn.needle.tools/static/fonts/msdf/arial/arial.png")?.addEventListener("ready",()=>{le.__webpack_exports__default.update()}))}static getTextLabel(e,t,i,n,o){this.ensureFont();let r=this.textLabelCache.pop(),a=1;o&&typeof o=="string"&&o?.length>=8&&o.startsWith("#")?(a=parseInt(o.substring(7),16)/255,o=o.substring(0,7),uE&&console.log(o,a)):typeof o=="object"&&o.a!==void 0&&(a=o.a);const l={boxSizing:"border-box",fontFamily:this.familyName,width:"auto",fontSize:i,color:n,lineHeight:1,backgroundColor:o??void 0,backgroundOpacity:a,textContent:t,borderRadius:.5*i,padding:.8*i,whiteSpace:"pre",offset:.05*i};if(r)r.set(l);else{r=new le.__webpack_exports__Text(l);const h=this,d=r;d.setText=function(u){this.set({textContent:u}),h.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(X.Current,r,e,this.textLabelCache),r}static getBox(e){let t=this.boxesCache.pop();if(!t){const i=new c.BoxGeometry(1,1,1);t=new c.Mesh(i)}return this.registerTimedObject(X.Current,t,e,this.boxesCache),t}static getLine(e){let t=this.linesCache.pop();if(!t){t=new c.Line;let i=t.geometry.getAttribute("position");i||(i=new c.BufferAttribute(new Float32Array(6),3),t.geometry.setAttribute("position",i))}return t.frustumCulled=!1,this.registerTimedObject(X.Current,t,e,this.linesCache),t}static getCircle(e){let t=this.circlesCache.pop();if(!t){t=new c.Line;let i=t.geometry.getAttribute("position");if(!i){i=new c.BufferAttribute(new Float32Array(fm*3),3),t.geometry.setAttribute("position",i);const n=F(0,1,0),o=F(0,0,1),r=F(o);r.cross(n).normalize();const a=F(r),l=Math.PI*2/(fm-1);for(let h=0;h<fm+1;h++){const d=l*h;n.copy(a).multiplyScalar(Math.cos(d)*1),r.copy(o).multiplyScalar(Math.sin(d)*1);const u=n.add(r);i.setXYZ(h,u.x,u.y,u.z)}}}return t.frustumCulled=!1,this.registerTimedObject(X.Current,t,e,this.circlesCache),t}static getSphere(e,t,i){let n=this.spheresCache.pop();return n||(n=new c.Mesh(new c.SphereGeometry(1,8,8))),n.scale.set(e,e,e),n.material.wireframe=i,this.registerTimedObject(X.Current,n,t,this.spheresCache),n}static getArrowHead(e){let t=this.arrowHeadsCache.pop();return t||(t=new c.Mesh(new c.CylinderGeometry(0,.5,1,8))),this.registerTimedObject(X.Current,t,e,this.arrowHeadsCache),t}static getMesh(e){let t=this.mesh.pop();return t||(t=new c.Mesh,t.material=new c.MeshBasicMaterial),this.registerTimedObject(X.Current,t,e,this.mesh),t}static linesCache=[];static circlesCache=[];static spheresCache=[];static boxesCache=[];static arrowHeadsCache=[];static mesh=[];static textLabelCache=[];static registerTimedObject(e,t,i,n){if(!e){console.error("No Needle Engine context available. Did you call a Gizmos function in global scope?");return}const o=this.contextBeforeRenderCallbacks.get(e),r=this.contextPostRenderCallbacks.get(e);if(o){if(e.pre_render_callbacks[e.pre_render_callbacks.length-1]!==o){const a=e.pre_render_callbacks.indexOf(o);a>=0&&e.pre_render_callbacks.splice(a,1),e.pre_render_callbacks.push(o)}}else{const a=()=>{this.onBeforeRender(e,this.timedObjectsBuffer)};this.contextBeforeRenderCallbacks.set(e,a),e.pre_render_callbacks.push(a)}if(r){if(e.post_render_callbacks[e.post_render_callbacks.length-1]!==r){const a=e.post_render_callbacks.indexOf(r);a>=0&&e.post_render_callbacks.splice(a,1),e.post_render_callbacks.push(r)}}else{const a=()=>{this.onPostRender(e,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(e,a),e.post_render_callbacks.push(a)}t.traverse(a=>{a.layers.disableAll(),a.layers.enable(2)}),t.renderOrder=999999,t[Lg]=n,t.castShadow=!1,t.receiveShadow=!1,t.isGizmo=!0,this.timedObjectsBuffer.push(t),this.timesBuffer.push(X.Current.time.realtimeSinceStartup+i),e.scene.add(t)}static timedObjectsBuffer=new Array;static timesBuffer=new Array;static contextPostRenderCallbacks=new Map;static contextBeforeRenderCallbacks=new Map;static tmuiNeedsUpdate=!1;static onBeforeRender(e,t){this.tmuiNeedsUpdate&&(this.tmuiNeedsUpdate=!1,le.__webpack_exports__default.update());for(let i=0;i<t.length;i++){const n=t[i];if(e.mainCamera&&n instanceof le.__webpack_exports__default.MeshUIBaseElement){if(Ao(n))continue;const o=e.isInVR,r=!1,a=!o;Ch(n,e.mainCamera,r,a),n[xS]===!0&&ri.applyLabelOnTop(n)}}}static applyLabelOnTop(e){e.traverse(t=>{const i=t.material;if(i){t.renderOrder=999999;for(const n of Array.isArray(i)?i:[i])n.depthTest=!1,n.depthWrite=!1}})}static onPostRender(e,t,i){const n=e.time.realtimeSinceStartup;for(let o=t.length-1;o>=0;o--){const r=t[o];n>=i[o]-1e-6&&(t.splice(o,1),i.splice(o,1),r.removeFromParent(),Ao(r)!=!0&&r[Lg].push(r))}}}const Yt=x("debugphysics"),pE=x("debugworker"),Gv=new c.Layers;class zr{static AllLayers=4294967295;ray;cam;screenPoint;raycaster;results;targets;recursive=!0;minDistance;maxDistance;lineThreshold;layerMask;ignore;testObject;useAcceleratedRaycast;allowSlowRaycastFallback=!0;screenPointFromOffset(e,t){this.screenPoint===void 0&&(this.screenPoint=new c.Vector2),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setLayer(e){Gv.set(e),this.layerMask=Gv}setMask(e){this.layerMask||(this.layerMask=new c.Layers);const t=this.layerMask;t?t.mask=e:this.layerMask=e}}class o_{distance;point;object;constructor(e,t,i){this.object=e,this.distance=t,this.point=i}}let Bg=null;function SS(s){Bg=s}class pl{static _raycasting=0;static get raycasting(){return this._raycasting>0}raycastPhysicsFast(e,t=void 0,i=1/0,n=!0){return this.context.physics.engine?.raycast(e,t,{maxDistance:i,solid:n})??null}raycastPhysicsFastAndGetNormal(e,t=void 0,i=1/0,n=!0){return this.context.physics.engine?.raycastAndGetNormal(e,t,{maxDistance:i,solid:n})??null}sphereOverlapPhysics(e,t){return this.context.physics.engine?.sphereOverlap(e,t)??null}context;_engine;get engine(){return this._engine}set engine(e){this._engine=e}getOrCreatePhysicsEngine(){return this._engine===void 0&&Bg&&(this._engine=Bg(this.context)),this._engine??null}constructor(e){this.context=e}raycaster=new c.Raycaster;defaultRaycastOptions=new zr;targetBuffer=new Array(1);defaultThresholds={Mesh:{},Line:{threshold:-1},LOD:{},Points:{threshold:0},Sprite:{}};sphereResults=new Array;sphereMask=new c.Layers;sphere=new c.Sphere;sphereOverlap(e,t,i=!0,n=!1,o=null){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;const r=this.sphereMask;r.enableAll(),r.disable(2);for(const a of this.context.scene.children)this.intersectSphere(a,e,t,r,this.sphereResults,i,n,o);return this.sphereResults.sort((a,l)=>a.distance-l.distance)}raycastFromRay(e,t=null){const i=t??this.defaultRaycastOptions;i.ray=e;const n=this.raycast(i);return i===this.defaultRaycastOptions&&(i.ray=void 0),n}raycast(e=null){Yt&&performance.mark("raycast.start"),e||(e=this.defaultRaycastOptions);const t=e.screenPoint??this.context.input.mousePositionRC,i=e.raycaster??this.raycaster;if(i.near=e.minDistance??0,i.far=e.maxDistance??1/0,i.params=this.defaultThresholds,e.lineThreshold===void 0&&(e.lineThreshold=-1),i.params.Line={threshold:e.lineThreshold},e.ray)i.ray.copy(e.ray);else{const a=e.cam??this.context.mainCamera;if(!a)return Yt&&console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];const l=this.context.xrCamera;this.context.isInXR&&l instanceof c.ArrayCamera&&l.cameras.length>0?i.setFromCamera(t,l.cameras[0]):i.setFromCamera(t,a)}let n=e.targets;n||(n=this.targetBuffer,n.length=1,n[0]=this.context.scene);let o=e.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),o||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),o=this.defaultRaycastOptions.results),e.layerMask!==void 0?e.layerMask instanceof c.Layers?i.layers.mask=e.layerMask.mask:i.layers.mask=e.layerMask:(i.layers.enableAll(),i.layers.disable(2)),Yt&&console.time("raycast"),o.length=0,pl._raycasting++,this.intersect(this.raycaster,n,o,e),o.sort((a,l)=>a.distance-l.distance);const r=e.ignore;return r!==void 0&&r.length>0&&(o=o.filter(a=>!r.includes(a.object))),pl._raycasting--,Yt&&(console.timeEnd("raycast"),console.warn("#"+this.context.time.frame+", hits:",o?.length?[...o]:"nothing"),performance.mark("raycast.end"),performance.measure("raycast","raycast.start","raycast.end")),o}intersect(e,t,i,n){for(const o of t){if(!o||o.visible===!1||B.isGizmo(o)||n.lineThreshold!==void 0&&n.lineThreshold<0&&o instanceof c.Line)continue;let r=!0;const a=o,l=a.geometry,h=!l&&o.raycast!==c.Object3D.prototype.raycast;if(o.raycastAllowed===!1&&(r=!1),r&&n.testObject){const d=n.testObject?.(o);if(d===!1)continue;d==="continue in children"&&(r=!1)}else r&&(!l&&!h||l&&!Hv(l))&&(r=!1);if(r){const d=i.length;if(h)e.intersectObject(a,!1,i);else{const u=o.raycastPreference||"lod";let f=u!=="bounds";if(n.precise===!1&&(f=!1),l&&(f||=l.getAttribute("position")?.array?.length<64),a instanceof V.GroundedSkybox&&(f=!1),u==="lod"){const m=re.getRaycastMesh(o);m&&(a.geometry=m)}!f&&gE(a,e,i)||(n.useAcceleratedRaycast!==!1?nf.runMeshBVHRaycast(e,a,i,this.context,n):e.intersectObject(a,!1,i)),a.geometry=l}if(Yt&&i.length!=d){const u=i[i.length-1];B.DrawWireSphere(u.point,.1,7798784,1,!1),B.DrawWireMesh({mesh:o,depthTest:!1,duration:.2,color:7798784})}}n.recursive!==!1&&this.intersect(e,o.children,i,n)}return i}tempBoundingBox=new c.Box3;intersectSphere(e,t,i,n,o,r,a,l){let h=e&&e.isMesh&&e.layers.test(n)&&!B.isGizmo(e);h&&=e.visible,h&&=!(e instanceof c.Line),h&&=!(e instanceof V.GroundedSkybox);const d=e,u=d.geometry;if(h&&l){const f=l(e);if(f===!1)return;f==="continue in children"&&(h=!1)}if(u&&Hv(u)||(h=!1),h){if(a){const f=this.sphere;f.center.copy(t),f.radius=i;const m=o.length;if(nf.runMeshBVHRaycast(this.sphere,d,o,this.context,{}),m!=o.length&&!r)return}else if(u.boundingBox||u.computeBoundingBox(),u.boundingBox){d.matrixWorldNeedsUpdate&&d.updateWorldMatrix(!1,!1);const f=this.tempBoundingBox.copy(u.boundingBox).applyMatrix4(d.matrixWorld),m=this.sphere;if(m.center.copy(t),m.radius=i,m.intersectsBox(f)){const g=ie(e),v=g.distanceTo(m.center),_=new o_(e,v,g);if(o.push(_),!r)return}}}if(e.children)for(const f of e.children){const m=o.length;if(this.intersectSphere(f,t,i,n,o,r,a,l),m!=o.length&&!r)return}}}function Hv(s){return!(s.index&&s.index.array.length<3)}const Jo=new c.Sphere,Td=new c.Plane,mE=new c.Matrix3;function gE(s,e,t){const i=s._computeIntersections;if(!i)return!1;let n=s["_computeIntersections:Needle"];return n||(n=s["_computeIntersections:Needle"]=function(o,r,a){const l=this,h=l.geometry.boundingSphere;if(h){if(l instanceof V.GroundedSkybox){Td.setFromNormalAndCoplanarPoint(F(0,1,0),F(0,-l.position.y,0)),Td.applyMatrix4(l.matrixWorld,mE);const u=o.ray.intersectPlane(Td,F());if(u){Jo.copy(h),Jo.applyMatrix4(l.matrixWorld);const m=F(u).sub(o.ray.origin).length(),g=Jo.radius*.5;m<g&&r.push({distance:m,point:u,object:l,normal:Td.normal.clone()})}return}Jo.copy(h),Jo.applyMatrix4(l.matrixWorld);const d=o.ray.intersectSphere(Jo,F());if(d){const u=F(d).sub(o.ray.origin),f=u.length();if(f>Jo.radius){const m=u.clone().normalize();r.push({distance:f,point:d,object:l,normal:m})}}}}),s._computeIntersections=n,e.intersectObject(s,!1,t),s._computeIntersections=i,!0}function Fg(s,e){const t=s.children;s.children=[];try{return e()}finally{s.children=t}}var nf;(s=>{let e=0;function t(b,w,C,k,O){if(!w.geometry||!w.geometry.hasAttribute("position"))return!1;const D=w.geometry;if(w?.isSkinnedMesh){const I=w,j=I.bvhNeedsUpdate;if(!I.staticGenerator)l(),r&&(Fg(w,()=>{I.staticGenerator=new r(w),I.staticGenerator.applyWorldTransforms=!1,I.staticGeometry=I.staticGenerator.generate()}),D.boundsTree=a?.call(I.staticGeometry),I.staticGeometryLastUpdate=performance.now()+Math.random()*200,I.bvhNeedsUpdate=!0);else if(D.boundsTree&&(I.autoUpdateMeshBvhInterval!==void 0&&I.autoUpdateMeshBvhInterval>=0||j===!0)){const $=performance.now(),W=$-I.staticGeometryLastUpdate,R=I.autoUpdateMeshBvhInterval??100;(j||W>R)&&(Yt&&console.warn(`Physics: updating skinned mesh bvh for ${w.name} after ${W.toFixed(2)}ms`),I.bvhNeedsUpdate=!1,I.staticGeometryLastUpdate=$,Fg(w,()=>I.staticGenerator?.generate(I.staticGeometry)),D.boundsTree.refit())}}else if(!D.boundsTree){d||y();let I=!0;if((k.xr||D[g]===!1||D.getAttribute("position")?.isInterleavedBufferAttribute||D.index&&D.index?.isInterleavedBufferAttribute||e>10)&&(I=!1),I&&f){if(D[m]===void 0){let j=null;if(_.length>0){const $=_.shift();$&&!$.running&&(j=$)}if(!j&&v.length<3)try{pE&&console.warn("[GenerateMeshBVHWorker] Creating worker with import.meta.url:",typeof document>"u"?require("url").pathToFileURL(__filename).href:Ha&&Ha.tagName.toUpperCase()==="SCRIPT"&&Ha.src||new URL("needle-engine.bundle-BuUj9B4K.umd.cjs",document.baseURI).href),j=new f,v.push(j)}catch($){$ instanceof DOMException&&$.name==="SecurityError"?(console.warn("Failed to create MeshBVH worker, falling back to main thread generation. This can happen when running from file://, if the browser does not support workers or if the browser is blocking workers for other reasons."),console.debug($),e+=10):(console.error("Failed to create MeshBVH worker. Please see below for more details:"),console.log($)),e++}if(j!=null&&!j.running){const $=w.name;Yt&&console.log("<<<< worker start",$,j),D[m]="queued",performance.mark("bvh.create.start");const W=D.clone();try{j.generate(W).then(R=>{D[m]="done",D.boundsTree=R}).catch(R=>{D[m]="failed - "+R?.message,D[g]=!1,Yt&&console.error("Failed to generate mesh bvh on worker",R)}).finally(()=>{Yt&&console.log(">>>>> worker done",$,{hasBoundsTre:D.boundsTree!=null}),_.push(j),W.dispose(),performance.mark("bvh.create.end"),performance.measure("bvh.create (worker)","bvh.create.start","bvh.create.end")})}catch(R){console.error("Failed to generate mesh bvh on worker",R)}}else Yt&&console.warn("No worker available")}}else(!u||!I)&&(l(),o&&(performance.mark("bvh.create.start"),D.boundsTree=new o(D),performance.mark("bvh.create.end"),performance.measure("bvh.create","bvh.create.start","bvh.create.end")))}if(b instanceof c.Raycaster){const I=b,j=w.raycast;if(D.boundsTree)l(),n&&(w.acceleratedRaycast||(w.acceleratedRaycast=n.bind(w),Yt&&console.debug(`Physics: bind acceleratedRaycast fn to "${w.name}"`)),w.raycast=w.acceleratedRaycast);else if(Yt&&console.warn("No bounds tree found for mesh",w.name,{workerTask:D[m],hasAcceleratedRaycast:n!=null}),O.allowSlowRaycastFallback===!1&&(D.getAttribute("position")?.array?.length??0)>2e3)return Yt&&console.warn("Skipping raycast because no bounds tree is available and allowSlowRaycastFallback is false"),!1;const $=I.firstHitOnly;return I.firstHitOnly=!1,I.intersectObject(w,!1,C),I.firstHitOnly=$,w.raycast=j,!0}else if(b instanceof c.Sphere){const I=D.boundsTree;if(I){const j=b;if(h.copy(w.matrixWorld).invert(),j.applyMatrix4(h),I.intersectsSphere(j)){const W=ie(w),R=W.distanceTo(j.center),U=new o_(w,R,W);C.push(U)}}return!0}return!1}s.runMeshBVHRaycast=t;let i=!1,n=null,o=null,r=null,a=null;function l(){i||(i=!0,Promise.resolve().then(()=>require("./vendor-BJviq-Oq.umd.cjs")).then(b=>b.index$1).then(b=>{n=b.acceleratedRaycast,o=b.MeshBVH,r=b.StaticGeometryGenerator,a=b.computeBoundsTree}).catch(b=>{(Yt||E())&&console.error("Failed to load BVH library...",b.message)}))}const h=new c.Matrix4;let d=!1,u=!1,f=null;const m=Symbol("Needle:MeshBVH-Worker"),g=Symbol("Needle:MeshBVH-CanUseWorker"),v=[],_=[];function y(){d=!0,u=!0,Promise.resolve().then(()=>z3).then(b=>{f=b.GenerateMeshBVHWorker}).catch(b=>{Yt||E()?console.warn("Failed to setup mesh bvh worker"):console.debug("Failed to setup mesh bvh worker",b)}).finally(()=>{u=!1})}})(nf||(nf={}));const qv=Symbol("gltf-loader-internal-usage-tracker"),yE=x("debugusers");class Za{get name(){return"NEEDLE_internal_usage_tracker"}static isLoading(e){return Za._loadingProcesses>0}static _loadingProcesses=0;parser;_getDependency;_loadingId;_loadedObjects=new Set;constructor(e){this.parser=e,this._getDependency=this.parser.getDependency,this._loadingId=Date.now().toString()}beforeRoot(){Za._loadingProcesses++;const e=this,t=this._getDependency;return this.parser.getDependency=function(i,n){const o=t.call(this,i,n);return o.then(r=>(r&&(e._loadedObjects.add(r),r[qv]=e._loadingId),r)),o},null}afterRoot(e){Za._loadingProcesses--,this.parser.getDependency=this._getDependency;for(const t of this._loadedObjects)delete t[qv],t instanceof c.Object3D&&(t.parent||t instanceof c.Mesh&&setTimeout(()=>{yE&&console.warn("> GLTF LOADER: Mesh not used in scene!",t),t.material=null,t.geometry=null},1e3));return null}}class CS{constructor(){window.addEventListener("unhandledrejection",e=>{if(e.defaultPrevented)return;const t=e?.reason?.path;if(t){const i=t[0];i&&i.tagName==="IMG"&&(console.warn(`Could not load image:
882
+ Target Framerate: `+this.targetFrameRate)}}this._dispatchReadyAfterFrame&&(this._dispatchReadyAfterFrame=!1,this.domElement.dispatchEvent(new CustomEvent("ready")),se.dispatchCallback(ae.ContextFirstFrameRendered,this))}_tempClearColor=new c.Color;_tempClearColor2=new c.Color;renderNow(e){if(!e&&(e=this.mainCamera,!e))return!1;if(this.handleRendererContextLost(),this._isRendering=!0,this.renderRequiredTextures(),this.renderer.toneMapping!==c.NoToneMapping&&nS(),this.postprocessing.update(),this.composer&&!this.isInXR){e&&"setMainCamera"in this.composer&&this.composer.passes[0]?.mainCamera!=e&&this.composer.setMainCamera(e);const t=this.renderer.getClearColor(this._tempClearColor),i=this.renderer.getClearAlpha();this._tempClearColor2.copy(t),this.renderer.setClearColor(t.convertSRGBToLinear(),this.renderer.getClearAlpha()),this.composer.render(this.time.deltaTime),this.renderer.setClearColor(this._tempClearColor2,i)}else e&&(this.isInXR&&exports.DeviceUtilities.isMacOS()&&this.renderer.clearDepth(),this.renderer.render(this.scene,e));return this._isRendering=!1,!0}_contextRestoreTries=0;handleRendererContextLost(){this.time.frame%10&&this.renderer.getContext().isContextLost()&&this._contextRestoreTries++<100&&(console.warn("Attempting to recover WebGL context..."),this.renderer.forceContextRestore())}_wasPaused=!1;onHandlePaused(){const e=this.evaluatePaused();if(this._wasPaused!==e){aE&&console.log("Paused?",e,"context:"+this.alias);for(let t=0;t<this.scripts_pausedChanged.length;t++){const i=this.scripts_pausedChanged[t];i.activeAndEnabled&&i.onPausedChanged!==void 0&&(_e.Current=this,i.onPausedChanged(e,this._wasPaused))}}return this._wasPaused=e,e}evaluatePaused(){return this.isInXR?!1:this.isPaused?!0:this.runInBackground?!1:!this.isVisibleToUser}renderRequiredTextures(){if(!this.mainCamera||!this._requireDepthTexture&&!this._requireColorTexture)return;if(!this._renderTarget){if(this._renderTarget=new c.WebGLRenderTarget(this.domWidth,this.domHeight),this._requireDepthTexture){const i=new c.DepthTexture(this.domWidth,this.domHeight);this._renderTarget.depthTexture=i}this._requireColorTexture&&(this._renderTarget.texture=new c.Texture,this._renderTarget.texture.generateMipmaps=!1,this._renderTarget.texture.minFilter=c.NearestFilter,this._renderTarget.texture.magFilter=c.NearestFilter,this._renderTarget.texture.format=c.RGBAFormat)}const e=this._renderTarget;e.texture&&(e.texture.colorSpace=this.renderer.outputColorSpace);const t=this.renderer.getRenderTarget();this.renderer.setRenderTarget(e),this.renderer.render(this.scene,this.mainCamera),this.renderer.setRenderTarget(t)}executeCoroutines(e){if(this.coroutines[e]){const i=this.coroutines[e];for(let n=0;n<i.length;n++)try{const o=i[n];if(!o.comp||o.comp.destroyed||!o.main||o.comp.enabled===!1){cE&&console.log("Removing coroutine",o.comp,o.comp.enabled),i.splice(n,1),--n;continue}const a=o.chained;if(a&&a.length>0){const u=a[a.length-1].next();if(u.done&&a.pop(),t(u)&&(o.chained||(o.chained=[]),o.chained.push(u.value)),!u.done)continue}const l=o.main.next();if(l.done===!0){i.splice(n,1),--n;continue}const h=l.value;if(t(h)){if(h.next().done)continue;o.chained||(o.chained=[]),o.chained.push(h)}else if(h instanceof Promise){const d=h;o.chained||(o.chained=[]);const u=zx(d);o.chained?.push(u);continue}}catch(o){console.error(o)}}function t(i){return!!(i&&i.next&&i.return)}}};ye([ge()],me.prototype,"scripts");ye([ge()],me.prototype,"scripts_pausedChanged");ye([ge()],me.prototype,"scripts_earlyUpdate");ye([ge()],me.prototype,"scripts_update");ye([ge()],me.prototype,"scripts_lateUpdate");ye([ge()],me.prototype,"scripts_onBeforeRender");ye([ge()],me.prototype,"scripts_onAfterRender");ye([ge()],me.prototype,"scripts_WithCorroutines");ye([ge()],me.prototype,"scripts_immersive_vr");ye([ge()],me.prototype,"scripts_immersive_ar");ye([ge()],me.prototype,"coroutines");ye([ge("keep")],me.prototype,"post_setup_callbacks");ye([ge("keep")],me.prototype,"pre_update_callbacks");ye([ge("keep")],me.prototype,"pre_render_callbacks");ye([ge("keep")],me.prototype,"post_render_callbacks");ye([ge()],me.prototype,"pre_update_oneshot_callbacks");ye([ge()],me.prototype,"new_scripts");ye([ge()],me.prototype,"new_script_start");ye([ge()],me.prototype,"new_scripts_pre_setup_callbacks");ye([ge()],me.prototype,"new_scripts_post_setup_callbacks");ye([ge()],me.prototype,"new_scripts_xr");ye([ge("undefined")],me.prototype,"mainCameraComponent");ye([ge("null")],me.prototype,"_mainCamera");ye([ge("null")],me.prototype,"_fallbackCamera");ye([ge("custom")],me.prototype,"_events");ye([ge("custom")],me.prototype,"lights");ye([ge("keep")],me.prototype,"_disposeCallbacks");ye([ge()],me.prototype,"_cameraStack");ye([ge("custom")],me.prototype,"_onBeforeRenderListeners");ye([ge("custom")],me.prototype,"_onAfterRenderListeners");ye([ge("keep")],me.prototype,"rootSceneSourceIdentifiers");let X=me;const um=x("debugwebxr");class wS{static tryFindAvatarObjects(e,t,i){if(i.head&&i.leftHand&&i.rightHand)return;const n=e.name.toLocaleLowerCase();!i.head&&n.includes("head")&&(um&&console.log("FOUND AVATAR HEAD",e.name),i.head=new J("",t,e)),n.includes("hand")&&(!i.leftHand&&n.includes("left")&&(um&&console.log("FOUND AVATAR LEFT HAND",e.name),i.leftHand=new J("",t,e)),!i.rightHand&&n.includes("right")&&(um&&console.log("FOUND AVATAR RIGHT HAND",e.name),i.rightHand=new J("",t,e)));for(let o=0;o<e.children.length;o++){if(i.head&&i.leftHand&&i.rightHand)return;const r=e.children[o];this.tryFindAvatarObjects(r,t,i)}}}class oe extends c.Color{alpha=1;get isRGBAColor(){return!0}set a(e){this.alpha=e}get a(){return this.alpha}constructor(e,t,i,n){super(),typeof e=="number"&&typeof t=="number"&&typeof i=="number"?(this.setRGB(Number.isFinite(e)?e:0,Number.isFinite(t)?t:0,Number.isFinite(i)?i:0),this.alpha=typeof n=="number"&&Number.isFinite(n)?n:1):e!==void 0&&(this.set(e),this.alpha=1)}clone(){const e=super.clone();return e.alpha=this.alpha,e}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,"alpha"in e&&typeof e.alpha=="number"?this.alpha=e.alpha:typeof e.a=="number"&&(this.alpha=e.a),this}lerp(e,t){const i=e;return i.alpha!=null&&(this.alpha=L.lerp(this.alpha,i.alpha,t)),super.lerp(e,t)}lerpColors(e,t,i){const n=e,o=t;return n.alpha!=null&&o.alpha!=null&&(this.alpha=L.lerp(n.alpha,o.alpha,i)),super.lerpColors(e,t,i)}multiply(e){const t=e;return t.alpha!=null&&(this.alpha=this.alpha*t.alpha),super.multiply(e)}fromArray(e,t=0){return this.alpha=e[t+3],super.fromArray(e,t)}static fromColorRepresentation(e){if(typeof e=="string"){if(e.trim()==="transparent")return new oe(0,0,0,0);if(e.startsWith("#")&&e.length===9){const t=parseInt(e.slice(1,9),16),i=t>>24&255,n=t>>16&255,o=t>>8&255,r=t>>0&255;return new oe(i/255,n/255,o/255,r/255)}else if(e.startsWith("#")){const t=parseInt(e.slice(1),16),i=t>>16&255,n=t>>8&255,o=t>>0&255;return new oe(i/255,n/255,o/255,1)}else if(e.startsWith("rgba")){const t=e.slice(5,-1).split(",").map(Number);return new oe(t[0]/255,t[1]/255,t[2]/255,t[3])}else if(e.startsWith("rgb")){const t=e.slice(4,-1).split(",").map(Number);return new oe(t[0]/255,t[1]/255,t[2]/255,1)}}else if(Array.isArray(e)){if(e.length===4)return new oe(e[0],e[1],e[2],e[3]);if(e.length===3)return new oe(e[0],e[1],e[2],1);console.error("Invalid color array length. Expected 3 or 4, got "+e.length)}return new oe(e)}}const Bt=new c.Vector3,Vv=new c.Vector3,Wv=new c.Quaternion,uE=x("debuggizmos"),un=8947848,fm=32;class B{constructor(){}static enabled=!0;static isGizmo(e){return e[Lg]!==void 0}static setVisible(e){for(const t of ri.timedObjectsBuffer)t.visible=e}static DrawLabel(e,t,i=.05,n=0,o,r,a,l=!0){if(!B.enabled)return null;o||(o=un);const h=N.active?.rigScale??1,d=ri.getTextLabel(n,t,i*h,o,r);return d[xS]=l===!1,a instanceof c.Object3D&&a.add(d),d.position.x=e.x,d.position.y=e.y,d.position.z=e.z,d}static DrawRay(e,t,i=un,n=0,o=!0){if(!B.enabled)return;const r=ri.getLine(n),a=r.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),Bt.set(t.x,t.y,t.z).multiplyScalar(999999999),a.setXYZ(1,e.x+Bt.x,e.y+Bt.y,e.z+Bt.z),a.needsUpdate=!0,r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1,mn(r.material,i)}static DrawDirection(e,t,i=un,n=0,o=!0,r=1){if(!B.enabled)return;const a=ri.getLine(n),l=a.geometry.getAttribute("position");l.setXYZ(0,e.x,e.y,e.z),t.w!==void 0?(Bt.set(0,0,-r),Wv.set(t.x,t.y,t.z,t.w),Bt.applyQuaternion(Wv)):(Bt.set(t.x,t.y,t.z),Bt.multiplyScalar(r)),l.setXYZ(1,e.x+Bt.x,e.y+Bt.y,e.z+Bt.z),l.needsUpdate=!0,a.material.depthTest=o,a.material.depthWrite=!1,mn(a.material,i)}static DrawLine(e,t,i=un,n=0,o=!0){if(!B.enabled)return;const r=ri.getLine(n),a=r.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),a.setXYZ(1,t.x,t.y,t.z),a.needsUpdate=!0,r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1,mn(r.material,i)}static DrawCircle(e,t,i,n=un,o=0,r=!0){if(!B.enabled)return;const a=ri.getCircle(o);a.position.set(e.x,e.y,e.z),a.scale.set(i,i,i),a.quaternion.setFromUnitVectors(this._up,Bt.set(t.x,t.y,t.z).normalize()),a.material.depthTest=r,a.material.depthWrite=!1,a.material.fog=!1,mn(a.material,n)}static DrawWireSphere(e,t,i=un,n=0,o=!0){if(!B.enabled)return;const r=ri.getSphere(t,n,!0);Ar(r,e.x,e.y,e.z),r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1,mn(r.material,i)}static DrawSphere(e,t,i=un,n=0,o=!0){if(!B.enabled)return;const r=ri.getSphere(t,n,!1);Ar(r,e.x,e.y,e.z),r.material.depthTest=o,r.material.depthWrite=!1,mn(r.material,i)}static DrawWireBox(e,t,i=un,n=0,o=!0,r=void 0){if(!B.enabled)return;const a=ri.getBox(n);a.position.set(e.x,e.y,e.z),a.scale.set(t.x,t.y,t.z),r?a.quaternion.copy(r):a.quaternion.identity(),a.material.depthTest=o,a.material.wireframe=!0,a.material.depthWrite=!1,a.material.fog=!1,mn(a.material,i)}static DrawWireBox3(e,t=un,i=0,n=!0){if(!B.enabled)return;const o=ri.getBox(i);o.position.copy(e.getCenter(Bt)),o.scale.copy(e.getSize(Bt)),o.material.depthTest=n,o.material.wireframe=!0,o.material.depthWrite=!1,o.material.fog=!1,mn(o.material,t)}static _up=new c.Vector3(0,1,0);static DrawArrow(e,t,i=un,n=0,o=!0,r=!1){if(!B.enabled)return;const a=ri.getArrowHead(n);a.position.set(t.x,t.y,t.z),a.quaternion.setFromUnitVectors(this._up.set(0,1,0),Bt.set(t.x,t.y,t.z).sub(Vv.set(e.x,e.y,e.z)).normalize());const h=Bt.set(t.x,t.y,t.z).sub(Vv.set(e.x,e.y,e.z)).length()*.1;a.scale.set(h,h,h),a.material.depthTest=o,a.material.wireframe=r,mn(a.material,i),this.DrawLine(e,t,i,n,o)}static DrawWireMesh(e){const t=ri.getMesh(e.duration??0);"mesh"in e?(t.geometry=e.mesh.geometry,t.matrixWorld.copy(e.mesh.matrixWorld)):(t.geometry=e.geometry,t.matrixWorld.copy(e.matrix)),t.matrixAutoUpdate=!1,t.matrixWorldAutoUpdate=!1,t.material.depthTest=e.depthTest??!0,t.material.wireframe=!0,mn(t.material,e.color??un)}}const fE=new c.BoxGeometry(1,1,1);function s_(s=null){const e=new c.Color(s??14540253),t=new c.EdgesGeometry(fE);return new c.LineSegments(t,new c.LineBasicMaterial({color:e}))}function mn(s,e){if(Array.isArray(s)){for(const i of s)mn(i,e);return}const t=e instanceof oe?e.a:1;s.color.set(e),s.opacity=t,s.transparent=t<1}const Lg=Symbol("GizmoCache"),xS=Symbol("GizmoLabelOnTop");class ri{static familyName="needle-gizmos";static ensureFont(){let e=le.__webpack_exports__default.FontLibrary.getFontFamily(this.familyName);e||(e=le.__webpack_exports__default.FontLibrary.addFontFamily(this.familyName),e.addVariant("normal","normal","https://cdn.needle.tools/static/fonts/msdf/arial/arial-msdf.json","https://cdn.needle.tools/static/fonts/msdf/arial/arial.png")?.addEventListener("ready",()=>{le.__webpack_exports__default.update()}))}static getTextLabel(e,t,i,n,o){this.ensureFont();let r=this.textLabelCache.pop(),a=1;o&&typeof o=="string"&&o?.length>=8&&o.startsWith("#")?(a=parseInt(o.substring(7),16)/255,o=o.substring(0,7),uE&&console.log(o,a)):typeof o=="object"&&o.a!==void 0&&(a=o.a);const l={boxSizing:"border-box",fontFamily:this.familyName,width:"auto",fontSize:i,color:n,lineHeight:1,backgroundColor:o??void 0,backgroundOpacity:a,textContent:t,borderRadius:.5*i,padding:.8*i,whiteSpace:"pre",offset:.05*i};if(r)r.set(l);else{r=new le.__webpack_exports__Text(l);const h=this,d=r;d.setText=function(u){this.set({textContent:u}),h.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(X.Current,r,e,this.textLabelCache),r}static getBox(e){let t=this.boxesCache.pop();if(!t){const i=new c.BoxGeometry(1,1,1);t=new c.Mesh(i)}return this.registerTimedObject(X.Current,t,e,this.boxesCache),t}static getLine(e){let t=this.linesCache.pop();if(!t){t=new c.Line;let i=t.geometry.getAttribute("position");i||(i=new c.BufferAttribute(new Float32Array(6),3),t.geometry.setAttribute("position",i))}return t.frustumCulled=!1,this.registerTimedObject(X.Current,t,e,this.linesCache),t}static getCircle(e){let t=this.circlesCache.pop();if(!t){t=new c.Line;let i=t.geometry.getAttribute("position");if(!i){i=new c.BufferAttribute(new Float32Array(fm*3),3),t.geometry.setAttribute("position",i);const n=F(0,1,0),o=F(0,0,1),r=F(o);r.cross(n).normalize();const a=F(r),l=Math.PI*2/(fm-1);for(let h=0;h<fm+1;h++){const d=l*h;n.copy(a).multiplyScalar(Math.cos(d)*1),r.copy(o).multiplyScalar(Math.sin(d)*1);const u=n.add(r);i.setXYZ(h,u.x,u.y,u.z)}}}return t.frustumCulled=!1,this.registerTimedObject(X.Current,t,e,this.circlesCache),t}static getSphere(e,t,i){let n=this.spheresCache.pop();return n||(n=new c.Mesh(new c.SphereGeometry(1,8,8))),n.scale.set(e,e,e),n.material.wireframe=i,this.registerTimedObject(X.Current,n,t,this.spheresCache),n}static getArrowHead(e){let t=this.arrowHeadsCache.pop();return t||(t=new c.Mesh(new c.CylinderGeometry(0,.5,1,8))),this.registerTimedObject(X.Current,t,e,this.arrowHeadsCache),t}static getMesh(e){let t=this.mesh.pop();return t||(t=new c.Mesh,t.material=new c.MeshBasicMaterial),this.registerTimedObject(X.Current,t,e,this.mesh),t}static linesCache=[];static circlesCache=[];static spheresCache=[];static boxesCache=[];static arrowHeadsCache=[];static mesh=[];static textLabelCache=[];static registerTimedObject(e,t,i,n){if(!e){console.error("No Needle Engine context available. Did you call a Gizmos function in global scope?");return}const o=this.contextBeforeRenderCallbacks.get(e),r=this.contextPostRenderCallbacks.get(e);if(o){if(e.pre_render_callbacks[e.pre_render_callbacks.length-1]!==o){const a=e.pre_render_callbacks.indexOf(o);a>=0&&e.pre_render_callbacks.splice(a,1),e.pre_render_callbacks.push(o)}}else{const a=()=>{this.onBeforeRender(e,this.timedObjectsBuffer)};this.contextBeforeRenderCallbacks.set(e,a),e.pre_render_callbacks.push(a)}if(r){if(e.post_render_callbacks[e.post_render_callbacks.length-1]!==r){const a=e.post_render_callbacks.indexOf(r);a>=0&&e.post_render_callbacks.splice(a,1),e.post_render_callbacks.push(r)}}else{const a=()=>{this.onPostRender(e,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(e,a),e.post_render_callbacks.push(a)}t.traverse(a=>{a.layers.disableAll(),a.layers.enable(2)}),t.renderOrder=999999,t[Lg]=n,t.castShadow=!1,t.receiveShadow=!1,t.isGizmo=!0,this.timedObjectsBuffer.push(t),this.timesBuffer.push(X.Current.time.realtimeSinceStartup+i),e.scene.add(t)}static timedObjectsBuffer=new Array;static timesBuffer=new Array;static contextPostRenderCallbacks=new Map;static contextBeforeRenderCallbacks=new Map;static tmuiNeedsUpdate=!1;static onBeforeRender(e,t){this.tmuiNeedsUpdate&&(this.tmuiNeedsUpdate=!1,le.__webpack_exports__default.update());for(let i=0;i<t.length;i++){const n=t[i];if(e.mainCamera&&n instanceof le.__webpack_exports__default.MeshUIBaseElement){if(Ao(n))continue;const o=e.isInVR,r=!1,a=!o;Ch(n,e.mainCamera,r,a),n[xS]===!0&&ri.applyLabelOnTop(n)}}}static applyLabelOnTop(e){e.traverse(t=>{const i=t.material;if(i){t.renderOrder=999999;for(const n of Array.isArray(i)?i:[i])n.depthTest=!1,n.depthWrite=!1}})}static onPostRender(e,t,i){const n=e.time.realtimeSinceStartup;for(let o=t.length-1;o>=0;o--){const r=t[o];n>=i[o]-1e-6&&(t.splice(o,1),i.splice(o,1),r.removeFromParent(),Ao(r)!=!0&&r[Lg].push(r))}}}const Yt=x("debugphysics"),pE=x("debugworker"),Gv=new c.Layers;class zr{static AllLayers=4294967295;ray;cam;screenPoint;raycaster;results;targets;recursive=!0;minDistance;maxDistance;lineThreshold;layerMask;ignore;testObject;useAcceleratedRaycast;allowSlowRaycastFallback=!0;screenPointFromOffset(e,t){this.screenPoint===void 0&&(this.screenPoint=new c.Vector2),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setLayer(e){Gv.set(e),this.layerMask=Gv}setMask(e){this.layerMask||(this.layerMask=new c.Layers);const t=this.layerMask;t?t.mask=e:this.layerMask=e}}class o_{distance;point;object;constructor(e,t,i){this.object=e,this.distance=t,this.point=i}}let Bg=null;function SS(s){Bg=s}class pl{static _raycasting=0;static get raycasting(){return this._raycasting>0}raycastPhysicsFast(e,t=void 0,i=1/0,n=!0){return this.context.physics.engine?.raycast(e,t,{maxDistance:i,solid:n})??null}raycastPhysicsFastAndGetNormal(e,t=void 0,i=1/0,n=!0){return this.context.physics.engine?.raycastAndGetNormal(e,t,{maxDistance:i,solid:n})??null}sphereOverlapPhysics(e,t){return this.context.physics.engine?.sphereOverlap(e,t)??null}context;_engine;get engine(){return this._engine}set engine(e){this._engine=e}getOrCreatePhysicsEngine(){return this._engine===void 0&&Bg&&(this._engine=Bg(this.context)),this._engine??null}constructor(e){this.context=e}raycaster=new c.Raycaster;defaultRaycastOptions=new zr;targetBuffer=new Array(1);defaultThresholds={Mesh:{},Line:{threshold:-1},LOD:{},Points:{threshold:0},Sprite:{}};sphereResults=new Array;sphereMask=new c.Layers;sphere=new c.Sphere;sphereOverlap(e,t,i=!0,n=!1,o=null){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;const r=this.sphereMask;r.enableAll(),r.disable(2);for(const a of this.context.scene.children)this.intersectSphere(a,e,t,r,this.sphereResults,i,n,o);return this.sphereResults.sort((a,l)=>a.distance-l.distance)}raycastFromRay(e,t=null){const i=t??this.defaultRaycastOptions;i.ray=e;const n=this.raycast(i);return i===this.defaultRaycastOptions&&(i.ray=void 0),n}raycast(e=null){Yt&&performance.mark("raycast.start"),e||(e=this.defaultRaycastOptions);const t=e.screenPoint??this.context.input.mousePositionRC,i=e.raycaster??this.raycaster;if(i.near=e.minDistance??0,i.far=e.maxDistance??1/0,i.params=this.defaultThresholds,e.lineThreshold===void 0&&(e.lineThreshold=-1),i.params.Line={threshold:e.lineThreshold},e.ray)i.ray.copy(e.ray);else{const a=e.cam??this.context.mainCamera;if(!a)return Yt&&console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];const l=this.context.xrCamera;this.context.isInXR&&l instanceof c.ArrayCamera&&l.cameras.length>0?i.setFromCamera(t,l.cameras[0]):i.setFromCamera(t,a)}let n=e.targets;n||(n=this.targetBuffer,n.length=1,n[0]=this.context.scene);let o=e.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),o||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),o=this.defaultRaycastOptions.results),e.layerMask!==void 0?e.layerMask instanceof c.Layers?i.layers.mask=e.layerMask.mask:i.layers.mask=e.layerMask:(i.layers.enableAll(),i.layers.disable(2)),Yt&&console.time("raycast"),o.length=0,pl._raycasting++,this.intersect(this.raycaster,n,o,e),o.sort((a,l)=>a.distance-l.distance);const r=e.ignore;return r!==void 0&&r.length>0&&(o=o.filter(a=>!r.includes(a.object))),pl._raycasting--,Yt&&(console.timeEnd("raycast"),console.warn("#"+this.context.time.frame+", hits:",o?.length?[...o]:"nothing"),performance.mark("raycast.end"),performance.measure("raycast","raycast.start","raycast.end")),o}intersect(e,t,i,n){for(const o of t){if(!o||o.visible===!1||B.isGizmo(o)||n.lineThreshold!==void 0&&n.lineThreshold<0&&o instanceof c.Line)continue;let r=!0;const a=o,l=a.geometry,h=!l&&o.raycast!==c.Object3D.prototype.raycast;if(o.raycastAllowed===!1&&(r=!1),r&&n.testObject){const d=n.testObject?.(o);if(d===!1)continue;d==="continue in children"&&(r=!1)}else r&&(!l&&!h||l&&!Hv(l))&&(r=!1);if(r){const d=i.length;if(h)e.intersectObject(a,!1,i);else{const u=o.raycastPreference||"lod";let f=u!=="bounds";if(n.precise===!1&&(f=!1),l&&(f||=l.getAttribute("position")?.array?.length<64),a instanceof V.GroundedSkybox&&(f=!1),u==="lod"){const m=re.getRaycastMesh(o);m&&(a.geometry=m)}!f&&gE(a,e,i)||(n.useAcceleratedRaycast!==!1?nf.runMeshBVHRaycast(e,a,i,this.context,n):e.intersectObject(a,!1,i)),a.geometry=l}if(Yt&&i.length!=d){const u=i[i.length-1];B.DrawWireSphere(u.point,.1,7798784,1,!1),B.DrawWireMesh({mesh:o,depthTest:!1,duration:.2,color:7798784})}}n.recursive!==!1&&this.intersect(e,o.children,i,n)}return i}tempBoundingBox=new c.Box3;intersectSphere(e,t,i,n,o,r,a,l){let h=e&&e.isMesh&&e.layers.test(n)&&!B.isGizmo(e);h&&=e.visible,h&&=!(e instanceof c.Line),h&&=!(e instanceof V.GroundedSkybox);const d=e,u=d.geometry;if(h&&l){const f=l(e);if(f===!1)return;f==="continue in children"&&(h=!1)}if(u&&Hv(u)||(h=!1),h){if(a){const f=this.sphere;f.center.copy(t),f.radius=i;const m=o.length;if(nf.runMeshBVHRaycast(this.sphere,d,o,this.context,{}),m!=o.length&&!r)return}else if(u.boundingBox||u.computeBoundingBox(),u.boundingBox){d.matrixWorldNeedsUpdate&&d.updateWorldMatrix(!1,!1);const f=this.tempBoundingBox.copy(u.boundingBox).applyMatrix4(d.matrixWorld),m=this.sphere;if(m.center.copy(t),m.radius=i,m.intersectsBox(f)){const g=ie(e),v=g.distanceTo(m.center),_=new o_(e,v,g);if(o.push(_),!r)return}}}if(e.children)for(const f of e.children){const m=o.length;if(this.intersectSphere(f,t,i,n,o,r,a,l),m!=o.length&&!r)return}}}function Hv(s){return!(s.index&&s.index.array.length<3)}const Jo=new c.Sphere,Td=new c.Plane,mE=new c.Matrix3;function gE(s,e,t){const i=s._computeIntersections;if(!i)return!1;let n=s["_computeIntersections:Needle"];return n||(n=s["_computeIntersections:Needle"]=function(o,r,a){const l=this,h=l.geometry.boundingSphere;if(h){if(l instanceof V.GroundedSkybox){Td.setFromNormalAndCoplanarPoint(F(0,1,0),F(0,-l.position.y,0)),Td.applyMatrix4(l.matrixWorld,mE);const u=o.ray.intersectPlane(Td,F());if(u){Jo.copy(h),Jo.applyMatrix4(l.matrixWorld);const m=F(u).sub(o.ray.origin).length(),g=Jo.radius*.5;m<g&&r.push({distance:m,point:u,object:l,normal:Td.normal.clone()})}return}Jo.copy(h),Jo.applyMatrix4(l.matrixWorld);const d=o.ray.intersectSphere(Jo,F());if(d){const u=F(d).sub(o.ray.origin),f=u.length();if(f>Jo.radius){const m=u.clone().normalize();r.push({distance:f,point:d,object:l,normal:m})}}}}),s._computeIntersections=n,e.intersectObject(s,!1,t),s._computeIntersections=i,!0}function Fg(s,e){const t=s.children;s.children=[];try{return e()}finally{s.children=t}}var nf;(s=>{let e=0;function t(b,w,C,k,O){if(!w.geometry||!w.geometry.hasAttribute("position"))return!1;const D=w.geometry;if(w?.isSkinnedMesh){const I=w,j=I.bvhNeedsUpdate;if(!I.staticGenerator)l(),r&&(Fg(w,()=>{I.staticGenerator=new r(w),I.staticGenerator.applyWorldTransforms=!1,I.staticGeometry=I.staticGenerator.generate()}),D.boundsTree=a?.call(I.staticGeometry),I.staticGeometryLastUpdate=performance.now()+Math.random()*200,I.bvhNeedsUpdate=!0);else if(D.boundsTree&&(I.autoUpdateMeshBvhInterval!==void 0&&I.autoUpdateMeshBvhInterval>=0||j===!0)){const $=performance.now(),W=$-I.staticGeometryLastUpdate,R=I.autoUpdateMeshBvhInterval??100;(j||W>R)&&(Yt&&console.warn(`Physics: updating skinned mesh bvh for ${w.name} after ${W.toFixed(2)}ms`),I.bvhNeedsUpdate=!1,I.staticGeometryLastUpdate=$,Fg(w,()=>I.staticGenerator?.generate(I.staticGeometry)),D.boundsTree.refit())}}else if(!D.boundsTree){d||y();let I=!0;if((k.xr||D[g]===!1||D.getAttribute("position")?.isInterleavedBufferAttribute||D.index&&D.index?.isInterleavedBufferAttribute||e>10)&&(I=!1),I&&f){if(D[m]===void 0){let j=null;if(_.length>0){const $=_.shift();$&&!$.running&&(j=$)}if(!j&&v.length<3)try{pE&&console.warn("[GenerateMeshBVHWorker] Creating worker with import.meta.url:",typeof document>"u"?require("url").pathToFileURL(__filename).href:Ha&&Ha.tagName.toUpperCase()==="SCRIPT"&&Ha.src||new URL("needle-engine.bundle-D3nBMgfk.umd.cjs",document.baseURI).href),j=new f,v.push(j)}catch($){$ instanceof DOMException&&$.name==="SecurityError"?(console.warn("Failed to create MeshBVH worker, falling back to main thread generation. This can happen when running from file://, if the browser does not support workers or if the browser is blocking workers for other reasons."),console.debug($),e+=10):(console.error("Failed to create MeshBVH worker. Please see below for more details:"),console.log($)),e++}if(j!=null&&!j.running){const $=w.name;Yt&&console.log("<<<< worker start",$,j),D[m]="queued",performance.mark("bvh.create.start");const W=D.clone();try{j.generate(W).then(R=>{D[m]="done",D.boundsTree=R}).catch(R=>{D[m]="failed - "+R?.message,D[g]=!1,Yt&&console.error("Failed to generate mesh bvh on worker",R)}).finally(()=>{Yt&&console.log(">>>>> worker done",$,{hasBoundsTre:D.boundsTree!=null}),_.push(j),W.dispose(),performance.mark("bvh.create.end"),performance.measure("bvh.create (worker)","bvh.create.start","bvh.create.end")})}catch(R){console.error("Failed to generate mesh bvh on worker",R)}}else Yt&&console.warn("No worker available")}}else(!u||!I)&&(l(),o&&(performance.mark("bvh.create.start"),D.boundsTree=new o(D),performance.mark("bvh.create.end"),performance.measure("bvh.create","bvh.create.start","bvh.create.end")))}if(b instanceof c.Raycaster){const I=b,j=w.raycast;if(D.boundsTree)l(),n&&(w.acceleratedRaycast||(w.acceleratedRaycast=n.bind(w),Yt&&console.debug(`Physics: bind acceleratedRaycast fn to "${w.name}"`)),w.raycast=w.acceleratedRaycast);else if(Yt&&console.warn("No bounds tree found for mesh",w.name,{workerTask:D[m],hasAcceleratedRaycast:n!=null}),O.allowSlowRaycastFallback===!1&&(D.getAttribute("position")?.array?.length??0)>2e3)return Yt&&console.warn("Skipping raycast because no bounds tree is available and allowSlowRaycastFallback is false"),!1;const $=I.firstHitOnly;return I.firstHitOnly=!1,I.intersectObject(w,!1,C),I.firstHitOnly=$,w.raycast=j,!0}else if(b instanceof c.Sphere){const I=D.boundsTree;if(I){const j=b;if(h.copy(w.matrixWorld).invert(),j.applyMatrix4(h),I.intersectsSphere(j)){const W=ie(w),R=W.distanceTo(j.center),U=new o_(w,R,W);C.push(U)}}return!0}return!1}s.runMeshBVHRaycast=t;let i=!1,n=null,o=null,r=null,a=null;function l(){i||(i=!0,Promise.resolve().then(()=>require("./vendor-BJviq-Oq.umd.cjs")).then(b=>b.index$1).then(b=>{n=b.acceleratedRaycast,o=b.MeshBVH,r=b.StaticGeometryGenerator,a=b.computeBoundsTree}).catch(b=>{(Yt||E())&&console.error("Failed to load BVH library...",b.message)}))}const h=new c.Matrix4;let d=!1,u=!1,f=null;const m=Symbol("Needle:MeshBVH-Worker"),g=Symbol("Needle:MeshBVH-CanUseWorker"),v=[],_=[];function y(){d=!0,u=!0,Promise.resolve().then(()=>z3).then(b=>{f=b.GenerateMeshBVHWorker}).catch(b=>{Yt||E()?console.warn("Failed to setup mesh bvh worker"):console.debug("Failed to setup mesh bvh worker",b)}).finally(()=>{u=!1})}})(nf||(nf={}));const qv=Symbol("gltf-loader-internal-usage-tracker"),yE=x("debugusers");class Za{get name(){return"NEEDLE_internal_usage_tracker"}static isLoading(e){return Za._loadingProcesses>0}static _loadingProcesses=0;parser;_getDependency;_loadingId;_loadedObjects=new Set;constructor(e){this.parser=e,this._getDependency=this.parser.getDependency,this._loadingId=Date.now().toString()}beforeRoot(){Za._loadingProcesses++;const e=this,t=this._getDependency;return this.parser.getDependency=function(i,n){const o=t.call(this,i,n);return o.then(r=>(r&&(e._loadedObjects.add(r),r[qv]=e._loadingId),r)),o},null}afterRoot(e){Za._loadingProcesses--,this.parser.getDependency=this._getDependency;for(const t of this._loadedObjects)delete t[qv],t instanceof c.Object3D&&(t.parent||t instanceof c.Mesh&&setTimeout(()=>{yE&&console.warn("> GLTF LOADER: Mesh not used in scene!",t),t.material=null,t.geometry=null},1e3));return null}}class CS{constructor(){window.addEventListener("unhandledrejection",e=>{if(e.defaultPrevented)return;const t=e?.reason?.path;if(t){const i=t[0];i&&i.tagName==="IMG"&&(console.warn(`Could not load image:
883
883
  `+i.src),e.preventDefault())}})}}const Nf=x("trackresources");function PS(){return Nf==="dispose"}let Nr=!0;Nf===0&&(Nr=!1);function _E(s){Nr=s}function kS(){return Nr}const MS=Symbol("disposable");function OS(s,e){s&&(s[MS]=e,Cr&&console.warn("Set disposable",e,s))}const ES=Symbol("disposed");function bE(s){return s[ES]===!0}function Oe(s){if(s){if(s[MS]===!1){Cr&&console.warn("Object is marked as not disposable",s);return}if(typeof s=="object"&&(s[ES]=!0),s instanceof c.Scene)Oe(s.environment),Oe(s.background),Oe(s.customDepthMaterial),Oe(s.customDistanceMaterial);else if(s instanceof c.SkinnedMesh)Oe(s.geometry),Oe(s.material),Oe(s.skeleton),Oe(s.bindMatrix),Oe(s.bindMatrixInverse),Oe(s.customDepthMaterial),Oe(s.customDistanceMaterial),s.visible=!1;else if(s instanceof c.Mesh)Oe(s.geometry),Oe(s.material),Oe(s.customDepthMaterial),Oe(s.customDistanceMaterial),s.visible=!1;else if(s instanceof c.Object3D)s.visible=!1;else if(s instanceof c.BufferGeometry){ya(s);for(const e of Object.keys(s.attributes)){const t=s.attributes[e];Oe(t)}}else if(s instanceof c.BufferAttribute||s instanceof c.InterleavedBufferAttribute)Cr&&console.warn("BufferAttribute dispose not supported",s.count);else if(s instanceof Array)for(const e of s)e instanceof c.Material&&Oe(e);else if(s instanceof c.Material){ya(s);for(const t of Object.keys(s)){const i=s[t];i instanceof c.Texture&&Oe(i)}const e=s.uniforms;if(e)for(const t of Object.keys(e)){const i=e[t];i instanceof c.Texture?Oe(i):i instanceof c.Uniform&&Oe(i.value)}}else s instanceof c.Texture?(ya(s),ya(s.source),s.source?.data instanceof ImageBitmap&&ya(s.source.data)):s instanceof c.Skeleton?(ya(s.boneTexture),s.boneTexture=null):s instanceof c.Bone||!(s instanceof c.Object3D)&&Cr&&console.warn("Unknown object type",s)}}function ya(s){s&&((Cr||PS()||Nf)&&console.warn("🧨 FREE",s),s instanceof ImageBitmap||"dispose"in s&&typeof s.dispose=="function"&&s.dispose())}function vE(s){}const wE=new Set;function r_(s,e,t=null,i){if(i||(i=wE,i.clear()),!s)return i;const n=s[oh];if(n)for(const o of n)i.has(o)||t?.call(null,o)!==!1&&(i.add(o),e&&r_(o,!0,t,i));return i}function xE(s){return s[Sc]}const Cr=x("debugresourceusers")||x("debugmemory"),oh=Symbol("needle-resource-users"),Sc=Symbol("needle-resource-users-count");function Gt(s,e){Tf(s,e,function(t,i){Nr&&!pl.raycasting&&(sf(oh,this,t,!1),sf(oh,this,i,!0))})}Nr&&(Gt(c.Mesh.prototype,"material"),Gt(c.Mesh.prototype,"geometry"),Gt(c.Material.prototype,"map"),Gt(c.Material.prototype,"bumpMap"),Gt(c.Material.prototype,"alphaMap"),Gt(c.Material.prototype,"normalMap"),Gt(c.Material.prototype,"displacementMap"),Gt(c.Material.prototype,"roughnessMap"),Gt(c.Material.prototype,"metalnessMap"),Gt(c.Material.prototype,"emissiveMap"),Gt(c.Material.prototype,"specularMap"),Gt(c.Material.prototype,"envMap"),Gt(c.Material.prototype,"lightMap"),Gt(c.Material.prototype,"aoMap"),Gt(c.Material.prototype,"gradientMap"));function SE(s){if(Nr===!1)return;const e=s[oh];if(e)for(const t of e)sf(oh,t,s,!1)}Nr&&Tf(c.Material.prototype,"dispose",function(){SE(this)});let jg=0;function sf(s,e,t,i){if(jg>0)return;if(Array.isArray(t)){for(const o of t)sf(s,e,o,i);return}if(!t)return;let n=t[s];if(n||(n=new Set),i){if(e&&!n.has(e)){n.add(e);let o=t[Sc]||0;o+=1,t[Sc]=o,Cr&&console.warn(`🟢 Added user of "${t.type}"`,e,t,o,"users:",n)}}else if(e&&n.has(e)){n.delete(e);let o=t[Sc]||0;o>0&&(o-=1,t[Sc]=o),Cr&&console.warn(`🔴 Removed user of "${t.type}"`,e,t,o,"users:",n),o<=0&&(Za.isLoading(t)||(Nf&&console.warn(`🔴 Removed all user of "${t.type}"`,t),PS()&&Oe(t)))}t[s]=n}try{Tf(c.WebGLRenderer.prototype,"render",function(){jg++},function(){jg--})}catch(s){console.warn("Could not wrap WebGLRenderer.render",s)}const rh=Symbol("NEEDLE_NEED_UPDATE_INSTANCE"),RS=Symbol("isUsingInstancing"),TS=Symbol("instancingRenderer"),Cc=Symbol("instancingAutoUpdateBounds");class Ki{static isUsingInstancing(e){return e[RS]===!0}static getRenderer(e){return e[TS]||null}setAutoUpdateBounds(e,t){const i=Ki.getRenderer(e);i&&(i[Cc]=t)}static markDirty(e,t=!0){if(e&&(this.isUsingInstancing(e)&&(e[rh]=!0,e.matrixWorldNeedsUpdate=!0),t))for(const i of e.children)Ki.markDirty(i,!0)}}const ko=x("debuginstantiate"),_a=new Map,ah=Symbol("original-component-name");function Ug(s,e,t){if(e===null||!s)return;const i=s.guid,n=s.guid;n?.length&&(_a.has(n)||(ko&&console.log('Creating InstanceIdProvider with key "'+n+'" for object '+s.name),_a.set(n,new ot(n))));const o=n&&_a.get(n)||e;if(s.guid=o.generateUUID(),i&&i!=="invalid"&&(t[i]=s.guid),s&&s.userData&&s.userData.components)for(const r of s.userData.components){if(r===null)continue;const a=r.guid;a?_a.has(a)||(ko&&console.log('Creating InstanceIdProvider with key "'+a+'" for component '+r[ah]),_a.set(a,new ot(a))):ko&&console.warn("Can not create IdProvider: component "+r[ah]+" has no guid",r.guid);const l=_a.get(a)||e,h=r.guid;r.guid=l.generateUUID(),h&&h!=="invalid"&&(t[h]=r.guid)}if(s.children)for(const r of s.children)Ug(r,e,t)}function CE(s){for(const e in s){const i=s[e].clone;if(!(!i?.isObject3D||!i?.userData?.components))for(let n=0;n<i.userData.components.length;n++){const o=i.userData.components[n],r=Object.entries(o);for(const[a,l]of r){if(l==null||a==="guid"||a===Rs||typeof l!="object"&&typeof l!="string")continue;const h=Dr(a,l,s);h!==void 0&&(o[a]=h)}}}}let wi=null;function Xv(s,e){if(!ko){zg(s,e);return}wi={objects:0,components:0,props:0,remapped:0};const t=typeof performance<"u"?performance.now():Date.now();zg(s,e);const i=(typeof performance<"u"?performance.now():Date.now())-t,n=wi;wi=null,console.log(`[resolveStringGuids] root="${s.name}" objects=${n.objects} components=${n.components} propsVisited=${n.props} remapped=${n.remapped} mapSize=${Object.keys(e).length} in ${i.toFixed(2)}ms`)}function zg(s,e){if(wi&&wi.objects++,s.userData?.components)for(const t of s.userData.components)t!==null&&(wi&&wi.components++,Ng(t,e));if(s.children)for(const t of s.children)zg(t,e)}function Ng(s,e,t){if(t||(t=new WeakSet),!t.has(s)){t.add(s);for(const i of Object.keys(s)){wi&&wi.props++;const n=s[i];if(n!=null)if(typeof n=="string"){const o=e[n];o&&(s[i]=o,wi&&wi.remapped++)}else if(Array.isArray(n))for(let o=0;o<n.length;o++){const r=n[o];if(typeof r=="string"){const a=e[r];a&&(n[o]=a,wi&&wi.remapped++)}else(Array.isArray(r)||$g(r))&&Ng(r,e,t)}else $g(n)&&Ng(n,e,t)}}}function Dr(s,e,t){if(e!==void 0){if(e===null)return null;if(typeof e=="string"){const i=t[e];return i?i.clone:void 0}if(typeof e=="object"){if(Af(e))return PE(e,t);if(e.isObject3D===!0){if(s==="gameObject")return;const i=e.uuid,n=t[i]?.clone;return n?(ko&&console.log(s,"old",e,"new",n),n):void 0}if(TE(e))return e.clone();if(Array.isArray(e))return kE(s,e,t);if(e instanceof Map)return ME(e,t);if(e instanceof Set)return OE(e,t);if(!(e instanceof WeakMap||e instanceof WeakSet)){if(kM(e)&&e.$serializedTypes)return EE(e,t);if($g(e))return RE(s,e,t)}}}}function PE(s,e){const t=s.gameObject;if(!t)return;const i=t.uuid,n=e[i]?.clone;if(!n){ko&&console.log("Component reference did not change (external)",s);return}const o=t.userData.components.indexOf(s);if(o>=0&&n.isObject3D)return ko&&console.log("Resolved component",i,"at index",o),n.userData.components[o];console.warn("Could not find component at expected index",s)}function kE(s,e,t){const i=[];for(let n=0;n<e.length;n++){const o=e[n];if(o==null){i.push(o);continue}if(typeof o!="object"&&typeof o!="string"){i.push(o);continue}const r=Dr(s,o,t);i.push(r!==void 0?r:o)}return i}function ME(s,e){const t=new Map;let i=!1;for(const[n,o]of s){let r=n,a=o;if(typeof n=="object"&&n!==null){const l=Dr("",n,e);l!==void 0&&(r=l,i=!0)}if(typeof o=="object"&&o!==null){const l=Dr("",o,e);l!==void 0&&(a=l,i=!0)}t.set(r,a)}return t}function OE(s,e){const t=new Set;for(const i of s)if(typeof i=="object"&&i!==null){const n=Dr("",i,e);t.add(n!==void 0?n:i)}else t.add(i);return t}function EE(s,e){const t=Object.assign(Object.create(Object.getPrototypeOf(s)),s);let i=!1;for(const n in t.$serializedTypes){const o=t[n];if(o!=null&&typeof o=="object"){ko&&console.log("Recursively resolve references for",n,o);const r=Dr(n,o,e);r!==void 0&&(t[n]=r,i=!0)}}return i?t:void 0}function RE(s,e,t){let i=!1;const n={...e};for(const o of Object.keys(n)){const r=n[o];if(r==null||typeof r!="object"&&typeof r!="string")continue;const a=Dr(o,r,t);a!==void 0&&(n[o]=a,i=!0)}return i?n:void 0}function $g(s){if(typeof s!="object"||s===null)return!1;const e=Object.getPrototypeOf(s);return e===Object.prototype||e===null}function TE(s){return s.isVector2===!0||s.isVector3===!0||s.isVector4===!0||s.isQuaternion===!0||s.isEuler===!0||s.isColor===!0||s.isMatrix2===!0||s.isMatrix3===!0||s.isMatrix4===!0}const AS=new Map;function DS(s,e){if(!s)return;if(!e){console.warn("No prototype found",s,s.prototype,s.constructor);return}const t=AS.get(e);t&&t.apply(s)}function a_(s){const e=AE(s.prototype);AS.set(s,e)}function AE(s){return new DE(s)}class DE{$symbol;extensions;descriptors;constructor(e){this.$symbol=Symbol("prototype-extension"),this.extensions=Object.keys(e),this.descriptors=new Array;for(let t=0;t<this.extensions.length;t++){const i=this.extensions[t],n=Object.getOwnPropertyDescriptor(e,i);n&&this.descriptors.push(n)}}apply(e){if(!e[this.$symbol]){e[this.$symbol]=!0;for(let t=0;t<this.extensions.length;t++){const i=this.extensions[t],n=this.descriptors[t];n&&Object.defineProperty(e,i,n)}}}}function lh(s){s&&s.isObject3D===!0&&DS(s,c.Object3D)}let Qv=!1;function IE(){if(Qv)return;if(Qv=!0,By.experimentalSmartHierarchyUpdate){const i=c.Object3D.prototype.add;c.Object3D.prototype.add=function(...r){return Ja(),i.apply(this,r)};const n=c.Object3D.prototype.attach;c.Object3D.prototype.attach=function(...r){return Ja(),n.apply(this,r)};const o=c.Object3D.prototype.remove;c.Object3D.prototype.remove=function(...r){return Ja(),o.apply(this,r)}}c.Object3D.prototype.SetActive=function(i){this.visible=i},c.Object3D.prototype.setActive=function(i){this.visible=i},c.Object3D.prototype.destroy=function(){fi(this)},c.Object3D.prototype.addComponent=function(i,n){return ss(this,i,n)},c.Object3D.prototype.addNewComponent=function(i,n){return ss(this,i,n)},c.Object3D.prototype.removeComponent=function(i){return Wf(this,i)},c.Object3D.prototype.getOrAddComponent=function(i,n){return Th(this,i,n)},c.Object3D.prototype.getComponent=function(i){return Bs(this,i)},c.Object3D.prototype.getComponents=function(i,n){return Cl(this,i,n)},c.Object3D.prototype.getComponentInChildren=function(i,n=!1){return Ah(this,i,n)},c.Object3D.prototype.getComponentsInChildren=function(i,n){return Pl(this,i,n)},c.Object3D.prototype.getComponentInParent=function(i,n=!1){return ch(this,i,n)},c.Object3D.prototype.getComponentsInParent=function(i,n){return Gf(this,i,n)},Object.getOwnPropertyDescriptor(c.Object3D.prototype,"activeSelf")||Object.defineProperty(c.Object3D.prototype,"activeSelf",{get:function(){return Sl(this)},set:function(i){Pr(this,i)}}),Object.getOwnPropertyDescriptor(c.Object3D.prototype,"raycastAllowed")||Object.defineProperty(c.Object3D.prototype,"raycastAllowed",{get:function(){return this.userData&&this.userData.raycastAllowed!==!1},set:function(i){const n=this;n.userData||(n.userData={}),n.userData.raycastAllowed=i}}),Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldPosition")||Object.defineProperty(c.Object3D.prototype,"worldPosition",{get:function(){return this instanceof V.TransformControlsGizmo?ie(this.object):ie(this)},set:function(i){Oi(this,i)}}),Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldQuaternion")||Object.defineProperty(c.Object3D.prototype,"worldQuaternion",{get:function(){return this instanceof V.TransformControlsGizmo?Se(this.object):Se(this)},set:function(i){vn(this,i)}}),Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldRotation")||Object.defineProperty(c.Object3D.prototype,"worldRotation",{get:function(){return Of(this)},set:function(i){Qw(this,i)}}),Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldScale")||Object.defineProperty(c.Object3D.prototype,"worldScale",{get:function(){return Ve(this)},set:function(i){rl(this,i)}});const s=new c.Matrix4,e=new c.Vector3(0,0,0),t=new c.Vector3(0,1,0);Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldForward")||Object.defineProperty(c.Object3D.prototype,"worldForward",{get:function(){return F().set(0,0,1).applyQuaternion(Se(this))},set:function(i){const n=ci().setFromRotationMatrix(s.lookAt(e.set(0,0,0),i,t.set(0,1,0)));this.worldQuaternion=n}}),Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldRight")||Object.defineProperty(c.Object3D.prototype,"worldRight",{get:function(){return F().set(1,0,0).applyQuaternion(Se(this))}}),Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldUp")||Object.defineProperty(c.Object3D.prototype,"worldUp",{get:function(){return F().set(0,1,0).applyQuaternion(Se(this))}}),Object.getOwnPropertyDescriptor(c.Object3D.prototype,"contains")||Object.defineProperty(c.Object3D.prototype,"contains",{value:function(i){if(!i)return!1;if(this===i)return!0;for(const n of this.children)if(n.contains(i))return!0;return!1}}),a_(c.Object3D)}const Pu=x("debuggetcomponent"),LE=x("debuginstantiate");class hs{idProvider;parent;keepWorldPosition;position;rotation;scale;visible;context;components;clone(){const e=new hs;return e.idProvider=this.idProvider,e.parent=this.parent,e.keepWorldPosition=this.keepWorldPosition,e.position=Array.isArray(this.position)?[...this.position]:this.position?.clone(),e.rotation=Array.isArray(this.rotation)?[...this.rotation]:this.rotation?.clone(),e.scale=Array.isArray(this.scale)?[...this.scale]:this.scale?.clone(),e.visible=this.visible,e.context=this.context,e.components=this.components,e}cloneAssign(e){this.idProvider=e.idProvider,this.parent=e.parent,this.keepWorldPosition=e.keepWorldPosition,this.position=Array.isArray(e.position)?[...e.position]:e.position?.clone(),this.rotation=Array.isArray(e.rotation)?[...e.rotation]:e.rotation?.clone(),this.scale=Array.isArray(e.scale)?[...e.scale]:e.scale?.clone(),this.visible=e.visible,this.context=e.context,this.components=e.components}}function Sl(s){return s.visible}function Pr(s,e){return typeof e=="number"&&(e=e>.5),s.visible=e,s.visible}function IS(s){return s[Zn]||$f(s)}function LS(s,e){s[RS]=e}function $f(s){return Ki.isUsingInstancing(s)}function l_(s,e){return Kc(s,e,!0,!0)}const BS=Symbol("isDestroyed");function Ao(s){return s[BS]}function FS(s,e){s[BS]=e}const Vg=Symbol("isDontDestroy");function Ea(s,e=!0){s[Vg]=e}const ku=[],Mu=[];function fi(s,e=!0,t=!1){ku.length=0,Mu.length=0,Wg(s,e,!0);for(const i of ku)i.gameObject=null,i.context=null;for(const i of Mu)FS(i,!0),t&&Oe(i);Mu.length=0,ku.length=0}function Wg(s,e=!0,t=!0){if(s==null)return;const i=s;if(i.isComponent){if(i[Vg])return;ku.push(i);const r=i.gameObject;i.__internalDisable?.(),i.__internalDestroy?.(),i.gameObject=r;return}if(s[Vg])return;const n=s;Pu&&console.log(n),Mu.push(n);const o=n.userData?.components;if(o!=null&&Array.isArray(o)){let r=o.length;for(let a=0;a<o.length;a++){const l=o[a];Wg(l,e,!1),o.length<r&&(r=o.length,a--)}}if(e&&n.children)for(const r of n.children)Wg(r,e,!1);t&&n.removeFromParent()}function xn(s,e,t=!0){return jS(s,e,t)}function*c_(s,e,t=!1,i=999,n=0){if(s?.userData.components&&!(n>i)){for(const o of s.userData.components)e&&o?.isComponent===!0&&o instanceof e?yield o:yield o;if(t===!0)for(const o of s.children)yield*c_(o,e,!0,i,n+1)}}function jS(s,e,t,i=0){if(s){if(s.isObject3D,i>1e3){console.warn("Failed to iterate components: too many levels");return}if(s.userData?.components)for(let n=0;n<s.userData.components.length;n++){const o=s.userData.components[n];if(o?.isComponent===!0){const r=e(o);if(r!==void 0)return r}}if(t&&s.children){const n=i+1;for(let o=0;o<s.children.length;o++){const r=s.children[o];if(!r)continue;const a=jS(r,e,t,n);if(a!==void 0)return a}}}}function Ls(s,e){if("isAssetReference"in s)return s.instantiate(e??void 0);let t=null;e!=null&&(e.x!==void 0?(t=new hs,t.position=e):t=e);let i=X.Current;t?.context&&(i=t.context),Pu&&i.alias&&console.log("context",i.alias),t&&!t.idProvider&&(t.idProvider=new ot(Date.now()));const n=[],o={},r={},a=US(i,s,t,n,o,r);a&&(CE(o),jE(r,o),FE(o)),Pu&&($u(s,!0),$u(a,!0));const l={};for(const h in o){const d=o[h],u=d.original,f=d.clone;u instanceof c.Object3D&&f instanceof c.Object3D&&(l[u.guid||u.uuid]=f.guid||f.uuid)}if(t?.components!==!1){const h=new Set;for(const d in n){const u=n[d],f=u.guid;if(t&&t.idProvider){const m=u[Rs],g=typeof m=="string"&&m.length>0?m:f;if(u.guid=g&&t.idProvider.remapUUID?t.idProvider.remapUUID(g):t.idProvider.generateUUID(),h.has(u.guid))if(console.warn(`[instantiate] duplicate component guid in source content ("${g}") — deriving a disambiguated guid. Fix the source: two components must not share a guid.`),t.idProvider.remapUUID&&g){let v=1;do u.guid=t.idProvider.remapUUID(`${g}:dup:${v++}`);while(h.has(u.guid))}else u.guid=t.idProvider.generateUUID();h.add(u.guid),l[f]=u.guid,g!==f&&(l[g]=u.guid),Pu&&console.log(u.name,u.guid)}zf(u,i),u.__internalNewInstanceCreated&&u.__internalNewInstanceCreated()}for(const d in n){const u=n[d];u.enabled!==!1&&(u.enabled=!0)}of(i)}return a}function US(s,e,t,i,n,o){if(!e||e[xi]||e instanceof c.Audio||e instanceof c.AudioListener||e.hideFlags&as.DontInstantiate)return null;const r=e.userData;e.userData={};const a=e.children;e.children=[];const l=e.clone(!1);lh(l),e.userData=r,e.children=a;const h={original:e,clone:l};if(n[e.uuid]=h,e.guid&&e.guid!==e.uuid&&(n[e.guid]=h),LE&&console.log("ADD",e,l),e.type==="SkinnedMesh"&&(o[e.uuid]={original:e,clone:l}),t?.visible!==void 0&&(l.visible=t.visible),t?.idProvider){const u=e.userData?.["needle-id"];l.uuid=u&&t.idProvider.remapUUID?t.idProvider.remapUUID(u):t.idProvider.generateUUID();const f=l;f&&(f.guid=l.uuid)}e.animations&&e.animations.length>0&&(l.animations=[...e.animations]);const d=e.parent;if(d&&d.add(l),t?.position)if(Array.isArray(t.position)){const u=new c.Vector3;u.fromArray(t.position),l.worldPosition=u}else l.worldPosition=t.position;else l.position.copy(e.position);if(t?.rotation){if(t.rotation instanceof c.Quaternion)l.worldQuaternion=t.rotation;else if(t.rotation instanceof c.Euler)l.worldQuaternion=ci().setFromEuler(t.rotation);else if(Array.isArray(t.rotation)){const u=new c.Euler;u.fromArray(t.rotation),l.worldQuaternion=ci().setFromEuler(u)}}else l.quaternion.copy(e.quaternion);if(t?.scale)if(Array.isArray(t.scale)){const u=new c.Vector3;u.fromArray(t.scale),t.scale=u}else l.scale.copy(t.scale);else l.scale.copy(e.scale);if(t?.parent&&t.parent!=="scene"){let u=null;if(typeof t.parent=="string"?u=Kc(t.parent,s.scene,!0):u=t.parent,u){const f=t.keepWorldPosition===!0?u.attach:u.add;f?f.call(u,l):console.error("Invalid parent object",u,"received when instantiating:",e)}else console.warn("could not find parent:",t.parent)}for(const[u,f]of Object.entries(e.userData))u!=="components"&&(l.userData[u]=f);if(e.userData?.components){const u=e.userData.components,f=[];l.userData.components=f;for(let m=0;m<u.length;m++){const g=u[m],v=new g.constructor;BE(g,v),g[Rs]!==void 0&&(v[Rs]=g[Rs]),f.push(v),v.gameObject=l,i.push(v),n[g.guid]={original:g,clone:v},Rf.dispatchComponentLifecycleEvent("component-added",v)}}t&&(t.position=void 0,t.rotation=void 0,t.scale=void 0,t.parent=void 0,t.visible=void 0);for(const u in e.children){const f=e.children[u],m=US(s,f,t,i,n,o);m&&(n[m.uuid]={original:f,clone:m},l.add(m))}return l}function BE(s,e,t){cl(e,s,void 0,{})}function FE(s){for(const e in s){const t=s[e],i=t.original;if(i.isDirectionalLight!==!0&&i.isSpotLight!==!0)continue;const n=i.target;if(!n||n.parent!==i)continue;const o=Object.values(s).find(a=>a.original===n);if(!o)continue;const r=o.clone;t.clone.target=r,r.hideFlags|=as.DontExport}}function jE(s,e){for(const t in s){const i=s[t],n=i.original,o=n.skeleton,r=i.clone;if(!o){console.warn("Skinned mesh has no skeleton?",i);continue}const a=o.bones,l=r.skeleton.clone();r.skeleton=l,r.bindMatrix.clone().copy(n.bindMatrix),r.bindMatrixInverse.copy(n.bindMatrixInverse);const h=[];l.bones=h;for(let d=0;d<a.length;d++){const u=a[d],m=e[u.uuid].clone;h.push(m)}}for(const t in s){const i=s[t].clone;i.skeleton.update(),i.bind(i.skeleton,i.bindMatrix),i.updateMatrixWorld(!0)}}function zc(s,e){try{e||s()}catch(t){return console.error(t),!1}return!0}const Gg=x("debugnewscripts"),UE=x("debughierarchy"),Te=[];function zE(){return Te.length>0}function of(s){if(Gg&&console.log("Register new components",s.new_scripts.length,[...s.new_scripts],s.alias?"element: "+s.alias:s.hash,s),zS(s),!(s.new_scripts.length<=0)){Te.length=0,s.new_scripts.length>0&&Te.push(...s.new_scripts),s.new_scripts.length=0;for(let e=0;e<Te.length;e++)try{const t=Te[e];if(t.isComponent!==!0){(E()||Gg)&&console.error(`Registered script is not a Needle Engine component.
884
884
  The script will be ignored. Please make sure your component extends "Behaviour" imported from "@needle-tools/engine"
885
885
  `,t),Te.splice(e,1),e--;continue}if(t.destroyed)continue;if(!t.gameObject){console.warn(`Component can not be initialized: no GameObject assigned.
@@ -1062,7 +1062,7 @@ ${NR}
1062
1062
  // gl_FragColor = vec4(blurAmount, 0.0, 0.0, 1.0);
1063
1063
  }
1064
1064
  `,c0=new Map;function gm(s,...e){const n=typeof performance<"u"?performance.now():Date.now();let o=c0.get(s);o||(o={count:0,mutedUntil:0},c0.set(s,o)),!(n<o.mutedUntil)&&(console.warn(...e),++o.count>=5&&(o.mutedUntil=n+1e4,o.count=0))}function aC(s){if(N.active)return console.warn("[OrbitControls] Can not fit camera while XR session is active"),null;const e=X.Current;if(!e)return console.warn("[OrbitControls] No context found"),null;const t=s?.camera||e.mainCamera;if(!t)return console.warn("No camera or controls found to fit camera to objects..."),null;s||(s={}),s.autoApply=s.autoApply!==!1,s.minZoom||=0,s.maxZoom||=1/0;const{centerCamera:i,cameraNearFar:n="auto",fitOffset:o=1.1,fov:r=t instanceof c.PerspectiveCamera?t?.fov:-1}=s,a=new c.Vector3,l=new c.Vector3,h=t instanceof c.PerspectiveCamera?t.aspect:1,d=s.objects||e.scene,u=pi(d,[t],t?.layers),f=u.clone();u.getCenter(l);const m=new c.Vector3;if(u.getSize(m),u.isEmpty()||!Number.isFinite(m.x)||!Number.isFinite(m.y)||!Number.isFinite(m.z))return gm("fit-empty","Camera fit skipped: no fittable content in the scene",u),null;if(t instanceof c.PerspectiveCamera&&t.updateProjectionMatrix(),t.updateMatrixWorld(),u.applyMatrix4(t.matrixWorldInverse),u.getSize(a),u.setFromCenterAndSize(l,a),Number.isNaN(a.x)||Number.isNaN(a.y)||Number.isNaN(a.z))return gm("fit-nan","Camera fit size resulted in NaN",t,u),null;if(a.length()<=1e-10)return gm("fit-zero","Camera fit size is zero",u),null;const g=r,v=2*Math.atan(Math.tan(g*Math.PI/360/2)*h)/Math.PI*360,_=a.y/(2*Math.atan(Math.PI*g/360)),y=a.x/(2*Math.atan(Math.PI*v/360)),b=o*Math.max(_,y)+a.z/2;s.maxZoom=b*10,s.minZoom=b*.01,s.debug===!0&&console.log("Fit camera to objects",{fitHeightDistance:_,fitWidthDistance:y,distance:b,verticalFov:g,horizontalFov:v});const w=.05,C=l.clone();if(C.y-=a.y*w,s.targetOffset&&(s.targetOffset.x!==void 0&&(C.x+=s.targetOffset.x),s.targetOffset.y!==void 0&&(C.y+=s.targetOffset.y),s.targetOffset.z!==void 0&&(C.z+=s.targetOffset.z)),s.relativeTargetOffset&&(s.relativeTargetOffset.x!==void 0&&(C.x+=s.relativeTargetOffset.x*a.x),s.relativeTargetOffset.y!==void 0&&(C.y+=s.relativeTargetOffset.y*a.y),s.relativeTargetOffset.z!==void 0&&(C.z+=s.relativeTargetOffset.z*a.z)),n==null||n=="auto"){const D=kl(ds),I=D?D.radius:0,j=Math.max(m.x,m.y,m.z,I);t instanceof c.PerspectiveCamera&&(t.near=b/100,t.far=j+b*10,t.updateProjectionMatrix()),D&&(s.maxZoom=Math.max(Math.min(s.maxZoom,I*.5),b))}s.currentZoom!==void 0&&(s.currentZoom<s.minZoom&&(s.minZoom=s.currentZoom*.9),s.currentZoom>s.maxZoom&&(s.maxZoom=s.currentZoom*1.1));const k=l.clone();if(s.fitDirection?k.sub(new c.Vector3().copy(s.fitDirection).multiplyScalar(1e6)):k.sub(t.worldPosition),i==="y"){const D=Math.sqrt(k.x*k.x+k.z*k.z);if(D>1e-4){const I=-D*w*4;k.y>I&&(k.y=I)}else k.set(0,-w*4,1)}k.normalize(),k.multiplyScalar(b);let O=l.clone().sub(k);return s.cameraOffset&&(s.cameraOffset.x!==void 0&&(O.x+=s.cameraOffset.x),s.cameraOffset.y!==void 0&&(O.y+=s.cameraOffset.y),s.cameraOffset.z!==void 0&&(O.z+=s.cameraOffset.z)),s.relativeCameraOffset&&(s.relativeCameraOffset.x!==void 0&&(O.x+=s.relativeCameraOffset.x*a.x),s.relativeCameraOffset.y!==void 0&&(O.y+=s.relativeCameraOffset.y*a.y),s.relativeCameraOffset.z!==void 0&&(O.z+=s.relativeCameraOffset.z*a.z)),t.parent&&(O=t.parent.worldToLocal(O)),s.debug&&(B.DrawWireBox3(u,16777011,10),B.DrawWireBox3(f,65280,10)),s.autoApply&&(t.position.copy(O),t.lookAt(C),r>0&&t instanceof c.PerspectiveCamera&&(t.fov=r,t.updateProjectionMatrix())),{camera:t,position:O,lookAt:C,fov:s.fov}}var qR=Object.defineProperty,p_=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&qR(e,t,n),n};class Vr extends T{constraintActive=!0;locked=!1;sources=[];setConstraintPosition(e){const t=this.sources[0];t&&(t.worldPosition=e)}}p_([p()],Vr.prototype,"constraintActive");p_([p()],Vr.prototype,"locked");p_([p(c.Object3D)],Vr.prototype,"sources");let Mr=class{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}x(){return this.bb.readFloat32(this.bb_pos)}y(){return this.bb.readFloat32(this.bb_pos+4)}z(){return this.bb.readFloat32(this.bb_pos+8)}static sizeOf(){return 12}static createVec3(e,t,i,n){return e.prep(4,12),e.writeFloat32(n),e.writeFloat32(i),e.writeFloat32(t),e.offset()}};class lC{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}position(e){return(e||new Mr).__init(this.bb_pos,this.bb)}rotation(e){return(e||new Mr).__init(this.bb_pos+12,this.bb)}scale(e){return(e||new Mr).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(e,t,i,n,o,r,a,l,h,d){return e.prep(4,36),e.prep(4,12),e.writeFloat32(d),e.writeFloat32(h),e.writeFloat32(l),e.prep(4,12),e.writeFloat32(a),e.writeFloat32(r),e.writeFloat32(o),e.prep(4,12),e.writeFloat32(n),e.writeFloat32(i),e.writeFloat32(t),e.offset()}}class Vn{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedTransformModel(e,t){return(t||new Vn).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedTransformModel(e,t){return e.setPosition(e.position()+ee.SIZE_PREFIX_LENGTH),(t||new Vn).__init(e.readInt32(e.position())+e.position(),e)}guid(e){const t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}fast(){const e=this.bb.__offset(this.bb_pos,6);return e?!!this.bb.readInt8(this.bb_pos+e):!1}transform(e){const t=this.bb.__offset(this.bb_pos,8);return t?(e||new lC).__init(this.bb_pos+t,this.bb):null}dontSave(){const e=this.bb.__offset(this.bb_pos,10);return e?!!this.bb.readInt8(this.bb_pos+e):!1}version(){const e=this.bb.__offset(this.bb_pos,12);return e?this.bb.readInt32(this.bb_pos+e):0}static startSyncedTransformModel(e){e.startObject(5)}static addGuid(e,t){e.addFieldOffset(0,t,0)}static addFast(e,t){e.addFieldInt8(1,+t,0)}static addTransform(e,t){e.addFieldStruct(2,t,0)}static addDontSave(e,t){e.addFieldInt8(3,+t,0)}static addVersion(e,t){e.addFieldInt32(4,t,0)}static endSyncedTransformModel(e){return e.endObject()}static finishSyncedTransformModelBuffer(e,t){e.finish(t)}static finishSizePrefixedSyncedTransformModelBuffer(e,t){e.finish(t,void 0,!0)}}var mt=(s=>(s[s.Average=0]="Average",s[s.Multiply=1]="Multiply",s[s.Minimum=2]="Minimum",s[s.Maximum=3]="Maximum",s))(mt||{}),Qf=(s=>(s[s.Discrete=0]="Discrete",s[s.Continuous=1]="Continuous",s))(Qf||{}),qe=(s=>(s[s.None=0]="None",s[s.FreezePositionX=2]="FreezePositionX",s[s.FreezePositionY=4]="FreezePositionY",s[s.FreezePositionZ=8]="FreezePositionZ",s[s.FreezePosition=14]="FreezePosition",s[s.FreezeRotationX=16]="FreezeRotationX",s[s.FreezeRotationY=32]="FreezeRotationY",s[s.FreezeRotationZ=64]="FreezeRotationZ",s[s.FreezeRotation=112]="FreezeRotation",s[s.FreezeAll=126]="FreezeAll",s))(qe||{}),$a=(s=>(s[s.None=0]="None",s[s.X=2]="X",s[s.Y=4]="Y",s[s.Z=8]="Z",s[s.All=-1]="All",s))($a||{});const je=function(s,e){return function(t,i,n){XR(t,i,n,s,e)}};function XR(s,e,t,i,n){if(!n&&!i&&!s.onValidate)return;if(t!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",s,e,t),Re("Invalid usage of validate decorator. Only fields can be validated. Property: "+e,{type:Ci.Error});return}let o="";if(typeof e=="string"?o=e:o=e.name,s.__internalAwake){const r=Symbol(o),a=s.__internalAwake;s.__internalAwake=function(){if(!this.onValidate){E()&&console.warn('Usage of @validate decorate detected but there is no onValidate method in your class: "'+s.constructor?.name+'"');return}const l=Object.getOwnPropertyDescriptor(this,o);if(!l||!l.get){this[r]=this[o];const h=this[o];if(h instanceof c.Vector2||h instanceof c.Vector3||h instanceof c.Vector4||h instanceof c.Quaternion){const d=this[o];Mf(d,()=>{this.onValidate(o)})}Object.defineProperty(this,o,{configurable:!0,set:function(d){if(this[kg]===!0)this[r]=d;else{i?.call(this,d);const u=this[r];this[r]=d,this.onValidate?.call(this,o,u)}},get:function(){return n?.call(this),this[r]}})}a.call(this)}}}const QR=function(s){return function(e,t,i){let n="";typeof t=="string"?n=t:n=t.name;const o=s.prototype,r=Object.getOwnPropertyDescriptor(o,n);if(!r?.value){console.warn("Can not apply prefix: type does not have method named",t,s);return}const a=r.value,l=e[n];Object.defineProperty(o,n,{value:function(...h){const d=l?.call(this,...h);if(d instanceof Promise){d.then(u=>{if(u!==!1)return a.call(this,...h)});return}if(d!==!1)return a.call(this,...h)}})}};var YR=Object.defineProperty,KR=Object.getOwnPropertyDescriptor,Di=(s,e,t,i)=>{for(var n=i>1?void 0:i?KR(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&YR(e,t,n),n};class ZR{get isDirty(){return this.positionChanged||this.rotationChanged}positionChanged=!1;rotationChanged=!1;position;quaternion;_positionKeys=["x","y","z"];_quaternionKeys=["_x","_y","_z","_w"];reset(e=!1){if(this.positionChanged=!1,this.rotationChanged=!1,this.mute=!1,e){if(this.position)for(const t of this._positionKeys)delete this.position[t];if(this.quaternion)for(const t of this._quaternionKeys)delete this.quaternion[t]}}syncValues(){for(const e of this._positionKeys)this.position[e]=this.obj.position[e];for(const e of this._quaternionKeys)this.quaternion[e]=this.obj.quaternion[e]}mute=!1;applyValues(){if(this.positionChanged&&this.position)for(const e of this._positionKeys){const t=this.position[e];t!==void 0&&(this.obj.position[e]=t)}if(this.rotationChanged&&this.quaternion)for(const e of this._quaternionKeys){const t=this.quaternion[e];t!==void 0&&(this.obj.quaternion[e]=t)}}context;obj;_positionWatch;_rotationWatch;constructor(e,t){this.context=t,this.obj=e}start(e,t){this.reset(),e&&(this._positionWatch||(this._positionWatch=new Es(this.obj.position,["x","y","z"])),this._positionWatch.apply(),this.position={},this._positionWatch.subscribeWrite((o,r)=>{if(this.context.physics.engine?.isUpdating||this.mute)return;const a=this.position[r];Math.abs(a-o)<1e-5||(this.position[r]=o,this.positionChanged=!0)})),t&&(this._rotationWatch||(this._rotationWatch=new Es(this.obj.quaternion,["_x","_y","_z","_w"])),this._rotationWatch.apply(),this.quaternion={},this._rotationWatch.subscribeWrite((o,r)=>{if(this.context.physics.engine?.isUpdating||this.mute)return;const a=this.quaternion[r];Math.abs(a-o)<1e-5||(this.quaternion[r]=o,this.rotationChanged=!0)}));const i=this.obj.matrixWorld.multiplyMatrices.bind(this.obj.matrixWorld),n=new c.Matrix4;this.obj.matrixWorld.multiplyMatrices=(o,r)=>(this.context.physics.engine?.isUpdating||this.mute||n.equals(o)||(this.positionChanged=!0,this.rotationChanged=!0,n.copy(o)),i(o,r))}stop(){this._positionWatch?.revoke(),this._rotationWatch?.revoke()}}const mi=class Ra extends T{get isRigidbody(){return!0}autoMass=!0;set mass(e){e!==this._mass&&(this._mass=e,this._propertiesChanged=!0,this.__didAwake&&(this.autoMass=!1))}get mass(){return this.autoMass?this.context.physics.engine?.getBody(this)?.mass()??-1:this._mass}_mass=0;useGravity=!0;centerOfMass=new c.Vector3(0,0,0);constraints=qe.None;isKinematic=!1;drag=0;angularDrag=1;detectCollisions=!0;sleepThreshold=.01;collisionDetectionMode=Qf.Discrete;get lockPositionX(){return(this.constraints&qe.FreezePositionX)!==0}get lockPositionY(){return(this.constraints&qe.FreezePositionY)!==0}get lockPositionZ(){return(this.constraints&qe.FreezePositionZ)!==0}get lockRotationX(){return(this.constraints&qe.FreezeRotationX)!==0}get lockRotationY(){return(this.constraints&qe.FreezeRotationY)!==0}get lockRotationZ(){return(this.constraints&qe.FreezeRotationZ)!==0}set lockPositionX(e){e?this.constraints|=qe.FreezePositionX:this.constraints&=~qe.FreezePositionX}set lockPositionY(e){e?this.constraints|=qe.FreezePositionY:this.constraints&=~qe.FreezePositionY}set lockPositionZ(e){e?this.constraints|=qe.FreezePositionZ:this.constraints&=~qe.FreezePositionZ}set lockRotationX(e){e?this.constraints|=qe.FreezeRotationX:this.constraints&=~qe.FreezeRotationX}set lockRotationY(e){e?this.constraints|=qe.FreezeRotationY:this.constraints&=~qe.FreezeRotationY}set lockRotationZ(e){e?this.constraints|=qe.FreezeRotationZ:this.constraints&=~qe.FreezeRotationZ}set gravityScale(e){this._gravityScale=e}get gravityScale(){return this._gravityScale}_gravityScale=1;dominanceGroup=0;static tempPosition=new c.Vector3;_propertiesChanged=!1;_currentVelocity=new c.Vector3;_smoothedVelocity=new c.Vector3;_smoothedVelocityGetter=new c.Vector3;_lastPosition=new c.Vector3;_watch;awake(){this._watch=void 0,this._propertiesChanged=!1}onEnable(){this._watch||(this._watch=new ZR(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),Ce.LateUpdate),E()&&(globalThis.NEEDLE_USE_RAPIER===!1?console.warn("RAPIER physics are disabled in your build. Enable them by setting NEEDLE_USE_RAPIER to true in your build config: Rigidbody could not be created."):A.RAPIER_PHYSICS.ready().then(async()=>{await kf(3),this.activeAndEnabled&&!this.context.physics.engine?.getBody(this)&&console.warn(`Rigidbody could not be created. Ensure "${this.name}" has a Collider component.`)}))}onDisable(){this._watch?.stop(),this.context.physics.engine?.removeBody(this)}onDestroy(){this.context.physics.engine?.removeBody(this)}onValidate(e){this._propertiesChanged=!0,e==="autoMass"&&!this.autoMass&&E()&&!Ra._didWarnAutoMass&&(Ra._didWarnAutoMass=!0,console.warn("[Rigidbody] autoMass disabled — consider using Collider.density instead of setting mass explicitly. Density scales naturally with collider size."))}static _didWarnAutoMass=!1;*beforePhysics(){for(;;)this._propertiesChanged&&(this._propertiesChanged=!1,this.context.physics.engine?.updateProperties(this)),this._watch?.isDirty?(this._watch.mute=!0,this._watch.applyValues(),this.context.physics.engine?.updateBody(this,this._watch.positionChanged,this._watch.rotationChanged),this._watch.reset()):this._watch?.syncValues(),this.captureVelocity(),yield}teleport(e,t=!0){this._watch?.reset(!0),t?this.gameObject.position.set(e.x,e.y,e.z):this.setWorldPosition(e.x,e.y,e.z),this.resetForcesAndTorques(),this.resetVelocities()}resetForces(e=!0){this.context.physics.engine?.resetForces(this,e)}resetTorques(e=!0){this.context.physics.engine?.resetTorques(this,e)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){this.context.physics.engine?.wakeup(this)}get isSleeping(){return this.context.physics.engine?.isSleeping(this)}updateProperties(){return this._propertiesChanged=!1,this.context.physics.engine?.updateProperties(this)}applyForce(e,t,i=!0){this._propertiesChanged&&this.updateProperties(),this.context.physics.engine?.addForce(this,e,i)}applyImpulse(e,t=!0){this._propertiesChanged&&this.updateProperties(),this.context.physics.engine?.applyImpulse(this,e,t)}setForce(e,t,i,n=!0){this.context.physics.engine?.resetForces(this,n),typeof e=="number"?(t??=0,i??=0,this.context.physics.engine?.addForce(this,{x:e,y:t,z:i},n)):this.context.physics.engine?.addForce(this,e,n)}getVelocity(){const e=this.context.physics.engine?.getLinearVelocity(this);return e?(this._currentVelocity.x=e.x,this._currentVelocity.y=e.y,this._currentVelocity.z=e.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setVelocity(e,t,i,n=!0){if(e instanceof c.Vector3){const o=e;this.context.physics.engine?.setLinearVelocity(this,o,n);return}t===void 0||i===void 0||this.context.physics.engine?.setLinearVelocity(this,{x:e,y:t,z:i},n)}getAngularVelocity(){const e=this.context.physics.engine?.getAngularVelocity(this);return e?(this._currentVelocity.x=e.x,this._currentVelocity.y=e.y,this._currentVelocity.z=e.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setAngularVelocity(e,t,i,n=!0){if(typeof e=="object"){const o=e;this.context.physics.engine?.setAngularVelocity(this,o,n);return}if(t===void 0||i===void 0||typeof t=="boolean"){console.warn("setAngularVelocity expects either a Vec3 or 3 numbers");return}this.context.physics.engine?.setAngularVelocity(this,{x:e,y:t,z:i},n)}setTorque(e,t,i){typeof e=="number"?this.setAngularVelocity(e,t,i):this.setAngularVelocity(e)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(e=null){}captureVelocity(){const e=this.gameObject.matrixWorld;Ra.tempPosition.setFromMatrixPosition(e);const t=Ra.tempPosition.sub(this._lastPosition);this._lastPosition.copy(Ra.tempPosition),this._smoothedVelocity.lerp(t,this.context.time.deltaTime/.1)}};Di([je()],mi.prototype,"autoMass",2);Di([p()],mi.prototype,"mass",1);Di([je(),p()],mi.prototype,"useGravity",2);Di([p(c.Vector3)],mi.prototype,"centerOfMass",2);Di([je(),p()],mi.prototype,"constraints",2);Di([je(),p()],mi.prototype,"isKinematic",2);Di([je(),p()],mi.prototype,"drag",2);Di([je(),p()],mi.prototype,"angularDrag",2);Di([je(),p()],mi.prototype,"detectCollisions",2);Di([je(),p()],mi.prototype,"sleepThreshold",2);Di([je(),p()],mi.prototype,"collisionDetectionMode",2);Di([je()],mi.prototype,"_gravityScale",2);Di([je()],mi.prototype,"dominanceGroup",2);let Xe=mi;const co=x("debugsync"),uh="STRS";Xy(uh,Vn.getRootAsSyncedTransformModel);const fn=new ee.Builder;function cC(s,e,t=!0){fn.clear();const i=fn.createString(s);Vn.startSyncedTransformModel(fn),Vn.addGuid(fn,i),Vn.addFast(fn,t);const n=e.worldPosition,o=e.worldEuler,r=e.gameObject.worldScale;Vn.addTransform(fn,lC.createTransform(fn,n.x,n.y,n.z,o.x,o.y,o.z,r.x,r.y,r.z)),Vn.addVersion(fn,1);const a=Vn.endSyncedTransformModel(fn);return fn.finish(a,uh),fn.asUint8Array()}let Jg=0,Wc=0;_x(s=>{const t=s.connection.currentServerUrl?.includes("glitch")?10:40;Wc=Math.floor(Jg/t),Jg=0,co&&Wc>0&&console.log("Sync Transform Fast Interval",Wc)});class Sn extends T{overridePhysics=!0;interpolatePosition=!0;interpolateRotation=!0;interpolateScale=!0;fastMode=!1;syncDestroy=!1;_model=null;_needsUpdate=!0;_hadOwnershipBeforeDisable=!1;rb=null;_wasKinematic=!1;_receivedDataBefore=!1;_targetPosition;_targetRotation;_targetScale;_receivedFastUpdate=!1;_shouldRequestOwnership=!1;requestOwnership(){co&&console.log("[SyncedTransform] Request ownership"),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}freeOwnership(){this._model?.freeOwnership()}hasOwnership(){return this._model?.hasOwnership??void 0}isOwned(){return this._model?.isOwned}joinedRoomCallback=null;receivedDataCallback=null;awake(){co&&console.log("[SyncedTransform] new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new c.Vector3,this._targetRotation=new c.Quaternion,this._targetScale=new c.Vector3,this.lastPosition=new c.Vector3,this.lastRotation=new c.Quaternion,this.lastScale=new c.Vector3,this.rb=P.getComponentInChildren(this.gameObject,Xe),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new Qx(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen(te.JoinedRoom,this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinary(uh,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&$y(this.guid,this.context.connection),this._model=null,this.context.connection.stopListen(te.JoinedRoom,this.joinedRoomCallback),this.context.connection.stopListenBinary(uh,this.receivedDataCallback)}tryGetLastState(){const e=this.context.connection.tryGetState(this.guid);e&&this.onReceivedData(e)}tempEuler=new c.Euler;onReceivedData(e){if(!this.destroyed&&typeof e.guid=="function"&&e.guid()===this.guid){co&&console.log("[SyncedTransform] new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,e),this.receivedUpdate=!0,this._receivedFastUpdate=e.fast();const t=e.transform(),i=e.version();if(t){Ki.markDirty(this.gameObject,!0);const n=t.position();n&&(this.interpolatePosition&&this._targetPosition?.set(n.x(),n.y(),n.z()),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(n.x(),n.y(),n.z()));const o=t.rotation();o&&(this.tempEuler.set(o.x(),o.y(),o.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&Ty(this.gameObject,this.tempEuler));const r=t.scale();r&&(i===0?this.gameObject.scale.set(r.x(),r.y(),r.z()):(this.interpolateScale&&this._targetScale.set(r.x(),r.y(),r.z()),(!this.interpolateScale||!this._receivedDataBefore)&&(this.gameObject.worldScale=F(r.x(),r.y(),r.z()))))}this._receivedDataBefore=!0}}onEnable(){this.lastPosition.copy(this.worldPosition),this.lastRotation.copy(this.worldQuaternion),this.lastScale.copy(this.gameObject.worldScale),this._needsUpdate=!0,this._model&&(this._model.updateIsOwned(),this._hadOwnershipBeforeDisable&&(this._hadOwnershipBeforeDisable=!1,this._model.requestOwnershipIfNotOwned()))}onDisable(){this._model&&(this._hadOwnershipBeforeDisable=this._model.hasOwnership===!0,this._model.freeOwnership())}receivedUpdate=!1;lastPosition;lastRotation;lastScale;onBeforeRender(){if(!this.activeAndEnabled||!this.context.connection.isConnected)return;if(!this.context.connection.isInRoom||!this._model){co&&console.log("[SyncedTransform] no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());const e=this.worldPosition,t=this.worldQuaternion,i=this.gameObject.worldScale;if(this._model.isOwned&&!this.receivedUpdate){const r=this._model.hasOwnership||this.fastMode?1e-4:.001;(e.distanceTo(this.lastPosition)>r||t.angleTo(this.lastRotation)>r||i.distanceTo(this.lastScale)>r)&&(this._model.hasOwnership?this._needsUpdate=!0:(co&&console.log(this.guid,"reset because not owned but",this.gameObject.name,this.lastPosition),this.worldPosition=this.lastPosition,e.copy(this.lastPosition),this.worldQuaternion=this.lastRotation,t.copy(this.lastRotation),this.gameObject.worldScale=this.lastScale,i.copy(this.lastScale),Ki.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){const r=this._receivedFastUpdate||this.fastMode?.5:.3;let a=!1;if(this.interpolatePosition&&this._targetPosition){const l=this.worldPosition;l.lerp(this._targetPosition,r),this.worldPosition=l,a=!0}if(this.interpolateRotation&&this._targetRotation){const l=this.worldQuaternion;l.slerp(this._targetRotation,r),this.worldQuaternion=l,a=!0}if(this.interpolateScale&&this._targetScale){const l=this.gameObject.worldScale;l.lerp(this._targetScale,r),this.gameObject.worldScale=l,a=!0}a&&Ki.markDirty(this.gameObject,!0)}if(this.receivedUpdate=!1,this.lastPosition.copy(e),this.lastRotation.copy(t),this.lastScale.copy(i),!this._model||!this._model||this._model.hasOwnership===void 0||!this._model.hasOwnership)return;this.rb&&this.overridePhysics&&this._wasKinematic!==void 0&&(co&&console.log("[SyncedTransform] reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic);const n=10,o=this.rb||this.fastMode;if(this._needsUpdate&&(this.context.time.frameCount%n===0||o)){if(Jg++,o&&Wc>0&&this.context.time.frameCount%Wc!==0)return;co&&console.debug("[SyncedTransform] Send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this._needsUpdate=!1;const r=cC(this.guid,this,!!o);this.context.connection.sendBinary(r)}}}class Ih{event;get deviceIndex(){return this.event.deviceIndex}get pointerId(){return this.event.pointerId}button;buttonName;get pressure(){return this.event.pressure}get used(){return this._used}_used=!1;use(){this._used||(this._used=!0,this.event.use())}_propagationStopped=!1;get propagationStopped(){return this._propagationStopped}stopPropagation(){this._propagationStopped=!0,this.event.stopImmediatePropagation()}stopImmediatePropagation(){this._propagationStopped=!0,this.event.stopImmediatePropagation()}z__pointer_ctured=!1;setPointerCapture(){this.z__pointer_ctured=!0}z__pointer_cture_rleased=!1;releasePointerCapture(){this.z__pointer_cture_rleased=!0}inputSource;get mode(){return this.event.mode}object;point;normal;face;distance;instanceId;intersection;isDown;isUp;isPressed;isClick;isDoubleClick;input;constructor(e,t){this.event=t,this.input=e,this.button=t.button}clone(){const e=new Ih(this.input,this.event);return Object.assign(e,this),e}Use(){this.use()}StopPropagation(){this.event.stopImmediatePropagation()}}function hf(s,e){return P.foreachComponent(s,i=>{if(!i.enabled)return;const n=i;if(e)switch(e){case"pointerdown":if(n.onPointerDown)return!0;break;case"pointerup":if(n.onPointerUp||n.onPointerClick)return!0;break;case"pointermove":if(n.onPointerEnter||n.onPointerExit||n.onPointerMove)return!0;break}else if(n.onPointerDown||n.onPointerUp||n.onPointerEnter||n.onPointerExit||n.onPointerClick)return!0},!1)===!0}var JR=Object.defineProperty,eT=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&JR(e,t,n),n};class fh extends T{awake(){ei.createIfNoneExists(this.context)}onEnable(){ei.get(this.context)?.register(this)}onDisable(){ei.get(this.context)?.unregister(this)}}class Ji extends fh{targets=null;raycastHits=[];ignoreSkinnedMeshes=!1;start(){this.targets=[this.gameObject]}performRaycast(e=null){if(!this.targets)return null;e??=new zr,e.targets=this.targets,e.results=this.raycastHits,e.useAcceleratedRaycast=!0;const t=e.testObject;this.ignoreSkinnedMeshes&&(e.testObject=n=>n instanceof c.SkinnedMesh?"continue in children":t?t(n):!0);const i=this.context.physics.raycast(e);return e.testObject=t,i}}eT([p()],Ji.prototype,"ignoreSkinnedMeshes");class Yf extends Ji{constructor(){super(),this.ignoreSkinnedMeshes=!0}}class Ir extends fh{static allow=!0;performRaycast(e){if(!N.active||!Ir.allow||!e?.ray)return null;const t=e.ray.origin;return this.context.physics.sphereOverlap(t,.015,!1,!0)}}class m_{static getObject(e){const t=e[xi];return t&&(t.isComponent===!0?e=t.gameObject:e=t),e}static isInteractable(e,t){if(t&&(t.canvasGroup=void 0,t.graphic=void 0),e==null||!e.visible||(e=this.getObject(e),!e.visible))return!1;const i=this.tryFindCanvasGroup(e);if(i?.isCanvasGroup===!0&&(t&&(t.canvasGroup=i),i.blocksRaycasts===!1||i.interactable===!1))return!1;const n=xn(e,o=>{if(o.isGraphic===!0)return o},!1);return t&&n?.isGraphic===!0&&(t.graphic=n),!(n?.raycastTarget===!1||n?.layer===2)}static tryFindCanvasGroup(e){if(!e)return null;const t=xn(e,i=>{if(i.activeAndEnabled){const n=i;if(n.blocksRaycasts!==void 0&&n.interactable!==void 0)return n}},!1);return t!==void 0?t:this.tryFindCanvasGroup(e.parent)}}function g_(s){const e=s[xi];return e||(s.parent?g_(s.parent):null)}function tT(s){return s.isUI===!0||typeof s[xi]=="object"}function df(s,e){if(!s)return;const t=s.material;if(t?.isMaterial===!0){const i=s.parent;i&&i.isText,t.side=e.doubleSided??!0?c.DoubleSide:c.FrontSide,t.shadowSide=e.doubleSided?c.DoubleSide:c.FrontSide,s.castShadow=e.castShadows?e.castShadows:!1,s.receiveShadow=e.receiveShadows?e.receiveShadows:!1}for(const i of s.children)df(i,e)}function Ta(s,e,t){s[e]===void 0&&console.warn("Field",e,"is undefined on",s);const i=Proxy.revocable(s[e],{set(r,a,l,h){const d=r[a],u=Reflect.set(r,a,l,h);return t(l,d),u}}),n=i.revoke,o=s[e];return i.revoke=()=>{s[e]=o,n()},s[e]=i.proxy,i}const h0=Symbol("Scheduled action");function iT(s,e,t=Ce.OnBeforeRender){let i=s[h0];i||(i=s[h0]={});const n=e.name;i[t]||(i[t]={});const o=i[t];if(o[n])return;function*a(){e?.call(s),o[n]=null}const l=s.startCoroutine(a(),t);o[n]=l}const ho=x("debugeventsystem");var ey=(s=>(s.BeforeHandleInput="BeforeHandleInput",s.AfterHandleInput="AfterHandleInput",s))(ey||{});Uy(s=>{ei.createIfNoneExists(s)});class ei extends T{static ensureUpdateMeshUI(e,t,i=!1){ac.update(e,t,i)}static markUIDirty(e){ac.markDirty()}static createIfNoneExists(e){e.scene.getComponent(ei)||e.scene.addComponent(ei)}static get(e){return this.createIfNoneExists(e),e.scene.getComponent(ei)}static get instance(){return this.get(X.Current)}raycaster=[];register(e){e&&this.raycaster&&!this.raycaster.includes(e)&&this.raycaster?.push(e)}unregister(e){const t=this.raycaster?.indexOf(e);t!==void 0&&t!==-1&&this.raycaster?.splice(t,1)}get hasActiveUI(){return this.currentActiveMeshUIComponents.length>0}get isHoveringObjects(){return this.hoveredByID.size>0}awake(){this.gameObject!==this.context.scene&&(console.debug(`[Needle Engine] EventSystem is only allowed on the scene root. Disabling EventSystem on '${this.gameObject.name}'`),this.enabled=!1)}start(){this.context.scene.getComponent(fh)||this.context.scene.addComponent(Ji)}onEnable(){this.context.input.addEventListener(xe.PointerDown,this.onPointerEvent),this.context.input.addEventListener(xe.PointerUp,this.onPointerEvent),this.context.input.addEventListener(xe.PointerMove,this.onPointerEvent)}onDisable(){this.context.input.removeEventListener(xe.PointerDown,this.onPointerEvent),this.context.input.removeEventListener(xe.PointerUp,this.onPointerEvent),this.context.input.removeEventListener(xe.PointerMove,this.onPointerEvent)}pressedByID=new Map;hoveredByID=new Map;onBeforeRender(){this.resetMeshUIStates()}onPointerEvent=e=>{if(e===void 0||e.propagationStopped||e.defaultPrevented||e.used)return;const t=new Ih(this.context.input,e);this._currentPointerEventName=e.type,t.inputSource=this.context.input,t.isClick=e.isClick,t.isDoubleClick=e.isDoubleClick,t.isDown=e.type==xe.PointerDown,t.isUp=e.type==xe.PointerUp,t.isPressed=this.context.input.getPointerPressed(e.pointerId);const i=new zr;e.hasRay?i.ray=e.ray:i.screenPoint=this.context.input.getPointerPositionRC(e.pointerId),i.allowSlowRaycastFallback=e.isClick||e.isDoubleClick;const n=this.performRaycast(i);if(ho&&(t.isDown?console.log("DOWN",{id:t.pointerId,hits:n.length}):t.isUp&&console.log("UP",{id:t.pointerId,hits:n.length}),t.isClick&&console.log("CLICK",{id:t.pointerId,hits:n.length})),n){for(const r of n)r.event=e,e.intersections.push(r);e.origin.onPointerHits&&e.origin.onPointerHits({sender:this,event:e,hits:n})}ho&&t.isClick&&Re("EventSystem: "+t.pointerId+" - "+this.context.time.frame+" - Up:"+t.isUp+", Down:"+t.isDown);const o={sender:this,args:t,hasActiveUI:this.currentActiveMeshUIComponents.length>0};this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:o})),this.handleIntersections(n,t),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:o}))};_sortedHits=[];_testObjectsCache=new Map;_currentlyActiveRaycaster=null;_currentPointerEventName=null;shouldRaycastObject=e=>{let t=null;tT(e)&&(t=e[xi]?.gameObject);const n=this._testObjectsCache.get(e)??(t?this._testObjectsCache.get(t):void 0);if(n!==void 0)return n===!1?"continue in children":!!this.isHandledByActiveRaycaster(e);if(!this.isHandledByActiveRaycaster(e))return!1;let o=hf(e,this._currentPointerEventName);if(!o&&t&&(o=hf(t,this._currentPointerEventName)),o){this._testObjectsCache.set(e,!0);for(const r of e.children)this.shouldRaycastObject_AddToYesCache(r);return!0}return this._testObjectsCache.set(e,!1),"continue in children"};isHandledByActiveRaycaster(e){const i=e?.userData?.components?.length>0&&"getComponent"in e?e.getComponent(fh):null;return!i||i===this._currentlyActiveRaycaster}shouldRaycastObject_AddToYesCache(e){this._testObjectsCache.set(e,!0);for(const t of e.children)this.shouldRaycastObject_AddToYesCache(t)}performRaycast(e){if(!this.raycaster)return null;this._testObjectsCache.clear(),this._sortedHits.length=0,e.testObject=this.shouldRaycastObject;for(const t of this.raycaster){if(!t.activeAndEnabled)continue;this._currentlyActiveRaycaster=t;const i=t.performRaycast(e);this._currentlyActiveRaycaster=null,i&&i.length>0&&this._sortedHits.push(...i)}return this._sortedHits.sort((t,i)=>t.distance-i.distance),this._sortedHits}assignHitInformation(e,t){t?(e.intersection=t,e.point=t.point,e.normal=t.normal,e.face=t.face,e.distance=t.distance,e.instanceId=t.instanceId):(e.intersection=void 0,e.point=void 0,e.normal=void 0,e.face=void 0,e.distance=void 0,e.instanceId=void 0)}handleIntersections(e,t){if(e?.length){e=this.sortCandidates(e);for(const n of e){if(t.event.immediatePropagationStopped)return!1;if(this.assignHitInformation(t,n),this.handleEventOnObject(n.object,t))return!0}}this.assignHitInformation(t,e?.[0]),this.invokePointerCapture(t);const i=this.hoveredByID.get(t.pointerId);return i&&this.propagatePointerExit(i.obj,i.data,null),this.hoveredByID.delete(t.pointerId),t.isUp&&(this.pressedByID.get(t.pointerId)?.handlers.forEach(n=>this.invokeOnPointerUp(t,n)),this.pressedByID.delete(t.pointerId)),!1}_sortingBuffer=[];_noDepthTestingResults=[];sortCandidates(e){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let t=0;t<e.length;t++){const i=e[t],n=i.object;if(n.material&&n.material.depthTest===!1){this._noDepthTestingResults.push(i);continue}this._sortingBuffer.push(i)}for(const t of this._sortingBuffer)this._noDepthTestingResults.push(t);return this._noDepthTestingResults}out={};handleEventOnObject(e,t){if(!this.testIsVisible(e))return t.isClick&&ho&&console.log("not allowed",e),!1;if(t.pointerId===void 0)return ho&&console.error("Event without pointer can't be handled",t),!1;t.object=e;const i=e.parent,n=t.isClick??!1;let o=null;if(i&&i.isUI){const d=(t.isPressed||t.isClick)??!1;if(i[xi]){const u=i[xi].gameObject;if(u){if(!m_.isInteractable(u,this.out))return!1;o=this.out.canvasGroup??null,this.handleMeshUIIntersection(e,d),e=u}}}n&&ho&&console.log(this.context.time.frame,e);const r=this.hoveredByID.get(t.pointerId),a=r?.obj;a!==e&&a&&this.propagatePointerExit(a,r.data,e);const h=this.hoveredByID.get(t.pointerId);if(h?(h.obj=e,h.data=t):this.hoveredByID.set(t.pointerId,{obj:e,data:t}),t.isDown){const d=this.pressedByID.get(t.pointerId);d?(d.obj=e,d.data=t):this.pressedByID.set(t.pointerId,{obj:e,data:t,handlers:new Set})}return(o===null||o.interactable)&&this.handleMainInteraction(e,t,a??null),!0}propagate(e,t){for(;e;)P.foreachComponent(e,i=>{t(i)},!1),e=e.parent}handleMainInteraction(e,t,i){const n=this.pressedByID.get(t.pointerId),o=i!==e;let r=!0;switch(t.event.pointerType){case"mouse":case"touch":const a=this.context.input.getPointerPositionLastFrame(t.pointerId),l=this.context.input.getPointerPosition(t.pointerId);r=a&&!L.approximately(a,l);break}this.propagate(e,a=>{const l=a;l.interactable!==!1&&(!l.activeAndEnabled||!l.enabled||(l.onPointerEnter&&o&&this.handlePointerEnter(l,t),t.isDown&&l.onPointerDown&&(l.onPointerDown(t),n?.handlers.add(l),this.handlePointerCapture(t,l)),l.onPointerMove&&(r&&l.onPointerMove(t),this.handlePointerCapture(t,l)),t.isUp&&(l.onPointerUp&&(this.invokeOnPointerUp(t,l),n?.handlers.delete(l)),l.onPointerExit&&t.event?.pointerType===Lf.Touch&&(this.handlePointerExit(l,t),this.hoveredByID.delete(t.pointerId))),t.isClick&&l.onPointerClick&&l.onPointerClick(t)))}),t.isUp&&(n?.handlers.forEach(a=>{this.invokeOnPointerUp(t,a)}),this.pressedByID.delete(t.pointerId))}propagatePointerExit(e,t,i){this.propagate(e,n=>{if(!n.gameObject||n.destroyed)return;const o=n;if(o.onPointerExit||o.onPointerEnter){if(i&&this.isChild(i,n.gameObject))return;this.handlePointerExit(o,t)}})}invokeOnPointerUp(e,t){t.onPointerUp?.call(t,e),this.releasePointerCapture(e,t)}handlePointerEnter(e,t){e.onPointerEnter&&this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!0)&&e.onPointerEnter(t),this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!1)}handlePointerExit(e,t){e.onPointerExit&&this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!0)&&e.onPointerExit(t),this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!1)}updatePointerState(e,t,i,n){let o=e[i];if(n)return o&&o.includes(t)?!1:(o=o||[],o.push(t),e[i]=o,!0);{if(!o||!o.includes(t))return!1;const r=o.indexOf(t);return r!==-1&&o.splice(r,1),!0}}_capturedPointer={};handlePointerCapture(e,t){if(e.z__pointer_ctured){e.z__pointer_ctured=!1;const i=e.pointerId;if(t.onPointerMove){const n=this._capturedPointer[i]||[];n.push(t),this._capturedPointer[i]=n}else E()&&!t.z__warned_no_pointermove&&(t.z__warned_no_pointermove=!0,console.warn("PointerCapture was requested but the component doesn't implement onPointerMove. It will not receive any pointer events"))}else e.z__pointer_cture_rleased&&(e.z__pointer_cture_rleased=!1,this.releasePointerCapture(e,t))}releasePointerCapture(e,t){const i=e.pointerId;if(this._capturedPointer[i]){const n=this._capturedPointer[i].indexOf(t);n!==-1&&(this._capturedPointer[i].splice(n,1),ho&&console.log("released pointer capture",i,t,this._capturedPointer))}}invokePointerCapture(e){if(e.event.type===xe.PointerMove){const t=e.pointerId,i=this._capturedPointer[t];if(i){ho&&console.log("Captured",t,i);for(let n=0;n<i.length;n++){const o=i[n];if(o.destroyed){i.splice(n,1),n--;continue}o.onPointerMove?.call(o,e)}}}}pointerEnterSymbol=Symbol("pointerEnter");pointerExitSymbol=Symbol("pointerExit");isChild(e,t){return!e||!t?!1:e===t?!0:e.parent?this.isChild(e.parent,t):!1}handleMeshUiObjectWithoutShadowDom(e,t){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,t)}currentActiveMeshUIComponents=[];handleMeshUIIntersection(e,t){const i=ac.updateState(e,t);return i&&this.currentActiveMeshUIComponents.push(i),i!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&ac.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){const t=this.currentActiveMeshUIComponents[e];ac.resetState(t)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?P.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}}class ac{static lastSelected=null;static lastUpdateFrame=[];static needsUpdate=!1;static markDirty(){this.needsUpdate=!0}static update(e,t,i=!1){if(i){e.update();return}const n=t.time.frameCount;for(const o of this.lastUpdateFrame)if(o.context===t){if(n===o.frame)return;o.frame=n;let r=this.needsUpdate||n<1;o.nextUpdate<=n&&(r=!0),r&&(ho&&console.log("Update threemeshui"),this.needsUpdate=!1,o.nextUpdate=n+60,e.update());return}this.lastUpdateFrame=[{context:t,frame:n,nextUpdate:n+60}],e.update(),this.needsUpdate=!1}static updateState(e,t){let i=null;if(e&&(i=this.findBlockOrTextInParent(e),i&&i!==this.lastSelected)){if(i.interactable===!1)return null;this.needsUpdate=!0}return i}static resetLastSelected(){const e=this.lastSelected;e&&(this.lastSelected=null,this.resetState(e))}static resetState(e){e&&(this.needsUpdate=!0)}static findBlockOrTextInParent(e){return e?e.isBlock||e.isText?e:this.findBlockOrTextInParent(e.parent):null}}var nT=Object.defineProperty,sT=Object.getOwnPropertyDescriptor,Pe=(s,e,t,i)=>{for(var n=i>1?void 0:i?sT(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&nT(e,t,n),n};const kt=x("debugorbit"),ym=x("freecam"),oT=x("debugcamerafit"),Id=x("smoothcam"),rT={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let _m;class ph extends CustomEvent{constructor(e,t){super("target-reached",{detail:{controls:e,type:t}})}}class ue extends T{get isCameraController(){return!0}get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(e){this.controls?.addEventListener("start",e)}autoTarget=!0;autoFit=!1;enableRotate=!0;autoRotate=!1;autoRotateSpeed=1;minAzimuthAngle=1/0;maxAzimuthAngle=1/0;minPolarAngle=0;maxPolarAngle=Math.PI;enableKeys=!1;enableDamping=!0;dampingFactor=.1;enableZoom=!0;minZoom=0;maxZoom=1/0;zoomSpeed=1;zoomToCursor=!1;enablePan=!0;lookAtTarget=null;lockLookAtTarget=!0;lookAtConstraint01=1;lookAtConstraint;allowInterrupt=!0;middleClickToFocus=!0;doubleClickToFocus=!0;clickBackgroundToFitScene=2;get targetElement(){return this._controls?.domElement??this._targetElement}set targetElement(e){this._targetElement=e,this._controls&&this._controls.domElement!==e&&(this._controls.disconnect(),this._controls.domElement=e,e&&this._controls.connect(e))}_targetElement=null;debugLog=!1;get targetLerpSpeed(){return 5}set targetLerpSpeed(e){this.targetLerpDuration=1/e}get targetLerpDuration(){return this._lookTargetLerpDuration}set targetLerpDuration(e){this._lookTargetLerpDuration=e}_lookTargetLerpDuration=1;targetBounds=null;rotateLeft(e){this._controls?._rotateLeft(e)}rotateUp(e){this._controls?._rotateUp(e)}pan(e,t){this._controls?._pan(e,t)}zoomIn(e){e>0?this._controls?._dollyIn(1-e):e<0&&this._controls?._dollyOut(1+e)}_controls=null;_cameraObject=null;_lookTargetLerpActive=!1;_lookTargetStartPosition=new c.Vector3;_lookTargetEndPosition=new c.Vector3;_lookTargetLerp01=0;_cameraLerpActive=!1;_cameraStartPosition=new c.Vector3;_cameraEndPosition=new c.Vector3;_cameraLerp01=0;_cameraLerpDuration=0;_fovLerpActive=!1;_fovLerpStartValue=0;_fovLerpEndValue=0;_fovLerp01=0;_fovLerpDuration=0;_inputs=0;_enableTime=0;_startedListeningToKeyEvents=!1;_eventSystem;_afterHandleInputFn;_camera=null;_syncedTransform;_didSetTarget=0;_didApplyLookAtTarget=!1;awake(){kt&&console.debug("OrbitControls",this),this.lookAtConstraint&&(console.warn("[OrbitControls] lookAtConstraint is deprecated, use lookTarget and lockLookAtTarget instead. This will be removed in a future version."),!this.lookAtTarget&&this.lookAtConstraint.sources?.[0]&&(this.lookAtTarget=this.lookAtConstraint.sources[0],this.lockLookAtTarget=this.lookAtConstraint.locked)),this._didSetTarget=0,this._didApplyLookAtTarget=!1,this._startedListeningToKeyEvents=!1,this.context.domElement.cameraControls===!1&&(this.enabled=!1)}start(){this._eventSystem=ei.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(ey.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){this._controls?.dispose(),this._eventSystem?.removeEventListener(ey.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._didSetTarget=0,this._didApplyLookAtTarget=!1,this._enableTime=this.context.time.time;const e=P.getComponent(this.gameObject,Jt);this._camera=e;let t=e?.threeCamera;if(!t&&this.gameObject instanceof c.PerspectiveCamera&&(t=this.gameObject),t&&fg(t,this,!0),!this._controls&&t instanceof c.Object3D){this._cameraObject=t;const i=this.targetElement??this.context.renderer.domElement,n=t?.quaternion.clone();this._controls=new V.OrbitControls(t,i),t?.quaternion.copy(n),_m===void 0&&(_m={...this._controls.keys});const o=ie(t),r=this.gameObject.worldForward,l=o.clone().sub(r.multiplyScalar(2.5));this._controls.target.copy(l)}if(this._controls)if(ym&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,exports.DeviceUtilities.isMobileDevice()&&(this.doubleClickToFocus=!0)),this._controls.addEventListener("start",this.onControlsChangeStarted),this._controls.addEventListener("endMovement",this.onControlsChangeEnded),!this._startedListeningToKeyEvents&&this.enableKeys)this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(this.context.domElement);else try{this._controls.stopListenToKeyEvents()}catch{}this._syncedTransform=P.getComponent(this.gameObject,Sn)??void 0,this.context.pre_render_callbacks.push(this.__onPreRender),this._activePointerEvents=[],this.context.input.addEventListener("pointerdown",this._onPointerDown,{queue:xo.Early}),this.context.input.addEventListener("pointerdown",this._onPointerDownLate,{queue:xo.Late}),this.context.input.addEventListener("pointerup",this._onPointerUp,{queue:xo.Early}),this.context.input.addEventListener("pointerup",this._onPointerUpLate,{queue:xo.Late})}onDisable(){if(this._camera?.threeCamera&&fg(this._camera.threeCamera,this,!1),this._controls){this._controls.enabled=!1,this._controls.autoRotate=!1,this._controls.removeEventListener("start",this.onControlsChangeStarted),this._controls.removeEventListener("endMovement",this.onControlsChangeEnded);try{this._controls.stopListenToKeyEvents()}catch{}this._startedListeningToKeyEvents=!1}this._activePointerEvents.length=0,this.context.input.removeEventListener("pointerdown",this._onPointerDown),this.context.input.removeEventListener("pointerdown",this._onPointerDownLate),this.context.input.removeEventListener("pointerup",this._onPointerUp),this.context.input.removeEventListener("pointerup",this._onPointerUpLate)}_activePointerEvents;_lastTimeClickOnBackground=-1;_clickOnBackgroundCount=0;_onPointerDown=e=>{this._activePointerEvents.push(e)};_onPointerDownLate=e=>{e.used&&this._controls&&(this._controls.enabled=!1)};_onPointerUp=e=>{for(let t=this._activePointerEvents.length-1;t>=0;t--){const i=this._activePointerEvents[t];if(i.pointerId===e.pointerId&&i.button===e.button){this._activePointerEvents.splice(t,1);break}}if(this.clickBackgroundToFitScene>0&&e.isClick&&e.button===0){if(e.hasRay||e.intersections.push(...this.context.physics.raycast()),e.intersections.length<=0){const t=this.context.time.time-this._lastTimeClickOnBackground;this._lastTimeClickOnBackground=this.context.time.time,this.clickBackgroundToFitScene<=1||t<this.clickBackgroundToFitScene*.15?(this._clickOnBackgroundCount+=1,this._clickOnBackgroundCount>=this.clickBackgroundToFitScene-1&&(this.autoRotate=!1,this.fitCamera({objects:this.context.scene,immediate:!1}))):this._clickOnBackgroundCount=0}kt&&console.log(this.clickBackgroundToFitScene,e.intersections.length,this._clickOnBackgroundCount)}};_onPointerUpLate=e=>{this.doubleClickToFocus&&e.isDoubleClick&&!e.used&&this.canFocusAtPointer()&&this.setTargetFromRaycast()};updateTargetNow(e){kt&&console.warn("OrbitControls: updateTargetNow is using raycasting to update the target immediately. This can be expensive and should be used with caution.",e);const t=new c.Ray(this._cameraObject?.worldPosition,this._cameraObject?.worldForward.multiplyScalar(-1)),i=this.context.physics.raycastFromRay(t,e),n=i.length>0?i[0]:void 0;n&&n.distance>this.minZoom&&n.distance<this.maxZoom?(kt&&B.DrawWireSphere(n.point,.1,16711680,2),this._controls?.target.copy(i[0].point)):kt&&console.log("OrbitControls: No hit found when updating target",{hits:[...i]})}_orbitStartAngle=0;_zoomStartDistance=0;onControlsChangeStarted=()=>{kt&&console.debug("OrbitControls: Change started"),this._controls&&(this._orbitStartAngle=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle(),this._zoomStartDistance=this._controls.getDistance()),this._syncedTransform&&this._syncedTransform.requestOwnership()};onControlsChangeEnded=()=>{if(kt&&console.debug("OrbitControls: Change ended",{autoTarget:this.autoTarget}),this._controls&&this.autoTarget){const t=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle()-this._orbitStartAngle;Math.abs(t)<.01?(kt&&console.debug("OrbitControls: Update target",{deltaAngle:t}),this.updateTargetNow({allowSlowRaycastFallback:!1})):kt&&console.debug("OrbitControls: No target update",{deltaAngle:t})}};_shouldDisable=!1;afterHandleInput(e){e.detail.args.pointerId===0&&(e.detail.args.isDown?this._controls&&this._eventSystem&&(this._shouldDisable=this._eventSystem.hasActiveUI):(!e.detail.args.isPressed||e.detail.args.isUp)&&(this._shouldDisable=!1))}onPausedChanged(e){this._controls&&e&&(this._controls.enabled=!1)}onBeforeRender(){if(!this._controls)return;if(this._cameraObject!==this.context.mainCamera){this._controls.enabled=!1;return}this._controls.enabled=!0;const e=this.context.input.getPointerDown(0)&&(this.context.input.getPointerPositionDelta(0)?.length()||0)>.1;if((this.context.input.getPointerDown(1)||this.context.input.getPointerDown(2)||this.context.input.mouseWheelChanged||e)&&(this._inputs+=1),this._inputs>0&&this.allowInterrupt&&(this.enableRotate&&(this.autoRotate=!1),this._cameraLerpActive=!1,this._lookTargetLerpActive=!1),this._inputs=0,this.autoTarget&&this._didSetTarget++===0){const i=P.getComponent(this.gameObject,Jt);if(i&&!this.setLookTargetFromConstraint()){this.debugLog&&console.log("NO TARGET");const n=ie(i.threeCamera),o=Math.max(.01,n.length()),r=new c.Vector3(0,0,-o).applyMatrix4(i.threeCamera.matrixWorld);kt&&B.DrawLine(n,r,5592575,10),this.setLookTargetPosition(r,!0)}if(!this.setLookTargetFromConstraint()){const n=new zr;n.screenPoint=new c.Vector2(0,0),n.lineThreshold=.1;const o=this.context.physics.raycast(n);o.length>0&&this.setLookTargetPosition(o[0].point,!0),oT&&console.log("OrbitControls hits",...o)}}if(this.middleClickToFocus&&this.context.input.getPointerClicked(1)&&this.canFocusAtPointer()&&this.setTargetFromRaycast(),this._lookTargetLerpActive||this._cameraLerpActive||this._fovLerpActive){if(this._cameraLerpActive&&this._cameraObject)if(this._cameraLerp01+=this.context.time.deltaTime/this._cameraLerpDuration,this._cameraLerp01>=1)this._cameraObject.position.copy(this._cameraEndPosition),this._cameraLerpActive=!1,this.dispatchEvent(new ph(this,"camera"));else{const i=L.easeInOutCubic(this._cameraLerp01);this._cameraObject.position.lerpVectors(this._cameraStartPosition,this._cameraEndPosition,i)}if(this._lookTargetLerpActive)if(this._lookTargetLerp01+=this.context.time.deltaTime/this._lookTargetLerpDuration,this._lookTargetLerp01>=1)this.lerpLookTarget(this._lookTargetEndPosition,this._lookTargetEndPosition,1),this._lookTargetLerpActive=!1,this.dispatchEvent(new ph(this,"lookat"));else{const i=L.easeInOutCubic(this._lookTargetLerp01);this.lerpLookTarget(this._lookTargetStartPosition,this._lookTargetEndPosition,i)}if(this._fovLerpActive&&this._cameraObject){const i=this._cameraObject;if(this._fovLerp01+=this.context.time.deltaTime/this._fovLerpDuration,this._fovLerp01>=1)i.fov=this._fovLerpEndValue,this._fovLerpActive=!1;else{const n=L.easeInOutCubic(this._fovLerp01);i.fov=L.lerp(this._fovLerpStartValue,this._fovLerpEndValue,n)}i.updateProjectionMatrix()}}if(this.targetBounds){const i=this.targetBounds.worldPosition,n=F(this.targetBounds.worldScale).multiplyScalar(.5),o=F(i).sub(n),r=F(i).add(n);if(this._lookTargetLerpActive)this._lookTargetEndPosition.clamp(o,r);else{const a=this._controls.target,l=F(a).clamp(o,r).sub(a);l.multiplyScalar(Math.min(1,this.context.time.deltaTime/.1)),a.add(l),this._cameraObject?.position.add(l)}kt&&B.DrawWireBox(i,n.multiplyScalar(2),16755200)}if(this._controls){this.debugLog&&(this._controls.domElement=this.context.renderer.domElement);const i=1/(this.context.focusRectSettings?.zoom||1);if(this._controls.enabled=!this._shouldDisable&&this._camera===this.context.mainCameraComponent&&!this.context.isInXR&&!this._activePointerEvents.some(n=>n.used),this._controls.keys=this.enableKeys?_m:rT,this._controls.autoRotate=this.autoRotate,this._controls.autoRotateSpeed=this.autoRotateSpeed,this._controls.enableZoom=this.enableZoom,this._controls.zoomSpeed=this.zoomSpeed,this._controls.zoomToCursor=this.zoomToCursor,this._controls.enableDamping=this.enableDamping,this._controls.dampingFactor=this.dampingFactor,this._controls.enablePan=this.enablePan,this._controls.panSpeed=i,this._controls.enableRotate=this.enableRotate,this._controls.minAzimuthAngle=this.minAzimuthAngle??1/0,this._controls.maxAzimuthAngle=this.maxAzimuthAngle??1/0,this._controls.minPolarAngle=this.minPolarAngle??0,this._controls.maxPolarAngle=this.maxPolarAngle??Math.PI,ym||(this._camera?.threeCamera?.type==="PerspectiveCamera"?(this._controls.minDistance=this.minZoom??0,this._controls.maxDistance=this.maxZoom??1/0,this._controls.minZoom=0,this._controls.maxZoom=1/0):(this._controls.minDistance=0,this._controls.maxDistance=1/0,this._controls.minZoom=this.minZoom??0,this._controls.maxZoom=this.maxZoom??1/0)),typeof Id=="number"||Id===!0){this._controls.enableDamping=!0;const n=typeof Id=="number"?Id:.99;this._controls.dampingFactor=Math.max(.001,1-Math.min(1,n))}if(this.allowInterrupt||(this._lookTargetLerpActive&&(this._controls.enablePan=!1),this._cameraLerpActive&&(this._controls.enableRotate=!1,this._controls.autoRotate=!1),(this._lookTargetLerpActive||this._cameraLerpActive)&&(this._controls.enableZoom=!1)),!this.context.isInXR&&(!ym&&this.lookAtTarget&&!this._lookTargetLerpActive&&(this.lockLookAtTarget?this.setLookTargetFromConstraint(this.lookAtConstraint01):this._didApplyLookAtTarget||(this._didApplyLookAtTarget=!0,this.setLookTargetFromConstraint(1))),this._controls.update(this.context.time.deltaTime),kt)){const n=this._controls.getDistance();B.DrawWireSphere(this._controls.target,.01*n,65280)}}}__onPreRender=()=>{const e=this.context.pre_render_callbacks.indexOf(this.__onPreRender);e>=0&&this.context.pre_render_callbacks.splice(e,1),this.autoFit&&(this.autoFit=!1,this.fitCamera({centerCamera:"y",immediate:!0,objects:this.scene.children}))};setCameraAndLookTarget(e,t=!1){if(!e)return(E()||kt)&&console.warn("[OrbitControls] setCameraAndLookTarget target is null"),!1;if(!(e instanceof c.Object3D)&&!(e instanceof Jt))return(E()||kt)&&console.warn("[OrbitControls] setCameraAndLookTarget target is not an Object3D or Camera"),!1;e instanceof Jt&&(e=e.gameObject);const i=e.worldPosition,n=e.worldForward;e instanceof c.Camera&&(kt&&console.debug("[OrbitControls] setCameraAndLookTarget flip forward direction for camera"),n.multiplyScalar(-1));const o=new c.Ray(i,n);return kt&&B.DrawRay(o.origin,o.direction,16711680,10),this.setTargetFromRaycast(o,t)||this.setLookTargetPosition(o.at(2,F()),t),this.setCameraTargetPosition(i,t),!0}setCameraTargetPosition(e,t=!1){e&&(e instanceof c.Object3D&&(e=ie(e)),this._cameraEndPosition||(this._cameraEndPosition=new c.Vector3),this._cameraEndPosition.copy(e),t===!0?(this._cameraLerpActive=!1,this._cameraObject&&this._cameraObject.position.copy(this._cameraEndPosition)):this._cameraObject&&(this._cameraLerpActive=!0,this._cameraLerp01=0,this._cameraStartPosition.copy(this._cameraObject?.position),typeof t=="number"?this._cameraLerpDuration=t:this._cameraLerpDuration=this.targetLerpDuration))}get cameraLerpActive(){return this._cameraLerpActive}stopCameraLerp(){this._cameraLerpActive=!1}setFieldOfView(e,t=!1){if(!this._controls||typeof e!="number")return;const i=this._camera?.threeCamera;i&&(t===!0?i.fov=e:(this._fovLerpActive=!0,this._fovLerp01=0,this._fovLerpStartValue=i.fov,this._fovLerpEndValue=e,typeof t=="number"?this._fovLerpDuration=t:this._fovLerpDuration=this.targetLerpDuration))}setLookTargetPosition(e=null,t=!1){if(this._controls&&e){if(e instanceof c.Object3D&&(e=ie(e)),this._lookTargetEndPosition.copy(e),this._didSetTarget++,kt){console.warn("OrbitControls: setLookTargetPosition",e,t);const i=this._controls.getDistance();B.DrawWireSphere(this._lookTargetEndPosition,.01*i,16733440,2)}t===!0?this.lerpLookTarget(this._lookTargetEndPosition,this._lookTargetEndPosition,1):(this._lookTargetLerpActive=!0,this._lookTargetLerp01=0,this._lookTargetStartPosition.copy(this._controls.target),typeof t=="number"?this._lookTargetLerpDuration=t:this._lookTargetLerpDuration=this.targetLerpDuration)}}get lookTargetLerpActive(){return this._lookTargetLerpActive}stopLookTargetLerp(){this._lookTargetLerpActive=!1}setLookTargetFromConstraint(e=1){return!this._controls||!this.lookAtTarget?!1:(this.lookAtTarget.getWorldPosition(this._lookTargetEndPosition),this.lerpLookTarget(this._controls.target,this._lookTargetEndPosition,e),!0)}lerpLookTarget(e,t,i){this._controls&&(i>=1?this._controls.target.copy(t):this._controls.target.lerpVectors(e,t,i),this.lookAtTarget&&this.lockLookAtTarget&&(this.lookAtTarget.worldPosition=this._controls.target))}canFocusAtPointer(){return!(this.lookAtTarget&&this.lockLookAtTarget)}setTargetFromRaycast(e,t=!1){if(!this.controls)return!1;const i=e?this.context.physics.raycastFromRay(e):this.context.physics.raycast();for(const n of i)if(n.distance>0&&P.isActiveInHierarchy(n.object)){const o=g_(n.object);if(o&&o.canvas?.screenspace)break;return this.setLookTargetPosition(n.point,t),!0}return!1}fitCamera(e,t){let i;if(Array.isArray(e)||e&&"type"in e?i=e:e&&typeof e=="object"&&!(e instanceof c.Object3D)&&!Array.isArray(e)&&(t=e,i=t.objects),i&&!Array.isArray(i)&&(i=[i]),(!Array.isArray(i)||i&&i.length<=0)&&(i=this.context.scene.children),!Array.isArray(i)||i.length<=0){console.warn("No objects to fit camera to...");return}const n=aC({objects:[...i],...t,autoApply:!1,context:this.context,camera:this._cameraObject,currentZoom:this._controls?.getDistance()||void 0,minZoom:this.minZoom,maxZoom:this.maxZoom});n&&(this.setLookTargetPosition(n.lookAt,t?.immediate||!1),this.setCameraTargetPosition(n.position,t?.immediate||!1),this.setFieldOfView(t?.fov,t?.immediate||!1),this.onBeforeRender())}_haveAttachedKeyboardEvents=!1}Pe([p()],ue.prototype,"autoTarget",2);Pe([p()],ue.prototype,"autoFit",2);Pe([p()],ue.prototype,"enableRotate",2);Pe([p()],ue.prototype,"autoRotate",2);Pe([p()],ue.prototype,"autoRotateSpeed",2);Pe([p()],ue.prototype,"minAzimuthAngle",2);Pe([p()],ue.prototype,"maxAzimuthAngle",2);Pe([p()],ue.prototype,"minPolarAngle",2);Pe([p()],ue.prototype,"maxPolarAngle",2);Pe([p()],ue.prototype,"enableKeys",2);Pe([p()],ue.prototype,"enableDamping",2);Pe([p()],ue.prototype,"dampingFactor",2);Pe([p()],ue.prototype,"enableZoom",2);Pe([p()],ue.prototype,"minZoom",2);Pe([p()],ue.prototype,"maxZoom",2);Pe([p()],ue.prototype,"zoomSpeed",2);Pe([p()],ue.prototype,"enablePan",2);Pe([p(c.Object3D)],ue.prototype,"lookAtTarget",2);Pe([p()],ue.prototype,"lockLookAtTarget",2);Pe([p()],ue.prototype,"lookAtConstraint01",2);Pe([p(Vr)],ue.prototype,"lookAtConstraint",2);Pe([p()],ue.prototype,"allowInterrupt",2);Pe([p()],ue.prototype,"middleClickToFocus",2);Pe([p()],ue.prototype,"doubleClickToFocus",2);Pe([p()],ue.prototype,"clickBackgroundToFitScene",2);Pe([p()],ue.prototype,"targetLerpDuration",1);Pe([p(c.Object3D)],ue.prototype,"targetBounds",2);var aT=Object.defineProperty,lT=Object.getOwnPropertyDescriptor,ii=(s,e,t,i)=>{for(var n=i>1?void 0:i?lT(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&aT(e,t,n),n},Or=(s=>(s[s.None=0]="None",s[s.Skybox=1]="Skybox",s[s.SolidColor=2]="SolidColor",s[s.Uninitialized=4]="Uninitialized",s))(Or||{});const uo=x("debugcam"),d0=x("debugscreenpointtoray"),zt=class kc extends T{get isCamera(){return!0}get aspect(){return this._cam instanceof c.PerspectiveCamera?this._cam.aspect:this.context.domWidth/this.context.domHeight}set aspect(e){this._cam instanceof c.PerspectiveCamera&&this._cam.aspect!==e&&(this._cam.aspect=e,this._cam.updateProjectionMatrix())}get fieldOfView(){return this._cam instanceof c.PerspectiveCamera?this._cam.fov:this._fov}set fieldOfView(e){const t=this.fieldOfView!=e;if(this._fov=e,t&&this._cam&&this._cam instanceof c.PerspectiveCamera){if(this._fov===void 0){console.warn("Can not set undefined fov on PerspectiveCamera");return}this._cam.fov=this._fov,this._cam.updateProjectionMatrix()}}get nearClipPlane(){return this._nearClipPlane}set nearClipPlane(e){const t=this._nearClipPlane!=e;this._nearClipPlane=e,this._cam&&(t||this._cam.near!=e)&&(this._cam.near=e,this._cam.updateProjectionMatrix())}_nearClipPlane=.1;get farClipPlane(){return this._farClipPlane}set farClipPlane(e){const t=this._farClipPlane!=e;this._farClipPlane=e,this._cam&&(t||this._cam.far!=e)&&(this._cam.far=e,this._cam.updateProjectionMatrix())}_farClipPlane=1e3;applyClippingPlane(){this._cam&&(this._cam.near=this._nearClipPlane,this._cam.far=this._farClipPlane,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(e){if(typeof e=="string")switch(e){case"skybox":e=1;break;case"solidcolor":e=2;break;default:e=0;break}e!==this._clearFlags&&(this._clearFlags=e,this.applyClearFlagsIfIsActiveCamera())}orthographic=!1;orthographicSize=5;ARBackgroundAlpha=0;set cullingMask(e){this._cullingMask=e,this._cam&&(this._cam.layers.mask=e)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}_cullingMask=4294967295;set cullingLayer(e){this.cullingMask=(1<<e|0)>>>0}set backgroundBlurriness(e){e!==this._backgroundBlurriness&&(e===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(e,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}_backgroundBlurriness=void 0;set backgroundIntensity(e){e!==this._backgroundIntensity&&(e===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(e,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}_backgroundIntensity=void 0;set backgroundRotation(e){e!==this._backgroundRotation&&(e===void 0?this._backgroundRotation=void 0:this._backgroundRotation=e,this.applyClearFlagsIfIsActiveCamera())}get backgroundRotation(){return this._backgroundRotation}_backgroundRotation=void 0;set environmentIntensity(e){this._environmentIntensity=e}get environmentIntensity(){return this._environmentIntensity}_environmentIntensity=void 0;get backgroundColor(){return this._backgroundColor??null}set backgroundColor(e){e&&(this._backgroundColor||(this._backgroundColor=new oe(1,1,1,1)),this._backgroundColor.copy(e),(!("alpha"in e)||e.alpha===void 0)&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera())}set targetTexture(e){this._targetTexture=e}get targetTexture(){return this._targetTexture}_targetTexture=null;_backgroundColor;_fov;_cam=null;_clearFlags=2;_skybox;get cam(){return this.threeCamera}get threeCamera(){return this.activeAndEnabled&&this.buildCamera(),this._cam}static _origin=new c.Vector3;static _direction=new c.Vector3;screenPointToRay(e,t,i){const n=this.threeCamera,o=kc._origin;o.set(e,t,-1),this.context.input.convertScreenspaceToRaycastSpace(o),d0&&console.log("screenPointToRay",e.toFixed(2),t.toFixed(2),"now:",o.x.toFixed(2),o.y.toFixed(2),"isInXR:"+this.context.isInXR),o.z=-1,o.unproject(n);const r=kc._direction.set(o.x,o.y,o.z),a=ie(n);return r.sub(a),r.normalize(),i?(i.set(a,r),i):new c.Ray(a.clone(),r.clone())}_frustum;getFrustum(){return this._frustum||(this._frustum=new c.Frustum,this.updateFrustum()),this._frustum}updateFrustum(){this._frustum||(this._frustum=new c.Frustum),this._frustum.setFromProjectionMatrix(this.getProjectionScreenMatrix(this._projScreenMatrix,!0),this.context.renderer.coordinateSystem)}getProjectionScreenMatrix(e,t){return t&&this._projScreenMatrix.multiplyMatrices(this.threeCamera.projectionMatrix,this.threeCamera.matrixWorldInverse),e===this._projScreenMatrix?e:e.copy(this._projScreenMatrix)}_projScreenMatrix=new c.Matrix4;awake(){d0&&window.addEventListener("pointerdown",e=>{const t=e.clientX,i=e.clientY;console.log("touch",t.toFixed(2),i.toFixed(2));const n=this.screenPointToRay(t,i),o="#"+Math.floor(Math.random()*16777215).toString(16);B.DrawRay(n.origin,n.direction,o,10)})}onEnable(){uo&&console.log(`Camera enabled: "${this.name}". ClearFlags=${Or[this._clearFlags]}`,this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),hT(this)),this.applyClearFlagsIfIsActiveCamera({applySkybox:!0})}onDisable(){this.context.removeCamera(this)}onLeaveXR(e){this.fieldOfView=this._fov}onBeforeRender(){if(this._cam&&(this._frustum&&this.updateFrustum(),this._clearFlags===2&&this.applyClearFlagsIfIsActiveCamera(),this._targetTexture)){this.context.isManagedExternally&&(this._warnedAboutExternalRenderer||(this._warnedAboutExternalRenderer=!0,console.warn("Rendering with external renderer is not supported yet. This may not work or throw errors. Please remove the the target texture from your camera: "+this.name,this.targetTexture))),this.context.composer;const e=this.context.renderer;if(e){const t=this.context.mainCameraComponent;this.applyClearFlags(),this._targetTexture.render(this.context.scene,this._cam,e),t?.applyClearFlags()}}}buildCamera(){if(this._cam)return;const e=this.gameObject.isCamera;let t=null;if(e?(t=this.gameObject,t?.layers.enableAll(),t instanceof c.PerspectiveCamera&&(this._fov=t.fov)):t=this.gameObject.children[0],t&&t.isCamera)t instanceof c.PerspectiveCamera&&(this._fov&&(t.fov=this._fov),t.near=this._nearClipPlane,t.far=this._farClipPlane,t.updateProjectionMatrix());else if(!this.orthographic)t=new c.PerspectiveCamera(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),this.fieldOfView&&(t.fov=this.fieldOfView),this.gameObject.add(t);else{const i=this.orthographicSize*100;t=new c.OrthographicCamera(window.innerWidth/-i,window.innerWidth/i,window.innerHeight/i,window.innerHeight/-i,this._nearClipPlane,this._farClipPlane),this.gameObject.add(t)}this._cam=t,this._cam.layers.mask=this._cullingMask,this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(e){this.context.mainCameraComponent===this&&this.applyClearFlags(e)}applyClearFlags(e){if(!this._cam){uo&&console.log("Camera does not exist (apply clear flags)");return}if(this.fieldOfView=this.fieldOfView,uo){const i=`[Camera] Apply ClearFlags: ${Or[this._clearFlags]} - "${this.name}"`;console.debug(i)}const t=this.context.domElement.getAttribute("background-image")||this.context.domElement.getAttribute("background-color");if(this._clearFlags!==0)if(kc.backgroundShouldBeTransparent(this.context)&&(!this.ARBackgroundAlpha||this.ARBackgroundAlpha<.001)){this.context.scene.background!==null&&(this._backgroundStashedForXR=this.context.scene.background),this.context.scene.background=null,this.context.renderer.setClearColor(0,0);return}else this._backgroundStashedForXR!==void 0&&(this.context.scene.background===null&&(this.context.scene.background=this._backgroundStashedForXR),this._backgroundStashedForXR=void 0);switch(this._clearFlags){case 0:return;case 1:(!this.scene.background||!this._skybox||e?.applySkybox===!0)&&this.applySceneSkybox(),this._backgroundBlurriness!==void 0&&!this.context.domElement.getAttribute("background-blurriness")?this.context.scene.backgroundBlurriness=this._backgroundBlurriness:uo&&console.warn(`Camera "${this.name}" has no background blurriness`),this._backgroundIntensity!==void 0&&!this.context.domElement.getAttribute("background-intensity")&&(this.context.scene.backgroundIntensity=this._backgroundIntensity),this._backgroundRotation!==void 0&&!this.context.domElement.getAttribute("background-rotation")?this.context.scene.backgroundRotation=this._backgroundRotation:uo&&console.warn(`Camera "${this.name}" has no background intensity`);break;case 2:if(this._backgroundColor&&!t){let i=this._backgroundColor.alpha;kc.backgroundShouldBeTransparent(this.context)&&(i=this.ARBackgroundAlpha??0),this.context.xr?.isVR?this.context.renderer.setClearColor(qw(this._backgroundColor).convertLinearToSRGB()):this.context.renderer.setClearColor(this._backgroundColor,i)}else this._backgroundColor||uo&&console.warn(`[Camera] has no background color "${this.name}" `);break;case 4:t||this.context.renderer.setClearColor(0,0);break}}_backgroundStashedForXR;applySceneSkybox(){this._skybox||(this._skybox=new cT(this)),this._skybox.apply()}static backgroundShouldBeTransparent(e){const t=e.renderer.xr?.getSession();if(!t)return!1;if(typeof t._transparent=="boolean")return t._transparent;const i=t.environmentBlendMode;uo&&Re("Environment blend mode: "+i+" on "+navigator.userAgent);let n=i==="additive"||i==="alpha-blend";if(e.isInAR&&i==="opaque"){if(navigator.userAgent?.includes("OculusBrowser"))n=!0;else if(navigator.userAgent?.includes("Mozilla")&&navigator.userAgent?.includes("Mobile WebXRViewer/v2"))n=!0;else if(exports.DeviceUtilities.isNeedleAppClip())return!0}return t._transparent=n,n}};ii([p()],zt.prototype,"aspect",1);ii([p()],zt.prototype,"fieldOfView",1);ii([p()],zt.prototype,"nearClipPlane",1);ii([p()],zt.prototype,"farClipPlane",1);ii([p()],zt.prototype,"clearFlags",1);ii([p()],zt.prototype,"orthographic",2);ii([p()],zt.prototype,"orthographicSize",2);ii([p()],zt.prototype,"ARBackgroundAlpha",2);ii([p()],zt.prototype,"cullingMask",1);ii([p()],zt.prototype,"backgroundBlurriness",1);ii([p()],zt.prototype,"backgroundIntensity",1);ii([p(c.Euler)],zt.prototype,"backgroundRotation",1);ii([p()],zt.prototype,"environmentIntensity",1);ii([p(oe)],zt.prototype,"backgroundColor",1);ii([p(es)],zt.prototype,"targetTexture",1);let Jt=zt;class cT{_camera;_skybox;get context(){return this._camera?.context}constructor(e){this._camera=e}apply(){if(this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),!this._skybox)this._did_log_failed_to_find_skybox||(this._did_log_failed_to_find_skybox=!0,console.warn(`Camera "${this._camera.name}" has no skybox texture. ${this._camera.sourceId}`));else if(this.context.scene.background!==this._skybox){const e=this.context.domElement.getAttribute("background-image")||this.context.domElement.getAttribute("background-color");uo&&console.debug(`[Camera] Apply Skybox ${this._skybox?.name} ${e} - "${this._camera.name}"`),e?.length||(this._skybox.mapping!==c.CubeUVReflectionMapping&&(this._skybox.mapping=c.EquirectangularReflectionMapping),this.context.scene.background=this._skybox)}}}function hT(s){x("freecam")&&s.context.mainCameraComponent===s&&P.getOrAddComponent(s.gameObject,ue)}class Ms extends T{get listener(){return this._listener==null&&(this._listener=new c.AudioListener),this._listener}_listener=null;onEnable(){wn.registerWaitForInteraction(this.onInteraction),this.addListenerIfItExists()}onDisable(){wn.unregisterWaitForInteraction(this.onInteraction),this.removeListenerIfItExists()}onInteraction=()=>{this.destroyed||this.listener==null||this.addListenerIfItExists()};addListenerIfItExists(){const e=this._listener;if(!e||e?.parent)return;const t=this.context.mainCameraComponent||P.getComponentInParent(this.gameObject,Jt);t?.threeCamera?t.threeCamera.add(e):this.gameObject.add(e),e.filter?(e.gain.connect(e.filter),e.filter.connect(e.context.destination)):e.gain.connect(e.context.destination)}removeListenerIfItExists(){const e=this._listener;e&&(e.removeFromParent(),e.filter&&e.filter.disconnect(),e.gain&&e.gain.disconnect())}}var dT=Object.defineProperty,uT=Object.getOwnPropertyDescriptor,Pn=(s,e,t,i)=>{for(var n=i>1?void 0:i?uT(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&dT(e,t,n),n};const ct=x("debugaudio");var hC=(s=>(s[s.Logarithmic=0]="Logarithmic",s[s.Linear=1]="Linear",s[s.Custom=2]="Custom",s))(hC||{});const nn=class vs extends T{static get userInteractionRegistered(){return wn.userInteractionRegistered}static registerWaitForAllowAudio(e){wn.registerWaitForInteraction(e)}clip="";playOnAwake=!1;preload=!0;playInBackground=!0;get isPlaying(){return this._audioElement?!this._audioElement.paused&&!this._audioElement.ended:this.sound?.isPlaying??!1}get duration(){const e=this._usesMediaElementSource?this._audioElement?.duration:void 0;if(e&&isFinite(e))return e;if(this.sound?.buffer?.duration)return this.sound.buffer.duration;if(this._loadedClip instanceof MediaStream)return}get time01(){const e=this.duration;return e?this.time/e:0}set time01(e){const t=this.duration;t&&(this.time=e*t)}get time(){return this._usesMediaElementSource&&this._audioElement?this._audioElement.currentTime:this.sound?.source?this.sound.source?.context.currentTime-this._lastContextTime+this.sound.offset:0}set time(e){if(this._usesMediaElementSource&&this._audioElement){this._audioElement.currentTime=e;return}if(this.sound){if(e===this.sound.offset)return;const t=this.isPlaying;this.stop(),this.sound.offset=e,t&&this.play()}}get loop(){return this._usesMediaElementSource&&this._audioElement?(this._loop=this._audioElement.loop,this._loop):(this.sound&&(this._loop=this.sound.getLoop()),this._loop)}set loop(e){this._loop=e,this._usesMediaElementSource&&this._audioElement?this._audioElement.loop=e:this.sound&&this.sound.setLoop(e)}get spatialBlend(){return this._spatialBlend}set spatialBlend(e){e!==this._spatialBlend&&(this._spatialBlend=e,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(e){this._minDistance!==e&&(this._minDistance=e,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(e){this._maxDistance!==e&&(this._maxDistance=e,this._needUpdateSpatialDistanceSettings=!0)}_spatialBlend=0;_minDistance=1;_maxDistance=100;get volume(){return this._volume}set volume(e){this._volume=e,this.sound&&!this.context.application.muted&&(ct&&console.log(this.name,"audio set volume",e),this.sound.setVolume(e))}_volume=1;set pitch(e){this._usesMediaElementSource&&this._audioElement?this._audioElement.playbackRate=e:this.sound&&this.sound.setPlaybackRate(e)}get pitch(){return this._usesMediaElementSource&&this._audioElement?this._audioElement.playbackRate:this.sound?this.sound.getPlaybackRate():1}rollOffMode=0;_loop=!1;sound=null;helper=null;wasPlaying=!1;shouldPlay=!1;_loadedClip=null;_audioElement=null;_usesMediaElementSource=!1;_entryNode=null;_spatialGain=null;_bypassGain=null;get Sound(){if(!this.sound&&vs.userInteractionRegistered){let e=this.gameObject.getComponent(Ms)??this.context.mainCamera.getComponent(Ms)??kl(Ms,this.context,!1);!e&&this.context.mainCamera&&(e=this.context.mainCamera.addComponent(Ms)),e?.listener?(this.sound=new c.PositionalAudio(e.listener),this.gameObject?.add(this.sound)):ct&&console.warn("No audio listener found in scene - can not play audio")}return this.sound}get ShouldPlay(){return this.shouldPlay}get audioContext(){return this.sound?.context}ensureContextResumed(){const e=this.audioContext;!e||(typeof document<"u"?document.visibilityState:"visible")!=="visible"||e.resume().catch(i=>{ct&&console.warn("[AudioSource] Failed to resume AudioContext:",i)})}awake(){ct&&console.log("[AudioSource]",this),this.playOnAwake&&(this.shouldPlay=!0),this.preload&&typeof this.clip=="string"&&this.clip.length>0&&(this.Sound?this.createAudioFromElement():vs.registerWaitForAllowAudio(()=>{this.destroyed||this.enabled===!1||typeof this.clip=="string"&&this.clip.length>0&&this.createAudioFromElement()}))}onEnable(){this.sound&&this.gameObject.add(this.sound),vs.userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():vs.registerWaitForAllowAudio(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.onNewClip(this.clip)}),globalThis.addEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.addEventListener(Mg.MuteChanged,this.onApplicationMuteChanged)}onDisable(){globalThis.removeEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.removeEventListener(Mg.MuteChanged,this.onApplicationMuteChanged),this.pause()}onVisibilityChanged=()=>{switch(document.visibilityState){case"hidden":if(this.playInBackground===!1||exports.DeviceUtilities.isMobileDevice()){const e=this.isPlaying;e&&this.pause(),this.wasPlaying=e}break;case"visible":ct&&console.log("visible",this.enabled,this.playOnAwake,!this.isPlaying,vs.userInteractionRegistered,this.wasPlaying),this.enabled&&!this.isPlaying&&vs.userInteractionRegistered&&this.wasPlaying&&this.play();break}};onApplicationMuteChanged=()=>{this.context.application.muted?this.sound?.setVolume(0):this.sound?.setVolume(this.volume)};createAudioFromElement(){if(this.destroyed){ct&&console.warn("AudioSource destroyed, not creating audio",this.name);return}const e=this.Sound;if(!e){ct&&console.warn("Failed getting sound?",this.name);return}if(this._audioElement&&this._usesMediaElementSource&&this._loadedClip===this.clip){this.context.application.muted?e.setVolume(0):e.setVolume(this.volume);return}if(this._audioElement&&this._loadedClip!==this.clip&&(this._audioElement.pause(),this._audioElement=null,this._usesMediaElementSource=!1),!this._audioElement){const i=new Audio;i.crossOrigin="anonymous",i.preload="auto",i.src=this.clip,this._audioElement=i}this._audioElement.loop=this._loop,this.setupSpatialBlendNodes(),this._usesMediaElementSource||(e.setMediaElementSource(this._audioElement),this._usesMediaElementSource=!0),this._loadedClip=this.clip,this.context.application.muted?e.setVolume(0):e.setVolume(this.volume),this.applySpatialDistanceSettings()}createAudio=()=>{if(this.destroyed){ct&&console.warn("AudioSource destroyed, not creating audio",this.name);return}const e=this.Sound;if(!e){ct&&console.warn("Failed getting sound?",this.name);return}this._loadedClip=this.clip,this.context.application.muted?e.setVolume(0):e.setVolume(this.volume),this.setupSpatialBlendNodes(),this.applySpatialDistanceSettings(),vs.registerWaitForAllowAudio(this.__onAllowAudioCallback)};__onAllowAudioCallback=()=>{this.shouldPlay&&this.play()};setupSpatialBlendNodes(){const e=this.sound;if(!e||this._entryNode)return;const t=e.context;this._entryNode=t.createGain(),this._spatialGain=t.createGain(),this._bypassGain=t.createGain();try{e.panner.disconnect(e.gain)}catch{}this._entryNode.connect(e.panner),e.panner.connect(this._spatialGain),this._spatialGain.connect(e.gain),this._entryNode.connect(this._bypassGain),this._bypassGain.connect(e.gain),e.getOutput=()=>this._entryNode;const i=e.connect;e.connect=function(){i.call(e);try{e.panner.disconnect(e.gain)}catch{}return e};const n=e.disconnect;e.disconnect=function(){try{n.call(e)}catch{}return e},this.updateSpatialBlendGains()}updateSpatialBlendGains(){if(!this._spatialGain||!this._bypassGain||!this.sound)return;const e=this.sound.context.currentTime;this._spatialGain.gain.setTargetAtTime(this._spatialBlend,e,.01),this._bypassGain.gain.setTargetAtTime(1-this._spatialBlend,e,.01)}applySpatialDistanceSettings(){const e=this.sound;if(!e)return;this._needUpdateSpatialDistanceSettings=!1;const t=Math.max(1e-4,this._minDistance),i=Math.max(.01,this._maxDistance);switch(ct&&console.log(this.name,t,i,this.spatialBlend),e.setRefDistance(t),e.setMaxDistance(i),this.rollOffMode){case 0:e.setDistanceModel("inverse"),e.setRolloffFactor(99*t/Math.max(.001,i-t));break;case 1:e.setDistanceModel("linear"),e.setRolloffFactor(1);break;case 2:console.warn("Custom rolloff for AudioSource is not supported: "+this.name);break}this.updateSpatialBlendGains(),this.spatialBlend>0?ct&&!this.helper&&(this.helper=new V.PositionalAudioHelper(e,e.getRefDistance()),e.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}async onNewClip(e){e&&(this.clip=e),typeof e=="string"?(ct&&console.log(e),e.endsWith(".mp3")||e.endsWith(".wav")||e.endsWith(".ogg")||e.endsWith(".opus")||e.endsWith(".flac")||e.endsWith(".aac")||e.endsWith(".webm")?(this.shouldPlay=!0,this.createAudioFromElement(),this.shouldPlay&&vs.userInteractionRegistered&&(this.ensureContextResumed(),this._hasEnded=!1,this._audioElement?.play().catch(t=>{ct&&console.warn(`[AudioSource] Failed to play audio clip "${e}":`,t)}),this.fadeEntryGain(1))):console.warn("Unsupported audio clip type",e)):(this.shouldPlay=!0,this.createAudio())}async play(e=void 0){!e&&this.clip&&(e=this.clip),e!==void 0&&typeof e!="string"&&!(e instanceof MediaStream)&&(e=this.clip,E()&&console.warn("[AudioSource] Called play on AudioSource with unknown argument type:",e+`
1065
- Using the assigned clip instead:`,this.clip));let t=!this.sound||e&&e!==this._loadedClip;return typeof e=="string"&&(!this._audioElement||!this._usesMediaElementSource)&&(t=!0),(e instanceof MediaStream||typeof e=="string")&&(this.clip=e),t?(this.shouldPlay=!0,this.onNewClip(e).then(()=>!0).catch(()=>!1)):(this.shouldPlay=!0,this._hasEnded=!1,ct&&console.log("[AudioSource] play",this.sound?.getVolume(),this.sound),this.sound&&!this.isPlaying?(this.ensureContextResumed(),this.context.application.muted&&this.sound.setVolume(0),this.gameObject?.add(this.sound),this.clip instanceof MediaStream?(this._usesMediaElementSource=!1,this.sound.setMediaStreamSource(this.clip),this._audioElement||(this._audioElement=document.createElement("audio"),this._audioElement.style.display="none"),this._audioElement.parentNode||this.context.domElement.shadowRoot?.append(this._audioElement),this._audioElement.srcObject=this.clip,this._audioElement.autoplay=!1,!0):(this._audioElement?.play().catch(n=>{ct&&console.warn("[AudioSource] Failed to play audio element:",n)}),this.fadeEntryGain(1),!0)):!1)}fadeEntryGain(e,t=.02){if(!this._entryNode||!this.sound)return;const i=this.sound.context,n=this._entryNode.gain;n.cancelScheduledValues(i.currentTime),n.setValueAtTime(n.value,i.currentTime),n.linearRampToValueAtTime(e,i.currentTime+t)}pause(){if(ct&&console.log("[AudioSource] pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.wasPlaying=!1,this._usesMediaElementSource){this.fadeEntryGain(0),this._audioElement?.pause();return}this.sound&&this.sound.isPlaying&&this.sound.source&&(this._lastContextTime=this.sound?.context.currentTime,this.sound.pause()),this._audioElement?.remove()}stop(){if(ct&&console.log("[AudioSource] stop",this),this._hasEnded=!0,this.shouldPlay=!1,this.wasPlaying=!1,this._usesMediaElementSource){this.fadeEntryGain(0),this._audioElement?.pause(),this._audioElement&&(this._audioElement.currentTime=0);return}this.sound&&this.sound.source&&(this._lastContextTime=this.sound?.context.currentTime,ct&&console.log("[AudioSource] lastContextTime",this._lastContextTime),this.sound.stop()),this._audioElement?.remove()}_lastContextTime=0;_hasEnded=!0;_needUpdateSpatialDistanceSettings=!1;update(){this.helper&&(this.isPlaying&&this.helper.update(),this.helper.visible=this.isPlaying),this._needUpdateSpatialDistanceSettings&&this.applySpatialDistanceSettings(),this.sound&&!this.isPlaying&&this.shouldPlay&&!this._hasEnded&&(this._hasEnded=!0,ct&&console.log("[AudioSource] Audio clip ended",this.clip),this.dispatchEvent(new CustomEvent("ended",{detail:this})))}};Pn([p(URL)],nn.prototype,"clip",2);Pn([p()],nn.prototype,"playOnAwake",2);Pn([p()],nn.prototype,"preload",2);Pn([p()],nn.prototype,"playInBackground",2);Pn([p()],nn.prototype,"loop",1);Pn([p()],nn.prototype,"spatialBlend",1);Pn([p()],nn.prototype,"minDistance",1);Pn([p()],nn.prototype,"maxDistance",1);Pn([p()],nn.prototype,"volume",1);Pn([p()],nn.prototype,"pitch",1);Pn([p()],nn.prototype,"rollOffMode",2);let Ei=nn;var fT=Object.defineProperty,Kf=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&fT(e,t,n),n};const pT=x("debugsignals");class Lh{guid}Kf([p()],Lh.prototype,"guid");class Ml{signal;reaction}Kf([p(Lh)],Ml.prototype,"signal");Kf([p(Z)],Ml.prototype,"reaction");const dC=class ws extends T{isSignalReceiver=!0;static receivers={};static invoke(e){if(ws.receivers[e]){const t=ws.receivers[e];if(!t)return;for(const i of t)i.invoke(e)}}events;awake(){pT&&console.log("SignalReceiver awake",this)}onEnable(){if(this.events)for(const e of this.events)ws.receivers[e.signal.guid]||(ws.receivers[e.signal.guid]=[]),ws.receivers[e.signal.guid].push(this)}onDisable(){if(this.events){for(const e of this.events)if(ws.receivers[e.signal.guid]){const t=ws.receivers[e.signal.guid].indexOf(this);t>=0&&ws.receivers[e.signal.guid].splice(t,1)}}}invoke(e){if(!this.events||!Array.isArray(this.events))return;const t=typeof e=="object"?e.guid:e;for(const i of this.events)if(i.signal.guid===t)try{if(i.reaction){if(!i.reaction.invoke){console.warn("Missing invoke - possibly a serialization error",i,this);continue}}else{console.warn("Missing reaction for signal",i,this);continue}i.reaction.invoke()}catch(n){console.error(n)}}};Kf([p(Ml)],dC.prototype,"events");let Lr=dC;var ve=(s=>(s.Activation="ActivationTrack",s.Animation="AnimationTrack",s.Audio="AudioTrack",s.Control="ControlTrack",s.Marker="MarkerTrack",s.Signal="SignalTrack",s))(ve||{}),et=(s=>(s[s.None=0]="None",s[s.Hold=1]="Hold",s[s.Loop=2]="Loop",s[s.PingPong=3]="PingPong",s[s.Continue=4]="Continue",s))(et||{});function mT(s){return typeof s=="object"&&s!==null&&"name"in s&&"type"in s&&"outputs"in s&&"muted"in s}var mh=(s=>(s.Signal="SignalEmitter",s))(mh||{});const bn=x("debugtimeline");class Wr{director;track;get muted(){return this.track.muted}set muted(e){e!==this.track.muted&&(this.track.muted=e,this.onMuteChanged?.call(this))}*forEachClip(e=!1){if(this.track?.clips)if(e)for(let t=this.track.clips.length-1;t>=0;t--)yield this.track.clips[t];else for(const t of this.track.clips)yield t}getClipTime(e,t){return t.clipIn+(e-t.start)*t.timeScale}getClipTimeNormalized(e,t){return(e-t.start)/t.duration}evaluateWeight(e,t,i,n=!0){if(t<0||t>=i.length)return 0;const o=i[t];if(n||e>=o.start&&e<=o.end){let r=1;if(o.easeInDuration>0){const a=Math.min((e-o.start)/o.easeInDuration,1);r*=a}if(o.easeOutDuration>0){const a=Math.min((o.end-e)/o.easeOutDuration,1);r*=a}return r}return 0}}class gT{clip;rootPositionOffset;rootQuaternionOffset;get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}rootStartPosition;rootEndPosition;rootStartQuaternion;rootEndQuaternion;constructor(e){const t=e.getClip();this.clip=t;const i=e.getRoot(),n=i.name+".position",o=i.name+".quaternion";bn&&console.log(t.name,t.tracks,n);for(const r of t.tracks)if(!(r.times.length<=0)){if(r.name.endsWith(n))this.rootStartPosition=new c.Vector3().fromArray(r.values,0),this.rootEndPosition=new c.Vector3().fromArray(r.values,r.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),bn&&console.log(this.rootPositionOffset);else if(r.name.endsWith(o)&&(this.rootStartQuaternion=new c.Quaternion().fromArray(r.values,0),this.rootEndQuaternion=new c.Quaternion().fromArray(r.values,r.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),bn)){const a=new c.Euler().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",a)}}}}class gh extends Wr{models=[];trackOffset;target;mixer;clips=[];actions=[];weight=1;_actionOffsets=[];_didBind=!1;_animator=null;onDisable(){this.mixer?.stopAllAction()}onDestroy(){this.director.context.animations.unregisterAnimationMixer(this.mixer)}onStateChanged(){this._animator&&exports.AnimationUtils.setObjectAnimated(this._animator.gameObject,this,this.director.enabled&&this.director.weight>0)}createHooks(e,t){if(t.tracks?.length<=0){console.warn("No tracks in AnimationClip",t);return}let i=!1,n=!1;const o=t.tracks.find(r=>r.name.includes(".position")||r.name.includes(".quaternion"))?.name.split(".");if(o){const r=o[o.length-2],a=r+".position",l=r+".quaternion";for(const h of t.tracks)!i&&h.name.endsWith(a)?(i=!0,this.createPositionInterpolant(t,e,h)):!n&&h.name.endsWith(l)&&(n=!0,this.createRotationInterpolant(t,e,h))}if(!i||!n){const r=this.mixer?.getRoot(),a=t.tracks[0],l=a.name.lastIndexOf("."),h=a.name.substring(0,l),d=h.substring(h.lastIndexOf(".")+1),u=r.getObjectByName(d);if(u)if(i){if(!n){const f=t.tracks[0].name.substring(0,l)+".quaternion";bn&&console.warn("Create quaternion track",d,u);const m=new c.QuaternionKeyframeTrack(f,[0,t.duration],[0,0,0,1,0,0,0,1]);t.tracks.push(m),this.createRotationInterpolant(t,e,m)}}else{const f=h+".position";bn&&console.warn("Create position track",d,u);const m=new c.VectorKeyframeTrack(f,[0,t.duration],[0,0,0,0,0,0]);t.tracks.push(m),this.createPositionInterpolant(t,e,m)}}}bind(){if(!this._didBind){this._didBind=!0,bn&&console.log(this.models),this.mixer?this.target=this.mixer.getRoot():console.warn("No mixer was assigned to animation track");for(const e of this.actions){const t=new gT(e);this._actionOffsets.push(t)}this.target&&(this._animator=P.getComponent(this.target,vt)??null,this._animator&&exports.AnimationUtils.setObjectAnimated(this._animator.gameObject,this,!0));for(const e of this.models){const t=e.asset,i=t.position,n=t.rotation;i&&i.x!==void 0&&(i.isVector3||(t.position=new c.Vector3(i.x,i.y,i.z)),n.isQuaternion||(t.rotation=new c.Quaternion(n.x,n.y,n.z,n.w)))}this.ensureTrackOffsets()}}ensureTrackOffsets(){if(this.trackOffset){const e=this.trackOffset.position;e&&(e.isVector3||(this.trackOffset.position=new c.Vector3(e.x,e.y,e.z)));const t=this.trackOffset.rotation;t&&(t.isQuaternion||(this.trackOffset.rotation=new c.Quaternion(t.x,t.y,t.z,t.w)))}}_useclipOffsets=!0;_totalOffsetPosition=new c.Vector3;_totalOffsetRotation=new c.Quaternion;_totalOffsetPosition2=new c.Vector3;_totalOffsetRotation2=new c.Quaternion;_summedPos=new c.Vector3;_tempPos=new c.Vector3;_summedRot=new c.Quaternion;_tempRot=new c.Quaternion;_clipRotQuat=new c.Quaternion;evaluate(e){if(this.track.muted||!this.mixer)return;this.bind(),this._totalOffsetPosition.set(0,0,0),this._totalOffsetRotation.set(0,0,0,1),this._totalOffsetPosition2.set(0,0,0),this._totalOffsetRotation2.set(0,0,0,1);let t=0,i=0,n=!1,o=!1,r=0;for(let a=0;a<this.clips.length;a++){const l=this.models[a],h=this.actions[a],d=l.asset;h.weight=0;const u=e>=l.start&&e<=l.end,f=l.preExtrapolationMode,m=l.postExtrapolationMode,g=a<this.clips.length-1?this.models[a+1]:null;let v=u,_=!1;if(!v&&!n&&l.end<e&&m!==et.None?(!g||g.start>e)&&(v=!0,n=!0):a==0&&!v&&!o&&l.start>e&&f!==et.None&&(!g||g.start<e)&&(v=!0,_=!0,o=!0),v){let y=this.weight;y*=this.evaluateWeight(e,a,this.models,v),y*=this.director.weight;let b=u;if(_)switch(f){case et.Hold:break;case et.Loop:e+=l.start,b=!0;break;default:e+=l.start,b=!0;break}let w=this.getClipTime(e,l),C=0;const k=d.duration;if(_&&f===et.Hold&&(w=0),b){if(d.loop)for(C+=Math.floor(w/(k+1e-6));w>k;)w-=k}else if(!u&&n)switch(m){case et.Hold:w=this.getClipTime(l.end,l);break;case et.Loop:w%=k;break;case et.PingPong:const I=Math.floor(w/k)%2!==0;w%=k,I&&(w=k-w);break}l.reversed===!0?h.time=h.getClip().duration-w:h.time=w,h.timeScale=0;const O=Math.max(0,y);if(h.weight=O,r+=O,h.clampWhenFinished=!1,h.isRunning()||h.play(),this._useclipOffsets){const D=t==0?this._totalOffsetPosition:this._totalOffsetPosition2,I=t==0?this._totalOffsetRotation:this._totalOffsetRotation2;t<1&&(i=1-y),t+=1;const j=this._summedPos.set(0,0,0),$=this._tempPos.set(0,0,0),W=this._summedRot.identity(),R=this._tempRot.identity(),U=d.rotation;U&&(this._clipRotQuat.identity(),this._clipRotQuat.slerp(U,y));const G=this._actionOffsets[a];if(G.hasOffsets)for(let Y=0;Y<C;Y++)G.rootPositionOffset?$.copy(G.rootPositionOffset):$.set(0,0,0),$.applyQuaternion(W),this._clipRotQuat&&$.applyQuaternion(this._clipRotQuat),G.rootQuaternionOffset&&(R.copy(G.rootQuaternionOffset),W.multiply(R)),j.add($);this._clipRotQuat&&I.multiply(this._clipRotQuat),I.multiply(W),d.position&&j.add(d.position),D.add(j)}}}if(this._useclipOffsets&&(this._totalOffsetPosition.lerp(this._totalOffsetPosition2,i),this._totalOffsetRotation.slerp(this._totalOffsetRotation2,i)),this.__mixerError===void 0&&(bn||E())&&this._animator?.runtimeAnimatorController?.mixer&&this.mixer!==this._animator?.runtimeAnimatorController?.mixer&&(this.__mixerError=!0,console.error("AnimationTrack mixer is not shared with the animator controller - this might result in the timeline to not animate properly. Please report a bug to the Needle Engine team!",this)),this._animator?.runtimeAnimatorController){const a=Math.max(0,1-r);this._animator?.runtimeAnimatorController?.update(a)}else this.mixer.update(e)}createRotationInterpolant(e,t,i){const n=i.createInterpolant.bind(i),o=new c.Quaternion;this.ensureTrackOffsets();const r=this.trackOffset?.rotation;i.createInterpolant=()=>{const a=n(),l=a.evaluate.bind(a);return a.evaluate=h=>{const d=l(h);if(o.set(d[0],d[1],d[2],d[3]),o.premultiply(this._totalOffsetRotation),r&&o.premultiply(r),this.director.animationCallbackReceivers)for(const u of this.director.animationCallbackReceivers)u?.onTimelineRotation?.call(u,this.director,this.target,h,o);return d[0]=o.x,d[1]=o.y,d[2]=o.z,d[3]=o.w,d},a}}createPositionInterpolant(e,t,i){const n=i.createInterpolant.bind(i),o=new c.Vector3;this.ensureTrackOffsets();const r=this.trackOffset?.rotation,a=this.trackOffset?.position;let l;i.createInterpolant=()=>{const h=n(),d=h.evaluate.bind(h);return h.evaluate=u=>{const f=d(u);if(o.set(f[0],f[1],f[2]),t.removeStartOffset&&(l===void 0?(l=null,l=this._actionOffsets.find(m=>m.clip===e)?.rootStartPosition?.clone()):l?.isVector3&&o.sub(l)),o.applyQuaternion(this._totalOffsetRotation),o.add(this._totalOffsetPosition),r&&o.applyQuaternion(r),a&&(o.x-=a.x,o.y+=a.y,o.z+=a.z),this.director.animationCallbackReceivers)for(const m of this.director.animationCallbackReceivers)m?.onTimelinePosition?.call(m,this.director,this.target,u,o);return f[0]=o.x,f[1]=o.y,f[2]=o.z,f},h}}}const yT=x("mutetimeline");class Os extends Wr{models=[];listener;audio=[];audioContextTimeOffset=[];lastTime=0;audioSource;get volume(){return this.track.volume??1}set volume(e){this.track.volume=e}_audioLoader=null;getAudioFilePath(e){const t=this.director.sourceId;return cs(t,e)}onAllowAudioChanged(e){for(let t=0;t<this.models.length;t++){const i=this.models[t];this.audio[t].setVolume(e?i.asset.volume:0)}}addModel(e){const t=new c.Audio(this.listener);this.audio.push(t);const i=e;i._didTriggerPlay=!1,this.models.push(i)}onDisable(){for(const e of this.audio)e.isPlaying&&e.stop();for(const e of this.models)e._didTriggerPlay=!1}onDestroy(){for(const e of this.audio)e.source&&e?.disconnect();this.audio.length=0}onMuteChanged(){if(this.muted)for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t?.isPlaying&&t.stop()}}stop(){for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t?.isPlaying&&t.stop()}for(const e of this.models)e._didTriggerPlay=!1}_playableDirectorResumed=!1;onPauseChanged(){for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t?.isPlaying&&t.stop()}this._playableDirectorResumed=this.director.isPlaying}evaluate(e){if(yT||this.track.muted||this.director.speed<0)return;const t=this.director.context.application.muted,i=this._playableDirectorResumed;this._playableDirectorResumed=!1;const n=t?.1:0;for(let o=0;o<this.models.length;o++){const r=this.models[o],a=this.audio[o],l=r.asset;if((!a||!a.buffer)&&this.isInTimeRange(r,e-1,e+1)&&this.handleAudioLoading(r,a),Ei.userInteractionRegistered!==!1&&!(a===null||!a.buffer))if(a.setPlaybackRate(this.director.context.time.timeScale*this.director.speed),a.setLoop(l.loop),e>=r.start&&e<=r.end&&e<this.director.duration){let h=l.volume;if(this.track.volume!==void 0&&(h*=this.track.volume),t&&(h=0),r.easeInDuration>0){const d=Math.min((e-r.start)/r.easeInDuration,1);h*=d}if(r.easeOutDuration>0){const d=Math.min((r.end-e)/r.easeOutDuration,1);h*=d}if(h*=this.director.weight,!a.isPlaying||!this.director.isPlaying){if(i||!r._didTriggerPlay&&this.lastTime<e){r.duration*r.timeScale>.3?a.offset=r.clipIn+(e-r.start)*r.timeScale:a.offset=0,bn&&console.log("Timeline Audio ("+this.track.name+") play with offset "+a.offset+" - "+r.asset.clip);const u=a.gain.gain;u.cancelScheduledValues(a.context.currentTime),u.setValueAtTime(h,a.context.currentTime),a.play(n),r._didTriggerPlay=!0}}else{const d=r.clipIn+(e-r.start)*r.timeScale,u=a.context.currentTime-a._startedAt+a.offset;if(Math.abs(d-u)>.3){a.offset=d,a.stop();const m=a.gain.gain;m.cancelScheduledValues(a.context.currentTime),m.setValueAtTime(h,a.context.currentTime),a.play(n)}}a.setVolume(h)}else r._didTriggerPlay=!1,this.director.isPlaying&&a.isPlaying&&a.stop()}this.lastTime=e}loadAudio(e,t=0,i=0){let n=null;const o=e-i,r=e+t;for(const a of this.models)if(this.isInTimeRange(a,o,r)){const l=this.audio[this.models.indexOf(a)],h=this.handleAudioLoading(a,l);h!==null&&(n===null&&(n=[]),n.push(h))}return n!==null?Promise.all(n):null}isInTimeRange(e,t,i){return t<=e.start&&i>=e.end||t>=e.start&&t<=e.end||i>=e.start&&i<=e.end}static _audioBuffers=new Map;static dispose(){Os._audioBuffers.clear()}handleAudioLoading(e,t){this._audioLoader||(this._audioLoader=new c.AudioLoader);const i=this.getAudioFilePath(e.asset.clip);if(Os._audioBuffers.get(i)){const o=Os._audioBuffers.get(i);return o.then(r=>{r&&t.setBuffer(r)}),o}bn&&console.warn("LOAD audio track",i,this.director.sourceId);const n=new Promise((o,r)=>{this._audioLoader.load(i,a=>{t.setBuffer(a),o(a)},void 0,a=>{console.error("Error loading audio",a),o(null)})});return Os._audioBuffers.set(i,n),n}}class Zf extends Wr{models=[];needsSorting=!0;*foreachMarker(e=null){this.needsSorting&&this.sort();for(const t of this.models)t&&t.type===e&&(yield t)}onEnable(){this.needsSorting=!0}evaluate(e){this.needsSorting&&this.sort()}sort(){this.needsSorting=!1,this.models.sort((e,t)=>e.time-t.time)}}class yh extends Wr{models=[];didTrigger=[];receivers=[];_lastTime=-1;onEnable(){this._lastTime=-1;for(let e=0;e<this.didTrigger.length;e++)this.didTrigger[e]=!1}onMuteChanged(){this.track.muted||(this._lastTime=-1)}evaluate(e){if(this.track.muted)return;let t=this._lastTime;t===-1&&(t=e),this._lastTime=e;const i=this.director.context.time.deltaTime*1.5;for(let n=0;n<this.models.length;n++){const o=this.models[n],r=this.didTrigger[n],a=o.time-e;let l=!1;if(o.retroActive)l=a<=1e-6;else{const h=Math.abs(a);(h===0||h>=1e-5&&h<i)&&(l=!0)}if(l){if(!r)if(bn&&console.log("Trigger signal",e,o.time,o),this.didTrigger[n]=!0,this.receivers?.length<=0)Lr.invoke(o.asset);else for(const h of this.receivers)h&&h.invoke(o.asset)}else o.emitOnce||e<o.time&&t>=o.time&&(this.didTrigger[n]=!1)}}}class Jf extends Wr{evaluate(e){if(!this.track.muted&&!(!this.director.isPlaying&&!this.director._isUserEvaluation))for(let t=0;t<this.track.outputs.length;t++){const i=this.track.outputs[t];if(typeof i!="object"||i===null)continue;let n=!1;if(this.track.clips){for(const r of this.track.clips)if(r.start<=e&&e<=r.end){n=!0;break}}const o=i;o.visible!==void 0&&o.visible!==n&&(o.visible=n,bn&&console.warn(this.director.name,"ActivationTrack-"+t,o.name,n,e))}}}class ep extends Wr{models=[];timelines=[];resolveSourceObjects(e){for(let t=this.models.length-1;t>=0;t--){const n=this.models[t].asset;if(!n.sourceObject||typeof n.sourceObject!="object"){console.log("no source object, removing model",t,n),this.models.splice(t,1);continue}else{const o=this.director.constructor,r=P.getComponent(n.sourceObject,o);this.timelines.push(r),r&&n.updateDirector&&(r.playOnAwake=!1)}}}_previousActiveModel=null;evaluate(e){this._previousActiveModel=null;for(let t=0;t<this.models.length;t++){const i=this.models[t],n=i.asset;if(e>=i.start&&e<=i.end){this._previousActiveModel=i;const o=this.getClipTime(e,i);if(n.controlActivation){const r=n.sourceObject;r.visible=!0}if(n.updateDirector){const r=this.timelines[t];r&&(r.isPlaying&&r.pause(),r.time=o,r.evaluate())}}else{const o=this._previousActiveModel?.asset;if(n.controlActivation){const r=n.sourceObject;o?.sourceObject!==r&&(r.visible=!1)}}}}}var _T=Object.defineProperty,bT=Object.getOwnPropertyDescriptor,y_=(s,e,t,i)=>{for(var n=i>1?void 0:i?bT(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&_T(e,t,n),n};const In=x("debugtimeline");var uC=(s=>(s[s.Hold=0]="Hold",s[s.Loop=1]="Loop",s[s.None=2]="None",s))(uC||{});const tp=class ty extends T{static createTrackFunctions={};static registerCreateTrack(e,t){this.createTrackFunctions[e]=t}get playableAsset(){return this._playableAsset}set playableAsset(e){this._playableAsset!==e&&(this._playableAsset=e,this._needsGraphRebuild=!0,this._didWarnInvalid=!1)}_playableAsset;_didWarnInvalid=!1;playOnAwake=!1;extrapolationMode=1;get isPlaying(){return this._isPlaying}get isPaused(){return this._isPaused}get time(){return this._time}set time(e){typeof e=="number"&&!Number.isNaN(e)?this._time=e:(In||ki())&&console.error("INVALID TIMELINE.TIME VALUE",e,this.name)}get duration(){return this._duration}set duration(e){this._duration=e}get weight(){return this._weight}set weight(e){this._weight=e}get speed(){return this._speed}set speed(e){this._speed=e}waitForAudio=!0;_visibilityChangeEvt;_clonedPlayableAsset=!1;_speed=1;awake(){In&&console.log(`[Timeline] Awake '${this.name}'`,this),this.rebuildGraph()}warnIfInvalid(e){return this.isValid()?!0:(!this._didWarnInvalid&&(In||E())&&(this._didWarnInvalid=!0,this.playableAsset?.tracks?.length?console.warn(`PlayableDirector '${this.name}' is not valid`,this):console.warn(`PlayableDirector '${this.name}' has no tracks — assign a playableAsset (or build one via TimelineBuilder) before calling ${e}().`,this)),!1)}onEnable(){In&&console.log("[Timeline] OnEnable",{name:this.name,playOnAwake:this.playOnAwake});for(const e of this._allTracks)for(const t of e)t.onEnable?.();this.playOnAwake&&this.play(),this._visibilityChangeEvt||(this._visibilityChangeEvt=()=>{switch(document.visibilityState){case"hidden":this.setAudioTracksAllowPlaying(!1);break;case"visible":this.setAudioTracksAllowPlaying(!0);break}}),window.addEventListener("visibilitychange",this._visibilityChangeEvt)}onDisable(){In&&console.log("[Timeline] OnDisable",this.name),this.stop();for(const e of this._audioTracks)e.onDisable?.();for(const e of this._customTracks)e.onDisable?.();for(const e of this._animationTracks)e.onDisable?.();this._visibilityChangeEvt&&window.removeEventListener("visibilitychange",this._visibilityChangeEvt)}onDestroy(){for(const e of this._allTracks)for(const t of e)t.onDestroy?.()}rebuildGraph(){this.isValid()&&(this.resolveBindings(),this.updateTimelineDuration(),this.setupAndCreateTrackHandlers(),this._needsGraphRebuild=!1)}async play(){if(!this.warnIfInvalid("play"))return;this._needsGraphRebuild&&this.rebuildGraph();const e=this._isPaused==!0;if(this._isPaused=!1,!this._isPlaying){if(this._isPlaying=!0,e&&this.invokePauseChangedMethodsOnTracks(),this.waitForAudio){const t=[];for(const n of this._audioTracks){const o=n.loadAudio(this._time,1,0);o&&t.push(o)}if(t.length>0&&(await Promise.all(t),!this._isPlaying))return;let i=0;for(;this._audioTracks.length>0&&this._isPlaying&&!Ei.userInteractionRegistered&&this.waitForAudio;)i++<=0&&(E()||In)&&console.warn(`[Timeline] Waiting for user interaction to play audio... (timeline '${this.name}' will start as soon as user interacts with the page). To start the timeline immediately without waiting for user interaction, set 'waitForAudio' to false on the PlayableDirector component.`),await Ds(200)}this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine=this.startCoroutine(this.internalUpdate(),Ce.LateUpdate)}}pause(){this.isValid()&&(this._isPlaying=!1,!this._isPaused&&(this._isPaused=!0,this.internalEvaluate(),this.invokePauseChangedMethodsOnTracks(),this.invokeStateChangedMethodsOnTracks()))}stop(){this._isStopping=!0;for(const i of this._audioTracks)i.stop();const e=this._isPaused==!0,t=this._isPlaying;this._isPlaying&&(this._time=0,this._isPlaying=!1,this._isPaused=!1,this.internalEvaluate(),e&&this.invokePauseChangedMethodsOnTracks()),this._isPlaying=!1,this._isPaused=!1,e&&!t&&this.invokePauseChangedMethodsOnTracks(),t&&this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine&&this.stopCoroutine(this._internalUpdateRoutine),this._internalUpdateRoutine=null,this._isStopping=!1}evaluate(){this.warnIfInvalid("evaluate")&&(this._needsGraphRebuild&&this.rebuildGraph(),this.internalEvaluate(!0))}isValid(){return this.playableAsset&&this.playableAsset.tracks&&Array.isArray(this.playableAsset.tracks)}*forEachTrack(){for(const e of this._allTracks)for(const t of e)yield t}get animationTracks(){return this._animationTracks}get audioTracks(){return this._audioTracks}get signalTracks(){return this._signalTracks}get markerTracks(){return this._markerTracks}get activationTracks(){return this._activationTracks}get tracks(){return this._allTracks.flat()}*foreachMarker(e=null){for(const t of this._markerTracks)for(const i of t.foreachMarker(e))yield i}_needsGraphRebuild=!1;_isPlaying=!1;_internalUpdateRoutine;_isPaused=!1;_isStopping=!1;_isUserEvaluation=!1;_time=0;_duration=0;_weight=1;_animationTracks=[];_audioTracks=[];_signalTracks=[];_markerTracks=[];_controlTracks=[];_activationTracks=[];_customTracks=[];_tracksArray=[];get _allTracks(){return this._tracksArray.length=0,this._tracksArray.push(this._animationTracks),this._tracksArray.push(this._audioTracks),this._tracksArray.push(this._signalTracks),this._tracksArray.push(this._markerTracks),this._tracksArray.push(this._controlTracks),this._tracksArray.push(this._activationTracks),this._tracksArray.push(this._customTracks),this._tracksArray}invokePauseChangedMethodsOnTracks(){for(const e of this.forEachTrack())e.onPauseChanged?.call(e)}invokeStateChangedMethodsOnTracks(){for(const e of this.forEachTrack())e.onStateChanged?.call(e,this._isPlaying)}*internalUpdate(){for(;this._isPlaying&&this.activeAndEnabled;)!this._isPaused&&this._isPlaying&&(this._time+=this.context.time.deltaTime*this.speed,this.internalEvaluate()),yield}internalEvaluate(e=!1){if(!this.isValid())return;let t=this._time;switch(this.extrapolationMode){case 0:this._speed>0?t=Math.min(t,this._duration):this._speed<0&&(t=Math.max(t,0)),this._time=t;break;case 1:t%=this._duration,this._time=t;break;case 2:if(t>this._duration){this.stop();return}break}const i=this._time;this._isUserEvaluation=e;for(const n of this._allTracks)for(const o of n)this._isStopping&&o instanceof gh||o.evaluate(i);this._isUserEvaluation=!1}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=Sh(this.playableAsset,(t,i,n)=>n?.isObject3D!==!0)),!this.playableAsset||!this.playableAsset.tracks)return;const e=this.findRoot(this.gameObject);for(const t of this.playableAsset.tracks){for(let i=t.outputs.length-1;i>=0;i--){const n=t.outputs[i];if(typeof n=="string"){const o=P.findByGuid(n,e);o===null||typeof o!="object"?(t.outputs.splice(i,1),console.warn(`[Timeline] Failed to resolve binding on track '${t.name}' of type '${t.type}' in director '${this.name}' with timeline asset '${this.playableAsset.name}' ('${n}' not found in scene)`)):(In&&console.log("Resolved binding",n,"to",o),t.outputs[i]=o)}else if(n===null){if(t.outputs.splice(i,1),ty.createTrackFunctions[t.type])continue;t.type!==ve.Audio&&t.type!==ve.Control&&t.type!==ve.Marker&&t.type!==ve.Signal&&console.warn(`[Timeline] Missing binding on track '${t.name}' of type '${t.type}' in director '${this.name}' with timeline asset '${this.playableAsset.name}' (null binding)`)}}if(t.type===ve.Control&&t.clips)for(let i=0;i<t.clips.length;i++){const n=t.clips[i],o=n.asset.sourceObject;if(typeof o=="string"){const r=P.findByGuid(o,e);r===null||typeof r!="object"?console.warn(`[Timeline] Failed to resolve sourceObject binding on track '${t.name}' of type '${t.type}' in director '${this.name}' with timeline asset '${this.playableAsset.name}' ('${o}' not found in scene)`):(In&&console.log("Resolved binding",o,"to",r),n.asset.sourceObject=r)}}}}findRoot(e){return e.parent?this.findRoot(e.parent):e}updateTimelineDuration(){if(this._duration=0,!(!this.playableAsset||!this.playableAsset.tracks)){for(const e of this.playableAsset.tracks)if(e.muted!==!0){if(e.clips)for(const t of e.clips)t.end>this._duration&&(this._duration=t.end);if(e.markers)for(const t of e.markers)t.time>this._duration&&(this._duration=t.time+.001)}}}setupAndCreateTrackHandlers(){if(this._animationTracks.length=0,this._audioTracks.length=0,this._signalTracks.length=0,this._activationTracks.length=0,!this.playableAsset)return;let e=P.findObjectOfType(Ms,this.context);for(const t of this.playableAsset.tracks){const i=t.type,n=ty.createTrackFunctions[i];if(n!=null){const o=n(this,t);if(typeof o.evaluate=="function"){o.director=this,o.track=t,this._customTracks.push(o);continue}}if(t.type===ve.Animation){if(!t.clips||t.clips.length<=0){In&&console.warn("Animation track has no clips",t);continue}for(let o=t.outputs.length-1;o>=0;o--){let r=t.outputs[o];if(r instanceof c.Object3D){const l=P.getOrAddComponent(r,vt);l&&(r=l)}const a=r?.gameObject?.animations;if(a){const l=new gh;l.trackOffset=t.trackOffset,l.director=this,l.track=t;for(let h=0;h<t.clips.length;h++){const d=t.clips[h],u=d.asset;if(!u){console.error(`Timeline ${this.name}: clip #${h} on track "${t.name}" has no animation data`);continue}const f=u.clip;let m=f;if((typeof m=="string"||typeof m=="number")&&(m=a.find(v=>v.name===f)),In&&console.log(u,f,"→",m),!m){console.warn("Could not find animationClip for model",d,t.name,this.name,this.playableAsset?.name,a,r);continue}r instanceof vt&&r.runtimeAnimatorController&&(r.__internalDidAwakeAndStart||r.initializeRuntimeAnimatorController(),r.runtimeAnimatorController.mixer||r.runtimeAnimatorController.bind(r),l.mixer=r.runtimeAnimatorController.mixer),l.mixer||(l.mixer=new c.AnimationMixer(r.gameObject),this.context.animations.registerAnimationMixer(l.mixer)),l.clips.push(m),l.mixer.uncacheAction(m),l.createHooks(d.asset,m);const g=l.mixer.clipAction(m);l.actions.push(g),l.models.push(d)}this._animationTracks.push(l)}}}else if(t.type===ve.Audio){if(!t.clips||t.clips.length<=0)continue;const o=new Os;o.director=this,o.track=t,o.audioSource=t.outputs.find(r=>r instanceof Ei),this._audioTracks.push(o),e||(e=this.context.mainCameraComponent?.gameObject.addComponent(Ms)),o.listener=e.listener;for(let r=0;r<t.clips.length;r++){const a=t.clips[r];o.addModel(a)}}else if(t.type===ve.Marker){if(t.markers){const o=new yh;o.director=this,o.track=t;const r=new Zf;r.director=this,r.track=t;for(const a of t.markers)a.type===mh.Signal?(o.models.push(a),o.didTrigger.push(!1)):r.models.push(a);if(o!==null&&o.models.length>0){const a=P.getComponent(this.gameObject,Lr);a&&(o.receivers.push(a),this._signalTracks.push(o))}r!==null&&r.models.length>0&&this._markerTracks.push(r)}}else if(t.type===ve.Signal){const o=new yh;if(o.director=this,o.track=t,t.markers)for(const r of t.markers)o.models.push(r),o.didTrigger.push(!1);for(const r of t.outputs)o.receivers.push(r);this._signalTracks.push(o)}else if(t.type===ve.Control){const o=new ep;if(o.director=this,o.track=t,t.clips)for(const r of t.clips)o.models.push(r);o.resolveSourceObjects(this.context),this._controlTracks.push(o)}else if(t.type===ve.Activation){const o=new Jf;o.director=this,o.track=t,this._activationTracks.push(o)}}}setAudioTracksAllowPlaying(e){for(const t of this._audioTracks)t.onAllowAudioChanged(e)}animationCallbackReceivers=[];registerAnimationCallback(e){this.animationCallbackReceivers.push(e)}unregisterAnimationCallback(e){const t=this.animationCallbackReceivers.indexOf(e);t!==-1&&this.animationCallbackReceivers.splice(t,1)}};y_([p()],tp.prototype,"playableAsset",1);y_([p()],tp.prototype,"playOnAwake",2);y_([p()],tp.prototype,"extrapolationMode",2);let ml=tp,u0=!1;function vT(){u0||(u0=!0,se.registerCallback(ae.ContextCreated,s=>{const e=s.context.domElement.getAttribute("autoplay");if(e!==void 0&&(e===""||e==="true"||e==="1")&&s.files)for(const t of s.files)P.foreachComponent(t.file.scene,n=>{if(n.enabled!==!1){if(n instanceof Ut&&n.playAutomatically||n instanceof vt||n instanceof ml&&n.playOnAwake===!0)return!0;if(n instanceof Ut)return n.playAutomatically=!0,!0;if(n instanceof ml)return n.playOnAwake=!0,!0}},!0)!==!0&&exports.AnimationUtils.autoplayAnimations(t.file)}))}const wT={topLight:{intensity:500,position:[.418,16.199,.3]},room:{position:[-.757,13.219,.717],scale:[31.713,28.305,28.591]},boxes:[{position:[-10.906,2.009,1.846],rotation:-.195,scale:[2.328,7.905,4.651]},{position:[-5.607,-.754,-.758],rotation:.994,scale:[1.97,1.534,3.955]},{position:[6.167,.857,7.803],rotation:.561,scale:[3.927,6.285,3.687]},{position:[-2.017,.018,6.124],rotation:.333,scale:[2.002,4.566,2.064]},{position:[2.291,-.756,-2.621],rotation:-.286,scale:[1.546,1.552,1.496]},{position:[-2.193,-.369,-5.547],rotation:.516,scale:[3.875,3.487,2.986]}],lights:[{intensity:50,position:[-16.116,14.37,8.208],scale:[.1,2.428,2.739]},{intensity:50,position:[-16.109,18.021,-8.207],scale:[.1,2.425,2.751]},{intensity:17,position:[14.904,12.198,-1.832],scale:[.15,4.265,6.331]},{intensity:43,position:[-.462,8.89,14.52],scale:[4.38,5.441,.088]},{intensity:20,position:[3.235,11.486,-12.541],scale:[2.5,2,.1]},{intensity:100,position:[0,20,0],scale:[1,.1,1]}]},xT={topLight:{intensity:400,position:[.5,14,.5]},room:{position:[0,13.2,0],scale:[31.5,28.5,31.5]},boxes:[{position:[-10.906,-1,1.846],rotation:-.195,scale:[2.328,7.905,4.651]},{position:[-5.607,-.754,-.758],rotation:.994,scale:[1.97,1.534,3.955]},{position:[6.167,-.16,7.803],rotation:.561,scale:[3.927,6.285,3.687]},{position:[-2.017,.018,6.124],rotation:.333,scale:[2.002,4.566,2.064]},{position:[2.291,-.756,-2.621],rotation:-.286,scale:[1.546,1.552,1.496]},{position:[-2.193,-.369,-5.547],rotation:.516,scale:[3.875,3.487,2.986]}],lights:[{intensity:80,position:[-14,10,8],scale:[.1,2.5,2.5]},{intensity:80,position:[-14,14,-4],scale:[.1,2.5,2.5]},{intensity:23,position:[14,12,0],scale:[.1,5,5]},{intensity:16,position:[0,9,14],scale:[5,5,.1]},{intensity:80,position:[7,8,-14],scale:[2.5,2.5,.1]},{intensity:80,position:[-7,16,-14],scale:[2.5,2.5,.1]},{intensity:1,position:[0,20,0],scale:[.1,.1,.1]}]};class ip extends c.Scene{constructor(e){super(),this.position.y=-3.5;const t=new c.BoxGeometry;t.deleteAttribute("uv");const i=new c.MeshStandardMaterial({metalness:0,side:c.BackSide}),n=new c.MeshStandardMaterial({metalness:0}),o=e=="legacy"?wT:xT,r=new c.PointLight(16777215,o.topLight.intensity,28,2);r.position.set(...o.topLight.position),this.add(r);const a=new c.Mesh(t,i);a.position.set(...o.room.position),a.scale.set(...o.room.scale),this.add(a);for(const l of o.boxes){const h=new c.Mesh(t,n);h.position.set(...l.position),h.rotation.set(0,l.rotation,0),h.scale.set(...l.scale),this.add(h)}for(const l of o.lights){const h=new c.Mesh(t,this.createAreaLightMaterial(l.intensity));h.position.set(...l.position),h.scale.set(...l.scale),this.add(h)}}createAreaLightMaterial(e){const t=new c.MeshBasicMaterial;return t.color.setScalar(e),t}}const Gc=x("debugmissingcamera");let f0=!1;function ST(){f0||(f0=!0,se.registerCallback(ae.MissingCamera,s=>{Gc&&console.warn("Creating missing camera");const e=s.context.scene,t=s.context.mainCamera;t.name||(t.name="Default Fallback Camera");const i=new Jt;if(i.sourceId=s.files?.[0]?.src??"unknown",i.fieldOfView=35,s.context.domElement.getAttribute("transparent")!=null)i.clearFlags=Or.Uninitialized;else if(s.context.domElement.getAttribute("background-image")?.length||s.context.lightmaps.tryGetSkybox(i.sourceId))i.clearFlags=Or.Skybox;else{if(i.clearFlags=Or.SolidColor,!s.context.domElement.getAttribute("background-color")&&!e.background){let a="#efefef";typeof window!==void 0&&window.matchMedia("(prefers-color-scheme: dark)").matches&&(a="#1f1f1f"),e.background=new c.Color(a)}if(!e.environment){const a=aO(s.context.renderer),l=new ip("neutral");e.environment=a.fromScene(l,.025).texture}}const o=kr(t,i,!0);return t.position.x=0,t.position.y=1,t.position.z=2,s.context.domElement?.cameraControls!=!1&&p0(s.context,o),o}),se.registerCallback(ae.ContextCreated,s=>{if(!s.context.mainCamera){Gc&&console.log("Will not auto-fit because a default camera exists");return}if(s.context.domElement?.cameraControls==!0){if(Vw(s.context.mainCamera)?.isCameraController==!0){Gc&&console.log("Will not auto-fit because a camera controller exists");return}p0(s.context)}}))}function p0(s,e){e=e??s.mainCameraComponent;const t=e?.gameObject;if(Gc&&console.log("Creating default camera controls",e?.name),t){const i=Th(t,ue);i.sourceId=e?.sourceId??"unknown";const n=s.domElement.getAttribute("auto-rotate");i.autoRotate=n!="0"&&n?.toLowerCase()!="false";const o=Number.parseFloat(n||".5");i.autoRotateSpeed=isNaN(o)?.5:o,Gc&&console.log("Auto-rotate",i.autoRotate,"speed:",i.autoRotateSpeed);const r=s.domElement.getAttribute("auto-fit");i.autoFit=r!=="0"&&r?.toLowerCase()!="false",i.autoTarget=!0}else console.warn("Missing camera object, can not add orbit controls")}var CT=Object.defineProperty,PT=Object.getOwnPropertyDescriptor,fC=(s,e,t,i)=>{for(var n=PT(e,t),o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&CT(e,t,n),n};const kT=x("debugpost");class z{isVolumeParameter=!0;constructor(e){e!==void 0&&this.initialize(e)}_isInitialized=!1;get isInitialized(){return this._isInitialized}initialize(e){e!==void 0&&(this._value=e,this._defaultValue=e,this._valueRaw=e,this._isInitialized=!0)}get overrideState(){return this._active}set overrideState(e){if(this._active===e)return;this._active=e;const t=e?this._valueRaw:this._defaultValue;this.processValue(t,!0)}_active=!0;get value(){return this._valueRaw}set value(e){this.isInitialized||this.initialize(e),this.processValue(e,!1)}_value;_valueRaw;set defaultValue(e){this._defaultValue=e}_defaultValue=void 0;__init(){this.processValue(this._valueRaw,!0)}valueProcessor;onValueChanged;processValue(e,t){if(e==null||!t&&this.testIfValueChanged(e)===!1)return;const i=this._value;kT&&typeof i=="number"&&typeof e=="number"&&(i?.toFixed(4),e?.toFixed(4)),!this._active&&this._defaultValue!==void 0?(this._value=this._defaultValue,e=this._defaultValue,this._valueRaw=e):(this._valueRaw=e,this._active&&this.valueProcessor&&(e=this.valueProcessor(e)),this._value=e),this.onValueChanged&&this.onValueChanged(e,i,this)}testIfValueChanged(e){return this._valueRaw!==e}}fC([p()],z.prototype,"overrideState");fC([p()],z.prototype,"value");class MT extends Ai{constructor(){super([z])}onSerialize(e,t){}onDeserialize(e,t){const i=t.target,n=t.path;let o;if(i&&n&&(o=i[n]),(typeof o!="object"||typeof o=="object"&&o.isVolumeParameter!==!0)&&(o=new z),typeof e=="object"&&"value"in e){const r=e.value;o.initialize(r),o.overrideState=e.overrideState}else o.value=e;return o}}function pC(){new MT}async function iy(s){const{NeedleEngineWebComponent:e}=await Promise.resolve().then(()=>P3);e.observedAttributes.includes(s)||e.observedAttributes.push(s)}var OT=Object.defineProperty,wt=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&OT(e,t,n),n};const yt=x("debugsceneswitcher"),ET=x("sceneswitcher:clearscene"),Eu="scene";function RT(){iy(Eu)}const io=Promise.resolve(!1);class Ye extends T{autoLoadFirstScene=!0;scenes=[];loadingScene;queryParameterName="scene";useSceneName=!0;clamp=!0;useHistory=!0;useKeyboard=!0;useSwipe=!0;useSceneLighting=!0;useSceneBackground=!0;preloadNext=1;preloadPrevious=1;preloadConcurrent=2;createMenuButtons=!1;get currentIndex(){return this._currentIndex}get currentLoadingProgress(){return this._currentLoadingProgress}get currentlyLoadingScene(){return this._currentlyLoadingScene}get currentlyLoadedScene(){return this._currentScene}sceneLoadingStart=new Z;sceneLoadingProgress=new Z;sceneLoaded=new Z;_currentIndex=-1;_currentScene=void 0;_currentSceneAsset=void 0;_engineElementOverserver=void 0;_preloadScheduler;_menuButtons;__lastSwitchScene;__lastSwitchScenePromise;awake(){this._currentScene=void 0,this._lastLoadingScene=void 0,this.__lastSwitchScenePromise=void 0,this.scenes===void 0&&(this.scenes=[]);for(const e of this.scenes)e&&!e.hasUrl&&e.asset instanceof c.Object3D?P.remove(e.asset):e instanceof c.Object3D&&P.remove(e);yt&&console.log("SceneSwitcher",this)}async onEnable(){if(globalThis.addEventListener("popstate",this.onPopState),this.context.input.addEventListener(xe.KeyDown,this.onInputKeyDown),this.context.input.addEventListener(xe.PointerMove,this.onInputPointerMove),this.context.input.addEventListener(xe.PointerUp,this.onInputPointerUp),this._engineElementOverserver||(this._engineElementOverserver=new MutationObserver(e=>{for(const t of e)if(t.type==="attributes"&&t.attributeName===Eu){const i=this.context.domElement.getAttribute(Eu);i!==null&&this.trySelectSceneFromValue(i)}})),this._engineElementOverserver.observe(this.context.domElement,{attributes:!0}),this._preloadScheduler||(this._preloadScheduler=new TT(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(Eu);(e===null||!await this.trySelectSceneFromValue(e))&&this._currentIndex===-1&&this.select(0)}this.createMenuButtons&&(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(){if(globalThis.removeEventListener("popstate",this.onPopState),this.context.input.removeEventListener(xe.KeyDown,this.onInputKeyDown),this.context.input.removeEventListener(xe.PointerMove,this.onInputPointerMove),this.context.input.removeEventListener(xe.PointerUp,this.onInputPointerUp),this._preloadScheduler?.stop(),this._menuButtons){for(const e of this._menuButtons)e.remove();this._menuButtons=void 0}}onPopState=async e=>{if(!this.useHistory)return;const t=this.useHistory;try{this.useHistory=!1;let i=!1;if(this.queryParameterName&&(i=await this.tryLoadFromQueryParam()),!i){const n=e?.state;if(n&&n.startsWith(this.guid)){const o=n.substr(this.guid.length+2);yt&&console.log("PopState",o),await this.trySelectSceneFromValue(o)}}}finally{this.useHistory=t}};normalizedSwipeThresholdX=.1;_didSwipe=!1;onInputPointerMove=e=>{if(this.useSwipe&&!this._didSwipe&&e.button===0&&e.pointerType==="touch"&&this.context.input.getPointerPressedCount()===1){const t=this.context.input.getPointerPositionDelta(e.button);if(t){const i=t.x/this.context.domWidth;i>=this.normalizedSwipeThresholdX?(this._didSwipe=!0,this.selectPrev()):i<=-this.normalizedSwipeThresholdX&&(this._didSwipe=!0,this.selectNext())}}};onInputPointerUp=e=>{e.button===0&&(this._didSwipe=!1)};onInputKeyDown=e=>{if(!this.useKeyboard||!this.scenes)return;const t=e.key.toLowerCase();if(!t)return;const i=parseInt(t)-1;if(i>=0){this.trySelectSceneFromValue(i);return}switch(t){case"arrowright":case"d":this.selectNext();break;case"arrowleft":case"a":this.selectPrev();break}};addScene(e){if(typeof e=="string"){let t=this.context.addressables.findAssetReference(e);return t||(t=new J(e),this.context.addressables.registerAssetReference(t)),this.scenes.push(t),t}return this.scenes.push(e),e}selectNext(){return this.select(this._currentIndex+1)}selectPrev(){return this.select(this._currentIndex-1)}select(e){if(yt&&console.log("[SceneSwitcher] select",e),typeof e=="object"&&console.warn('[SceneSwitcher] Switching to "'+e+'" might not work. Please either use an index or a AssetReference (not a scene reference)'),typeof e=="string"){const i=this.scenes?.find(n=>n.url===e);if(!i){const n=J.getOrCreate(this.sourceId??"",e,this.context);return this.switchScene(n)}if(i)e=this.scenes?.indexOf(i);else return io}if(!this.scenes?.length)return io;if(e<0){if(this.clamp)return io;e=this.scenes.length-1}else if(e>=this.scenes.length){if(this.clamp)return io;e=0}const t=this.scenes[e];return this.switchScene(t)}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){if(!(e instanceof J)){const i=typeof e;if(i==="string")return this.select(e);if(i==="number")return this.select(e);if(e&&e instanceof c.Object3D){const n=this.scenes?.indexOf(e);e=new J(e.name,void 0,e),n>=0&&(this.scenes[n]=e)}else return console.warn(`[SceneSwitcher] Can't switch to scene of type ${i}`),!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){yt&&console.log("[SceneSwitcher] UNLOAD",e.url,"HasURL?: "+e.hasUrl);const t=this._currentSceneAsset,i=this.tryGetSceneEventListener(t);if(i?.sceneClosing){const n=i.sceneClosing();n instanceof Promise&&await n}e.hasUrl?(e.unload(),t&&fi(t,!0,!1)):P.remove(t),this._currentSceneAsset=void 0}}_currentlyLoadingScene;_loadingRequestId=0;_activeLoadingRequestId=0;async __internalSwitchScene(e){await this.__unloadCurrentScene();const t=this._currentIndex=this.scenes?.indexOf(e)??-1,i=++this._loadingRequestId;try{yt&&console.debug(`${Date.now()} [SceneSwitcher] Loading scene start: ${e.url} (index: ${t})`),this._currentlyLoadingScene=e,this._currentLoadingProgress=new ProgressEvent("progress",{loaded:0,total:1});const n=new CustomEvent("loadscene-start",{detail:{scene:e,switcher:this,index:t}});this.dispatchEvent(n),this.sceneLoadingStart?.invoke(n.detail),await this.onStartLoading(i),await e.loadAssetAsync((r,a)=>{if(i===this._activeLoadingRequestId){if(yt){const l=a.loaded/a.total,h="["+"=".repeat(Math.floor(l*20))+"-".repeat(20-Math.floor(l*20))+"]";console.debug(`${Date.now()} [SceneSwitcher] Loading scene progress: ${(l*100).toFixed(1)} % ${h}`,e.url)}this._currentLoadingProgress=a,this.dispatchEvent(a),this.sceneLoadingProgress?.invoke(a)}}).catch(console.error),await this.onEndLoading(i);const o=new CustomEvent("loadscene-finished",{detail:{scene:e,switcher:this,index:t}});if(this.dispatchEvent(o),i===this._activeLoadingRequestId&&(this._currentLoadingProgress=void 0,this._currentlyLoadingScene=void 0),o.defaultPrevented)return yt&&console.warn("[SceneSwitcher] Adding loaded scene prevented:",e,o),!1;if(!e.asset)return yt&&console.warn("[SceneSwitcher] Failed loading scene:",e),!1;if(this._currentIndex===t){if(yt&&console.log("[SceneSwitcher] ADD",e.url),this._currentScene=e,ET){const l=this.context.mainCameraComponent?.gameObject||this.context.mainCamera;l?.removeFromParent();const h=this.gameObject.removeFromParent();fi(this.context.scene,!0,!0),this.context.scene=new c.Scene,this.context.scene.add(h),l&&this.context.scene.add(l)}if(e.asset.parent?this._currentSceneAsset=Ls(e.asset,{parent:this.gameObject}):(this._currentSceneAsset=e.asset,P.add(e.asset,this.gameObject)),this.useSceneLighting&&this.context.sceneLighting.enable(e),this.useSceneBackground){const l=this.context.lightmaps.tryGetSkybox(e.url);l?(l.mapping!==c.CubeUVReflectionMapping&&(l.mapping=c.EquirectangularReflectionMapping),this.context.scene.background=l,this.context.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()):yt&&console.warn("[SceneSwitcher] Can't find skybox for scene "+e.url)}if(this.useHistory&&t>=0){let l=t.toString();if(this.useSceneName&&(e instanceof c.Object3D?l=e.name:e instanceof J&&e.asset?.name?l=e.asset.name:e.url&&(l=m0(e.url))),this.queryParameterName?.length)Yc(this.queryParameterName,l,this.useHistory);else{const h=history.state,d=this.guid+"::"+t;h!==d&&history.pushState(d,"unused",location.href)}}const r=this.tryGetSceneEventListener(this._currentSceneAsset);if(r?.sceneOpened){const l=r.sceneOpened(this);l instanceof Promise&&await l}yt&&console.debug(`${Date.now()} [SceneSwitcher] Loading scene finished: ${e.url} (index: ${t})`);const a=new CustomEvent("scene-opened",{detail:{scene:e,switcher:this,index:t}});return this.dispatchEvent(a),this.sceneLoaded?.invoke(this),this._currentSceneAsset&&this.context.events.emit("scene-content-changed",{source:this,object:this._currentSceneAsset}),!0}}catch(n){console.error(n)}return!1}preload(e){if(e>=0&&e<this.scenes.length){const t=this.scenes[e];if(t instanceof J)return t.preload()}return io}tryLoadFromQueryParam(){if(!this.queryParameterName?.length)return io;const e=x(this.queryParameterName);return typeof e=="boolean"?io:this.trySelectSceneFromValue(e)}trySelectSceneFromValue(e){if(typeof e=="string"){const t=parseInt(e);if(t>=0&&t<this.scenes.length)return this.select(t);{const i=e.toLowerCase();for(let n=0;n<this.scenes.length;n++){const o=this.scenes[n];if(!o)continue;const r=[];if(o instanceof c.Object3D)r.push(o.name);else{o.url&&r.push(m0(o.url));const a=o.asset;a instanceof c.Object3D&&a.name&&r.push(a.name)}if(r.some(a=>a?.toLowerCase().includes(i)))return this.select(n)}}}else if(typeof e=="number"&&e>=0&&e<this.scenes.length)return this.select(e);return ki()&&console.warn('[SceneSwitcher] Can not find scene: "'+e+'"',this),io}_lastLoadingScene=void 0;_loadingScenePromise=void 0;_isCurrentlyLoading=!1;_currentLoadingProgress=void 0;async onStartLoading(e){if(this._activeLoadingRequestId=e,this._isCurrentlyLoading=!0,this.loadingScene&&(this._lastLoadingScene!==this.loadingScene&&(this._loadingScenePromise=void 0),this._lastLoadingScene=this.loadingScene,this._loadingScenePromise||(this._loadingScenePromise=this.loadingScene?.loadAssetAsync().then(t=>t!=null)),await this._loadingScenePromise,e===this._activeLoadingRequestId&&this._isCurrentlyLoading&&this.loadingScene?.asset)){yt&&console.log("Add loading scene",this.loadingScene.url,this.loadingScene.asset);const t=this.loadingScene.asset;P.add(t,this.gameObject);const i=this.tryGetSceneEventListener(t);if(i?.sceneOpened){const n=i.sceneOpened(this);n instanceof Promise&&await n}}if(e===this._activeLoadingRequestId&&this._isCurrentlyLoading){const t=this.tryGetSceneEventListener(this.gameObject);if(t&&t.sceneOpened){const i=t.sceneOpened(this);i instanceof Promise&&await i}}}async onEndLoading(e){if(e===this._activeLoadingRequestId){if(this._isCurrentlyLoading=!1,this.loadingScene?.asset){yt&&console.log("Remove loading scene",this.loadingScene.url);const t=this.loadingScene.asset,i=this.tryGetSceneEventListener(t);if(typeof i?.sceneClosing=="function"){const n=i.sceneClosing();n instanceof Promise&&await n}P.remove(t)}if(!this._isCurrentlyLoading){const t=this.tryGetSceneEventListener(this.gameObject);if(t&&t.sceneClosing){const i=t.sceneClosing();i instanceof Promise&&await i}}}}tryGetSceneEventListener(e,t=0){if(!e)return null;const i=P.foreachComponent(e,n=>{const o=n;if(o.sceneClosing||o.sceneOpened)return o});if(t===0&&!i&&e.children.length)for(const n of e.children){const o=this.tryGetSceneEventListener(n,t+1);if(o)return o}return i||null}}wt([p()],Ye.prototype,"autoLoadFirstScene");wt([p(J)],Ye.prototype,"scenes");wt([p(J)],Ye.prototype,"loadingScene");wt([p()],Ye.prototype,"queryParameterName");wt([p()],Ye.prototype,"useSceneName");wt([p()],Ye.prototype,"clamp");wt([p()],Ye.prototype,"useHistory");wt([p()],Ye.prototype,"useKeyboard");wt([p()],Ye.prototype,"useSwipe");wt([p()],Ye.prototype,"useSceneLighting");wt([p()],Ye.prototype,"useSceneBackground");wt([p()],Ye.prototype,"preloadNext");wt([p()],Ye.prototype,"preloadPrevious");wt([p()],Ye.prototype,"preloadConcurrent");wt([p()],Ye.prototype,"createMenuButtons");wt([p(Z)],Ye.prototype,"sceneLoadingStart");wt([p(Z)],Ye.prototype,"sceneLoadingProgress");wt([p(Z)],Ye.prototype,"sceneLoaded");function m0(s){const t=s.split("/").pop()?.split(".").shift();return t?.length?t:s}class TT{maxLoadAhead;maxLoadBehind;maxConcurrent;_isRunning=!1;_switcher;_loadTasks=[];_maxConcurrentLoads=1;constructor(e,t=1,i=1,n=2){this._switcher=e,this.maxLoadAhead=t,this.maxLoadBehind=i,this.maxConcurrent=n}begin(e){if(this._isRunning)return;yt&&console.log("[SceneSwitcher] Preload scheduled",{delay:e}),this._isRunning=!0;let t=-10,i,n;const o=this._switcher.scenes,r=Date.now()+e,a=setInterval(()=>{if(this.allLoaded()&&(yt&&console.log("[SceneSwitcher] All scenes (pre-)loaded"),this.stop()),!this._isRunning){clearInterval(a);return}if(Date.now()<r||this.canLoadNewScene()===!1)return;(t===-10||t!==this._switcher.currentIndex)&&(t=this._switcher.currentIndex,n=0,i=0);const l=n%2===0;l&&(i+=1),n+=1;const h=l?this.maxLoadAhead:this.maxLoadBehind;if(i>h)return;const d=l?t+i:t-i;if(!(d<0)&&!(d<0||d>=o.length)&&!this._loadTasks.some(u=>u.index===d)){const u=o[d];yt&&console.log("[SceneSwitcher] Schedule preload scene",{roomIndex:d,searchForward:l,lastRoom:t,currentIndex:this._switcher.currentIndex,tasks:this._loadTasks.length},u?.url),new AT(d,u,this._loadTasks)}},200)}stop(){this._isRunning=!1}canLoadNewScene(){return this._loadTasks.length<this._maxConcurrentLoads}allLoaded(){if(this._switcher.scenes){for(const e of this._switcher.scenes)if(e?.isLoaded&&e.isLoaded()===!1)return!1}return!0}}class AT{index;asset;tasks;constructor(e,t,i){this.index=e,this.asset=t,this.tasks=i,i.push(this),this.awaitLoading()}async awaitLoading(){this.asset&&!this.asset.isLoaded()&&(yt&&console.log("[SceneSwitcher] Preload start: "+this.asset.url,this.index),await this.asset.preload(),yt&&console.log("[SceneSwitcher] Preload finished: "+this.asset.url,this.index));const e=this.tasks.indexOf(this);e>=0&&this.tasks.splice(e,1)}}const _o=x("debugautosync"),bm=Symbol("syncerId");class DT{_syncers={};getOrCreateSyncer(e){if(!e.guid)return null;if(this._syncers[e.guid])return this._syncers[e.guid];const t=new IT(e);return t[bm]=e.guid,this._syncers[t[bm]]=t,t}removeSyncer(e){delete this._syncers[e[bm]]}}const __=new DT;class IT{comp;constructor(e){this.comp=e}hasChanges=!1;changedProperties={};get networkingKey(){return this.comp.guid}_isReceiving=!1;_isInit=!1;init(e){if(this._isInit)return;this._isInit=!0,this.comp=e,this.comp.context.post_render_callbacks.push(this.onHandleSending),this.comp.context.connection.beginListen(this.networkingKey,this.onHandleReceiving);const t=this.comp.context.connection.tryGetState(this.comp.guid);t&&this.onHandleReceiving(t)}destroy(){this._isInit&&(this.comp.context.post_render_callbacks.splice(this.comp.context.post_render_callbacks.indexOf(this.onHandleSending),1),this.comp.context.connection.stopListen(this.networkingKey,this.onHandleReceiving),this.comp=null,this._isInit=!1)}notifyChanged(e,t){this._isReceiving||(_o&&console.log("Property changed: "+e,t),this.hasChanges=!0,this.changedProperties[e]=t)}onHandleSending=()=>{if(!this.hasChanges)return;this.hasChanges=!1;const e=this.comp.context.connection;if(!e||!e.isConnected||!e.isInRoom){for(const t in this.changedProperties)delete this.changedProperties[t];return}for(const t in this.changedProperties){const i=this.changedProperties[t];_o&&console.log("SEND",this.comp.guid,this.networkingKey),e.send(this.networkingKey,{guid:this.comp.guid,property:t,data:i},yn.Queued),delete this.changedProperties[t]}};onHandleReceiving=e=>{if(_o&&console.log("SYNCFIELD RECEIVE",this.comp.name,this.comp.guid,e),!!this._isInit&&this.comp&&e.guid===this.comp.guid)try{this._isReceiving=!0,this.comp[e.property]=e.data}catch(t){console.error(t)}finally{this._isReceiving=!1}}}function LT(s,e){let t=e!==s;return!t&&s&&e&&(Array.isArray(s)&&Array.isArray(e)||typeof s=="object"&&typeof e=="object")&&(t=!0),t}const Hc=Symbol("AutoSyncHandler");function BT(s){if(s[Hc])return s[Hc];const e=__.getOrCreateSyncer(s);return e?.init(s),s[Hc]=e,e}function FT(s){const e=s[Hc];e&&(__.removeSyncer(e),e.destroy(),delete s[Hc])}const b_=function(s=null){return function(e,t){let i="";typeof t=="string"?i=t:i=t.name;let n=null,o;typeof s=="string"?o=e[s]:typeof s=="function"&&(o=s),o==null&&(E()||_o)&&s!=null&&console.warn('syncField: no callback function found for property "'+i+'"','"'+s+'"');const r=e,a=r.__internalAwake;if(typeof a!="function"){(_o||E())&&console.error('@syncField can currently only used on Needle Engine Components, custom object of type "'+e?.constructor?.name+'" is not supported',e);return}_o&&console.log(i);const l=Symbol(i);r.__internalAwake=function(){if(this[l]!==void 0)return;if(this[l]=this[i],n=__.getOrCreateSyncer(this),Object.getOwnPropertyDescriptor(this,i)?.set===void 0){let u=!1;Object.defineProperty(this,i,{set:function(f){const m=this[l];if(this[l]=f,u){(E()||_o)&&console.warn("Recursive call detected",i);return}u=!0;try{const g=LT(f,m);_o&&console.log("SyncField assignment",i,"changed?",g,f,o),g&&o?.call(this,f,m)!==!1&&BT(this)?.notifyChanged(i,f)}finally{u=!1}},get:function(){return this[l]},configurable:!0,enumerable:!0})}n?.init(this),a.call(this)};const h=r.__internalDestroy;r.__internalDestroy=function(){FT(this),h.call(this)}}},Ld=new Map;function Bh(s,e,t){const i=t?.format===void 0?s:`${s}|format=${t.format}`;if(Ld.has(i))return Ld.get(i);const n=new URL(s,window.location.href),o=jT(n,e,t);return Ld.set(i,o),o.finally(()=>{Ld.delete(i)}),o}async function jT(s,e,t){if(!s)return Promise.resolve(null);const i=s.pathname,n=t?.format!==void 0?t.format==="pmrem":s.toString().toLowerCase().includes("pmrem")||s.searchParams.get("pmrem")!=null;let o=i.endsWith(".exr"),r=i.endsWith(".hdr"),a=i.endsWith(".ktx2");if(!o&&!r&&!a)try{const f=await fetch(s.toString(),{method:"GET",headers:{range:"bytes=0-15"}}),m=f.headers.get("content-type")?.toLowerCase()??"";if(m==="image/x-exr"||m==="image/aces")o=!0;else if(m==="image/vnd.radiance"||m==="image/x-hdr")r=!0;else if(m==="image/ktx2")a=!0;else{const g=new Uint8Array(await f.arrayBuffer());g.length>=4&&g[0]===118&&g[1]===47&&g[2]===49&&g[3]===1?o=!0:g.length>=12&&g[0]===171&&g[1]===75&&g[2]===84&&g[3]===88&&g[4]===32&&g[5]===50&&g[6]===48&&g[7]===187?a=!0:g.length>=10&&g[0]===35&&g[1]===63&&g[2]===82&&g[3]===65&&g[4]===68&&g[5]===73&&g[6]===65&&g[7]===78&&g[8]===67&&g[9]===69&&(r=!0)}}catch(f){console.warn("loadPMREM: failed to probe URL for format detection",s,f)}let l;if(o)l=new V.EXRLoader;else if(r)l=new V.HDRLoader;else if(a){const{ktx2Loader:f}=re.createLoaders(e);l=f}else l=new c.TextureLoader;const h=s.toString();return await l.loadAsync(h).then(f=>{if(f){const m=i.lastIndexOf("/");f.name=t?.name||i.substring(m>=0?m+1:0),n?f.mapping=c.CubeUVReflectionMapping:f.mapping=c.EquirectangularRefractionMapping,l instanceof c.TextureLoader&&(f.colorSpace=c.SRGBColorSpace)}return f}).catch(f=>(console.warn("Failed to load texture from url:",s),null))}var UT=Object.defineProperty,Fh=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&UT(e,t,n),n};const tt=x("debugskybox");function zT(){iy("background-image"),iy("environment-image"),$T()}function Bd(){return{url:null,texture:null,loadId:0}}const ny=new WeakMap,Fd=new Array,jd=Math.PI/180;function g0(s,e){const t=s.trim().split(/\s+/);if(t.length===1){const i=parseFloat(t[0]);isNaN(i)||e.set(0,i*jd,0)}else if(t.length>=3){const i=parseFloat(t[0]),n=parseFloat(t[1]),o=parseFloat(t[2]);!isNaN(i)&&!isNaN(n)&&!isNaN(o)&&e.set(i*jd,n*jd,o*jd)}}function y0(s,e,t,i){if(!s.scene){tt&&console.warn("Skybox: skipping applyTexture — context was torn down before the texture finished loading");return}!(e instanceof c.CubeTexture||e instanceof c.CompressedCubeTexture)&&e.mapping!==c.CubeUVReflectionMapping&&(e.mapping=c.EquirectangularRefractionMapping,e.needsUpdate=!0),i&&(s.scene.environment=e),t&&!Jt.backgroundShouldBeTransparent(s)&&(s.scene.background=e);const n=s.domElement;if(t){const o=n.getAttribute("background-blurriness");if(o){const l=parseFloat(o);isNaN(l)||(s.scene.backgroundBlurriness=l)}else s.mainCameraComponent?.backgroundBlurriness!==void 0&&(s.scene.backgroundBlurriness=s.mainCameraComponent.backgroundBlurriness);const r=n.getAttribute("background-intensity");if(r){const l=parseFloat(r);isNaN(l)||(s.scene.backgroundIntensity=l)}const a=n.getAttribute("background-rotation");a&&g0(a,s.scene.backgroundRotation)}if(i){const o=n.getAttribute("environment-rotation");o&&g0(o,s.scene.environmentRotation)}}function NT(s,e,t,i){const n=e.url?Bw(e.url):void 0;e.url=null,e.texture=null,i&&(!n||!s.sceneLighting.internalEnableReflection(n))&&(s.scene.environment=null),t&&(s.scene.background=n?s.lightmaps.tryGetSkybox(n):null)}function Ud(s,e,t,i,n,o){const r=s.currentContext;if(!r)return null;const a=o?mC(o,n,i):null;if(tt&&console.log(`Skybox attribute [${t}]: raw="${o}" → resolved="${a}"`),a&&(a==="transparent"||a.startsWith("rgb")||a.startsWith("#")))return console.warn(`Needle Engine: Invalid ${t} value (${a}). Did you mean to set background-color instead?`),null;const l=++e.loadId;return a?e.url===a&&e.texture?(tt&&console.log(`Skybox attribute [${t}]: cache hit, re-applying`),y0(r,e.texture,i,n),null):(e.url=a,e.texture=null,(async()=>{tt&&console.log(`Skybox attribute [${t}]: loading ${a}`);const d=await Bh(a,r.renderer);if(e.loadId!==l){tt&&console.warn(`Skybox attribute [${t}]: loadId mismatch (stale load), skipping apply`);return}if(!d){tt&&console.warn(`Skybox attribute [${t}]: failed to load ${a}`);return}tt&&console.log(`Skybox attribute [${t}]: loaded, applying to scene`),e.texture=d,y0(r,d,i,n),r.domElement.dispatchEvent(new CustomEvent(`${t}-loaded`,{detail:{texture:d}}))})()):(NT(r,e,i,n),null)}function _0(s){const e=ny.get(s.context.domElement);return!e||e.currentContext!==s.context?null:e}let b0=!1;function $T(){b0||(b0=!0,se.registerCallback(ae.ContextCreationStart,s=>{const e=s.context,t=e.domElement;let i=ny.get(t);i?i.currentContext=e:(i={currentContext:e,bg:Bd(),env:Bd(),listenersInstalled:!1},ny.set(t,i));const n=Ud(i,i.bg,"background-image",!0,!1,t.getAttribute("background-image"));n&&Fd.push(n);const o=Ud(i,i.env,"environment-image",!1,!0,t.getAttribute("environment-image"));if(o&&Fd.push(o),!i.listenersInstalled){i.listenersInstalled=!0;const r=i;ju(t,"background-image",a=>{const l=typeof a=="string"&&a.length>0?a:null;tt&&console.log("background-image CHANGED TO",l),Ud(r,r.bg,"background-image",!0,!1,l)}),ju(t,"environment-image",a=>{const l=typeof a=="string"&&a.length>0?a:null;tt&&console.log("environment-image CHANGED TO",l),Ud(r,r.env,"environment-image",!1,!0,l)})}}),se.registerCallback(ae.ContextCreationStart,()=>Promise.all(Fd).finally(()=>{Fd.length=0})),se.registerCallback(ae.ContextClearing,s=>{const e=_0(s);e&&(e.bg=Bd(),e.env=Bd())}),se.registerCallback(ae.ContextDestroyed,s=>{const e=_0(s);e&&(e.currentContext=null,e.bg.loadId++,e.env.loadId++)}))}const Br=class extends T{url="studio";allowDrop=!0;background=!0;environment=!0;allowNetworking=!0;_prevUrl;_prevLoadedEnvironment;_inFlightLoad;_prevEnvironment=null;_prevBackground=null;revertAppliedSceneState(){if(!this.context||!this._prevLoadedEnvironment)return!1;let e=!1;return this.context.scene.environment===this._prevLoadedEnvironment&&(this.context.scene.environment=this._prevEnvironment,e=!0),this.context.scene.background===this._prevLoadedEnvironment&&(Jt.backgroundShouldBeTransparent(this.context)||(this.context.scene.background=this._prevBackground),e=!0),e}discardPendingLoad(){if(this._prevUrl=void 0,this._inFlightLoad=void 0,!this.context){this._prevLoadedEnvironment?.dispose(),this._prevLoadedEnvironment=void 0;return}this.revertAppliedSceneState(),this._prevLoadedEnvironment=void 0}onEnable(){this.setSkybox(this.url),this.registerDropEvents()}onDisable(){this.revertAppliedSceneState()&&(this._prevLoadedEnvironment=void 0),this.unregisterDropEvents(),this.context.mainCameraComponent?.applyClearFlags()}onDestroy(){this._prevLoadedEnvironment=void 0}urlChangedSyncField(){this.allowNetworking&&this.url&&(this.isRemoteTexture(this.url)?this.setSkybox(this.url):tt&&console.warn(`RemoteSkybox: Not setting skybox: ${this.url} is not a remote texture. If you want to set a local texture, set allowNetworking to false.`))}async setSkybox(e,t){if(!this.activeAndEnabled||(e=mC(e,this.environment,this.background),!e))return!1;if(t??=e,this.isValidTextureType(t)||console.warn('Potentially invalid skybox URL: "'+t+'" on '+(this.name||this.gameObject?.name||"context")),tt&&console.log("Set RemoteSkybox url: "+e),this._prevUrl===e){if(this._prevLoadedEnvironment)return this.apply(),!0;if(this._inFlightLoad)return this._inFlightLoad}this._prevLoadedEnvironment?.dispose(),this._prevLoadedEnvironment=void 0,this._prevUrl=e;const i=(async()=>{const n=await Bh(e,this.context.renderer);return n?!this.enabled||this.destroyed?(tt&&console.warn("RemoteSkybox: Component is disabled or destroyed"),!1):this._prevUrl!==e?(tt&&console.warn("RemoteSkybox: URL changed while loading texture, aborting setSkybox"),!1):(this.url=e,this._prevLoadedEnvironment=n,this.apply(),!0):(tt&&console.warn("RemoteSkybox: Failed to load texture from url",e),!1)})();this._inFlightLoad=i;try{return await i}finally{this._inFlightLoad===i&&(this._inFlightLoad=void 0)}}apply(){const e=this._prevLoadedEnvironment;if(e&&(e instanceof c.CubeTexture||e instanceof c.CompressedCubeTexture||e.mapping==c.CubeUVReflectionMapping||(e.mapping=c.EquirectangularRefractionMapping,e.needsUpdate=!0),!this.destroyed)){if(!this.context){console.warn("RemoteSkybox: Context is not available - can not apply skybox.");return}this.context.scene.background!==e&&(this._prevBackground=this.context.scene.background),this.context.scene.environment!==e&&(this._prevEnvironment=this.context.scene.environment),tt&&console.log("Set RemoteSkybox ("+(this.environment&&this.background?"environment and background":this.environment?"environment":this.background?"background":"none")+")",this.url,!Jt.backgroundShouldBeTransparent(this.context)),this.environment&&(this.context.scene.environment=e),this.background&&!Jt.backgroundShouldBeTransparent(this.context)&&(this.context.scene.background=e),this.context.mainCameraComponent?.backgroundBlurriness!==void 0&&(this.context.scene.backgroundBlurriness=this.context.mainCameraComponent.backgroundBlurriness)}}validProtocols=["file:","blob:","data:"];validTextureTypes=[".ktx2",".hdr",".exr",".jpg",".jpeg",".png"];isRemoteTexture(e){return e.startsWith("http://")||e.startsWith("https://")}isValidTextureType(e){for(const t of this.validTextureTypes)if(e.includes(t))return!0;for(const t of this.validProtocols)if(e.startsWith(t))return!0;return!1}registerDropEvents(){this.unregisterDropEvents(),this.context.domElement.addEventListener("dragover",this.onDragOverEvent),this.context.domElement.addEventListener("drop",this.onDrop)}unregisterDropEvents(){this.context.domElement.removeEventListener("dragover",this.onDragOverEvent),this.context.domElement.removeEventListener("drop",this.onDrop)}onDragOverEvent=e=>{if(this.allowDrop&&e.dataTransfer)for(const t of e.dataTransfer.types)(t==="text/uri-list"||t==="Files")&&e.preventDefault()};onDrop=e=>{if(this.allowDrop&&e.dataTransfer){for(const t of e.dataTransfer.types)if(tt&&console.log(t),t==="text/uri-list"){const i=e.dataTransfer.getData(t);tt&&console.log(t,i);let n=new RegExp(/polyhaven.com\/asset_img\/.+?\/(?<name>.+)\.png/).exec(i)?.groups?.name;if(n||(n=new RegExp(/polyhaven\.com\/a\/(?<name>.+)/).exec(i)?.groups?.name),tt&&console.log(n),n){const o="https://dl.polyhaven.org/file/ph-assets/HDRIs/exr/1k/"+n+"_1k.exr";console.log(`[Remote Skybox] Setting skybox from url: ${o}`),e.preventDefault(),this.setSkybox(o);break}else if(this.isValidTextureType(i)){console.log("[Remote Skybox] Setting skybox from url: "+i),e.preventDefault(),this.setSkybox(i);break}else{console.warn(`[RemoteSkybox] Unknown url ${i}. If you want to load a skybox from a url, make sure it is a valid image url. Url must end with${this.validTextureTypes.join(", ")}.`);const o=new CustomEvent("dropped-unknown-url",{detail:{sender:this,event:e,url:i,apply:r=>{e.preventDefault(),this.setSkybox(r)}}});this.dispatchEvent(o)}}else if(t=="Files"){const i=e.dataTransfer.files.item(0);if(tt&&console.log(t,i),!i)continue;if(!this.isValidTextureType(i.name)){console.warn(`[RemoteSkybox]: File "${i.name}" is not supported. Supported files are ${this.validTextureTypes.join(", ")}`);return}e.preventDefault(),this.setSkybox(i.name);break}}}};Fh([b_(Br.prototype.urlChangedSyncField),p(URL)],Br.prototype,"url");Fh([p()],Br.prototype,"allowDrop");Fh([p()],Br.prototype,"background");Fh([p()],Br.prototype,"environment");Fh([p()],Br.prototype,"allowNetworking");let v_=Br;const v0={studio:{url:"https://cdn.needle.tools/static/skybox/modelviewer-Neutral.pmrem4x4.ktx2?pmrem",url_low:"https://cdn.needle.tools/static/skybox/modelviewer-Neutral-small.pmrem4x4.ktx2?pmrem"},"blurred-skybox":{url:"https://cdn.needle.tools/static/skybox/blurred-skybox.pmrem4x4.ktx2?pmrem",url_low:"https://cdn.needle.tools/static/skybox/blurred-skybox-small.pmrem4x4.ktx2?pmrem"},"quicklook-ar":{url:"https://cdn.needle.tools/static/skybox/QuickLook-ARMode.pmrem4x4.ktx2?pmrem",url_low:"https://cdn.needle.tools/static/skybox/QuickLook-ARMode-small.pmrem4x4.ktx2?pmrem"},quicklook:{url:"https://cdn.needle.tools/static/skybox/QuickLook-ObjectMode.pmrem4x4.ktx2?pmrem",url_low:"https://cdn.needle.tools/static/skybox/QuickLook-ObjectMode-small.pmrem4x4.ktx2?pmrem"}};function mC(s,e,t){if(s==null)return null;const i=e&&!t,n=v0[s.toLowerCase()];return n?i?n.url_low:n.url:(typeof s=="string"&&s?.length&&(E()||tt)&&(s.includes("/")||s.includes(".")||console.warn(`RemoteSkybox: Unknown magic skybox name "${s}". Valid names are: ${Object.keys(v0).map(r=>`"${r}"`).join(", ")}`)),s)}var VT=Object.defineProperty,gC=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&VT(e,t,n),n};class jh extends T{from;to;width=0;centered=!0;_centerPos;awake(){this._centerPos=new c.Vector3}update(){if(!this.from||!this.to)return;const e=ie(this.from).clone(),t=ie(this.to).clone(),i=e.distanceTo(t);this._centerPos.copy(e),this._centerPos.add(t),this._centerPos.multiplyScalar(.5),Oi(this.gameObject,this.centered?this._centerPos:e),this.gameObject.lookAt(ie(this.to).clone()),this.gameObject.scale.set(this.width,this.width,i)}}gC([p(P)],jh.prototype,"from");gC([p(P)],jh.prototype,"to");var WT=Object.defineProperty,w_=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&WT(e,t,n),n};class Ol extends T{length=1;depthTest=!0;isGizmo=!1;_axes=null;onEnable(){if(this.isGizmo&&!Oh)return;this._axes||(this._axes=new c.AxesHelper(this.length)),this._axes.layers.disableAll(),this._axes.layers.set(this.layer),this.gameObject.add(this._axes);const e=this._axes.material;e&&e.depthTest!==void 0&&(e.depthTest=this.depthTest)}onDisable(){this._axes&&this.gameObject.remove(this._axes)}}w_([p()],Ol.prototype,"length");w_([p()],Ol.prototype,"depthTest");w_([p()],Ol.prototype,"isGizmo");class x_ extends T{from;to;hint;desiredDistance=1;onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;const e=ie(this.to).clone(),t=ie(this.from).clone(),i=e.distanceTo(t),n=e.clone();n.sub(t);const o=t.clone();o.add(e),o.multiplyScalar(.5);const r=ie(this.hint).clone();r.sub(o);const a=new c.Vector3;a.crossVectors(r,n),a.crossVectors(n,a),a.normalize();const l=i*.5,h=Math.max(this.desiredDistance,l),d=Math.sqrt(h*h-l*l),u=a.clone();u.multiplyScalar(d),u.add(o),Oi(this.gameObject,u);const f=o.clone();f.sub(a),this.gameObject.lookAt(f)}}const GT=x("gizmos"),HT=x("debugboxhelper");class At extends T{box=null;static testBox=new c.Box3;_lastMatrixUpdateFrame=-1;static _position=new c.Vector3;static _size=new c.Vector3(.01,.01,.01);static _emptyObjectSize=new c.Vector3(.01,.01,.01);isInBox(e){if(!e)return;if(this.box||(this.box=new c.Box3),pi([e],void 0,void 0,At.testBox),At.testBox.isEmpty()){const i=ie(e,At._position);At.testBox.setFromCenterAndSize(i,At._emptyObjectSize)}this.updateBox();const t=this.box?.intersectsBox(At.testBox);return t&&HT&&B.DrawWireBox3(At.testBox,16711680,5),t}intersects(e){return e?this.updateBox(!1).intersectsBox(e):!1}updateBox(e=!1){if(this.box||(this.box=new c.Box3),e||this.context.time.frameCount!=this._lastMatrixUpdateFrame){const t=this._lastMatrixUpdateFrame<0;this._lastMatrixUpdateFrame=this.context.time.frameCount;const i=t,n=ie(this.gameObject,At._position,i),o=Ve(this.gameObject,At._size);this.box.setFromCenterAndSize(n,o)}return this.box}_helper=null;_color=null;awake(){this._helper=null,this._color=null,this.box=null}showHelper(e=null,t=!1){if(!(!GT&&!t)){if(this._helper){e&&this._color?.set(e),this.gameObject.add(this._helper);return}this._helper=s_(e),this.gameObject.add(this._helper)}}}var qT=Object.defineProperty,ni=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&qT(e,t,n),n};class Ii extends T{get isCollider(){return!0}attachedRigidbody=null;isTrigger=!1;sharedMaterial;membership=[0];filter;density;_propertiesDirty=!1;onValidate(e){this.activeAndEnabled?e==="sharedMaterial"?this.updatePhysicsMaterial():this.updateProperties():this._propertiesDirty=!0}awake(){super.awake(),this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Xe))}start(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Xe))}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Xe))}onDisable(){this.context.physics.engine?.setColliderEnabled(this,!1)||this.context.physics.engine?.removeBody(this)}onDestroy(){this.context.physics.engine?.removeBody(this)}get body(){return this.context.physics.engine?.getBody(this)}updateProperties=()=>{this.context.physics.engine?.updateProperties(this)};updatePhysicsMaterial(){this.context.physics.engine?.updatePhysicsMaterial(this)}}ni([p(Xe)],Ii.prototype,"attachedRigidbody");ni([je(),p()],Ii.prototype,"isTrigger");ni([je(),p()],Ii.prototype,"sharedMaterial");ni([je(),p()],Ii.prototype,"membership");ni([je(),p()],Ii.prototype,"filter");ni([je(),p()],Ii.prototype,"density");class El extends Ii{radius=.5;center=new c.Vector3(0,0,0);onEnable(){super.onEnable();const e=this.context.physics.getOrCreatePhysicsEngine();e?.setColliderEnabled(this,!0)?this._propertiesDirty&&(this.updateProperties(),this.updatePhysicsMaterial()):e?.addSphereCollider(this),this._propertiesDirty=!1,Mf(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),Cy(this.gameObject.scale,this.updateProperties)}}ni([je(),p()],El.prototype,"radius");ni([p(c.Vector3)],El.prototype,"center");const S_=class yC extends Ii{static add(e,t){const i=ss(e,yC);return i.autoFit(),t?.rigidbody===!0&&ss(e,Xe,{isKinematic:!1}),i}size=new c.Vector3(1,1,1);center=new c.Vector3(0,0,0);onEnable(){super.onEnable();const e=this.context.physics.getOrCreatePhysicsEngine();e?.setColliderEnabled(this,!0)?this._propertiesDirty&&(this.updateProperties(),this.updatePhysicsMaterial()):e?.addBoxCollider(this,this.size),this._propertiesDirty=!1,Mf(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),Cy(this.gameObject.scale,this.updateProperties)}autoFit(e){const t=this.gameObject,i=t.position.clone(),n=t.quaternion.clone(),o=t.scale.clone(),r=t.parent;t.position.set(0,0,0),t.quaternion.set(0,0,0,1),t.scale.set(1,1,1),t.parent=null,t.updateMatrix();const a=pi([t]);t.position.copy(i),t.quaternion.copy(n),t.scale.copy(o),t.parent=r,e?.debug===!0&&B.DrawWireBox3(a,16768256,20),this.size=a.getSize(new c.Vector3)||new c.Vector3(1,1,1),this.center=a.getCenter(new c.Vector3)||new c.Vector3(0,0,0),this.size.length()<=0&&this.size.set(.01,.01,.01)}};ni([je(),p(c.Vector3)],S_.prototype,"size");ni([p(c.Vector3)],S_.prototype,"center");let np=S_;class Uo extends Ii{sharedMesh;convex=!1;onEnable(){super.onEnable();const e=this.context.physics.getOrCreatePhysicsEngine();if(!e)return;if(e.setColliderEnabled(this,!0)){this._propertiesDirty&&(this.updateProperties(),this.updatePhysicsMaterial()),this._propertiesDirty=!1;return}this._propertiesDirty=!1,this.sharedMesh?.isMesh||(this.gameObject instanceof c.Mesh||this.gameObject instanceof c.Group)&&(this.sharedMesh=this.gameObject);const t=0;if(this.sharedMesh?.isMesh)e.addMeshCollider(this,this.sharedMesh,this.convex),re.NEEDLE_progressive.assignMeshLOD(this.sharedMesh,t).then(i=>{i&&this.activeAndEnabled&&this.context.physics.engine&&this.sharedMesh&&(this.context.physics.engine.removeBody(this),this.sharedMesh.geometry=i,this.context.physics.engine.addMeshCollider(this,this.sharedMesh,this.convex))});else{const i=this.sharedMesh;if(i?.isGroup){console.warn(`MeshCollider mesh is a group "${this.sharedMesh?.name||this.gameObject.name}", adding all children as colliders. This is currently not fully supported (colliders can not be removed from world again)`,this);const n=new Array;for(const o in i.children){const r=i.children[o];r.isMesh&&(e.addMeshCollider(this,r,this.convex),n.push(re.NEEDLE_progressive.assignMeshLOD(r,t)))}Promise.all(n).then(o=>{if(o.some(a=>a)==!1)return;this.context.physics.engine?.removeBody(this);const r=new c.Mesh;for(const a of o)a&&this.activeAndEnabled&&(r.geometry=a,this.context.physics.engine?.addMeshCollider(this,r,this.convex))})}else(E()||x("showcolliders"))&&console.warn(`[MeshCollider] A MeshCollider mesh is assigned to an unknown object on "${this.gameObject.name}", but it's neither a Mesh nor a Group. Please double check that you attached the collider component to the right object and report a bug otherwise!`,this)}}}ni([p(c.Mesh)],Uo.prototype,"sharedMesh");ni([p()],Uo.prototype,"convex");class Fs extends Ii{center=new c.Vector3(0,0,0);radius=.5;height=2;onEnable(){super.onEnable();const e=this.context.physics.getOrCreatePhysicsEngine();e?.setColliderEnabled(this,!0)?this._propertiesDirty&&(this.updateProperties(),this.updatePhysicsMaterial()):e?.addCapsuleCollider(this,this.height,this.radius),this._propertiesDirty=!1}}ni([p(c.Vector3)],Fs.prototype,"center");ni([p()],Fs.prototype,"radius");ni([p()],Fs.prototype,"height");var XT=Object.defineProperty,zs=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&XT(e,t,n),n};const w0=x("debugcharactercontroller");class Gr extends T{center=new c.Vector3(0,0,0);radius=.5;height=2;_rigidbody=null;get rigidbody(){return this._rigidbody?this._rigidbody:(this._rigidbody=this.gameObject.getComponent(Xe),this._rigidbody||(this._rigidbody=this.gameObject.addComponent(Xe)),this.rigidbody)}_activeGroundCollisions;awake(){this._activeGroundCollisions=new Set}onEnable(){const e=this.rigidbody;let t=this.gameObject.getComponent(Fs);t||(t=this.gameObject.addComponent(Fs)),t.center.copy(this.center),t.radius=this.radius,t.height=this.height;const i=new c.Vector3(0,0,1),n=new c.Vector3(1,0,0),o=new c.Vector3(0,1,0),r=this.gameObject.getWorldDirection(new c.Vector3);r.y=0;const a=n.dot(r)<0?-1:1,l=i.angleTo(r)*a;this.gameObject.setRotationFromAxisAngle(o,l),e.lockRotationX=!0,e.lockRotationY=!0,e.lockRotationZ=!0}move(e){this.gameObject.position.add(e)}onCollisionEnter(e){(e.contacts.length==0||e.contacts.some(t=>t.normal.y>.2))&&(this._activeGroundCollisions.add(e),w0&&console.log(`Collision(${this._activeGroundCollisions.size}): ${e.contacts.map(t=>t.normal.y.toFixed(2)).join(", ")} - ${this.isGrounded}`))}onCollisionExit(e){this._activeGroundCollisions.delete(e),w0&&console.log(`Collision(${this._activeGroundCollisions.size}) - ${this.isGrounded}`)}get isGrounded(){return this._activeGroundCollisions.size>0}_contactVelocity=new c.Vector3;get contactVelocity(){this._contactVelocity.set(0,0,0);for(const e of this._activeGroundCollisions){const t=this.context.physics.engine?.getLinearVelocity(e.collider);t&&(this._contactVelocity.x+=t.x,this._contactVelocity.y+=t.y,this._contactVelocity.z+=t.z)}return this._contactVelocity}}zs([p(c.Vector3)],Gr.prototype,"center");zs([p()],Gr.prototype,"radius");zs([p()],Gr.prototype,"height");class Ns extends T{controller;movementSpeed=2;rotationSpeed=2;jumpForce=1;doubleJumpForce=2;animator;lookForward=!0;awake(){this._currentRotation=new c.Quaternion}update(){const e=this.context.input;e.isKeyPressed("KeyW")?this.moveInput.y+=1:e.isKeyPressed("KeyS")&&(this.moveInput.y-=1),e.isKeyPressed("KeyD")?this.lookInput.x+=1:e.isKeyPressed("KeyA")&&(this.lookInput.x-=1),this.jumpInput||=e.isKeyDown("Space")}move(e){this.moveInput.add(e)}look(e){this.lookInput.add(e)}jump(){this.jumpInput=!0}lookInput=new c.Vector2(0,0);moveInput=new c.Vector2(0,0);jumpInput=!1;onBeforeRender(){this.handleInput(this.moveInput,this.lookInput,this.jumpInput),this.lookInput.set(0,0),this.moveInput.set(0,0),this.jumpInput=!1}_currentSpeed=new c.Vector3(0,0,0);_currentAngularSpeed=new c.Vector3(0,0,0);_temp=new c.Vector3(0,0,0);_jumpCount=0;_currentRotation;handleInput(e,t,i){if(this.controller?.isGrounded&&(this._jumpCount=0,this.doubleJumpForce>0&&this.animator?.setBool("doubleJump",!1)),this._currentSpeed.z+=e.y*this.movementSpeed*this.context.time.deltaTime,this.animator?.setBool("running",e.length()>.01),this.animator?.setBool("jumping",this.controller?.isGrounded===!0&&i),this._temp.copy(this._currentSpeed),this._temp.applyQuaternion(this.gameObject.quaternion),this.controller?this.controller.move(this._temp):this.gameObject.position.add(this._temp),this._currentAngularSpeed.y+=L.toRadians(-t.x*this.rotationSpeed)*this.context.time.deltaTime,this.lookForward&&Math.abs(this._currentAngularSpeed.y)<.01){const n=this.context.mainCameraComponent.forward;n.y=0,n.normalize(),this._currentRotation.setFromUnitVectors(new c.Vector3(0,0,1),n),this.gameObject.quaternion.slerp(this._currentRotation,this.context.time.deltaTime*10)}if(this.gameObject.rotateY(this._currentAngularSpeed.y),this._currentSpeed.multiplyScalar(1-this.context.time.deltaTime*10),this._currentAngularSpeed.y*=1-this.context.time.deltaTime*10,this.controller&&i&&this.jumpForce>0){let n=this.controller?.isGrounded;if(this.doubleJumpForce>0&&!this.controller?.isGrounded&&this._jumpCount===1&&(n=!0,this.animator?.setBool("doubleJump",!0)),n){this._jumpCount+=1;const o=this.controller.rigidbody,r=this._jumpCount===2?this.doubleJumpForce:this.jumpForce;o.applyImpulse(new c.Vector3(0,1,0).multiplyScalar(r))}}if(this.controller){const n=this.controller?.rigidbody.getVelocity().y;if(n<-1){this._raycastOptions.ray||(this._raycastOptions.ray=new c.Ray),this._raycastOptions.ray.origin.copy(ie(this.gameObject)),this._raycastOptions.ray.direction.set(0,-1,0);const o=this.layer;this.gameObject.layers.disableAll(),this.gameObject.layers.set(2);const r=this.context.physics.raycast(this._raycastOptions);this.gameObject.layers.set(o),(r.length&&r[0].distance>2||n<-10)&&this.animator?.setBool("falling",!0)}else this.animator?.setBool("falling",!1)}}_raycastOptions=new zr}zs([p(Gr)],Ns.prototype,"controller");zs([p()],Ns.prototype,"movementSpeed");zs([p()],Ns.prototype,"rotationSpeed");zs([p()],Ns.prototype,"jumpForce");zs([p()],Ns.prototype,"doubleJumpForce");zs([p(vt)],Ns.prototype,"animator");const _C=Symbol("customVisibilityFlag");function Qn(s,e){s.layers[_C]=e}const x0=Symbol("DidPatchLayers");function QT(){const s=c.Layers.prototype;if(s[x0])return;s[x0]=!0;const e=s.test;s.test=function(t){return this[_C]===!1?!1:e.call(this,t)}}var YT=Object.defineProperty,Rl=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&YT(e,t,n),n};const ba=x("debugcontactshadows");If(s=>{const e=s.domElement.getAttribute("contactshadows")||s.domElement.getAttribute("contact-shadows");if(e!=null&&e!="0"&&e!="false"){console.debug("Auto-creating ContactShadows because of `contactshadows` attribute");const t=Uh.auto(s),i=parseFloat(e);isNaN(i)||(t.opacity=i,t.darkness=i)}});const Hr=class Mc extends T{static _instances=new WeakMap;static auto(e,t){if(e||(e=X.Current),!e)throw new Error("No context provided and no current context set.");let i=this._instances.get(e);if(!i||i.destroyed){const n=new c.Object3D;n.name="ContactShadows",i=ss(n,Mc,{autoFit:!0,occludeBelowGround:!1}),this._instances.set(e,i)}return e.scene.add(i.gameObject),i.fitShadows(t),i}autoFit=!1;darkness=.5;opacity=.5;blur=4;occludeBelowGround=!1;backfaceShadows=!0;minSize;manualUpdate=!1;set needsUpdate(e){this._needsUpdate=e}get needsUpdate(){return this._needsUpdate}_needsUpdate=!1;_needsFit=!1;shadowsRoot=new c.Object3D;shadowGroup=new c.Group;shadowCamera;renderTarget;renderTargetBlur;plane;occluderMesh;blurPlane;planeMaterial;depthMaterial;horizontalBlurMaterial;verticalBlurMaterial;textureSize=512;fitShadows(e={}){ba&&console.warn("Fitting shadows to scene"),zu(this.shadowsRoot,!1);const t=e.object||this.context.scene,i=pi(t,[this.shadowsRoot]),n=Math.max(1,this.blur/32),o=i.max.x-i.min.x,r=i.max.z-i.min.z;i.expandByVector(new c.Vector3(n*o,0,n*r)),ba&&B.DrawWireBox3(i,16776960,60),this.gameObject.parent&&i.applyMatrix4(this.gameObject.parent.matrixWorld.clone().invert());const a=i.min,l=Math.max(1e-5,(i.max.y-a.y)*.002);i.max.y+=l,this.shadowsRoot.position.set((a.x+i.max.x)/2,a.y-l,(a.z+i.max.z)/2),this.shadowsRoot.scale.set(i.max.x-a.x,i.max.y-a.y,i.max.z-a.z),e.positionOffset&&(e.positionOffset.x!==void 0&&(this.shadowsRoot.position.x+=e.positionOffset.x),e.positionOffset.y!==void 0&&(this.shadowsRoot.position.y+=e.positionOffset.y),e.positionOffset.z!==void 0&&(this.shadowsRoot.position.z+=e.positionOffset.z)),e.scaleFactor&&(e.scaleFactor.x!==void 0&&(this.shadowsRoot.scale.x*=e.scaleFactor.x),e.scaleFactor.y!==void 0&&(this.shadowsRoot.scale.y*=e.scaleFactor.y),e.scaleFactor.z!==void 0&&(this.shadowsRoot.scale.z*=e.scaleFactor.z)),this.applyMinSize(),this.shadowsRoot.matrixWorldNeedsUpdate=!0,ba&&console.log("Fitted shadows to scene",this.shadowsRoot.scale.clone())}renderShadowsNow(){this._renderShadows()}awake(){Mc._instances.set(this.context,this)}onEnable(){this.shadowsRoot.hideFlags=as.DontExport,zu(this.shadowsRoot,!1),this._needsUpdate=!0,this.autoCleanup(this.context.events.on("scene-content-changed",()=>{this.autoFit&&(this._needsFit=!0,this._needsUpdate=!0)})),this.autoFit?this.fitShadows():this.applyMinSize()}onDestroy(){ba&&console.warn("Destroying ContactShadows on "+this.gameObject.name),Mc._instances.get(this.context)===this&&Mc._instances.delete(this.context),this.renderTarget?.dispose(),this.renderTargetBlur?.dispose(),this.depthMaterial?.dispose(),this.horizontalBlurMaterial?.dispose(),this.verticalBlurMaterial?.dispose(),this.blurPlane?.geometry.dispose(),this.plane?.geometry.dispose(),this.occluderMesh?.geometry.dispose()}onBeforeRender(e){this._needsFit&&this.autoFit&&(this._needsFit=!1,this.fitShadows()),!(this.manualUpdate&&!this._needsUpdate)&&(this._needsUpdate=!1,this._renderShadows())}_ensureSetup(){if(this.shadowsRoot.parent!==this.gameObject&&this.gameObject.add(this.shadowsRoot),this.depthMaterial&&this.horizontalBlurMaterial&&this.verticalBlurMaterial&&this.planeMaterial)return;ba&&console.log("Create ContactShadows on "+this.gameObject.name,this),this.shadowsRoot.name="ContactShadows Root",this.shadowGroup.name="ContactShadows Group",this.gameObject.add(this.shadowsRoot),this.shadowsRoot.add(this.shadowGroup),this.renderTarget=new c.WebGLRenderTarget(this.textureSize,this.textureSize),this.renderTarget.texture.generateMipmaps=!1,this.renderTargetBlur=new c.WebGLRenderTarget(this.textureSize,this.textureSize),this.renderTargetBlur.texture.generateMipmaps=!1;const e=new c.PlaneGeometry(1,1).rotateX(Math.PI/2);this.gameObject instanceof c.Mesh&&(console.warn("ContactShadows can not be added to a Mesh. Please add it to a Group or an empty Object"),Qn(this.gameObject,!1));const t=this.planeMaterial=new c.MeshBasicMaterial({map:this.renderTarget.texture,opacity:this.opacity,color:0,transparent:!0,depthWrite:!1,side:c.FrontSide});t.name="ContactShadows Plane",this.plane=new c.Mesh(e,t),this.plane.scale.y=-1,this.plane.layers.set(2),this.shadowsRoot.add(this.plane),this.plane&&(this.plane.renderOrder=1);const i=new c.MeshBasicMaterial({depthWrite:!0,stencilWrite:!0,colorWrite:!1,side:c.BackSide});i.name="ContactShadows Occluder",this.occluderMesh=new c.Mesh(this.plane.geometry,i).translateY(-1e-4),this.occluderMesh.renderOrder=-100,this.occluderMesh.layers.set(2),this.shadowsRoot.add(this.occluderMesh),this.blurPlane=new c.Mesh(e),this.blurPlane.visible=!1,this.shadowGroup.add(this.blurPlane);const n=0,o=1;this.shadowCamera=new c.OrthographicCamera(-1/2,1/2,1/2,-1/2,n,o),this.shadowCamera.name="ContactShadows Camera",this.shadowCamera.layers.enableAll(),this.shadowCamera.rotation.x=Math.PI/2,this.shadowCamera.matrixWorldAutoUpdate=!1,this.shadowGroup.add(this.shadowCamera),this.shadowCamera.updateMatrix(),this.depthMaterial=new c.MeshDepthMaterial,this.depthMaterial.name="ContactShadows Depth",this.depthMaterial.userData.darkness={value:this.darkness},this.depthMaterial.blending=c.CustomBlending,this.depthMaterial.blendEquation=c.MaxEquation,this.depthMaterial.onBeforeCompile=r=>{this.depthMaterial&&(r.uniforms.darkness=this.depthMaterial.userData.darkness,r.fragmentShader=`
1065
+ Using the assigned clip instead:`,this.clip));let t=!this.sound||e&&e!==this._loadedClip;return typeof e=="string"&&(!this._audioElement||!this._usesMediaElementSource)&&(t=!0),(e instanceof MediaStream||typeof e=="string")&&(this.clip=e),t?(this.shouldPlay=!0,this.onNewClip(e).then(()=>!0).catch(()=>!1)):(this.shouldPlay=!0,this._hasEnded=!1,ct&&console.log("[AudioSource] play",this.sound?.getVolume(),this.sound),this.sound&&!this.isPlaying?(this.ensureContextResumed(),this.context.application.muted&&this.sound.setVolume(0),this.gameObject?.add(this.sound),this.clip instanceof MediaStream?(this._usesMediaElementSource=!1,this.sound.setMediaStreamSource(this.clip),this._audioElement||(this._audioElement=document.createElement("audio"),this._audioElement.style.display="none"),this._audioElement.parentNode||this.context.domElement.shadowRoot?.append(this._audioElement),this._audioElement.srcObject=this.clip,this._audioElement.autoplay=!1,!0):(this._audioElement?.play().catch(n=>{ct&&console.warn("[AudioSource] Failed to play audio element:",n)}),this.fadeEntryGain(1),!0)):!1)}fadeEntryGain(e,t=.02){if(!this._entryNode||!this.sound)return;const i=this.sound.context,n=this._entryNode.gain;n.cancelScheduledValues(i.currentTime),n.setValueAtTime(n.value,i.currentTime),n.linearRampToValueAtTime(e,i.currentTime+t)}pause(){if(ct&&console.log("[AudioSource] pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.wasPlaying=!1,this._usesMediaElementSource){this.fadeEntryGain(0),this._audioElement?.pause();return}this.sound&&this.sound.isPlaying&&this.sound.source&&(this._lastContextTime=this.sound?.context.currentTime,this.sound.pause()),this._audioElement?.remove()}stop(){if(ct&&console.log("[AudioSource] stop",this),this._hasEnded=!0,this.shouldPlay=!1,this.wasPlaying=!1,this._usesMediaElementSource){this.fadeEntryGain(0),this._audioElement?.pause(),this._audioElement&&(this._audioElement.currentTime=0);return}this.sound&&this.sound.source&&(this._lastContextTime=this.sound?.context.currentTime,ct&&console.log("[AudioSource] lastContextTime",this._lastContextTime),this.sound.stop()),this._audioElement?.remove()}_lastContextTime=0;_hasEnded=!0;_needUpdateSpatialDistanceSettings=!1;update(){this.helper&&(this.isPlaying&&this.helper.update(),this.helper.visible=this.isPlaying),this._needUpdateSpatialDistanceSettings&&this.applySpatialDistanceSettings(),this.sound&&!this.isPlaying&&this.shouldPlay&&!this._hasEnded&&(this._hasEnded=!0,ct&&console.log("[AudioSource] Audio clip ended",this.clip),this.dispatchEvent(new CustomEvent("ended",{detail:this})))}};Pn([p(URL)],nn.prototype,"clip",2);Pn([p()],nn.prototype,"playOnAwake",2);Pn([p()],nn.prototype,"preload",2);Pn([p()],nn.prototype,"playInBackground",2);Pn([p()],nn.prototype,"loop",1);Pn([p()],nn.prototype,"spatialBlend",1);Pn([p()],nn.prototype,"minDistance",1);Pn([p()],nn.prototype,"maxDistance",1);Pn([p()],nn.prototype,"volume",1);Pn([p()],nn.prototype,"pitch",1);Pn([p()],nn.prototype,"rollOffMode",2);let Ei=nn;var fT=Object.defineProperty,Kf=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&fT(e,t,n),n};const pT=x("debugsignals");class Lh{guid}Kf([p()],Lh.prototype,"guid");class Ml{signal;reaction}Kf([p(Lh)],Ml.prototype,"signal");Kf([p(Z)],Ml.prototype,"reaction");const dC=class ws extends T{isSignalReceiver=!0;static receivers={};static invoke(e){if(ws.receivers[e]){const t=ws.receivers[e];if(!t)return;for(const i of t)i.invoke(e)}}events;awake(){pT&&console.log("SignalReceiver awake",this)}onEnable(){if(this.events)for(const e of this.events)ws.receivers[e.signal.guid]||(ws.receivers[e.signal.guid]=[]),ws.receivers[e.signal.guid].push(this)}onDisable(){if(this.events){for(const e of this.events)if(ws.receivers[e.signal.guid]){const t=ws.receivers[e.signal.guid].indexOf(this);t>=0&&ws.receivers[e.signal.guid].splice(t,1)}}}invoke(e){if(!this.events||!Array.isArray(this.events))return;const t=typeof e=="object"?e.guid:e;for(const i of this.events)if(i.signal.guid===t)try{if(i.reaction){if(!i.reaction.invoke){console.warn("Missing invoke - possibly a serialization error",i,this);continue}}else{console.warn("Missing reaction for signal",i,this);continue}i.reaction.invoke()}catch(n){console.error(n)}}};Kf([p(Ml)],dC.prototype,"events");let Lr=dC;var we=(s=>(s.Activation="ActivationTrack",s.Animation="AnimationTrack",s.Audio="AudioTrack",s.Control="ControlTrack",s.Marker="MarkerTrack",s.Signal="SignalTrack",s))(we||{}),et=(s=>(s[s.None=0]="None",s[s.Hold=1]="Hold",s[s.Loop=2]="Loop",s[s.PingPong=3]="PingPong",s[s.Continue=4]="Continue",s))(et||{});function mT(s){return typeof s=="object"&&s!==null&&"name"in s&&"type"in s&&"outputs"in s&&"muted"in s}var mh=(s=>(s.Signal="SignalEmitter",s))(mh||{});const bn=x("debugtimeline");class Wr{director;track;get muted(){return this.track.muted}set muted(e){e!==this.track.muted&&(this.track.muted=e,this.onMuteChanged?.call(this))}*forEachClip(e=!1){if(this.track?.clips)if(e)for(let t=this.track.clips.length-1;t>=0;t--)yield this.track.clips[t];else for(const t of this.track.clips)yield t}getClipTime(e,t){return t.clipIn+(e-t.start)*t.timeScale}getClipTimeNormalized(e,t){return(e-t.start)/t.duration}evaluateWeight(e,t,i,n=!0){if(t<0||t>=i.length)return 0;const o=i[t];if(n||e>=o.start&&e<=o.end){let r=1;if(o.easeInDuration>0){const a=Math.min((e-o.start)/o.easeInDuration,1);r*=a}if(o.easeOutDuration>0){const a=Math.min((o.end-e)/o.easeOutDuration,1);r*=a}return r}return 0}}class gT{clip;rootPositionOffset;rootQuaternionOffset;get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}rootStartPosition;rootEndPosition;rootStartQuaternion;rootEndQuaternion;constructor(e){const t=e.getClip();this.clip=t;const i=e.getRoot(),n=i.name+".position",o=i.name+".quaternion";bn&&console.log(t.name,t.tracks,n);for(const r of t.tracks)if(!(r.times.length<=0)){if(r.name.endsWith(n))this.rootStartPosition=new c.Vector3().fromArray(r.values,0),this.rootEndPosition=new c.Vector3().fromArray(r.values,r.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),bn&&console.log(this.rootPositionOffset);else if(r.name.endsWith(o)&&(this.rootStartQuaternion=new c.Quaternion().fromArray(r.values,0),this.rootEndQuaternion=new c.Quaternion().fromArray(r.values,r.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),bn)){const a=new c.Euler().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",a)}}}}class gh extends Wr{models=[];trackOffset;target;mixer;clips=[];actions=[];weight=1;_actionOffsets=[];_didBind=!1;_animator=null;onDisable(){this.mixer?.stopAllAction()}onDestroy(){this.director.context.animations.unregisterAnimationMixer(this.mixer)}onStateChanged(){this._animator&&exports.AnimationUtils.setObjectAnimated(this._animator.gameObject,this,this.director.enabled&&this.director.weight>0)}createHooks(e,t){if(t.tracks?.length<=0){console.warn("No tracks in AnimationClip",t);return}let i=!1,n=!1;const o=t.tracks.find(r=>r.name.includes(".position")||r.name.includes(".quaternion"))?.name.split(".");if(o){const r=o[o.length-2],a=r+".position",l=r+".quaternion";for(const h of t.tracks)!i&&h.name.endsWith(a)?(i=!0,this.createPositionInterpolant(t,e,h)):!n&&h.name.endsWith(l)&&(n=!0,this.createRotationInterpolant(t,e,h))}if(!i||!n){const r=this.mixer?.getRoot(),a=t.tracks[0],l=a.name.lastIndexOf("."),h=a.name.substring(0,l),d=h.substring(h.lastIndexOf(".")+1),u=r.getObjectByName(d);if(u)if(i){if(!n){const f=t.tracks[0].name.substring(0,l)+".quaternion";bn&&console.warn("Create quaternion track",d,u);const m=new c.QuaternionKeyframeTrack(f,[0,t.duration],[0,0,0,1,0,0,0,1]);t.tracks.push(m),this.createRotationInterpolant(t,e,m)}}else{const f=h+".position";bn&&console.warn("Create position track",d,u);const m=new c.VectorKeyframeTrack(f,[0,t.duration],[0,0,0,0,0,0]);t.tracks.push(m),this.createPositionInterpolant(t,e,m)}}}bind(){if(!this._didBind){this._didBind=!0,bn&&console.log(this.models),this.mixer?this.target=this.mixer.getRoot():console.warn("No mixer was assigned to animation track");for(const e of this.actions){const t=new gT(e);this._actionOffsets.push(t)}this.target&&(this._animator=P.getComponent(this.target,vt)??null,this._animator&&exports.AnimationUtils.setObjectAnimated(this._animator.gameObject,this,!0));for(const e of this.models){const t=e.asset,i=t.position,n=t.rotation;i&&i.x!==void 0&&(i.isVector3||(t.position=new c.Vector3(i.x,i.y,i.z)),n.isQuaternion||(t.rotation=new c.Quaternion(n.x,n.y,n.z,n.w)))}this.ensureTrackOffsets()}}ensureTrackOffsets(){if(this.trackOffset){const e=this.trackOffset.position;e&&(e.isVector3||(this.trackOffset.position=new c.Vector3(e.x,e.y,e.z)));const t=this.trackOffset.rotation;t&&(t.isQuaternion||(this.trackOffset.rotation=new c.Quaternion(t.x,t.y,t.z,t.w)))}}_useclipOffsets=!0;_totalOffsetPosition=new c.Vector3;_totalOffsetRotation=new c.Quaternion;_totalOffsetPosition2=new c.Vector3;_totalOffsetRotation2=new c.Quaternion;_summedPos=new c.Vector3;_tempPos=new c.Vector3;_summedRot=new c.Quaternion;_tempRot=new c.Quaternion;_clipRotQuat=new c.Quaternion;evaluate(e){if(this.track.muted||!this.mixer)return;this.bind(),this._totalOffsetPosition.set(0,0,0),this._totalOffsetRotation.set(0,0,0,1),this._totalOffsetPosition2.set(0,0,0),this._totalOffsetRotation2.set(0,0,0,1);let t=0,i=0,n=!1,o=!1,r=0;for(let a=0;a<this.clips.length;a++){const l=this.models[a],h=this.actions[a],d=l.asset;h.weight=0;const u=e>=l.start&&e<=l.end,f=l.preExtrapolationMode,m=l.postExtrapolationMode,g=a<this.clips.length-1?this.models[a+1]:null;let v=u,_=!1;if(!v&&!n&&l.end<e&&m!==et.None?(!g||g.start>e)&&(v=!0,n=!0):a==0&&!v&&!o&&l.start>e&&f!==et.None&&(!g||g.start<e)&&(v=!0,_=!0,o=!0),v){let y=this.weight;y*=this.evaluateWeight(e,a,this.models,v),y*=this.director.weight;let b=u;if(_)switch(f){case et.Hold:break;case et.Loop:e+=l.start,b=!0;break;default:e+=l.start,b=!0;break}let w=this.getClipTime(e,l),C=0;const k=d.duration;if(_&&f===et.Hold&&(w=0),b){if(d.loop)for(C+=Math.floor(w/(k+1e-6));w>k;)w-=k}else if(!u&&n)switch(m){case et.Hold:w=this.getClipTime(l.end,l);break;case et.Loop:w%=k;break;case et.PingPong:const I=Math.floor(w/k)%2!==0;w%=k,I&&(w=k-w);break}l.reversed===!0?h.time=h.getClip().duration-w:h.time=w,h.timeScale=0;const O=Math.max(0,y);if(h.weight=O,r+=O,h.clampWhenFinished=!1,h.isRunning()||h.play(),this._useclipOffsets){const D=t==0?this._totalOffsetPosition:this._totalOffsetPosition2,I=t==0?this._totalOffsetRotation:this._totalOffsetRotation2;t<1&&(i=1-y),t+=1;const j=this._summedPos.set(0,0,0),$=this._tempPos.set(0,0,0),W=this._summedRot.identity(),R=this._tempRot.identity(),U=d.rotation;U&&(this._clipRotQuat.identity(),this._clipRotQuat.slerp(U,y));const G=this._actionOffsets[a];if(G.hasOffsets)for(let Y=0;Y<C;Y++)G.rootPositionOffset?$.copy(G.rootPositionOffset):$.set(0,0,0),$.applyQuaternion(W),this._clipRotQuat&&$.applyQuaternion(this._clipRotQuat),G.rootQuaternionOffset&&(R.copy(G.rootQuaternionOffset),W.multiply(R)),j.add($);this._clipRotQuat&&I.multiply(this._clipRotQuat),I.multiply(W),d.position&&j.add(d.position),D.add(j)}}}if(this._useclipOffsets&&(this._totalOffsetPosition.lerp(this._totalOffsetPosition2,i),this._totalOffsetRotation.slerp(this._totalOffsetRotation2,i)),this.__mixerError===void 0&&(bn||E())&&this._animator?.runtimeAnimatorController?.mixer&&this.mixer!==this._animator?.runtimeAnimatorController?.mixer&&(this.__mixerError=!0,console.error("AnimationTrack mixer is not shared with the animator controller - this might result in the timeline to not animate properly. Please report a bug to the Needle Engine team!",this)),this._animator?.runtimeAnimatorController){const a=Math.max(0,1-r);this._animator?.runtimeAnimatorController?.update(a)}else this.mixer.update(e)}createRotationInterpolant(e,t,i){const n=i.createInterpolant.bind(i),o=new c.Quaternion;this.ensureTrackOffsets();const r=this.trackOffset?.rotation;i.createInterpolant=()=>{const a=n(),l=a.evaluate.bind(a);return a.evaluate=h=>{const d=l(h);if(o.set(d[0],d[1],d[2],d[3]),o.premultiply(this._totalOffsetRotation),r&&o.premultiply(r),this.director.animationCallbackReceivers)for(const u of this.director.animationCallbackReceivers)u?.onTimelineRotation?.call(u,this.director,this.target,h,o);return d[0]=o.x,d[1]=o.y,d[2]=o.z,d[3]=o.w,d},a}}createPositionInterpolant(e,t,i){const n=i.createInterpolant.bind(i),o=new c.Vector3;this.ensureTrackOffsets();const r=this.trackOffset?.rotation,a=this.trackOffset?.position;let l;i.createInterpolant=()=>{const h=n(),d=h.evaluate.bind(h);return h.evaluate=u=>{const f=d(u);if(o.set(f[0],f[1],f[2]),t.removeStartOffset&&(l===void 0?(l=null,l=this._actionOffsets.find(m=>m.clip===e)?.rootStartPosition?.clone()):l?.isVector3&&o.sub(l)),o.applyQuaternion(this._totalOffsetRotation),o.add(this._totalOffsetPosition),r&&o.applyQuaternion(r),a&&(o.x-=a.x,o.y+=a.y,o.z+=a.z),this.director.animationCallbackReceivers)for(const m of this.director.animationCallbackReceivers)m?.onTimelinePosition?.call(m,this.director,this.target,u,o);return f[0]=o.x,f[1]=o.y,f[2]=o.z,f},h}}}const yT=x("mutetimeline");class Os extends Wr{models=[];listener;audio=[];audioContextTimeOffset=[];lastTime=0;audioSource;get volume(){return this.track.volume??1}set volume(e){this.track.volume=e}_audioLoader=null;getAudioFilePath(e){const t=this.director.sourceId;return cs(t,e)}onAllowAudioChanged(e){for(let t=0;t<this.models.length;t++){const i=this.models[t];this.audio[t].setVolume(e?i.asset.volume:0)}}addModel(e){const t=new c.Audio(this.listener);this.audio.push(t);const i=e;i._didTriggerPlay=!1,this.models.push(i)}onDisable(){for(const e of this.audio)e.isPlaying&&e.stop();for(const e of this.models)e._didTriggerPlay=!1}onDestroy(){for(const e of this.audio)e.source&&e?.disconnect();this.audio.length=0}onMuteChanged(){if(this.muted)for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t?.isPlaying&&t.stop()}}stop(){for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t?.isPlaying&&t.stop()}for(const e of this.models)e._didTriggerPlay=!1}_playableDirectorResumed=!1;onPauseChanged(){for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t?.isPlaying&&t.stop()}this._playableDirectorResumed=this.director.isPlaying}evaluate(e){if(yT||this.track.muted||this.director.speed<0)return;const t=this.director.context.application.muted,i=this._playableDirectorResumed;this._playableDirectorResumed=!1;const n=t?.1:0;for(let o=0;o<this.models.length;o++){const r=this.models[o],a=this.audio[o],l=r.asset;if((!a||!a.buffer)&&this.isInTimeRange(r,e-1,e+1)&&this.handleAudioLoading(r,a),Ei.userInteractionRegistered!==!1&&!(a===null||!a.buffer))if(a.setPlaybackRate(this.director.context.time.timeScale*this.director.speed),a.setLoop(l.loop),e>=r.start&&e<=r.end&&e<this.director.duration){let h=l.volume;if(this.track.volume!==void 0&&(h*=this.track.volume),t&&(h=0),r.easeInDuration>0){const d=Math.min((e-r.start)/r.easeInDuration,1);h*=d}if(r.easeOutDuration>0){const d=Math.min((r.end-e)/r.easeOutDuration,1);h*=d}if(h*=this.director.weight,!a.isPlaying||!this.director.isPlaying){if(i||!r._didTriggerPlay&&this.lastTime<e){r.duration*r.timeScale>.3?a.offset=r.clipIn+(e-r.start)*r.timeScale:a.offset=0,bn&&console.log("Timeline Audio ("+this.track.name+") play with offset "+a.offset+" - "+r.asset.clip);const u=a.gain.gain;u.cancelScheduledValues(a.context.currentTime),u.setValueAtTime(h,a.context.currentTime),a.play(n),r._didTriggerPlay=!0}}else{const d=r.clipIn+(e-r.start)*r.timeScale,u=a.context.currentTime-a._startedAt+a.offset;if(Math.abs(d-u)>.3){a.offset=d,a.stop();const m=a.gain.gain;m.cancelScheduledValues(a.context.currentTime),m.setValueAtTime(h,a.context.currentTime),a.play(n)}}a.setVolume(h)}else r._didTriggerPlay=!1,this.director.isPlaying&&a.isPlaying&&a.stop()}this.lastTime=e}loadAudio(e,t=0,i=0){let n=null;const o=e-i,r=e+t;for(const a of this.models)if(this.isInTimeRange(a,o,r)){const l=this.audio[this.models.indexOf(a)],h=this.handleAudioLoading(a,l);h!==null&&(n===null&&(n=[]),n.push(h))}return n!==null?Promise.all(n):null}isInTimeRange(e,t,i){return t<=e.start&&i>=e.end||t>=e.start&&t<=e.end||i>=e.start&&i<=e.end}static _audioBuffers=new Map;static dispose(){Os._audioBuffers.clear()}handleAudioLoading(e,t){this._audioLoader||(this._audioLoader=new c.AudioLoader);const i=this.getAudioFilePath(e.asset.clip);if(Os._audioBuffers.get(i)){const o=Os._audioBuffers.get(i);return o.then(r=>{r&&t.setBuffer(r)}),o}bn&&console.warn("LOAD audio track",i,this.director.sourceId);const n=new Promise((o,r)=>{this._audioLoader.load(i,a=>{t.setBuffer(a),o(a)},void 0,a=>{console.error("Error loading audio",a),o(null)})});return Os._audioBuffers.set(i,n),n}}class Zf extends Wr{models=[];needsSorting=!0;*foreachMarker(e=null){this.needsSorting&&this.sort();for(const t of this.models)t&&t.type===e&&(yield t)}onEnable(){this.needsSorting=!0}evaluate(e){this.needsSorting&&this.sort()}sort(){this.needsSorting=!1,this.models.sort((e,t)=>e.time-t.time)}}class yh extends Wr{models=[];didTrigger=[];receivers=[];_lastTime=-1;onEnable(){this._lastTime=-1;for(let e=0;e<this.didTrigger.length;e++)this.didTrigger[e]=!1}onMuteChanged(){this.track.muted||(this._lastTime=-1)}evaluate(e){if(this.track.muted)return;let t=this._lastTime;t===-1&&(t=e),this._lastTime=e;const i=this.director.context.time.deltaTime*1.5;for(let n=0;n<this.models.length;n++){const o=this.models[n],r=this.didTrigger[n],a=o.time-e;let l=!1;if(o.retroActive)l=a<=1e-6;else{const h=Math.abs(a);(h===0||h>=1e-5&&h<i)&&(l=!0)}if(l){if(!r)if(bn&&console.log("Trigger signal",e,o.time,o),this.didTrigger[n]=!0,this.receivers?.length<=0)Lr.invoke(o.asset);else for(const h of this.receivers)h&&h.invoke(o.asset)}else o.emitOnce||e<o.time&&t>=o.time&&(this.didTrigger[n]=!1)}}}class Jf extends Wr{evaluate(e){if(!this.track.muted&&!(!this.director.isPlaying&&!this.director._isUserEvaluation))for(let t=0;t<this.track.outputs.length;t++){const i=this.track.outputs[t];if(typeof i!="object"||i===null)continue;let n=!1;if(this.track.clips){for(const r of this.track.clips)if(r.start<=e&&e<=r.end){n=!0;break}}const o=i;o.visible!==void 0&&o.visible!==n&&(o.visible=n,bn&&console.warn(this.director.name,"ActivationTrack-"+t,o.name,n,e))}}}class ep extends Wr{models=[];timelines=[];resolveSourceObjects(e){for(let t=this.models.length-1;t>=0;t--){const n=this.models[t].asset;if(!n.sourceObject||typeof n.sourceObject!="object"){console.log("no source object, removing model",t,n),this.models.splice(t,1);continue}else{const o=this.director.constructor,r=P.getComponent(n.sourceObject,o);this.timelines.push(r),r&&n.updateDirector&&(r.playOnAwake=!1)}}}_previousActiveModel=null;evaluate(e){this._previousActiveModel=null;for(let t=0;t<this.models.length;t++){const i=this.models[t],n=i.asset;if(e>=i.start&&e<=i.end){this._previousActiveModel=i;const o=this.getClipTime(e,i);if(n.controlActivation){const r=n.sourceObject;r.visible=!0}if(n.updateDirector){const r=this.timelines[t];r&&(r.isPlaying&&r.pause(),r.time=o,r.evaluate())}}else{const o=this._previousActiveModel?.asset;if(n.controlActivation){const r=n.sourceObject;o?.sourceObject!==r&&(r.visible=!1)}}}}}var _T=Object.defineProperty,bT=Object.getOwnPropertyDescriptor,y_=(s,e,t,i)=>{for(var n=i>1?void 0:i?bT(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&_T(e,t,n),n};const In=x("debugtimeline");var uC=(s=>(s[s.Hold=0]="Hold",s[s.Loop=1]="Loop",s[s.None=2]="None",s))(uC||{});const tp=class ty extends T{static createTrackFunctions={};static registerCreateTrack(e,t){this.createTrackFunctions[e]=t}get playableAsset(){return this._playableAsset}set playableAsset(e){this._playableAsset!==e&&(this._playableAsset=e,this._needsGraphRebuild=!0,this._didWarnInvalid=!1)}_playableAsset;_didWarnInvalid=!1;playOnAwake=!1;extrapolationMode=1;get isPlaying(){return this._isPlaying}get isPaused(){return this._isPaused}get time(){return this._time}set time(e){typeof e=="number"&&!Number.isNaN(e)?this._time=e:(In||ki())&&console.error("INVALID TIMELINE.TIME VALUE",e,this.name)}get duration(){return this._duration}set duration(e){this._duration=e}get weight(){return this._weight}set weight(e){this._weight=e}get speed(){return this._speed}set speed(e){this._speed=e}waitForAudio=!0;_visibilityChangeEvt;_clonedPlayableAsset=!1;_speed=1;awake(){In&&console.log(`[Timeline] Awake '${this.name}'`,this),this.rebuildGraph()}warnIfInvalid(e){return this.isValid()?!0:(!this._didWarnInvalid&&(In||E())&&(this._didWarnInvalid=!0,this.playableAsset?.tracks?.length?console.warn(`PlayableDirector '${this.name}' is not valid`,this):console.warn(`PlayableDirector '${this.name}' has no tracks — assign a playableAsset (or build one via TimelineBuilder) before calling ${e}().`,this)),!1)}onEnable(){In&&console.log("[Timeline] OnEnable",{name:this.name,playOnAwake:this.playOnAwake});for(const e of this._allTracks)for(const t of e)t.onEnable?.();this.playOnAwake&&this.play(),this._visibilityChangeEvt||(this._visibilityChangeEvt=()=>{switch(document.visibilityState){case"hidden":this.setAudioTracksAllowPlaying(!1);break;case"visible":this.setAudioTracksAllowPlaying(!0);break}}),window.addEventListener("visibilitychange",this._visibilityChangeEvt)}onDisable(){In&&console.log("[Timeline] OnDisable",this.name),this.stop();for(const e of this._audioTracks)e.onDisable?.();for(const e of this._customTracks)e.onDisable?.();for(const e of this._animationTracks)e.onDisable?.();this._visibilityChangeEvt&&window.removeEventListener("visibilitychange",this._visibilityChangeEvt)}onDestroy(){for(const e of this._allTracks)for(const t of e)t.onDestroy?.()}rebuildGraph(){this.isValid()&&(this.resolveBindings(),this.updateTimelineDuration(),this.setupAndCreateTrackHandlers(),this._needsGraphRebuild=!1)}async play(){if(!this.warnIfInvalid("play"))return;this._needsGraphRebuild&&this.rebuildGraph();const e=this._isPaused==!0;if(this._isPaused=!1,!this._isPlaying){if(this._isPlaying=!0,e&&this.invokePauseChangedMethodsOnTracks(),this.waitForAudio){const t=[];for(const n of this._audioTracks){const o=n.loadAudio(this._time,1,0);o&&t.push(o)}if(t.length>0&&(await Promise.all(t),!this._isPlaying))return;let i=0;for(;this._audioTracks.length>0&&this._isPlaying&&!Ei.userInteractionRegistered&&this.waitForAudio;)i++<=0&&(E()||In)&&console.warn(`[Timeline] Waiting for user interaction to play audio... (timeline '${this.name}' will start as soon as user interacts with the page). To start the timeline immediately without waiting for user interaction, set 'waitForAudio' to false on the PlayableDirector component.`),await Ds(200)}this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine=this.startCoroutine(this.internalUpdate(),Ce.LateUpdate)}}pause(){this.isValid()&&(this._isPlaying=!1,!this._isPaused&&(this._isPaused=!0,this.internalEvaluate(),this.invokePauseChangedMethodsOnTracks(),this.invokeStateChangedMethodsOnTracks()))}stop(){this._isStopping=!0;for(const i of this._audioTracks)i.stop();const e=this._isPaused==!0,t=this._isPlaying;this._isPlaying&&(this._time=0,this._isPlaying=!1,this._isPaused=!1,this.internalEvaluate(),e&&this.invokePauseChangedMethodsOnTracks()),this._isPlaying=!1,this._isPaused=!1,e&&!t&&this.invokePauseChangedMethodsOnTracks(),t&&this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine&&this.stopCoroutine(this._internalUpdateRoutine),this._internalUpdateRoutine=null,this._isStopping=!1}evaluate(){this.warnIfInvalid("evaluate")&&(this._needsGraphRebuild&&this.rebuildGraph(),this.internalEvaluate(!0))}isValid(){return this.playableAsset&&this.playableAsset.tracks&&Array.isArray(this.playableAsset.tracks)}*forEachTrack(){for(const e of this._allTracks)for(const t of e)yield t}get animationTracks(){return this._animationTracks}get audioTracks(){return this._audioTracks}get signalTracks(){return this._signalTracks}get markerTracks(){return this._markerTracks}get activationTracks(){return this._activationTracks}get tracks(){return this._allTracks.flat()}*foreachMarker(e=null){for(const t of this._markerTracks)for(const i of t.foreachMarker(e))yield i}_needsGraphRebuild=!1;_isPlaying=!1;_internalUpdateRoutine;_isPaused=!1;_isStopping=!1;_isUserEvaluation=!1;_time=0;_duration=0;_weight=1;_animationTracks=[];_audioTracks=[];_signalTracks=[];_markerTracks=[];_controlTracks=[];_activationTracks=[];_customTracks=[];_tracksArray=[];get _allTracks(){return this._tracksArray.length=0,this._tracksArray.push(this._animationTracks),this._tracksArray.push(this._audioTracks),this._tracksArray.push(this._signalTracks),this._tracksArray.push(this._markerTracks),this._tracksArray.push(this._controlTracks),this._tracksArray.push(this._activationTracks),this._tracksArray.push(this._customTracks),this._tracksArray}invokePauseChangedMethodsOnTracks(){for(const e of this.forEachTrack())e.onPauseChanged?.call(e)}invokeStateChangedMethodsOnTracks(){for(const e of this.forEachTrack())e.onStateChanged?.call(e,this._isPlaying)}*internalUpdate(){for(;this._isPlaying&&this.activeAndEnabled;)!this._isPaused&&this._isPlaying&&(this._time+=this.context.time.deltaTime*this.speed,this.internalEvaluate()),yield}internalEvaluate(e=!1){if(!this.isValid())return;let t=this._time;switch(this.extrapolationMode){case 0:this._speed>0?t=Math.min(t,this._duration):this._speed<0&&(t=Math.max(t,0)),this._time=t;break;case 1:t%=this._duration,this._time=t;break;case 2:if(t>this._duration){this.stop();return}break}const i=this._time;this._isUserEvaluation=e;for(const n of this._allTracks)for(const o of n)this._isStopping&&o instanceof gh||o.evaluate(i);this._isUserEvaluation=!1}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=Sh(this.playableAsset,(t,i,n)=>n?.isObject3D!==!0)),!this.playableAsset||!this.playableAsset.tracks)return;const e=this.findRoot(this.gameObject);for(const t of this.playableAsset.tracks){for(let i=t.outputs.length-1;i>=0;i--){const n=t.outputs[i];if(typeof n=="string"){const o=P.findByGuid(n,e);o===null||typeof o!="object"?(t.outputs.splice(i,1),console.warn(`[Timeline] Failed to resolve binding on track '${t.name}' of type '${t.type}' in director '${this.name}' with timeline asset '${this.playableAsset.name}' ('${n}' not found in scene)`)):(In&&console.log("Resolved binding",n,"to",o),t.outputs[i]=o)}else if(n===null){if(t.outputs.splice(i,1),ty.createTrackFunctions[t.type])continue;t.type!==we.Audio&&t.type!==we.Control&&t.type!==we.Marker&&t.type!==we.Signal&&console.warn(`[Timeline] Missing binding on track '${t.name}' of type '${t.type}' in director '${this.name}' with timeline asset '${this.playableAsset.name}' (null binding)`)}}if(t.type===we.Control&&t.clips)for(let i=0;i<t.clips.length;i++){const n=t.clips[i],o=n.asset.sourceObject;if(typeof o=="string"){const r=P.findByGuid(o,e);r===null||typeof r!="object"?console.warn(`[Timeline] Failed to resolve sourceObject binding on track '${t.name}' of type '${t.type}' in director '${this.name}' with timeline asset '${this.playableAsset.name}' ('${o}' not found in scene)`):(In&&console.log("Resolved binding",o,"to",r),n.asset.sourceObject=r)}}}}findRoot(e){return e.parent?this.findRoot(e.parent):e}updateTimelineDuration(){if(this._duration=0,!(!this.playableAsset||!this.playableAsset.tracks)){for(const e of this.playableAsset.tracks)if(e.muted!==!0){if(e.clips)for(const t of e.clips)t.end>this._duration&&(this._duration=t.end);if(e.markers)for(const t of e.markers)t.time>this._duration&&(this._duration=t.time+.001)}}}setupAndCreateTrackHandlers(){if(this._animationTracks.length=0,this._audioTracks.length=0,this._signalTracks.length=0,this._activationTracks.length=0,!this.playableAsset)return;let e=P.findObjectOfType(Ms,this.context);for(const t of this.playableAsset.tracks){const i=t.type,n=ty.createTrackFunctions[i];if(n!=null){const o=n(this,t);if(typeof o.evaluate=="function"){o.director=this,o.track=t,this._customTracks.push(o);continue}}if(t.type===we.Animation){if(!t.clips||t.clips.length<=0){In&&console.warn("Animation track has no clips",t);continue}for(let o=t.outputs.length-1;o>=0;o--){let r=t.outputs[o];if(r instanceof c.Object3D){const l=P.getOrAddComponent(r,vt);l&&(r=l)}const a=r?.gameObject?.animations;if(a){const l=new gh;l.trackOffset=t.trackOffset,l.director=this,l.track=t;for(let h=0;h<t.clips.length;h++){const d=t.clips[h],u=d.asset;if(!u){console.error(`Timeline ${this.name}: clip #${h} on track "${t.name}" has no animation data`);continue}const f=u.clip;let m=f;if((typeof m=="string"||typeof m=="number")&&(m=a.find(v=>v.name===f)),In&&console.log(u,f,"→",m),!m){console.warn("Could not find animationClip for model",d,t.name,this.name,this.playableAsset?.name,a,r);continue}r instanceof vt&&r.runtimeAnimatorController&&(r.__internalDidAwakeAndStart||r.initializeRuntimeAnimatorController(),r.runtimeAnimatorController.mixer||r.runtimeAnimatorController.bind(r),l.mixer=r.runtimeAnimatorController.mixer),l.mixer||(l.mixer=new c.AnimationMixer(r.gameObject),this.context.animations.registerAnimationMixer(l.mixer)),l.clips.push(m),l.mixer.uncacheAction(m),l.createHooks(d.asset,m);const g=l.mixer.clipAction(m);l.actions.push(g),l.models.push(d)}this._animationTracks.push(l)}}}else if(t.type===we.Audio){if(!t.clips||t.clips.length<=0)continue;const o=new Os;o.director=this,o.track=t,o.audioSource=t.outputs.find(r=>r instanceof Ei),this._audioTracks.push(o),e||(e=this.context.mainCameraComponent?.gameObject.addComponent(Ms)),o.listener=e.listener;for(let r=0;r<t.clips.length;r++){const a=t.clips[r];o.addModel(a)}}else if(t.type===we.Marker){if(t.markers){const o=new yh;o.director=this,o.track=t;const r=new Zf;r.director=this,r.track=t;for(const a of t.markers)a.type===mh.Signal?(o.models.push(a),o.didTrigger.push(!1)):r.models.push(a);if(o!==null&&o.models.length>0){const a=P.getComponent(this.gameObject,Lr);a&&(o.receivers.push(a),this._signalTracks.push(o))}r!==null&&r.models.length>0&&this._markerTracks.push(r)}}else if(t.type===we.Signal){const o=new yh;if(o.director=this,o.track=t,t.markers)for(const r of t.markers)o.models.push(r),o.didTrigger.push(!1);for(const r of t.outputs)o.receivers.push(r);this._signalTracks.push(o)}else if(t.type===we.Control){const o=new ep;if(o.director=this,o.track=t,t.clips)for(const r of t.clips)o.models.push(r);o.resolveSourceObjects(this.context),this._controlTracks.push(o)}else if(t.type===we.Activation){const o=new Jf;o.director=this,o.track=t,this._activationTracks.push(o)}}}setAudioTracksAllowPlaying(e){for(const t of this._audioTracks)t.onAllowAudioChanged(e)}animationCallbackReceivers=[];registerAnimationCallback(e){this.animationCallbackReceivers.push(e)}unregisterAnimationCallback(e){const t=this.animationCallbackReceivers.indexOf(e);t!==-1&&this.animationCallbackReceivers.splice(t,1)}};y_([p()],tp.prototype,"playableAsset",1);y_([p()],tp.prototype,"playOnAwake",2);y_([p()],tp.prototype,"extrapolationMode",2);let ml=tp,u0=!1;function vT(){u0||(u0=!0,se.registerCallback(ae.ContextCreated,s=>{const e=s.context.domElement.getAttribute("autoplay");if(e!==void 0&&(e===""||e==="true"||e==="1")&&s.files)for(const t of s.files)P.foreachComponent(t.file.scene,n=>{if(n.enabled!==!1){if(n instanceof Ut&&n.playAutomatically||n instanceof vt||n instanceof ml&&n.playOnAwake===!0)return!0;if(n instanceof Ut)return n.playAutomatically=!0,!0;if(n instanceof ml)return n.playOnAwake=!0,!0}},!0)!==!0&&exports.AnimationUtils.autoplayAnimations(t.file)}))}const wT={topLight:{intensity:500,position:[.418,16.199,.3]},room:{position:[-.757,13.219,.717],scale:[31.713,28.305,28.591]},boxes:[{position:[-10.906,2.009,1.846],rotation:-.195,scale:[2.328,7.905,4.651]},{position:[-5.607,-.754,-.758],rotation:.994,scale:[1.97,1.534,3.955]},{position:[6.167,.857,7.803],rotation:.561,scale:[3.927,6.285,3.687]},{position:[-2.017,.018,6.124],rotation:.333,scale:[2.002,4.566,2.064]},{position:[2.291,-.756,-2.621],rotation:-.286,scale:[1.546,1.552,1.496]},{position:[-2.193,-.369,-5.547],rotation:.516,scale:[3.875,3.487,2.986]}],lights:[{intensity:50,position:[-16.116,14.37,8.208],scale:[.1,2.428,2.739]},{intensity:50,position:[-16.109,18.021,-8.207],scale:[.1,2.425,2.751]},{intensity:17,position:[14.904,12.198,-1.832],scale:[.15,4.265,6.331]},{intensity:43,position:[-.462,8.89,14.52],scale:[4.38,5.441,.088]},{intensity:20,position:[3.235,11.486,-12.541],scale:[2.5,2,.1]},{intensity:100,position:[0,20,0],scale:[1,.1,1]}]},xT={topLight:{intensity:400,position:[.5,14,.5]},room:{position:[0,13.2,0],scale:[31.5,28.5,31.5]},boxes:[{position:[-10.906,-1,1.846],rotation:-.195,scale:[2.328,7.905,4.651]},{position:[-5.607,-.754,-.758],rotation:.994,scale:[1.97,1.534,3.955]},{position:[6.167,-.16,7.803],rotation:.561,scale:[3.927,6.285,3.687]},{position:[-2.017,.018,6.124],rotation:.333,scale:[2.002,4.566,2.064]},{position:[2.291,-.756,-2.621],rotation:-.286,scale:[1.546,1.552,1.496]},{position:[-2.193,-.369,-5.547],rotation:.516,scale:[3.875,3.487,2.986]}],lights:[{intensity:80,position:[-14,10,8],scale:[.1,2.5,2.5]},{intensity:80,position:[-14,14,-4],scale:[.1,2.5,2.5]},{intensity:23,position:[14,12,0],scale:[.1,5,5]},{intensity:16,position:[0,9,14],scale:[5,5,.1]},{intensity:80,position:[7,8,-14],scale:[2.5,2.5,.1]},{intensity:80,position:[-7,16,-14],scale:[2.5,2.5,.1]},{intensity:1,position:[0,20,0],scale:[.1,.1,.1]}]};class ip extends c.Scene{constructor(e){super(),this.position.y=-3.5;const t=new c.BoxGeometry;t.deleteAttribute("uv");const i=new c.MeshStandardMaterial({metalness:0,side:c.BackSide}),n=new c.MeshStandardMaterial({metalness:0}),o=e=="legacy"?wT:xT,r=new c.PointLight(16777215,o.topLight.intensity,28,2);r.position.set(...o.topLight.position),this.add(r);const a=new c.Mesh(t,i);a.position.set(...o.room.position),a.scale.set(...o.room.scale),this.add(a);for(const l of o.boxes){const h=new c.Mesh(t,n);h.position.set(...l.position),h.rotation.set(0,l.rotation,0),h.scale.set(...l.scale),this.add(h)}for(const l of o.lights){const h=new c.Mesh(t,this.createAreaLightMaterial(l.intensity));h.position.set(...l.position),h.scale.set(...l.scale),this.add(h)}}createAreaLightMaterial(e){const t=new c.MeshBasicMaterial;return t.color.setScalar(e),t}}const Gc=x("debugmissingcamera");let f0=!1;function ST(){f0||(f0=!0,se.registerCallback(ae.MissingCamera,s=>{Gc&&console.warn("Creating missing camera");const e=s.context.scene,t=s.context.mainCamera;t.name||(t.name="Default Fallback Camera");const i=new Jt;if(i.sourceId=s.files?.[0]?.src??"unknown",i.fieldOfView=35,s.context.domElement.getAttribute("transparent")!=null)i.clearFlags=Or.Uninitialized;else if(s.context.domElement.getAttribute("background-image")?.length||s.context.lightmaps.tryGetSkybox(i.sourceId))i.clearFlags=Or.Skybox;else{if(i.clearFlags=Or.SolidColor,!s.context.domElement.getAttribute("background-color")&&!e.background){let a="#efefef";typeof window!==void 0&&window.matchMedia("(prefers-color-scheme: dark)").matches&&(a="#1f1f1f"),e.background=new c.Color(a)}if(!e.environment){const a=aO(s.context.renderer),l=new ip("neutral");e.environment=a.fromScene(l,.025).texture}}const o=kr(t,i,!0);return t.position.x=0,t.position.y=1,t.position.z=2,s.context.domElement?.cameraControls!=!1&&p0(s.context,o),o}),se.registerCallback(ae.ContextCreated,s=>{if(!s.context.mainCamera){Gc&&console.log("Will not auto-fit because a default camera exists");return}if(s.context.domElement?.cameraControls==!0){if(Vw(s.context.mainCamera)?.isCameraController==!0){Gc&&console.log("Will not auto-fit because a camera controller exists");return}p0(s.context)}}))}function p0(s,e){e=e??s.mainCameraComponent;const t=e?.gameObject;if(Gc&&console.log("Creating default camera controls",e?.name),t){const i=Th(t,ue);i.sourceId=e?.sourceId??"unknown";const n=s.domElement.getAttribute("auto-rotate");i.autoRotate=n!="0"&&n?.toLowerCase()!="false";const o=Number.parseFloat(n||".5");i.autoRotateSpeed=isNaN(o)?.5:o,Gc&&console.log("Auto-rotate",i.autoRotate,"speed:",i.autoRotateSpeed);const r=s.domElement.getAttribute("auto-fit");i.autoFit=r!=="0"&&r?.toLowerCase()!="false",i.autoTarget=!0}else console.warn("Missing camera object, can not add orbit controls")}var CT=Object.defineProperty,PT=Object.getOwnPropertyDescriptor,fC=(s,e,t,i)=>{for(var n=PT(e,t),o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&CT(e,t,n),n};const kT=x("debugpost");class z{isVolumeParameter=!0;constructor(e){e!==void 0&&this.initialize(e)}_isInitialized=!1;get isInitialized(){return this._isInitialized}initialize(e){e!==void 0&&(this._value=e,this._defaultValue=e,this._valueRaw=e,this._isInitialized=!0)}get overrideState(){return this._active}set overrideState(e){if(this._active===e)return;this._active=e;const t=e?this._valueRaw:this._defaultValue;this.processValue(t,!0)}_active=!0;get value(){return this._valueRaw}set value(e){this.isInitialized||this.initialize(e),this.processValue(e,!1)}_value;_valueRaw;set defaultValue(e){this._defaultValue=e}_defaultValue=void 0;__init(){this.processValue(this._valueRaw,!0)}valueProcessor;onValueChanged;processValue(e,t){if(e==null||!t&&this.testIfValueChanged(e)===!1)return;const i=this._value;kT&&typeof i=="number"&&typeof e=="number"&&(i?.toFixed(4),e?.toFixed(4)),!this._active&&this._defaultValue!==void 0?(this._value=this._defaultValue,e=this._defaultValue,this._valueRaw=e):(this._valueRaw=e,this._active&&this.valueProcessor&&(e=this.valueProcessor(e)),this._value=e),this.onValueChanged&&this.onValueChanged(e,i,this)}testIfValueChanged(e){return this._valueRaw!==e}}fC([p()],z.prototype,"overrideState");fC([p()],z.prototype,"value");class MT extends Ai{constructor(){super([z])}onSerialize(e,t){}onDeserialize(e,t){const i=t.target,n=t.path;let o;if(i&&n&&(o=i[n]),(typeof o!="object"||typeof o=="object"&&o.isVolumeParameter!==!0)&&(o=new z),typeof e=="object"&&"value"in e){const r=e.value;o.initialize(r),o.overrideState=e.overrideState}else o.value=e;return o}}function pC(){new MT}async function iy(s){const{NeedleEngineWebComponent:e}=await Promise.resolve().then(()=>P3);e.observedAttributes.includes(s)||e.observedAttributes.push(s)}var OT=Object.defineProperty,wt=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&OT(e,t,n),n};const yt=x("debugsceneswitcher"),ET=x("sceneswitcher:clearscene"),Eu="scene";function RT(){iy(Eu)}const io=Promise.resolve(!1);class Ye extends T{autoLoadFirstScene=!0;scenes=[];loadingScene;queryParameterName="scene";useSceneName=!0;clamp=!0;useHistory=!0;useKeyboard=!0;useSwipe=!0;useSceneLighting=!0;useSceneBackground=!0;preloadNext=1;preloadPrevious=1;preloadConcurrent=2;createMenuButtons=!1;get currentIndex(){return this._currentIndex}get currentLoadingProgress(){return this._currentLoadingProgress}get currentlyLoadingScene(){return this._currentlyLoadingScene}get currentlyLoadedScene(){return this._currentScene}sceneLoadingStart=new Z;sceneLoadingProgress=new Z;sceneLoaded=new Z;_currentIndex=-1;_currentScene=void 0;_currentSceneAsset=void 0;_engineElementOverserver=void 0;_preloadScheduler;_menuButtons;__lastSwitchScene;__lastSwitchScenePromise;awake(){this._currentScene=void 0,this._lastLoadingScene=void 0,this.__lastSwitchScenePromise=void 0,this.scenes===void 0&&(this.scenes=[]);for(const e of this.scenes)e&&!e.hasUrl&&e.asset instanceof c.Object3D?P.remove(e.asset):e instanceof c.Object3D&&P.remove(e);yt&&console.log("SceneSwitcher",this)}async onEnable(){if(globalThis.addEventListener("popstate",this.onPopState),this.context.input.addEventListener(xe.KeyDown,this.onInputKeyDown),this.context.input.addEventListener(xe.PointerMove,this.onInputPointerMove),this.context.input.addEventListener(xe.PointerUp,this.onInputPointerUp),this._engineElementOverserver||(this._engineElementOverserver=new MutationObserver(e=>{for(const t of e)if(t.type==="attributes"&&t.attributeName===Eu){const i=this.context.domElement.getAttribute(Eu);i!==null&&this.trySelectSceneFromValue(i)}})),this._engineElementOverserver.observe(this.context.domElement,{attributes:!0}),this._preloadScheduler||(this._preloadScheduler=new TT(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(Eu);(e===null||!await this.trySelectSceneFromValue(e))&&this._currentIndex===-1&&this.select(0)}this.createMenuButtons&&(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(){if(globalThis.removeEventListener("popstate",this.onPopState),this.context.input.removeEventListener(xe.KeyDown,this.onInputKeyDown),this.context.input.removeEventListener(xe.PointerMove,this.onInputPointerMove),this.context.input.removeEventListener(xe.PointerUp,this.onInputPointerUp),this._preloadScheduler?.stop(),this._menuButtons){for(const e of this._menuButtons)e.remove();this._menuButtons=void 0}}onPopState=async e=>{if(!this.useHistory)return;const t=this.useHistory;try{this.useHistory=!1;let i=!1;if(this.queryParameterName&&(i=await this.tryLoadFromQueryParam()),!i){const n=e?.state;if(n&&n.startsWith(this.guid)){const o=n.substr(this.guid.length+2);yt&&console.log("PopState",o),await this.trySelectSceneFromValue(o)}}}finally{this.useHistory=t}};normalizedSwipeThresholdX=.1;_didSwipe=!1;onInputPointerMove=e=>{if(this.useSwipe&&!this._didSwipe&&e.button===0&&e.pointerType==="touch"&&this.context.input.getPointerPressedCount()===1){const t=this.context.input.getPointerPositionDelta(e.button);if(t){const i=t.x/this.context.domWidth;i>=this.normalizedSwipeThresholdX?(this._didSwipe=!0,this.selectPrev()):i<=-this.normalizedSwipeThresholdX&&(this._didSwipe=!0,this.selectNext())}}};onInputPointerUp=e=>{e.button===0&&(this._didSwipe=!1)};onInputKeyDown=e=>{if(!this.useKeyboard||!this.scenes)return;const t=e.key.toLowerCase();if(!t)return;const i=parseInt(t)-1;if(i>=0){this.trySelectSceneFromValue(i);return}switch(t){case"arrowright":case"d":this.selectNext();break;case"arrowleft":case"a":this.selectPrev();break}};addScene(e){if(typeof e=="string"){let t=this.context.addressables.findAssetReference(e);return t||(t=new J(e),this.context.addressables.registerAssetReference(t)),this.scenes.push(t),t}return this.scenes.push(e),e}selectNext(){return this.select(this._currentIndex+1)}selectPrev(){return this.select(this._currentIndex-1)}select(e){if(yt&&console.log("[SceneSwitcher] select",e),typeof e=="object"&&console.warn('[SceneSwitcher] Switching to "'+e+'" might not work. Please either use an index or a AssetReference (not a scene reference)'),typeof e=="string"){const i=this.scenes?.find(n=>n.url===e);if(!i){const n=J.getOrCreate(this.sourceId??"",e,this.context);return this.switchScene(n)}if(i)e=this.scenes?.indexOf(i);else return io}if(!this.scenes?.length)return io;if(e<0){if(this.clamp)return io;e=this.scenes.length-1}else if(e>=this.scenes.length){if(this.clamp)return io;e=0}const t=this.scenes[e];return this.switchScene(t)}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){if(!(e instanceof J)){const i=typeof e;if(i==="string")return this.select(e);if(i==="number")return this.select(e);if(e&&e instanceof c.Object3D){const n=this.scenes?.indexOf(e);e=new J(e.name,void 0,e),n>=0&&(this.scenes[n]=e)}else return console.warn(`[SceneSwitcher] Can't switch to scene of type ${i}`),!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){yt&&console.log("[SceneSwitcher] UNLOAD",e.url,"HasURL?: "+e.hasUrl);const t=this._currentSceneAsset,i=this.tryGetSceneEventListener(t);if(i?.sceneClosing){const n=i.sceneClosing();n instanceof Promise&&await n}e.hasUrl?(e.unload(),t&&fi(t,!0,!1)):P.remove(t),this._currentSceneAsset=void 0}}_currentlyLoadingScene;_loadingRequestId=0;_activeLoadingRequestId=0;async __internalSwitchScene(e){await this.__unloadCurrentScene();const t=this._currentIndex=this.scenes?.indexOf(e)??-1,i=++this._loadingRequestId;try{yt&&console.debug(`${Date.now()} [SceneSwitcher] Loading scene start: ${e.url} (index: ${t})`),this._currentlyLoadingScene=e,this._currentLoadingProgress=new ProgressEvent("progress",{loaded:0,total:1});const n=new CustomEvent("loadscene-start",{detail:{scene:e,switcher:this,index:t}});this.dispatchEvent(n),this.sceneLoadingStart?.invoke(n.detail),await this.onStartLoading(i),await e.loadAssetAsync((r,a)=>{if(i===this._activeLoadingRequestId){if(yt){const l=a.loaded/a.total,h="["+"=".repeat(Math.floor(l*20))+"-".repeat(20-Math.floor(l*20))+"]";console.debug(`${Date.now()} [SceneSwitcher] Loading scene progress: ${(l*100).toFixed(1)} % ${h}`,e.url)}this._currentLoadingProgress=a,this.dispatchEvent(a),this.sceneLoadingProgress?.invoke(a)}}).catch(console.error),await this.onEndLoading(i);const o=new CustomEvent("loadscene-finished",{detail:{scene:e,switcher:this,index:t}});if(this.dispatchEvent(o),i===this._activeLoadingRequestId&&(this._currentLoadingProgress=void 0,this._currentlyLoadingScene=void 0),o.defaultPrevented)return yt&&console.warn("[SceneSwitcher] Adding loaded scene prevented:",e,o),!1;if(!e.asset)return yt&&console.warn("[SceneSwitcher] Failed loading scene:",e),!1;if(this._currentIndex===t){if(yt&&console.log("[SceneSwitcher] ADD",e.url),this._currentScene=e,ET){const l=this.context.mainCameraComponent?.gameObject||this.context.mainCamera;l?.removeFromParent();const h=this.gameObject.removeFromParent();fi(this.context.scene,!0,!0),this.context.scene=new c.Scene,this.context.scene.add(h),l&&this.context.scene.add(l)}if(e.asset.parent?this._currentSceneAsset=Ls(e.asset,{parent:this.gameObject}):(this._currentSceneAsset=e.asset,P.add(e.asset,this.gameObject)),this.useSceneLighting&&this.context.sceneLighting.enable(e),this.useSceneBackground){const l=this.context.lightmaps.tryGetSkybox(e.url);l?(l.mapping!==c.CubeUVReflectionMapping&&(l.mapping=c.EquirectangularReflectionMapping),this.context.scene.background=l,this.context.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()):yt&&console.warn("[SceneSwitcher] Can't find skybox for scene "+e.url)}if(this.useHistory&&t>=0){let l=t.toString();if(this.useSceneName&&(e instanceof c.Object3D?l=e.name:e instanceof J&&e.asset?.name?l=e.asset.name:e.url&&(l=m0(e.url))),this.queryParameterName?.length)Yc(this.queryParameterName,l,this.useHistory);else{const h=history.state,d=this.guid+"::"+t;h!==d&&history.pushState(d,"unused",location.href)}}const r=this.tryGetSceneEventListener(this._currentSceneAsset);if(r?.sceneOpened){const l=r.sceneOpened(this);l instanceof Promise&&await l}yt&&console.debug(`${Date.now()} [SceneSwitcher] Loading scene finished: ${e.url} (index: ${t})`);const a=new CustomEvent("scene-opened",{detail:{scene:e,switcher:this,index:t}});return this.dispatchEvent(a),this.sceneLoaded?.invoke(this),this._currentSceneAsset&&this.context.events.emit("scene-content-changed",{source:this,object:this._currentSceneAsset}),!0}}catch(n){console.error(n)}return!1}preload(e){if(e>=0&&e<this.scenes.length){const t=this.scenes[e];if(t instanceof J)return t.preload()}return io}tryLoadFromQueryParam(){if(!this.queryParameterName?.length)return io;const e=x(this.queryParameterName);return typeof e=="boolean"?io:this.trySelectSceneFromValue(e)}trySelectSceneFromValue(e){if(typeof e=="string"){const t=parseInt(e);if(t>=0&&t<this.scenes.length)return this.select(t);{const i=e.toLowerCase();for(let n=0;n<this.scenes.length;n++){const o=this.scenes[n];if(!o)continue;const r=[];if(o instanceof c.Object3D)r.push(o.name);else{o.url&&r.push(m0(o.url));const a=o.asset;a instanceof c.Object3D&&a.name&&r.push(a.name)}if(r.some(a=>a?.toLowerCase().includes(i)))return this.select(n)}}}else if(typeof e=="number"&&e>=0&&e<this.scenes.length)return this.select(e);return ki()&&console.warn('[SceneSwitcher] Can not find scene: "'+e+'"',this),io}_lastLoadingScene=void 0;_loadingScenePromise=void 0;_isCurrentlyLoading=!1;_currentLoadingProgress=void 0;async onStartLoading(e){if(this._activeLoadingRequestId=e,this._isCurrentlyLoading=!0,this.loadingScene&&(this._lastLoadingScene!==this.loadingScene&&(this._loadingScenePromise=void 0),this._lastLoadingScene=this.loadingScene,this._loadingScenePromise||(this._loadingScenePromise=this.loadingScene?.loadAssetAsync().then(t=>t!=null)),await this._loadingScenePromise,e===this._activeLoadingRequestId&&this._isCurrentlyLoading&&this.loadingScene?.asset)){yt&&console.log("Add loading scene",this.loadingScene.url,this.loadingScene.asset);const t=this.loadingScene.asset;P.add(t,this.gameObject);const i=this.tryGetSceneEventListener(t);if(i?.sceneOpened){const n=i.sceneOpened(this);n instanceof Promise&&await n}}if(e===this._activeLoadingRequestId&&this._isCurrentlyLoading){const t=this.tryGetSceneEventListener(this.gameObject);if(t&&t.sceneOpened){const i=t.sceneOpened(this);i instanceof Promise&&await i}}}async onEndLoading(e){if(e===this._activeLoadingRequestId){if(this._isCurrentlyLoading=!1,this.loadingScene?.asset){yt&&console.log("Remove loading scene",this.loadingScene.url);const t=this.loadingScene.asset,i=this.tryGetSceneEventListener(t);if(typeof i?.sceneClosing=="function"){const n=i.sceneClosing();n instanceof Promise&&await n}P.remove(t)}if(!this._isCurrentlyLoading){const t=this.tryGetSceneEventListener(this.gameObject);if(t&&t.sceneClosing){const i=t.sceneClosing();i instanceof Promise&&await i}}}}tryGetSceneEventListener(e,t=0){if(!e)return null;const i=P.foreachComponent(e,n=>{const o=n;if(o.sceneClosing||o.sceneOpened)return o});if(t===0&&!i&&e.children.length)for(const n of e.children){const o=this.tryGetSceneEventListener(n,t+1);if(o)return o}return i||null}}wt([p()],Ye.prototype,"autoLoadFirstScene");wt([p(J)],Ye.prototype,"scenes");wt([p(J)],Ye.prototype,"loadingScene");wt([p()],Ye.prototype,"queryParameterName");wt([p()],Ye.prototype,"useSceneName");wt([p()],Ye.prototype,"clamp");wt([p()],Ye.prototype,"useHistory");wt([p()],Ye.prototype,"useKeyboard");wt([p()],Ye.prototype,"useSwipe");wt([p()],Ye.prototype,"useSceneLighting");wt([p()],Ye.prototype,"useSceneBackground");wt([p()],Ye.prototype,"preloadNext");wt([p()],Ye.prototype,"preloadPrevious");wt([p()],Ye.prototype,"preloadConcurrent");wt([p()],Ye.prototype,"createMenuButtons");wt([p(Z)],Ye.prototype,"sceneLoadingStart");wt([p(Z)],Ye.prototype,"sceneLoadingProgress");wt([p(Z)],Ye.prototype,"sceneLoaded");function m0(s){const t=s.split("/").pop()?.split(".").shift();return t?.length?t:s}class TT{maxLoadAhead;maxLoadBehind;maxConcurrent;_isRunning=!1;_switcher;_loadTasks=[];_maxConcurrentLoads=1;constructor(e,t=1,i=1,n=2){this._switcher=e,this.maxLoadAhead=t,this.maxLoadBehind=i,this.maxConcurrent=n}begin(e){if(this._isRunning)return;yt&&console.log("[SceneSwitcher] Preload scheduled",{delay:e}),this._isRunning=!0;let t=-10,i,n;const o=this._switcher.scenes,r=Date.now()+e,a=setInterval(()=>{if(this.allLoaded()&&(yt&&console.log("[SceneSwitcher] All scenes (pre-)loaded"),this.stop()),!this._isRunning){clearInterval(a);return}if(Date.now()<r||this.canLoadNewScene()===!1)return;(t===-10||t!==this._switcher.currentIndex)&&(t=this._switcher.currentIndex,n=0,i=0);const l=n%2===0;l&&(i+=1),n+=1;const h=l?this.maxLoadAhead:this.maxLoadBehind;if(i>h)return;const d=l?t+i:t-i;if(!(d<0)&&!(d<0||d>=o.length)&&!this._loadTasks.some(u=>u.index===d)){const u=o[d];yt&&console.log("[SceneSwitcher] Schedule preload scene",{roomIndex:d,searchForward:l,lastRoom:t,currentIndex:this._switcher.currentIndex,tasks:this._loadTasks.length},u?.url),new AT(d,u,this._loadTasks)}},200)}stop(){this._isRunning=!1}canLoadNewScene(){return this._loadTasks.length<this._maxConcurrentLoads}allLoaded(){if(this._switcher.scenes){for(const e of this._switcher.scenes)if(e?.isLoaded&&e.isLoaded()===!1)return!1}return!0}}class AT{index;asset;tasks;constructor(e,t,i){this.index=e,this.asset=t,this.tasks=i,i.push(this),this.awaitLoading()}async awaitLoading(){this.asset&&!this.asset.isLoaded()&&(yt&&console.log("[SceneSwitcher] Preload start: "+this.asset.url,this.index),await this.asset.preload(),yt&&console.log("[SceneSwitcher] Preload finished: "+this.asset.url,this.index));const e=this.tasks.indexOf(this);e>=0&&this.tasks.splice(e,1)}}const _o=x("debugautosync"),bm=Symbol("syncerId");class DT{_syncers={};getOrCreateSyncer(e){if(!e.guid)return null;if(this._syncers[e.guid])return this._syncers[e.guid];const t=new IT(e);return t[bm]=e.guid,this._syncers[t[bm]]=t,t}removeSyncer(e){delete this._syncers[e[bm]]}}const __=new DT;class IT{comp;constructor(e){this.comp=e}hasChanges=!1;changedProperties={};get networkingKey(){return this.comp.guid}_isReceiving=!1;_isInit=!1;init(e){if(this._isInit)return;this._isInit=!0,this.comp=e,this.comp.context.post_render_callbacks.push(this.onHandleSending),this.comp.context.connection.beginListen(this.networkingKey,this.onHandleReceiving);const t=this.comp.context.connection.tryGetState(this.comp.guid);t&&this.onHandleReceiving(t)}destroy(){this._isInit&&(this.comp.context.post_render_callbacks.splice(this.comp.context.post_render_callbacks.indexOf(this.onHandleSending),1),this.comp.context.connection.stopListen(this.networkingKey,this.onHandleReceiving),this.comp=null,this._isInit=!1)}notifyChanged(e,t){this._isReceiving||(_o&&console.log("Property changed: "+e,t),this.hasChanges=!0,this.changedProperties[e]=t)}onHandleSending=()=>{if(!this.hasChanges)return;this.hasChanges=!1;const e=this.comp.context.connection;if(!e||!e.isConnected||!e.isInRoom){for(const t in this.changedProperties)delete this.changedProperties[t];return}for(const t in this.changedProperties){const i=this.changedProperties[t];_o&&console.log("SEND",this.comp.guid,this.networkingKey),e.send(this.networkingKey,{guid:this.comp.guid,property:t,data:i},yn.Queued),delete this.changedProperties[t]}};onHandleReceiving=e=>{if(_o&&console.log("SYNCFIELD RECEIVE",this.comp.name,this.comp.guid,e),!!this._isInit&&this.comp&&e.guid===this.comp.guid)try{this._isReceiving=!0,this.comp[e.property]=e.data}catch(t){console.error(t)}finally{this._isReceiving=!1}}}function LT(s,e){let t=e!==s;return!t&&s&&e&&(Array.isArray(s)&&Array.isArray(e)||typeof s=="object"&&typeof e=="object")&&(t=!0),t}const Hc=Symbol("AutoSyncHandler");function BT(s){if(s[Hc])return s[Hc];const e=__.getOrCreateSyncer(s);return e?.init(s),s[Hc]=e,e}function FT(s){const e=s[Hc];e&&(__.removeSyncer(e),e.destroy(),delete s[Hc])}const b_=function(s=null){return function(e,t){let i="";typeof t=="string"?i=t:i=t.name;let n=null,o;typeof s=="string"?o=e[s]:typeof s=="function"&&(o=s),o==null&&(E()||_o)&&s!=null&&console.warn('syncField: no callback function found for property "'+i+'"','"'+s+'"');const r=e,a=r.__internalAwake;if(typeof a!="function"){(_o||E())&&console.error('@syncField can currently only used on Needle Engine Components, custom object of type "'+e?.constructor?.name+'" is not supported',e);return}_o&&console.log(i);const l=Symbol(i);r.__internalAwake=function(){if(this[l]!==void 0)return;if(this[l]=this[i],n=__.getOrCreateSyncer(this),Object.getOwnPropertyDescriptor(this,i)?.set===void 0){let u=!1;Object.defineProperty(this,i,{set:function(f){const m=this[l];if(this[l]=f,u){(E()||_o)&&console.warn("Recursive call detected",i);return}u=!0;try{const g=LT(f,m);_o&&console.log("SyncField assignment",i,"changed?",g,f,o),g&&o?.call(this,f,m)!==!1&&BT(this)?.notifyChanged(i,f)}finally{u=!1}},get:function(){return this[l]},configurable:!0,enumerable:!0})}n?.init(this),a.call(this)};const h=r.__internalDestroy;r.__internalDestroy=function(){FT(this),h.call(this)}}},Ld=new Map;function Bh(s,e,t){const i=t?.format===void 0?s:`${s}|format=${t.format}`;if(Ld.has(i))return Ld.get(i);const n=new URL(s,window.location.href),o=jT(n,e,t);return Ld.set(i,o),o.finally(()=>{Ld.delete(i)}),o}async function jT(s,e,t){if(!s)return Promise.resolve(null);const i=s.pathname,n=t?.format!==void 0?t.format==="pmrem":s.toString().toLowerCase().includes("pmrem")||s.searchParams.get("pmrem")!=null;let o=i.endsWith(".exr"),r=i.endsWith(".hdr"),a=i.endsWith(".ktx2");if(!o&&!r&&!a)try{const f=await fetch(s.toString(),{method:"GET",headers:{range:"bytes=0-15"}}),m=f.headers.get("content-type")?.toLowerCase()??"";if(m==="image/x-exr"||m==="image/aces")o=!0;else if(m==="image/vnd.radiance"||m==="image/x-hdr")r=!0;else if(m==="image/ktx2")a=!0;else{const g=new Uint8Array(await f.arrayBuffer());g.length>=4&&g[0]===118&&g[1]===47&&g[2]===49&&g[3]===1?o=!0:g.length>=12&&g[0]===171&&g[1]===75&&g[2]===84&&g[3]===88&&g[4]===32&&g[5]===50&&g[6]===48&&g[7]===187?a=!0:g.length>=10&&g[0]===35&&g[1]===63&&g[2]===82&&g[3]===65&&g[4]===68&&g[5]===73&&g[6]===65&&g[7]===78&&g[8]===67&&g[9]===69&&(r=!0)}}catch(f){console.warn("loadPMREM: failed to probe URL for format detection",s,f)}let l;if(o)l=new V.EXRLoader;else if(r)l=new V.HDRLoader;else if(a){const{ktx2Loader:f}=re.createLoaders(e);l=f}else l=new c.TextureLoader;const h=s.toString();return await l.loadAsync(h).then(f=>{if(f){const m=i.lastIndexOf("/");f.name=t?.name||i.substring(m>=0?m+1:0),n?f.mapping=c.CubeUVReflectionMapping:f.mapping=c.EquirectangularRefractionMapping,l instanceof c.TextureLoader&&(f.colorSpace=c.SRGBColorSpace)}return f}).catch(f=>(console.warn("Failed to load texture from url:",s),null))}var UT=Object.defineProperty,Fh=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&UT(e,t,n),n};const tt=x("debugskybox");function zT(){iy("background-image"),iy("environment-image"),$T()}function Bd(){return{url:null,texture:null,loadId:0}}const ny=new WeakMap,Fd=new Array,jd=Math.PI/180;function g0(s,e){const t=s.trim().split(/\s+/);if(t.length===1){const i=parseFloat(t[0]);isNaN(i)||e.set(0,i*jd,0)}else if(t.length>=3){const i=parseFloat(t[0]),n=parseFloat(t[1]),o=parseFloat(t[2]);!isNaN(i)&&!isNaN(n)&&!isNaN(o)&&e.set(i*jd,n*jd,o*jd)}}function y0(s,e,t,i){if(!s.scene){tt&&console.warn("Skybox: skipping applyTexture — context was torn down before the texture finished loading");return}!(e instanceof c.CubeTexture||e instanceof c.CompressedCubeTexture)&&e.mapping!==c.CubeUVReflectionMapping&&(e.mapping=c.EquirectangularRefractionMapping,e.needsUpdate=!0),i&&(s.scene.environment=e),t&&!Jt.backgroundShouldBeTransparent(s)&&(s.scene.background=e);const n=s.domElement;if(t){const o=n.getAttribute("background-blurriness");if(o){const l=parseFloat(o);isNaN(l)||(s.scene.backgroundBlurriness=l)}else s.mainCameraComponent?.backgroundBlurriness!==void 0&&(s.scene.backgroundBlurriness=s.mainCameraComponent.backgroundBlurriness);const r=n.getAttribute("background-intensity");if(r){const l=parseFloat(r);isNaN(l)||(s.scene.backgroundIntensity=l)}const a=n.getAttribute("background-rotation");a&&g0(a,s.scene.backgroundRotation)}if(i){const o=n.getAttribute("environment-rotation");o&&g0(o,s.scene.environmentRotation)}}function NT(s,e,t,i){const n=e.url?Bw(e.url):void 0;e.url=null,e.texture=null,i&&(!n||!s.sceneLighting.internalEnableReflection(n))&&(s.scene.environment=null),t&&(s.scene.background=n?s.lightmaps.tryGetSkybox(n):null)}function Ud(s,e,t,i,n,o){const r=s.currentContext;if(!r)return null;const a=o?mC(o,n,i):null;if(tt&&console.log(`Skybox attribute [${t}]: raw="${o}" → resolved="${a}"`),a&&(a==="transparent"||a.startsWith("rgb")||a.startsWith("#")))return console.warn(`Needle Engine: Invalid ${t} value (${a}). Did you mean to set background-color instead?`),null;const l=++e.loadId;return a?e.url===a&&e.texture?(tt&&console.log(`Skybox attribute [${t}]: cache hit, re-applying`),y0(r,e.texture,i,n),null):(e.url=a,e.texture=null,(async()=>{tt&&console.log(`Skybox attribute [${t}]: loading ${a}`);const d=await Bh(a,r.renderer);if(e.loadId!==l){tt&&console.warn(`Skybox attribute [${t}]: loadId mismatch (stale load), skipping apply`);return}if(!d){tt&&console.warn(`Skybox attribute [${t}]: failed to load ${a}`);return}tt&&console.log(`Skybox attribute [${t}]: loaded, applying to scene`),e.texture=d,y0(r,d,i,n),r.domElement.dispatchEvent(new CustomEvent(`${t}-loaded`,{detail:{texture:d}}))})()):(NT(r,e,i,n),null)}function _0(s){const e=ny.get(s.context.domElement);return!e||e.currentContext!==s.context?null:e}let b0=!1;function $T(){b0||(b0=!0,se.registerCallback(ae.ContextCreationStart,s=>{const e=s.context,t=e.domElement;let i=ny.get(t);i?i.currentContext=e:(i={currentContext:e,bg:Bd(),env:Bd(),listenersInstalled:!1},ny.set(t,i));const n=Ud(i,i.bg,"background-image",!0,!1,t.getAttribute("background-image"));n&&Fd.push(n);const o=Ud(i,i.env,"environment-image",!1,!0,t.getAttribute("environment-image"));if(o&&Fd.push(o),!i.listenersInstalled){i.listenersInstalled=!0;const r=i;ju(t,"background-image",a=>{const l=typeof a=="string"&&a.length>0?a:null;tt&&console.log("background-image CHANGED TO",l),Ud(r,r.bg,"background-image",!0,!1,l)}),ju(t,"environment-image",a=>{const l=typeof a=="string"&&a.length>0?a:null;tt&&console.log("environment-image CHANGED TO",l),Ud(r,r.env,"environment-image",!1,!0,l)})}}),se.registerCallback(ae.ContextCreationStart,()=>Promise.all(Fd).finally(()=>{Fd.length=0})),se.registerCallback(ae.ContextClearing,s=>{const e=_0(s);e&&(e.bg=Bd(),e.env=Bd())}),se.registerCallback(ae.ContextDestroyed,s=>{const e=_0(s);e&&(e.currentContext=null,e.bg.loadId++,e.env.loadId++)}))}const Br=class extends T{url="studio";allowDrop=!0;background=!0;environment=!0;allowNetworking=!0;_prevUrl;_prevLoadedEnvironment;_inFlightLoad;_prevEnvironment=null;_prevBackground=null;revertAppliedSceneState(){if(!this.context||!this._prevLoadedEnvironment)return!1;let e=!1;return this.context.scene.environment===this._prevLoadedEnvironment&&(this.context.scene.environment=this._prevEnvironment,e=!0),this.context.scene.background===this._prevLoadedEnvironment&&(Jt.backgroundShouldBeTransparent(this.context)||(this.context.scene.background=this._prevBackground),e=!0),e}discardPendingLoad(){if(this._prevUrl=void 0,this._inFlightLoad=void 0,!this.context){this._prevLoadedEnvironment?.dispose(),this._prevLoadedEnvironment=void 0;return}this.revertAppliedSceneState(),this._prevLoadedEnvironment=void 0}onEnable(){this.setSkybox(this.url),this.registerDropEvents()}onDisable(){this.revertAppliedSceneState()&&(this._prevLoadedEnvironment=void 0),this.unregisterDropEvents(),this.context.mainCameraComponent?.applyClearFlags()}onDestroy(){this._prevLoadedEnvironment=void 0}urlChangedSyncField(){this.allowNetworking&&this.url&&(this.isRemoteTexture(this.url)?this.setSkybox(this.url):tt&&console.warn(`RemoteSkybox: Not setting skybox: ${this.url} is not a remote texture. If you want to set a local texture, set allowNetworking to false.`))}async setSkybox(e,t){if(!this.activeAndEnabled||(e=mC(e,this.environment,this.background),!e))return!1;if(t??=e,this.isValidTextureType(t)||console.warn('Potentially invalid skybox URL: "'+t+'" on '+(this.name||this.gameObject?.name||"context")),tt&&console.log("Set RemoteSkybox url: "+e),this._prevUrl===e){if(this._prevLoadedEnvironment)return this.apply(),!0;if(this._inFlightLoad)return this._inFlightLoad}this._prevLoadedEnvironment?.dispose(),this._prevLoadedEnvironment=void 0,this._prevUrl=e;const i=(async()=>{const n=await Bh(e,this.context.renderer);return n?!this.enabled||this.destroyed?(tt&&console.warn("RemoteSkybox: Component is disabled or destroyed"),!1):this._prevUrl!==e?(tt&&console.warn("RemoteSkybox: URL changed while loading texture, aborting setSkybox"),!1):(this.url=e,this._prevLoadedEnvironment=n,this.apply(),!0):(tt&&console.warn("RemoteSkybox: Failed to load texture from url",e),!1)})();this._inFlightLoad=i;try{return await i}finally{this._inFlightLoad===i&&(this._inFlightLoad=void 0)}}apply(){const e=this._prevLoadedEnvironment;if(e&&(e instanceof c.CubeTexture||e instanceof c.CompressedCubeTexture||e.mapping==c.CubeUVReflectionMapping||(e.mapping=c.EquirectangularRefractionMapping,e.needsUpdate=!0),!this.destroyed)){if(!this.context){console.warn("RemoteSkybox: Context is not available - can not apply skybox.");return}this.context.scene.background!==e&&(this._prevBackground=this.context.scene.background),this.context.scene.environment!==e&&(this._prevEnvironment=this.context.scene.environment),tt&&console.log("Set RemoteSkybox ("+(this.environment&&this.background?"environment and background":this.environment?"environment":this.background?"background":"none")+")",this.url,!Jt.backgroundShouldBeTransparent(this.context)),this.environment&&(this.context.scene.environment=e),this.background&&!Jt.backgroundShouldBeTransparent(this.context)&&(this.context.scene.background=e),this.context.mainCameraComponent?.backgroundBlurriness!==void 0&&(this.context.scene.backgroundBlurriness=this.context.mainCameraComponent.backgroundBlurriness)}}validProtocols=["file:","blob:","data:"];validTextureTypes=[".ktx2",".hdr",".exr",".jpg",".jpeg",".png"];isRemoteTexture(e){return e.startsWith("http://")||e.startsWith("https://")}isValidTextureType(e){for(const t of this.validTextureTypes)if(e.includes(t))return!0;for(const t of this.validProtocols)if(e.startsWith(t))return!0;return!1}registerDropEvents(){this.unregisterDropEvents(),this.context.domElement.addEventListener("dragover",this.onDragOverEvent),this.context.domElement.addEventListener("drop",this.onDrop)}unregisterDropEvents(){this.context.domElement.removeEventListener("dragover",this.onDragOverEvent),this.context.domElement.removeEventListener("drop",this.onDrop)}onDragOverEvent=e=>{if(this.allowDrop&&e.dataTransfer)for(const t of e.dataTransfer.types)(t==="text/uri-list"||t==="Files")&&e.preventDefault()};onDrop=e=>{if(this.allowDrop&&e.dataTransfer){for(const t of e.dataTransfer.types)if(tt&&console.log(t),t==="text/uri-list"){const i=e.dataTransfer.getData(t);tt&&console.log(t,i);let n=new RegExp(/polyhaven.com\/asset_img\/.+?\/(?<name>.+)\.png/).exec(i)?.groups?.name;if(n||(n=new RegExp(/polyhaven\.com\/a\/(?<name>.+)/).exec(i)?.groups?.name),tt&&console.log(n),n){const o="https://dl.polyhaven.org/file/ph-assets/HDRIs/exr/1k/"+n+"_1k.exr";console.log(`[Remote Skybox] Setting skybox from url: ${o}`),e.preventDefault(),this.setSkybox(o);break}else if(this.isValidTextureType(i)){console.log("[Remote Skybox] Setting skybox from url: "+i),e.preventDefault(),this.setSkybox(i);break}else{console.warn(`[RemoteSkybox] Unknown url ${i}. If you want to load a skybox from a url, make sure it is a valid image url. Url must end with${this.validTextureTypes.join(", ")}.`);const o=new CustomEvent("dropped-unknown-url",{detail:{sender:this,event:e,url:i,apply:r=>{e.preventDefault(),this.setSkybox(r)}}});this.dispatchEvent(o)}}else if(t=="Files"){const i=e.dataTransfer.files.item(0);if(tt&&console.log(t,i),!i)continue;if(!this.isValidTextureType(i.name)){console.warn(`[RemoteSkybox]: File "${i.name}" is not supported. Supported files are ${this.validTextureTypes.join(", ")}`);return}e.preventDefault(),this.setSkybox(i.name);break}}}};Fh([b_(Br.prototype.urlChangedSyncField),p(URL)],Br.prototype,"url");Fh([p()],Br.prototype,"allowDrop");Fh([p()],Br.prototype,"background");Fh([p()],Br.prototype,"environment");Fh([p()],Br.prototype,"allowNetworking");let v_=Br;const v0={studio:{url:"https://cdn.needle.tools/static/skybox/modelviewer-Neutral.pmrem4x4.ktx2?pmrem",url_low:"https://cdn.needle.tools/static/skybox/modelviewer-Neutral-small.pmrem4x4.ktx2?pmrem"},"blurred-skybox":{url:"https://cdn.needle.tools/static/skybox/blurred-skybox.pmrem4x4.ktx2?pmrem",url_low:"https://cdn.needle.tools/static/skybox/blurred-skybox-small.pmrem4x4.ktx2?pmrem"},"quicklook-ar":{url:"https://cdn.needle.tools/static/skybox/QuickLook-ARMode.pmrem4x4.ktx2?pmrem",url_low:"https://cdn.needle.tools/static/skybox/QuickLook-ARMode-small.pmrem4x4.ktx2?pmrem"},quicklook:{url:"https://cdn.needle.tools/static/skybox/QuickLook-ObjectMode.pmrem4x4.ktx2?pmrem",url_low:"https://cdn.needle.tools/static/skybox/QuickLook-ObjectMode-small.pmrem4x4.ktx2?pmrem"}};function mC(s,e,t){if(s==null)return null;const i=e&&!t,n=v0[s.toLowerCase()];return n?i?n.url_low:n.url:(typeof s=="string"&&s?.length&&(E()||tt)&&(s.includes("/")||s.includes(".")||console.warn(`RemoteSkybox: Unknown magic skybox name "${s}". Valid names are: ${Object.keys(v0).map(r=>`"${r}"`).join(", ")}`)),s)}var VT=Object.defineProperty,gC=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&VT(e,t,n),n};class jh extends T{from;to;width=0;centered=!0;_centerPos;awake(){this._centerPos=new c.Vector3}update(){if(!this.from||!this.to)return;const e=ie(this.from).clone(),t=ie(this.to).clone(),i=e.distanceTo(t);this._centerPos.copy(e),this._centerPos.add(t),this._centerPos.multiplyScalar(.5),Oi(this.gameObject,this.centered?this._centerPos:e),this.gameObject.lookAt(ie(this.to).clone()),this.gameObject.scale.set(this.width,this.width,i)}}gC([p(P)],jh.prototype,"from");gC([p(P)],jh.prototype,"to");var WT=Object.defineProperty,w_=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&WT(e,t,n),n};class Ol extends T{length=1;depthTest=!0;isGizmo=!1;_axes=null;onEnable(){if(this.isGizmo&&!Oh)return;this._axes||(this._axes=new c.AxesHelper(this.length)),this._axes.layers.disableAll(),this._axes.layers.set(this.layer),this.gameObject.add(this._axes);const e=this._axes.material;e&&e.depthTest!==void 0&&(e.depthTest=this.depthTest)}onDisable(){this._axes&&this.gameObject.remove(this._axes)}}w_([p()],Ol.prototype,"length");w_([p()],Ol.prototype,"depthTest");w_([p()],Ol.prototype,"isGizmo");class x_ extends T{from;to;hint;desiredDistance=1;onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;const e=ie(this.to).clone(),t=ie(this.from).clone(),i=e.distanceTo(t),n=e.clone();n.sub(t);const o=t.clone();o.add(e),o.multiplyScalar(.5);const r=ie(this.hint).clone();r.sub(o);const a=new c.Vector3;a.crossVectors(r,n),a.crossVectors(n,a),a.normalize();const l=i*.5,h=Math.max(this.desiredDistance,l),d=Math.sqrt(h*h-l*l),u=a.clone();u.multiplyScalar(d),u.add(o),Oi(this.gameObject,u);const f=o.clone();f.sub(a),this.gameObject.lookAt(f)}}const GT=x("gizmos"),HT=x("debugboxhelper");class At extends T{box=null;static testBox=new c.Box3;_lastMatrixUpdateFrame=-1;static _position=new c.Vector3;static _size=new c.Vector3(.01,.01,.01);static _emptyObjectSize=new c.Vector3(.01,.01,.01);isInBox(e){if(!e)return;if(this.box||(this.box=new c.Box3),pi([e],void 0,void 0,At.testBox),At.testBox.isEmpty()){const i=ie(e,At._position);At.testBox.setFromCenterAndSize(i,At._emptyObjectSize)}this.updateBox();const t=this.box?.intersectsBox(At.testBox);return t&&HT&&B.DrawWireBox3(At.testBox,16711680,5),t}intersects(e){return e?this.updateBox(!1).intersectsBox(e):!1}updateBox(e=!1){if(this.box||(this.box=new c.Box3),e||this.context.time.frameCount!=this._lastMatrixUpdateFrame){const t=this._lastMatrixUpdateFrame<0;this._lastMatrixUpdateFrame=this.context.time.frameCount;const i=t,n=ie(this.gameObject,At._position,i),o=Ve(this.gameObject,At._size);this.box.setFromCenterAndSize(n,o)}return this.box}_helper=null;_color=null;awake(){this._helper=null,this._color=null,this.box=null}showHelper(e=null,t=!1){if(!(!GT&&!t)){if(this._helper){e&&this._color?.set(e),this.gameObject.add(this._helper);return}this._helper=s_(e),this.gameObject.add(this._helper)}}}var qT=Object.defineProperty,ni=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&qT(e,t,n),n};class Ii extends T{get isCollider(){return!0}attachedRigidbody=null;isTrigger=!1;sharedMaterial;membership=[0];filter;density;_propertiesDirty=!1;onValidate(e){this.activeAndEnabled?e==="sharedMaterial"?this.updatePhysicsMaterial():this.updateProperties():this._propertiesDirty=!0}awake(){super.awake(),this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Xe))}start(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Xe))}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Xe))}onDisable(){this.context.physics.engine?.setColliderEnabled(this,!1)||this.context.physics.engine?.removeBody(this)}onDestroy(){this.context.physics.engine?.removeBody(this)}get body(){return this.context.physics.engine?.getBody(this)}updateProperties=()=>{this.context.physics.engine?.updateProperties(this)};updatePhysicsMaterial(){this.context.physics.engine?.updatePhysicsMaterial(this)}}ni([p(Xe)],Ii.prototype,"attachedRigidbody");ni([je(),p()],Ii.prototype,"isTrigger");ni([je(),p()],Ii.prototype,"sharedMaterial");ni([je(),p()],Ii.prototype,"membership");ni([je(),p()],Ii.prototype,"filter");ni([je(),p()],Ii.prototype,"density");class El extends Ii{radius=.5;center=new c.Vector3(0,0,0);onEnable(){super.onEnable();const e=this.context.physics.getOrCreatePhysicsEngine();e?.setColliderEnabled(this,!0)?this._propertiesDirty&&(this.updateProperties(),this.updatePhysicsMaterial()):e?.addSphereCollider(this),this._propertiesDirty=!1,Mf(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),Cy(this.gameObject.scale,this.updateProperties)}}ni([je(),p()],El.prototype,"radius");ni([p(c.Vector3)],El.prototype,"center");const S_=class yC extends Ii{static add(e,t){const i=ss(e,yC);return i.autoFit(),t?.rigidbody===!0&&ss(e,Xe,{isKinematic:!1}),i}size=new c.Vector3(1,1,1);center=new c.Vector3(0,0,0);onEnable(){super.onEnable();const e=this.context.physics.getOrCreatePhysicsEngine();e?.setColliderEnabled(this,!0)?this._propertiesDirty&&(this.updateProperties(),this.updatePhysicsMaterial()):e?.addBoxCollider(this,this.size),this._propertiesDirty=!1,Mf(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),Cy(this.gameObject.scale,this.updateProperties)}autoFit(e){const t=this.gameObject,i=t.position.clone(),n=t.quaternion.clone(),o=t.scale.clone(),r=t.parent;t.position.set(0,0,0),t.quaternion.set(0,0,0,1),t.scale.set(1,1,1),t.parent=null,t.updateMatrix();const a=pi([t]);t.position.copy(i),t.quaternion.copy(n),t.scale.copy(o),t.parent=r,e?.debug===!0&&B.DrawWireBox3(a,16768256,20),this.size=a.getSize(new c.Vector3)||new c.Vector3(1,1,1),this.center=a.getCenter(new c.Vector3)||new c.Vector3(0,0,0),this.size.length()<=0&&this.size.set(.01,.01,.01)}};ni([je(),p(c.Vector3)],S_.prototype,"size");ni([p(c.Vector3)],S_.prototype,"center");let np=S_;class Uo extends Ii{sharedMesh;convex=!1;onEnable(){super.onEnable();const e=this.context.physics.getOrCreatePhysicsEngine();if(!e)return;if(e.setColliderEnabled(this,!0)){this._propertiesDirty&&(this.updateProperties(),this.updatePhysicsMaterial()),this._propertiesDirty=!1;return}this._propertiesDirty=!1,this.sharedMesh?.isMesh||(this.gameObject instanceof c.Mesh||this.gameObject instanceof c.Group)&&(this.sharedMesh=this.gameObject);const t=0;if(this.sharedMesh?.isMesh)e.addMeshCollider(this,this.sharedMesh,this.convex),re.NEEDLE_progressive.assignMeshLOD(this.sharedMesh,t).then(i=>{i&&this.activeAndEnabled&&this.context.physics.engine&&this.sharedMesh&&(this.context.physics.engine.removeBody(this),this.sharedMesh.geometry=i,this.context.physics.engine.addMeshCollider(this,this.sharedMesh,this.convex))});else{const i=this.sharedMesh;if(i?.isGroup){console.warn(`MeshCollider mesh is a group "${this.sharedMesh?.name||this.gameObject.name}", adding all children as colliders. This is currently not fully supported (colliders can not be removed from world again)`,this);const n=new Array;for(const o in i.children){const r=i.children[o];r.isMesh&&(e.addMeshCollider(this,r,this.convex),n.push(re.NEEDLE_progressive.assignMeshLOD(r,t)))}Promise.all(n).then(o=>{if(o.some(a=>a)==!1)return;this.context.physics.engine?.removeBody(this);const r=new c.Mesh;for(const a of o)a&&this.activeAndEnabled&&(r.geometry=a,this.context.physics.engine?.addMeshCollider(this,r,this.convex))})}else(E()||x("showcolliders"))&&console.warn(`[MeshCollider] A MeshCollider mesh is assigned to an unknown object on "${this.gameObject.name}", but it's neither a Mesh nor a Group. Please double check that you attached the collider component to the right object and report a bug otherwise!`,this)}}}ni([p(c.Mesh)],Uo.prototype,"sharedMesh");ni([p()],Uo.prototype,"convex");class Fs extends Ii{center=new c.Vector3(0,0,0);radius=.5;height=2;onEnable(){super.onEnable();const e=this.context.physics.getOrCreatePhysicsEngine();e?.setColliderEnabled(this,!0)?this._propertiesDirty&&(this.updateProperties(),this.updatePhysicsMaterial()):e?.addCapsuleCollider(this,this.height,this.radius),this._propertiesDirty=!1}}ni([p(c.Vector3)],Fs.prototype,"center");ni([p()],Fs.prototype,"radius");ni([p()],Fs.prototype,"height");var XT=Object.defineProperty,zs=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&XT(e,t,n),n};const w0=x("debugcharactercontroller");class Gr extends T{center=new c.Vector3(0,0,0);radius=.5;height=2;_rigidbody=null;get rigidbody(){return this._rigidbody?this._rigidbody:(this._rigidbody=this.gameObject.getComponent(Xe),this._rigidbody||(this._rigidbody=this.gameObject.addComponent(Xe)),this.rigidbody)}_activeGroundCollisions;awake(){this._activeGroundCollisions=new Set}onEnable(){const e=this.rigidbody;let t=this.gameObject.getComponent(Fs);t||(t=this.gameObject.addComponent(Fs)),t.center.copy(this.center),t.radius=this.radius,t.height=this.height;const i=new c.Vector3(0,0,1),n=new c.Vector3(1,0,0),o=new c.Vector3(0,1,0),r=this.gameObject.getWorldDirection(new c.Vector3);r.y=0;const a=n.dot(r)<0?-1:1,l=i.angleTo(r)*a;this.gameObject.setRotationFromAxisAngle(o,l),e.lockRotationX=!0,e.lockRotationY=!0,e.lockRotationZ=!0}move(e){this.gameObject.position.add(e)}onCollisionEnter(e){(e.contacts.length==0||e.contacts.some(t=>t.normal.y>.2))&&(this._activeGroundCollisions.add(e),w0&&console.log(`Collision(${this._activeGroundCollisions.size}): ${e.contacts.map(t=>t.normal.y.toFixed(2)).join(", ")} - ${this.isGrounded}`))}onCollisionExit(e){this._activeGroundCollisions.delete(e),w0&&console.log(`Collision(${this._activeGroundCollisions.size}) - ${this.isGrounded}`)}get isGrounded(){return this._activeGroundCollisions.size>0}_contactVelocity=new c.Vector3;get contactVelocity(){this._contactVelocity.set(0,0,0);for(const e of this._activeGroundCollisions){const t=this.context.physics.engine?.getLinearVelocity(e.collider);t&&(this._contactVelocity.x+=t.x,this._contactVelocity.y+=t.y,this._contactVelocity.z+=t.z)}return this._contactVelocity}}zs([p(c.Vector3)],Gr.prototype,"center");zs([p()],Gr.prototype,"radius");zs([p()],Gr.prototype,"height");class Ns extends T{controller;movementSpeed=2;rotationSpeed=2;jumpForce=1;doubleJumpForce=2;animator;lookForward=!0;awake(){this._currentRotation=new c.Quaternion}update(){const e=this.context.input;e.isKeyPressed("KeyW")?this.moveInput.y+=1:e.isKeyPressed("KeyS")&&(this.moveInput.y-=1),e.isKeyPressed("KeyD")?this.lookInput.x+=1:e.isKeyPressed("KeyA")&&(this.lookInput.x-=1),this.jumpInput||=e.isKeyDown("Space")}move(e){this.moveInput.add(e)}look(e){this.lookInput.add(e)}jump(){this.jumpInput=!0}lookInput=new c.Vector2(0,0);moveInput=new c.Vector2(0,0);jumpInput=!1;onBeforeRender(){this.handleInput(this.moveInput,this.lookInput,this.jumpInput),this.lookInput.set(0,0),this.moveInput.set(0,0),this.jumpInput=!1}_currentSpeed=new c.Vector3(0,0,0);_currentAngularSpeed=new c.Vector3(0,0,0);_temp=new c.Vector3(0,0,0);_jumpCount=0;_currentRotation;handleInput(e,t,i){if(this.controller?.isGrounded&&(this._jumpCount=0,this.doubleJumpForce>0&&this.animator?.setBool("doubleJump",!1)),this._currentSpeed.z+=e.y*this.movementSpeed*this.context.time.deltaTime,this.animator?.setBool("running",e.length()>.01),this.animator?.setBool("jumping",this.controller?.isGrounded===!0&&i),this._temp.copy(this._currentSpeed),this._temp.applyQuaternion(this.gameObject.quaternion),this.controller?this.controller.move(this._temp):this.gameObject.position.add(this._temp),this._currentAngularSpeed.y+=L.toRadians(-t.x*this.rotationSpeed)*this.context.time.deltaTime,this.lookForward&&Math.abs(this._currentAngularSpeed.y)<.01){const n=this.context.mainCameraComponent.forward;n.y=0,n.normalize(),this._currentRotation.setFromUnitVectors(new c.Vector3(0,0,1),n),this.gameObject.quaternion.slerp(this._currentRotation,this.context.time.deltaTime*10)}if(this.gameObject.rotateY(this._currentAngularSpeed.y),this._currentSpeed.multiplyScalar(1-this.context.time.deltaTime*10),this._currentAngularSpeed.y*=1-this.context.time.deltaTime*10,this.controller&&i&&this.jumpForce>0){let n=this.controller?.isGrounded;if(this.doubleJumpForce>0&&!this.controller?.isGrounded&&this._jumpCount===1&&(n=!0,this.animator?.setBool("doubleJump",!0)),n){this._jumpCount+=1;const o=this.controller.rigidbody,r=this._jumpCount===2?this.doubleJumpForce:this.jumpForce;o.applyImpulse(new c.Vector3(0,1,0).multiplyScalar(r))}}if(this.controller){const n=this.controller?.rigidbody.getVelocity().y;if(n<-1){this._raycastOptions.ray||(this._raycastOptions.ray=new c.Ray),this._raycastOptions.ray.origin.copy(ie(this.gameObject)),this._raycastOptions.ray.direction.set(0,-1,0);const o=this.layer;this.gameObject.layers.disableAll(),this.gameObject.layers.set(2);const r=this.context.physics.raycast(this._raycastOptions);this.gameObject.layers.set(o),(r.length&&r[0].distance>2||n<-10)&&this.animator?.setBool("falling",!0)}else this.animator?.setBool("falling",!1)}}_raycastOptions=new zr}zs([p(Gr)],Ns.prototype,"controller");zs([p()],Ns.prototype,"movementSpeed");zs([p()],Ns.prototype,"rotationSpeed");zs([p()],Ns.prototype,"jumpForce");zs([p()],Ns.prototype,"doubleJumpForce");zs([p(vt)],Ns.prototype,"animator");const _C=Symbol("customVisibilityFlag");function Qn(s,e){s.layers[_C]=e}const x0=Symbol("DidPatchLayers");function QT(){const s=c.Layers.prototype;if(s[x0])return;s[x0]=!0;const e=s.test;s.test=function(t){return this[_C]===!1?!1:e.call(this,t)}}var YT=Object.defineProperty,Rl=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&YT(e,t,n),n};const ba=x("debugcontactshadows");If(s=>{const e=s.domElement.getAttribute("contactshadows")||s.domElement.getAttribute("contact-shadows");if(e!=null&&e!="0"&&e!="false"){console.debug("Auto-creating ContactShadows because of `contactshadows` attribute");const t=Uh.auto(s),i=parseFloat(e);isNaN(i)||(t.opacity=i,t.darkness=i)}});const Hr=class Mc extends T{static _instances=new WeakMap;static auto(e,t){if(e||(e=X.Current),!e)throw new Error("No context provided and no current context set.");let i=this._instances.get(e);if(!i||i.destroyed){const n=new c.Object3D;n.name="ContactShadows",i=ss(n,Mc,{autoFit:!0,occludeBelowGround:!1}),this._instances.set(e,i)}return e.scene.add(i.gameObject),i.fitShadows(t),i}autoFit=!1;darkness=.5;opacity=.5;blur=4;occludeBelowGround=!1;backfaceShadows=!0;minSize;manualUpdate=!1;set needsUpdate(e){this._needsUpdate=e}get needsUpdate(){return this._needsUpdate}_needsUpdate=!1;_needsFit=!1;shadowsRoot=new c.Object3D;shadowGroup=new c.Group;shadowCamera;renderTarget;renderTargetBlur;plane;occluderMesh;blurPlane;planeMaterial;depthMaterial;horizontalBlurMaterial;verticalBlurMaterial;textureSize=512;fitShadows(e={}){ba&&console.warn("Fitting shadows to scene"),zu(this.shadowsRoot,!1);const t=e.object||this.context.scene,i=pi(t,[this.shadowsRoot]),n=Math.max(1,this.blur/32),o=i.max.x-i.min.x,r=i.max.z-i.min.z;i.expandByVector(new c.Vector3(n*o,0,n*r)),ba&&B.DrawWireBox3(i,16776960,60),this.gameObject.parent&&i.applyMatrix4(this.gameObject.parent.matrixWorld.clone().invert());const a=i.min,l=Math.max(1e-5,(i.max.y-a.y)*.002);i.max.y+=l,this.shadowsRoot.position.set((a.x+i.max.x)/2,a.y-l,(a.z+i.max.z)/2),this.shadowsRoot.scale.set(i.max.x-a.x,i.max.y-a.y,i.max.z-a.z),e.positionOffset&&(e.positionOffset.x!==void 0&&(this.shadowsRoot.position.x+=e.positionOffset.x),e.positionOffset.y!==void 0&&(this.shadowsRoot.position.y+=e.positionOffset.y),e.positionOffset.z!==void 0&&(this.shadowsRoot.position.z+=e.positionOffset.z)),e.scaleFactor&&(e.scaleFactor.x!==void 0&&(this.shadowsRoot.scale.x*=e.scaleFactor.x),e.scaleFactor.y!==void 0&&(this.shadowsRoot.scale.y*=e.scaleFactor.y),e.scaleFactor.z!==void 0&&(this.shadowsRoot.scale.z*=e.scaleFactor.z)),this.applyMinSize(),this.shadowsRoot.matrixWorldNeedsUpdate=!0,ba&&console.log("Fitted shadows to scene",this.shadowsRoot.scale.clone())}renderShadowsNow(){this._renderShadows()}awake(){Mc._instances.set(this.context,this)}onEnable(){this.shadowsRoot.hideFlags=as.DontExport,zu(this.shadowsRoot,!1),this._needsUpdate=!0,this.autoCleanup(this.context.events.on("scene-content-changed",()=>{this.autoFit&&(this._needsFit=!0,this._needsUpdate=!0)})),this.autoFit?this.fitShadows():this.applyMinSize()}onDestroy(){ba&&console.warn("Destroying ContactShadows on "+this.gameObject.name),Mc._instances.get(this.context)===this&&Mc._instances.delete(this.context),this.renderTarget?.dispose(),this.renderTargetBlur?.dispose(),this.depthMaterial?.dispose(),this.horizontalBlurMaterial?.dispose(),this.verticalBlurMaterial?.dispose(),this.blurPlane?.geometry.dispose(),this.plane?.geometry.dispose(),this.occluderMesh?.geometry.dispose()}onBeforeRender(e){this._needsFit&&this.autoFit&&(this._needsFit=!1,this.fitShadows()),!(this.manualUpdate&&!this._needsUpdate)&&(this._needsUpdate=!1,this._renderShadows())}_ensureSetup(){if(this.shadowsRoot.parent!==this.gameObject&&this.gameObject.add(this.shadowsRoot),this.depthMaterial&&this.horizontalBlurMaterial&&this.verticalBlurMaterial&&this.planeMaterial)return;ba&&console.log("Create ContactShadows on "+this.gameObject.name,this),this.shadowsRoot.name="ContactShadows Root",this.shadowGroup.name="ContactShadows Group",this.gameObject.add(this.shadowsRoot),this.shadowsRoot.add(this.shadowGroup),this.renderTarget=new c.WebGLRenderTarget(this.textureSize,this.textureSize),this.renderTarget.texture.generateMipmaps=!1,this.renderTargetBlur=new c.WebGLRenderTarget(this.textureSize,this.textureSize),this.renderTargetBlur.texture.generateMipmaps=!1;const e=new c.PlaneGeometry(1,1).rotateX(Math.PI/2);this.gameObject instanceof c.Mesh&&(console.warn("ContactShadows can not be added to a Mesh. Please add it to a Group or an empty Object"),Qn(this.gameObject,!1));const t=this.planeMaterial=new c.MeshBasicMaterial({map:this.renderTarget.texture,opacity:this.opacity,color:0,transparent:!0,depthWrite:!1,side:c.FrontSide});t.name="ContactShadows Plane",this.plane=new c.Mesh(e,t),this.plane.scale.y=-1,this.plane.layers.set(2),this.shadowsRoot.add(this.plane),this.plane&&(this.plane.renderOrder=1);const i=new c.MeshBasicMaterial({depthWrite:!0,stencilWrite:!0,colorWrite:!1,side:c.BackSide});i.name="ContactShadows Occluder",this.occluderMesh=new c.Mesh(this.plane.geometry,i).translateY(-1e-4),this.occluderMesh.renderOrder=-100,this.occluderMesh.layers.set(2),this.shadowsRoot.add(this.occluderMesh),this.blurPlane=new c.Mesh(e),this.blurPlane.visible=!1,this.shadowGroup.add(this.blurPlane);const n=0,o=1;this.shadowCamera=new c.OrthographicCamera(-1/2,1/2,1/2,-1/2,n,o),this.shadowCamera.name="ContactShadows Camera",this.shadowCamera.layers.enableAll(),this.shadowCamera.rotation.x=Math.PI/2,this.shadowCamera.matrixWorldAutoUpdate=!1,this.shadowGroup.add(this.shadowCamera),this.shadowCamera.updateMatrix(),this.depthMaterial=new c.MeshDepthMaterial,this.depthMaterial.name="ContactShadows Depth",this.depthMaterial.userData.darkness={value:this.darkness},this.depthMaterial.blending=c.CustomBlending,this.depthMaterial.blendEquation=c.MaxEquation,this.depthMaterial.onBeforeCompile=r=>{this.depthMaterial&&(r.uniforms.darkness=this.depthMaterial.userData.darkness,r.fragmentShader=`
1066
1066
  uniform float darkness;
1067
1067
  ${r.fragmentShader.replace("gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );","gl_FragColor = vec4( vec3( 1.0 ), ( 1.0 - fragCoordZ ) * darkness * opacity * (gl_FrontFacing ? 1.0 : 0.66) );")}
1068
1068
  `)},this.depthMaterial.depthTest=!1,this.depthMaterial.depthWrite=!1,this.horizontalBlurMaterial=new c.ShaderMaterial(V.HorizontalBlurShader),this.horizontalBlurMaterial.name="ContactShadows Horizontal Blur",this.horizontalBlurMaterial.depthTest=!1,this.verticalBlurMaterial=new c.ShaderMaterial(V.VerticalBlurShader),this.verticalBlurMaterial.name="ContactShadows Vertical Blur",this.verticalBlurMaterial.depthTest=!1,this.shadowGroup.visible=!1}_renderShadows(){if(this._ensureSetup(),!this.renderTarget||!this.renderTargetBlur||!this.depthMaterial||!this.shadowCamera||!this.blurPlane||!this.shadowGroup||!this.plane||!this.horizontalBlurMaterial||!this.verticalBlurMaterial||!this.planeMaterial){ba&&console.error("ContactShadows: not initialized yet");return}this.depthMaterial.userData.darkness.value=this.darkness,this.planeMaterial.opacity=this.opacity;const e=this.context.scene,t=this.context.renderer,i=t.getRenderTarget();this.shadowGroup.visible=!0,this.occluderMesh&&(this.occluderMesh.visible=!1);const n=this.plane.visible;this.plane.visible=!1,this.gameObject instanceof c.Mesh&&Qn(this.gameObject,!1);const o=e.background;e.background=null,e.overrideMaterial=this.depthMaterial,this.backfaceShadows?this.depthMaterial.side=c.DoubleSide:this.depthMaterial.side=c.FrontSide;const r=t.getClearAlpha();t.setClearAlpha(0);const a=t.xr.enabled;t.xr.enabled=!1;const l=this.context.scene.matrixWorldAutoUpdate;this.context.scene.matrixWorldAutoUpdate=!1;const h=t.renderLists.get(e,0),d=h.transparent;S0.length=0,h.transparent=S0,vm.length=0;for(const f of h.opaque){if(!f.object.visible)continue;const m=f.material;let g=f.material.colorWrite==!1||m.wireframe===!0||Zw(f.object)===!1;!g&&f.material.isLineMaterial&&(g=!0),!g&&f.material.isPointsMaterial&&(g=!0),g&&(vm.push(f.object),f.object["needle:visible"]=f.object.visible,f.object.visible=!1)}this.shadowCamera.parent?this.shadowCamera.matrixWorld.multiplyMatrices(this.shadowCamera.parent.matrixWorld,this.shadowCamera.matrix):this.shadowCamera.matrixWorld.copy(this.shadowCamera.matrix),this.shadowCamera.matrixWorldInverse.copy(this.shadowCamera.matrixWorld).invert(),t.setRenderTarget(this.renderTarget),t.clear(),t.render(e,this.shadowCamera),h.transparent=d;for(const f of vm)f["needle:visible"]!=null&&(f.visible=f["needle:visible"]);e.overrideMaterial=null;const u=Math.max(this.blur,.05);this.blurShadow(u*2),this.blurShadow(u*.5),this.shadowGroup.visible=!1,this.occluderMesh&&(this.occluderMesh.visible=this.occludeBelowGround),this.plane.visible=n,t.setRenderTarget(i),t.setClearAlpha(r),e.background=o,t.xr.enabled=a,this.context.scene.matrixWorldAutoUpdate=l}blurShadow(e){if(!this.blurPlane||!this.shadowCamera||!this.renderTarget||!this.renderTargetBlur||!this.horizontalBlurMaterial||!this.verticalBlurMaterial)return;this.blurPlane.visible=!0;const t=this.shadowsRoot.worldScale,i=(t.x+t.z)/2,n=t.z/i,o=t.x/i;this.blurPlane.material=this.horizontalBlurMaterial,this.blurPlane.material.uniforms.tDiffuse.value=this.renderTarget.texture,this.horizontalBlurMaterial.uniforms.h.value=e*1/this.textureSize*n;const r=this.context.renderer,a=r.getRenderTarget();r.setRenderTarget(this.renderTargetBlur),r.render(this.blurPlane,this.shadowCamera),this.blurPlane.material=this.verticalBlurMaterial,this.blurPlane.material.uniforms.tDiffuse.value=this.renderTargetBlur.texture,this.verticalBlurMaterial.uniforms.v.value=e*1/this.textureSize*o,r.setRenderTarget(this.renderTarget),r.render(this.blurPlane,this.shadowCamera),this.blurPlane.visible=!1,r.setRenderTarget(a)}applyMinSize(){this.minSize&&this.shadowsRoot.scale.set(Math.max(this.minSize.x||0,this.shadowsRoot.scale.x),Math.max(this.minSize.y||0,this.shadowsRoot.scale.y),Math.max(this.minSize.z||0,this.shadowsRoot.scale.z))}};Rl([p()],Hr.prototype,"autoFit");Rl([p()],Hr.prototype,"darkness");Rl([p()],Hr.prototype,"opacity");Rl([p()],Hr.prototype,"blur");Rl([p()],Hr.prototype,"occludeBelowGround");Rl([p()],Hr.prototype,"backfaceShadows");let Uh=Hr;const S0=[],vm=new Array,KT=x("logstats");class C_ extends T{onEnable(){console.log(this),KT&&this.startCoroutine(this.run(),Ce.OnAfterRender)}*run(){for(;this.enabled;){const e=this.context.renderer.info;console.log(e.memory,e.render,e.programs),yield}}}class zh extends T{isUsed=!0;usedBy=null}class P_ extends T{}const C0=x("debugdeletable");class Oo extends At{static _instances=[];onEnable(){Oo._instances.push(this)}onDisable(){const e=Oo._instances.indexOf(this);e>=0&&Oo._instances.splice(e,1)}}class k_ extends T{update(){for(const e of Oo._instances){const t=this.gameObject;if(e.isInBox(t)===!0){const n=P.getComponentInParent(this.gameObject,zh);if(n)C0&&console.warn("DeleteBox: Not deleting object with usage marker",this.guid,n);else{if(C0)try{if(e.box){const o=e.box,r=At.testBox;B.DrawWireBox3(o,16711680,5),B.DrawWireBox3(r,255,5),console.log("DeleteBox: Destroying",this.gameObject,{deleteBoxArea:o,deletedObjectArea:r})}else console.log("DeleteBox: Destroying",this.gameObject)}catch{}Mh(this.gameObject,this.context.connection)}}}}}var ZT=Object.defineProperty,JT=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&ZT(e,t,n),n};class sp extends T{visibleOn;onEnable(){this.apply()}apply(){this.test()||P.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:exports.DeviceUtilities.isMobileDevice()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}}JT([p()],sp.prototype,"visibleOn");class op{constructor(e){this.snapGridResolution=e}snapGridResolution;apply(e){const t=this.snapGridResolution;if(t<=0)return;const i=e.worldPosition;i.x=Math.round(i.x/t)*t,i.y=Math.round(i.y/t)*t,i.z=Math.round(i.z/t)*t,e.worldPosition=i,e.updateMatrix()}}class Nh{plane;hitPointInLocalSpace=null;snapResolution=0;constructor(e){this.plane=e}init(e){this.hitPointInLocalSpace=e.hitPointInLocalSpace}apply(e){if(!this.hitPointInLocalSpace)return;const t=this.hitPointInLocalSpace.clone();e.localToWorld(t);const i=e.worldPosition,n=i.x-t.x,o=i.y-t.y,r=i.z-t.z;let a=!1;const l=this.snapResolution;l>0&&(t.x=Math.round(t.x/l)*l,t.y=Math.round(t.y/l)*l,t.z=Math.round(t.z/l)*l,a=!0);const h=t.x,d=t.y,u=t.z;this.plane.projectPoint(t,t);const f=Math.abs(t.x-h)+Math.abs(t.y-d)+Math.abs(t.z-u)>1e-5;(a||f)&&(i.set(t.x+n,t.y+o,t.z+r),e.worldPosition=i,e.updateMatrix())}}class rp{_savedQuat=new c.Quaternion;init(e){this._savedQuat.copy(e.gameObject.worldQuaternion)}apply(e){e.worldQuaternion=this._savedQuat,e.updateMatrix()}}class bC{_savedScale=new c.Vector3(1,1,1);init(e){this._savedScale.copy(e.gameObject.worldScale)}apply(e){e.worldScale=this._savedScale,e.updateMatrix()}}const P0=new c.Vector3;class M_{constructor(e,t,i=!0){this.min=e,this.max=t,this.relativeToInitialScale=i}min;max;relativeToInitialScale;_initialWorldScale=new c.Vector3(1,1,1);init(e){const t=e.initialWorldScale??e.gameObject.worldScale;this._initialWorldScale.copy(t)}apply(e){const t=e;t.updateWorldMatrix(!0,!1);const i=t.matrixWorld.elements,n=Math.sqrt(i[0]*i[0]+i[1]*i[1]+i[2]*i[2]),o=Math.sqrt(i[4]*i[4]+i[5]*i[5]+i[6]*i[6]),r=Math.sqrt(i[8]*i[8]+i[9]*i[9]+i[10]*i[10]);P0.set(n,o,r);const a=P0;if(this.relativeToInitialScale){const l=this._initialWorldScale.length();if(l<1e-10)return;const h=a.length()/l,d=Math.max(this.min,Math.min(this.max,h));Math.abs(d-h)>1e-9&&(e.worldScale=a.copy(this._initialWorldScale).multiplyScalar(d),e.updateMatrix())}else{const l=Math.max(this.min,Math.min(this.max,a.x)),h=Math.max(this.min,Math.min(this.max,a.y)),d=Math.max(this.min,Math.min(this.max,a.z));(l!==a.x||h!==a.y||d!==a.z)&&(e.worldScale=a.set(l,h,d),e.updateMatrix())}}}class vC{constructor(e,t=!1){this.frozenAxes=e,this.useLocalSpace=t}frozenAxes;useLocalSpace;_startEuler=new c.Euler;_eulerCache=new c.Euler;init(e){const t=this.useLocalSpace?e.gameObject.quaternion:e.gameObject.worldQuaternion;this._startEuler.setFromQuaternion(t,"XYZ")}apply(e){const t=this.frozenAxes;if(t===0)return;const i=this.useLocalSpace?e.quaternion:e.worldQuaternion;this._eulerCache.setFromQuaternion(i,"XYZ"),t&1&&(this._eulerCache.x=this._startEuler.x),t&2&&(this._eulerCache.y=this._startEuler.y),t&4&&(this._eulerCache.z=this._startEuler.z),wm.setFromEuler(this._eulerCache),this.useLocalSpace?e.quaternion.copy(wm):e.worldQuaternion=wm,e.updateMatrix()}}const wm=new c.Quaternion;class O_{_startQuat=new c.Quaternion;_axis;constructor(e){this._axis=e.clone().normalize()}init(e){this._startQuat.copy(e.gameObject.worldQuaternion)}apply(e){const t=e.worldQuaternion;zd.copy(this._startQuat).invert(),er.multiplyQuaternions(t,zd);const i=this._axis.x,n=this._axis.y,o=this._axis.z,r=er.x*i+er.y*n+er.z*o,a=r*i,l=r*n,h=r*o,d=er.w,u=Math.sqrt(a*a+l*l+h*h+d*d);if(u<1e-10)e.worldQuaternion=this._startQuat;else{const f=1/u;zd.set(a*f,l*f,h*f,d*f),er.multiplyQuaternions(zd,this._startQuat),e.worldQuaternion=er}e.updateMatrix()}}const zd=new c.Quaternion,er=new c.Quaternion;class E_{constructor(e){this.plane=e}plane;_lockedHeight=0;_boundsBottomSignedDistFromPivot=0;currentScaleRatio=1;init(e){const t=e.gameObject.worldPosition;this._lockedHeight=this.plane.normal.dot(t)+this.plane.constant,this._boundsBottomSignedDistFromPivot=e.boundsAtScaleOne!==null&&e.initialWorldScale!==null?e.boundsAtScaleOne.min.y*e.initialWorldScale.y:0,this.currentScaleRatio=1}apply(e){const t=this._lockedHeight+this._boundsBottomSignedDistFromPivot*(1-this.currentScaleRatio),i=e.worldPosition,n=t-(this.plane.normal.dot(i)+this.plane.constant);Math.abs(n)>1e-9&&(i.addScaledVector(this.plane.normal,n),e.worldPosition=i,e.updateMatrix())}}class ap{constructor(e){this._context=e}_context;_gameObject=null;_boundsAtScaleOne=null;_ray=new c.Ray;_hasRay=!1;_t1=new c.Vector3;_t2=new c.Vector3;_t3=new c.Vector3;_t4=new c.Vector3;init(e){this._gameObject=e.gameObject,this._boundsAtScaleOne=e.boundsAtScaleOne,this._hasRay=!1}setRay(e,t){this._ray.origin.copy(e),this._ray.direction.copy(t),this._hasRay=!0}apply(e){if(!this._gameObject||!this._boundsAtScaleOne||!this._hasRay)return;const t=e.worldPosition,i=this._context.physics.raycastFromRay(this._ray,{testObject:a=>a!==e&&a!==this._gameObject});if(i.length===0)return;const n=i[0];if(!n.face)return;this._t2.copy(n.normal??n.face.normal).applyQuaternion(n.object.worldQuaternion);const o=this._t2;this._boundsAtScaleOne.getCenter(this._t3),this._boundsAtScaleOne.getSize(this._t4),this._t3.sub(this._t4.multiplyScalar(.5).multiply(o));const r=this._t3.dot(o);this._t3.copy(o).multiplyScalar(r),this._t4.copy(this._t3),e.localToWorld(this._t4),this._t1.copy(n.point).sub(this._t4).add(t),e.worldPosition=this._t1,e.updateMatrix()}}function wC(s,e){for(const t of e)t.apply(s)}var eA=Object.defineProperty,kn=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&eA(e,t,n),n};const ts=x("debugdrag"),xm=[];function Er(s){return s==="tracked-pointer"||s==="transient-pointer"||(N.active?.isScreenBasedAR??!1)}var R_=(s=>(s[s.XZPlane=0]="XZPlane",s[s.Attached=1]="Attached",s[s.HitNormal=2]="HitNormal",s[s.DynamicViewAngle=3]="DynamicViewAngle",s[s.SnapToSurfaces=4]="SnapToSurfaces",s[s.None=5]="None",s))(R_||{});class uf{constructor(e,t){this._dc=e,this._xr=t}_dc;_xr;get dragMode(){return this._xr?this._dc.xrDragMode:this._dc.dragMode}get keepRotation(){return this._xr?this._dc.xrKeepRotation:this._dc.keepRotation}get keepScale(){return this._xr?this._dc.xrKeepScale:this._dc.keepScale}get distanceDragFactor(){return this._xr?this._dc.xrDistanceDragFactor:1}}const sn=class Ni extends T{static get HasAnySelected(){return this._activePointers.size>0}static _activePointers=new Set;static get CurrentlySelected(){xm.length=0;for(const e of this._instances)e._isDragging&&xm.push(e);return xm}static _instances=[];dragMode=3;snapGridResolution=0;keepRotation=!0;keepScale=!1;xrDragMode=1;xrKeepRotation=!1;xrKeepScale=!1;xrDistanceDragFactor=1;screenProfile=new uf(this,!1);xrProfile=new uf(this,!0);dragStarted=new Z;dragUpdated=new Z;dragEnded=new Z;get draggedObject(){return this._targetObject}setTargetObject(e){this._targetObject=e;for(const i of this._dragHandlers.values())i.setTargetObject(e);const t="_rigidbody-was-kinematic";this._rigidbody?.[t]===!1&&(this._rigidbody.isKinematic=!1,this._rigidbody[t]=void 0),this._rigidbody=null,e&&(this._rigidbody=P.getComponentInChildren(e,Xe),this._rigidbody?.isKinematic===!1&&(this._rigidbody.isKinematic=!0,this._rigidbody[t]=!1))}_rigidbody=null;_targetObject=null;static _lastHovered;static get lastHovered(){return this._lastHovered?.deref()}static set lastHovered(e){this._lastHovered=e?new WeakRef(e):void 0}_draggingRigidbodies=[];_potentialDragStartEvt=null;_dragHandlers=new Map;_totalMovement=new c.Vector3;_marker=null;_isDragging=!1;_didDrag=!1;awake(){this._potentialDragStartEvt=null,this._dragHandlers=new Map,this._totalMovement=new c.Vector3,this._marker=null,this._isDragging=!1,this._didDrag=!1,this._draggingRigidbodies=[]}start(){this.gameObject.getComponentInParent(Ji)||this.gameObject.addComponent(Ji)}onEnable(){Ni._instances.push(this),this.context.accessibility.updateElement(this,{role:"button",label:"Drag "+(this.gameObject.name||"object"),hidden:!1})}onDisable(){this.context.accessibility.updateElement(this,{hidden:!0}),Ni._instances=Ni._instances.filter(e=>e!==this)}onDestroy(){this.context.accessibility.removeElement(this),this._isDragging&&this._cancelDrag()}allowEdit(e=null){return this.context.connection.allowEditing}onPointerEnter(e){if(!this.allowEdit(this.gameObject)||e.mode!=="screen"||(Er(e.event.mode)?this.xrDragMode:this.dragMode)===5)return;const i=P.getComponentInParent(e.object,Ni);!i||i!==this||(Ni.lastHovered=e.object,this.context.domElement.style.cursor="pointer",this.context.accessibility.hover(this,`Draggable ${e.object?.name}`))}onPointerMove(e){(this._isDragging||this._potentialDragStartEvt!==null)&&e.use()}onPointerExit(e){this.allowEdit(this.gameObject)&&e.mode==="screen"&&Ni.lastHovered===e.object&&(this.context.domElement.style.cursor="auto")}onPointerDown(e){if(!(!this.allowEdit(this.gameObject)||e.used||(Er(e.mode)?this.xrDragMode:this.dragMode)===5)&&(Ni.lastHovered=e.object,e.button===0)){this._dragHandlers.size===0&&(this._didDrag=!1,this._totalMovement.set(0,0,0),this._potentialDragStartEvt=e),this._targetObject||this.setTargetObject(this.gameObject),Ni._activePointers.add(e.event.space);const i=new Cm(this,this._targetObject);if(this._dragHandlers.set(e.event.space,i),i.onDragStart(e),this._dragHandlers.size===2){const n=this._dragHandlers.values(),o=n.next().value,r=n.next().value;if(o instanceof Cm&&r instanceof Cm){const a=new tA(this,this._targetObject,o,r);this._dragHandlers.set(this.gameObject,a),a.onDragStart(e)}else console.error("Attempting to construct a MultiTouchDragHandler with invalid DragPointerHandlers. This is likely a bug.",{a:o,b:r})}e.use(),this.context.accessibility.updateElement(this,{role:"button",label:"Dragging "+(this.gameObject.name||"object"),hidden:!1,busy:!0}),this.context.accessibility.focus(this)}}onPointerUp(e){if(ts&&B.DrawLabel(e.point??this.gameObject.worldPosition,"POINTERUP:"+e.pointerId+", "+e.button,.03,3),!this.allowEdit(this.gameObject)||e.button!==0)return;this._potentialDragStartEvt=null;const t=this._dragHandlers.get(e.event.space),i=this._dragHandlers.get(this.gameObject);i&&(i.handlerA===t||i.handlerB===t)&&(this._dragHandlers.delete(this.gameObject),i.onDragEnd(e)),t&&(Ni._activePointers.delete(e.event.space),t.onDragEnd&&t.onDragEnd(e),this._dragHandlers.delete(e.event.space),this._dragHandlers.size===0&&(this.setTargetObject(null),this.onLastDragEnd(e)),(!e.isDoubleClick||this._didDrag)&&e.use()),this.context.accessibility.unfocus(this),this.context.accessibility.updateElement(this,{busy:!1})}update(){const e=this._targetObject??this.gameObject;if(this._isDragging&&!e.parent){this._cancelDrag();return}for(const t of this._dragHandlers.values())if(t.collectMovementInfo&&t.collectMovementInfo(),t.getTotalMovement){const i=t.getTotalMovement();i.length()>this._totalMovement.length()&&this._totalMovement.copy(i)}if(this._potentialDragStartEvt){if(!this._didDrag)if(this._totalMovement.length()>3e-4)this._didDrag=!0;else return;const t=this._potentialDragStartEvt;this._potentialDragStartEvt=null,this.onFirstDragStart(t)}for(const t of this._dragHandlers.values())t.onDragUpdate&&t.onDragUpdate(this._dragHandlers.size);this._isDragging&&this.onAnyDragUpdate()}onFirstDragStart(e){if(!e||!e.object)return;const t=P.getComponentInParent(e.object,Ni);if(!t||t!==this&&t._isDragging)return;const i=this._targetObject||this.gameObject;if(!i)return;this._isDragging=!0,this.dragStarted?.invoke();const n=P.getComponentInChildren(i,Sn);ts&&console.log("DRAG START",n,i),n&&(n.fastMode=!0,n?.requestOwnership()),this._marker=P.addComponent(i,zh),this._draggingRigidbodies.length=0;const o=P.getComponentsInChildren(i,Xe);o&&this._draggingRigidbodies.push(...o),i.matrixAutoUpdate===!1&&!globalThis["DragControls:MatrixWarningShown"]&&(globalThis["DragControls:MatrixWarningShown"]=!0,console.warn("Dragging an object with matrixAutoUpdate=false can lead to unexpected behavior. Consider enabling matrixAutoUpdate or updating the matrix manually during dragging."))}onAnyDragUpdate(){for(const t of this._draggingRigidbodies)t.wakeUp(),t.resetVelocities(),t.resetForcesAndTorques();const e=this._targetObject||this.gameObject;Ki.markDirty(e),this.dragUpdated?.invoke()}_cancelDrag(){for(const e of this._dragHandlers.keys())e!==this.gameObject&&Ni._activePointers.delete(e);this._dragHandlers.clear(),this._potentialDragStartEvt=null,this.setTargetObject(null),this.onLastDragEnd(null)}onLastDragEnd(e){if(!(!this||!this._isDragging)){this._isDragging=!1,this.dragEnded?.invoke();for(const t of this._draggingRigidbodies)t.setVelocity(t.smoothedVelocity.multiplyScalar(this.context.time.deltaTime));if(this._draggingRigidbodies.length=0,this._targetObject=null,e?.object){const t=P.getComponentInChildren(e.object,Sn);t&&(t.fastMode=!1)}this._marker&&this._marker.destroy()}}};kn([p()],sn.prototype,"dragMode");kn([p()],sn.prototype,"snapGridResolution");kn([p()],sn.prototype,"keepRotation");kn([p()],sn.prototype,"keepScale");kn([p()],sn.prototype,"xrDragMode");kn([p()],sn.prototype,"xrKeepRotation");kn([p()],sn.prototype,"xrKeepScale");kn([p()],sn.prototype,"xrDistanceDragFactor");kn([p(Z)],sn.prototype,"dragStarted");kn([p(Z)],sn.prototype,"dragUpdated");kn([p(Z)],sn.prototype,"dragEnded");let vr=sn;const Nd=new c.Quaternion,k0=new c.Vector3,M0=new c.Vector3,O0=new c.Vector3,$d=new c.Vector3,Vd=new c.Vector3;class tA{handlerA;handlerB;context;settings;gameObject;_handlerAAttachmentPoint=new c.Vector3;_handlerBAttachmentPoint=new c.Vector3;_followObject;_manipulatorObject;_deviceMode;_followObjectStartWorldQuaternion=new c.Quaternion;_gridSnapConstraint=new op(0);_keepRotationConstraint=new rp;_planeConstraint=null;_snapToSurfaceConstraint=null;_activeConstraints=[];constructor(e,t,i,n){if(this.context=e.context,this.settings=e,this.gameObject=t,this.handlerA=i,this.handlerB=n,this._followObject=new c.Object3D,this._manipulatorObject=new c.Object3D,this.context.scene.add(this._manipulatorObject),!this.handlerA||!this.handlerB||!this.handlerA.hitPointInLocalSpace||!this.handlerB.hitPointInLocalSpace){console.error("Invalid: MultiTouchDragHandler needs two valid DragPointerHandlers with hitPointInLocalSpace set.");return}if(this._tempVec1.copy(this.handlerA.hitPointInLocalSpace),this._tempVec2.copy(this.handlerB.hitPointInLocalSpace),this.gameObject.localToWorld(this._tempVec1),this.gameObject.localToWorld(this._tempVec2),this._initialDistance=this._tempVec1.distanceTo(this._tempVec2),this._initialDistance<.02?(ts&&console.log("Finding alternative drag attachment points since initial distance is too low: "+this._initialDistance.toFixed(2)),this.handlerA.followObject.parent.getWorldPosition(this._tempVec1),this.handlerB.followObject.parent.getWorldPosition(this._tempVec2),this._handlerAAttachmentPoint.copy(this._tempVec1),this._handlerBAttachmentPoint.copy(this._tempVec2),this.gameObject.worldToLocal(this._handlerAAttachmentPoint),this.gameObject.worldToLocal(this._handlerBAttachmentPoint),this._initialDistance=this._tempVec1.distanceTo(this._tempVec2),this._initialDistance<.001&&(console.warn("Not supported right now - controller drag points for multitouch are too close!"),this._initialDistance=1)):(this._handlerAAttachmentPoint.copy(this.handlerA.hitPointInLocalSpace),this._handlerBAttachmentPoint.copy(this.handlerB.hitPointInLocalSpace)),this._tempVec3.lerpVectors(this._tempVec1,this._tempVec2,.5),ts){this._followObject.add(new c.AxesHelper(2)),this._manipulatorObject.add(new c.AxesHelper(5));const o=r=>`${r.x.toFixed(2)}, ${r.y.toFixed(2)}, ${r.z.toFixed(2)}`;B.DrawLine(this._tempVec1,this._tempVec2,65535,0,!1),B.DrawLabel(this._tempVec3,"A:B "+this._initialDistance.toFixed(2)+`
@@ -1404,7 +1404,7 @@ ${new Error().stack}`:""}`),r}switch(i){case"unsupported":return null;default:ca
1404
1404
  Use import { NeedleEngineModelLoader } from "@needle-tools/engine" namespace to register your loader.`,s);const n=new V.GLTFLoader;return await mf(n,e,s,t),n}case"model/fbx":case"model/vnd.autodesk.fbx":return new V.FBXLoader;case"model/obj":return new V.OBJLoader;case"model/vnd.usdz+zip":case"model/vnd.usd+zip":case"model/vnd.usda+zip":return console.warn(i.toUpperCase()+" files are not supported."),null;case"model/gltf+json":case"model/gltf-binary":case"model/vrm":{const n=new V.GLTFLoader;return await mf(n,e,s,t),n}case"application/materialx+xml":return new EA}}function C1(s,e){return db(e?.context||X.Current,s,s,e?.seed||null,e?.onprogress)}async function vp(s,e,t,i,n){typeof t!="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",t,typeof t),t=""),w1&&console.log("Parse glTF",t);const o=await x1(s,e,t);if(o)return o;const r=await S1(t,s,t);if(!r)return;const{componentsExtension:a}=P1(r,s);if(r instanceof V.OBJLoader){typeof e!="string"&&(e=new TextDecoder().decode(e));const d=r.parse(e);return await Xc(r,s,t,d,i,a)}if(!(r instanceof V.GLTFLoader)){if(!("parse"in r)||typeof r.parse!="function"){console.error("Loader does not support parse");return}const d=await r.parse(e,t);return await Xc(r,s,t,d,i,a)}let h=n?.resolveUrl;return!h&&_1(t)&&(h=await b1(t)??void 0),new Promise((d,u)=>{try{let f=t.split("?")[0].trimEnd();const m=f.split("/");if(m.length>0&&m[m.length-1]!==""&&m.pop(),f=m.join("/"),f.endsWith("/")||(f+="/"),r.resourcePath=f,h){const g=new c.LoadingManager;g.resolveURL=h,r.manager=g}r.parse(e,"",async g=>{const v=await Xc(r,s,t,g,i,a);d(v)},g=>{console.error('Loading asset at "'+t+`" failed
1405
1405
  `,g),d(void 0)})}catch(f){console.error(f),u(f)}})}async function db(s,e,t,i,n){if(TI(e),e.split("?")[0].toLowerCase().endsWith(".json")){const a=await fetch(e).then(l=>l.ok?l.text():null).catch(()=>null);if(a!==null){const l=await x1(s,a,e,n);return l||vp(s,a,e,i)}}const o=await S1(e,s,t);if(!o)return;const{componentsExtension:r}=P1(o,s);if(!(o instanceof V.GLTFLoader)){const a=await o.loadAsync(e,n);return await Xc(o,s,e,a,i,r)}if(_1(e)){const a=await b1(e);if(a){const l=new c.LoadingManager;l.resolveURL=a,o.manager=l}}return new Promise((a,l)=>{try{o.load(e,async h=>{const d=await Xc(o,s,t,h,i,r);a(d)},h=>{n?.call(o,h)},h=>{console.error('Loading asset at "'+e+`" failed
1406
1406
  `,h),a(void 0)})}catch(h){console.error(h),l(h)}})}function P1(s,e){const t=I_(s);return s instanceof V.GLTFLoader&&r1(s,e),{componentsExtension:t}}async function Xc(s,e,t,i,n,o){if(w1&&console.warn("Loaded",t,i),i==null)return console.error(`Loaded model is null '${t}' - please make sure the loader is registered correctly`),{scene:new c.Object3D,animations:[],scenes:[]};if(typeof i!="object")return console.error(`Loaded model is not an object '${t}' - please make sure the loader is registered correctly`),{scene:new c.Object3D,animations:[],scenes:[]};if(i instanceof c.Object3D)i={scene:i,animations:i.animations,scenes:[i]};else if(i instanceof c.BufferGeometry){const r=new c.MeshStandardMaterial({color:new c.Color(14540253)}),a=new c.Mesh(i,r);i={scene:a,animations:[],scenes:[a]}}else Array.isArray(i.scenes)===!1&&console.error(`[Needle Engine] The loaded model object does not have a scenes property '${t}' - please make sure the loader is registered correctly and three.js is not imported multiple times.`);return t.includes("?")&&(t=t.split("?")[0]),AI(s,i),dx(i)&&(EI(i),OC(t,i,e),await Is().createBuiltinComponents(e,t,i,n,o||void 0)),i.scene&&await RI(i.scene,e,e.mainCamera),i}function EI(s){const e=s.parser;e?.json&&ee.attachNeedleIdsToLoadedGltf(e.json,e.associations,s.scenes);const t=e?.associations;if(t)for(const[i,n]of t){if(n==null)continue;const o=i;!o||typeof o!="object"||o.userData&&o.userData.associations===void 0&&(o.userData.associations=n)}}async function RI(s,e,t){t||(t=e.mainCamera);try{t?await e.renderer.compileAsync(s,t,e.scene).catch(i=>{console.warn(i.message)}):$E(s,e)}catch(i){console.warn(i?.message||i)}}function TI(s){if(new URL(s,window.location.href).href.startsWith("file://")){const t=`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.
1407
- Please refer to the documentation on <a href="https://fwd.needle.tools/needle-engine/docs/local-server">https://docs.needle.tools</a> or ask for help in our <a href="https://discord.needle.tools">discord community</a>`;Re(t),console.warn(t)}}function AI(s,e){if("scenes"in e){for(const t of e.scenes)if(t&&!t.animations?.length)for(const i of e.animations)t.animations.includes(i)||t.animations.push(i)}if(s instanceof V.FBXLoader||s instanceof V.OBJLoader){let t=e;t instanceof c.Object3D||(t=e.scene||e.scenes.find(i=>i)),t.traverse(i=>{const n=i;n?.isMesh&&Dy(n,n.material)})}}var DI=Object.defineProperty,II=Object.getOwnPropertyDescriptor,wp=(s,e,t,i)=>{for(var n=II(e,t),o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&DI(e,t,n),n};class Kr extends T{set url(e){e!==this._url&&(this._url=e,e&&this.__internalDidAwake&&this.activeAndEnabled&&!this._loading&&this.load(e))}get url(){return this._url}_url;set opacity(e){this._opacity=e,this._splatMesh&&(this._splatMesh.opacity=e,this._splatMesh.updateVersion())}get opacity(){return this._opacity}_opacity=1;set raycastable(e){this._raycastable=e,this._splatMesh&&(this._splatMesh.raycastable=e)}get raycastable(){return this._raycastable}_raycastable=!0;set quality(e){e!==this._quality&&(this._quality=e,this._splatMesh&&Tg(this.context,this._splatMesh,e))}get quality(){return this._quality}_quality="auto";get splatMesh(){return this._splatMesh}get isLoaded(){return this._splatMesh?.isInitialized===!0}get initialized(){return this._initialized}_splatMesh=null;_initialized=Promise.resolve();_loading=!1;_loadGeneration=0;awake(){this._loadGeneration++,this._splatMesh=null,this._initialized=Promise.resolve(),this._loading=!1}onEnable(){this.url&&!this._splatMesh&&!this._loading&&this.load(this.url),this._splatMesh&&(this._splatMesh.visible=!0,this._splatMesh.updateVersion())}onDisable(){this._splatMesh&&(this._splatMesh.visible=!1,this._splatMesh.updateVersion())}onDestroy(){this._splatMesh&&(this._splatMesh.removeFromParent(),this._splatMesh.dispose(),this._splatMesh=null)}async load(e){const t=++this._loadGeneration;this._url=e,this._splatMesh&&(this._splatMesh.removeFromParent(),this._splatMesh.dispose(),this._splatMesh=null),this._loading=!0;const i=await C1(e,{context:this.context});if(t!==this._loadGeneration||this.destroyed)return i?.scene?.dispose(),null;const n=i?.scene;return n?(n.name="Gaussian Splat",n.hideFlags|=as.DontExport|as.DontInstantiate,n.opacity=this._opacity,n.raycastable=this.raycastable,this._splatMesh=n,this.gameObject.add(n),this.activeAndEnabled||(n.visible=!1),this._initialized=n.initialized.then(()=>{t===this._loadGeneration&&(this._loading=!1)}),await this._initialized,t!==this._loadGeneration||this.destroyed?null:(Tg(this.context,n,this._quality),n)):(this._loading=!1,null)}}wp([p(URL)],Kr.prototype,"url");wp([p()],Kr.prototype,"opacity");wp([p()],Kr.prototype,"raycastable");wp([p()],Kr.prototype,"quality");var LI=Object.defineProperty,ub=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&LI(e,t,n),n};class Zr extends T{objectBounds=!1;color;isGizmo=!0;_gizmoObject=null;_boxHelper=null;onEnable(){this.isGizmo&&!Oh||(this._gizmoObject||(this.objectBounds?this._gizmoObject=new c.BoxHelper(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=s_(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),Ce.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){for(;this._boxHelper;)this._boxHelper?.update(),yield}}ub([p()],Zr.prototype,"objectBounds");ub([p(c.Color)],Zr.prototype,"color");ub([p()],Zr.prototype,"isGizmo");var BI=Object.defineProperty,fb=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&BI(e,t,n),n};class jl extends T{isGizmo=!1;color0;color1;gridHelper;size;divisions;offset;onEnable(){if(this.isGizmo&&!Oh)return;const e=this.size,t=this.divisions;this.gridHelper||(this.gridHelper=new c.GridHelper(e,t,this.color0??new c.Color(.4,.4,.4),this.color1??new c.Color(.6,.6,.6)),this.offset!==void 0&&(this.gridHelper.position.y+=this.offset)),this.gridHelper&&this.gameObject.add(this.gridHelper)}onDisable(){this.gridHelper&&(this.gameObject.remove(this.gridHelper),this.gridHelper=null)}}fb([p()],jl.prototype,"isGizmo");fb([p(c.Color)],jl.prototype,"color0");fb([p(c.Color)],jl.prototype,"color1");var FI=Object.defineProperty,pb=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&FI(e,t,n),n};class mb extends T{connectedBody;get rigidBody(){return this._rigidBody}_rigidBody=null;_jointHandle=null;onEnable(){this._rigidBody||(this._rigidBody=this.gameObject.getComponent(Xe)),this.rigidBody&&this.connectedBody&&this.startCoroutine(this.create())}onDisable(){this._jointHandle&&(this.context.physics.engine?.removeJoint(this._jointHandle),this._jointHandle=null)}*create(){if(yield,!this._jointHandle&&this.rigidBody&&this.connectedBody&&this.activeAndEnabled){const e=this.createJoint(this.rigidBody,this.connectedBody);e instanceof Promise?yield e.then(t=>this._jointHandle=t):this._jointHandle=e}}}pb([p(Xe)],mb.prototype,"connectedBody");class gb extends mb{createJoint(e,t){return this.context.physics.engine?.addFixedJoint(e,t)??null}}class Kh extends mb{anchor;axis;createJoint(e,t){return this.axis&&this.anchor?this.context.physics.engine?.addHingeJoint(e,t,this.anchor,this.axis)??null:null}}pb([p(c.Vector3)],Kh.prototype,"anchor");pb([p(c.Vector3)],Kh.prototype,"axis");var jI=Object.defineProperty,UI=Object.getOwnPropertyDescriptor,Bi=(s,e,t,i)=>{for(var n=i>1?void 0:i?UI(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&jI(e,t,n),n};function Pa(s){return s*Math.PI/180}const ow=300,Bn=x("debuglights");var fy=(s=>(s[s.Spot=0]="Spot",s[s.Directional=1]="Directional",s[s.Point=2]="Point",s[s.Area=3]="Area",s[s.Rectangle=3]="Rectangle",s[s.Disc=4]="Disc",s))(fy||{});class Lt extends T{get type(){return this._type}set type(e){if(this.light&&this.__didAwake)throw new Error("Changing the light type at runtime is not supported");switch(e){case 1:this._type="directional";break;case 2:this._type="point";break;case 0:this._type="spot";break;case"directional":case"point":case"spot":this._type=e;break;default:(Bn||E())&&console.warn(`[Light] Unsupported light type: ${fy[e]} (${e}) on '${this.name}'`),this._type="unsupported";break}}_type="point";get range(){return this._range}set range(e){this._range=e,this.light&&(this.light.type==="SpotLight"||this.light.type==="PointLight")&&"distance"in this.light&&(this.light.distance=e)}_range=1;get spotAngle(){return this._spotAngle}set spotAngle(e){this._spotAngle=e,this.light&&this.light.type==="SpotLight"&&"angle"in this.light&&(this.light.angle=Pa(e/2))}_spotAngle=30;get innerSpotAngle(){return this._innerSpotAngle}set innerSpotAngle(e){if(this._innerSpotAngle=e,this.light&&this.light.type==="SpotLight"&&"penumbra"in this.light){const t=this.spotAngle,n=1-Pa(e/2)/Pa(t/2);this.light.penumbra=n}}_innerSpotAngle=10;set color(e){this._color=e,this.light!==void 0&&(this.light.color=e)}get color(){return this.light?this.light.color:this._color}_color=new c.Color(16777215);set shadowNearPlane(e){if(e!==this._shadowNearPlane&&(this._shadowNearPlane=e,this.shadowLight?.shadow?.camera!==void 0)){const t=this.shadowLight.shadow.camera;t.near=e}}get shadowNearPlane(){return this._shadowNearPlane}_shadowNearPlane=.1;set shadowBias(e){e!==this._shadowBias&&(this._shadowBias=e,this.shadowLight?.shadow?.bias!==void 0&&(this.shadowLight.shadow.bias=e,this.shadowLight.shadow.needsUpdate=!0))}get shadowBias(){return this._shadowBias}_shadowBias=0;set shadowNormalBias(e){e!==this._shadowNormalBias&&(this._shadowNormalBias=e,this.shadowLight?.shadow?.normalBias!==void 0&&(this.shadowLight.shadow.normalBias=e,this.shadowLight.shadow.needsUpdate=!0))}get shadowNormalBias(){return this._shadowNormalBias}_shadowNormalBias=0;_overrideShadowBiasSettings=!1;set shadows(e){this._shadows=e,this.light&&(this.light.castShadow=e!==0,this.updateShadowSoftHard())}get shadows(){return this._shadows}_shadows=1;lightmapBakeType=4;set intensity(e){this._intensity=e,this.light&&(this.light.intensity=e),Bn&&console.log("Set light intensity to "+this._intensity,e,this)}get intensity(){return this._intensity}_intensity=-1;get shadowDistance(){const e=this.shadowLight;return e?.shadow?e.shadow.camera.far:-1}set shadowDistance(e){this._shadowDistance=e;const t=this.shadowLight;if(t?.shadow){const i=t.shadow.camera;i.far=e,i.updateProjectionMatrix()}}_shadowDistance;shadowWidth;shadowHeight;get shadowResolution(){const e=this.shadowLight;return e?.shadow?e.shadow.mapSize.x:-1}set shadowResolution(e){if(e===this._shadowResolution)return;this._shadowResolution=e;const t=this.shadowLight;t?.shadow&&(t.shadow.mapSize.set(e,e),t.shadow.needsUpdate=!0)}_shadowResolution=void 0;get isBaked(){return this.lightmapBakeType===2}get selfIsLight(){if(this.gameObject.isLight===!0)return!0;switch(this.gameObject.type){case"SpotLight":case"PointLight":case"DirectionalLight":return!0}return!1}light=void 0;get shadowLight(){const e=this.light;if(e&&"shadow"in e)return e}getWorldPosition(e){return this.light?this.type==="directional"?this.light.getWorldPosition(e).multiplyScalar(1):this.light.getWorldPosition(e):e}awake(){this.color=new c.Color(this.color??16777215),Bn&&console.log(this.name,this)}onEnable(){Bn&&console.log("ENABLE LIGHT",this.name),this.createLight(),!this.isBaked&&(this.light&&(this.light.visible=!0,this.light.intensity=this._intensity,Bn&&console.log("Set light intensity to "+this.light.intensity,this.name),this.selfIsLight||this.light.parent!==this.gameObject&&this.gameObject.add(this.light)),this.context.lights.push(this))}onDisable(){Bn&&console.log("DISABLE LIGHT",this.name);const e=this.context.lights.indexOf(this);e!==-1&&this.context.lights.splice(e,1),this.light&&(this.selfIsLight?this.light.intensity=0:this.light.visible=!1)}createLight(){const e=this.selfIsLight;if(e&&!this.light)this.light=this.gameObject,this.light.name=this.name,this._intensity=this.light.intensity,this.type==="directional"&&this.setDirectionalLight(this.light);else if(!this.light)switch(this.type){case"directional":const t=new c.DirectionalLight(this.color,this.intensity*Math.PI);if(t.position.set(0,0,-ow*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(t.target),Ar(t.target,0,0,0),this.light=t,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),Bn){const r=new c.DirectionalLightHelper(this.light,.2,this.color);this.context.scene.add(r)}break;case"spot":const i=new c.SpotLight(this.color,this.intensity*Math.PI,this.range,Pa(this.spotAngle/2),1-Pa(this.innerSpotAngle/2)/Pa(this.spotAngle/2),2);i.position.set(0,0,0),i.rotation.set(0,0,0),this.light=i;const n=i.target;i.add(n),n.position.set(0,0,this.range),n.rotation.set(0,0,0);break;case"point":const o=new c.PointLight(this.color,this.intensity*Math.PI,this.range);this.light=o;break;default:Bn&&console.warn(`[Light] Unsupported light type: ${fy[this.type]} (${this.type}) on '${this.name}'`);break}if(this.light){if(this._intensity>=0?this.light.intensity=this._intensity:this._intensity=this.light.intensity,this.shadows!==0?this.light.castShadow=!0:this.light.castShadow=!1,this.shadowLight?.shadow){this._shadowResolution!==void 0&&this._shadowResolution>4?(this.shadowLight.shadow.mapSize.width=this._shadowResolution,this.shadowLight.shadow.mapSize.height=this._shadowResolution):(this.shadowLight.shadow.mapSize.width=2048,this.shadowLight.shadow.mapSize.height=2048),Bn&&console.log("Override shadow bias?",this._overrideShadowBiasSettings,this.shadowBias,this.shadowNormalBias),this.shadowLight.shadow.bias=this.shadowBias,this.shadowLight.shadow.normalBias=this.shadowNormalBias,this.updateShadowSoftHard();const t=this.shadowLight.shadow.camera;if(t.near=this.shadowNearPlane,this._shadowDistance!==void 0&&typeof this._shadowDistance=="number"?t.far=this._shadowDistance:t.far=ow*Math.abs(this.gameObject.scale.z),this.gameObject.scale.set(1,1,1),this.shadowWidth!==void 0)t.left=-this.shadowWidth/2,t.right=this.shadowWidth/2;else{const i=this.gameObject.scale.x;t.left*=i,t.right*=i}if(this.shadowHeight!==void 0)t.top=this.shadowHeight/2,t.bottom=-this.shadowHeight/2;else{const i=this.gameObject.scale.y;t.top*=i,t.bottom*=i}this.shadowLight.shadow.needsUpdate=!0,Bn&&this.context.scene.add(new c.CameraHelper(t))}this.isBaked?this.light.removeFromParent():e||this.gameObject.add(this.light)}}static allowChangingRendererShadowMapType=!0;updateShadowSoftHard(){this.light&&this.shadowLight.shadow&&(this.shadows===2||(this.shadowLight.shadow.radius=1,this.shadowLight.shadow.blurSamples=1))}onEnterXR(e){this.applyXRScale(e.xr.rigScale)}onUpdateXR(e){this.applyXRScale(e.xr.rigScale)}onLeaveXR(e){this.applyXRScale(1)}applyXRScale(e){this.light&&("distance"in this.light?(this.light.intensity=this._intensity/e,this.light.distance=this._range/e):this.light.intensity=this._intensity)}setDirectionalLight(e){e.add(e.target),e.target.position.set(0,0,-1)}}Bi([p()],Lt.prototype,"type",1);Bi([p()],Lt.prototype,"range",1);Bi([p()],Lt.prototype,"spotAngle",1);Bi([p()],Lt.prototype,"innerSpotAngle",1);Bi([p(c.Color)],Lt.prototype,"color",1);Bi([p()],Lt.prototype,"shadowNearPlane",1);Bi([p()],Lt.prototype,"shadowBias",1);Bi([p()],Lt.prototype,"shadowNormalBias",1);Bi([p()],Lt.prototype,"shadows",1);Bi([p()],Lt.prototype,"lightmapBakeType",2);Bi([p()],Lt.prototype,"intensity",1);Bi([p()],Lt.prototype,"shadowDistance",1);Bi([p()],Lt.prototype,"shadowResolution",1);var zI=Object.defineProperty,xp=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&zI(e,t,n),n};const Vm=x("debuglods"),NI=x("nolods");class Ul{screenRelativeTransitionHeight;distance;renderers}xp([p()],Ul.prototype,"screenRelativeTransitionHeight");xp([p()],Ul.prototype,"distance");xp([p(ti)],Ul.prototype,"renderers");class $I{model;get renderers(){return this.model.renderers}constructor(e){this.model=e}}class Sp extends T{lodModels=[];_lods=[];_settings=[];_lodsHandler;start(){if(Vm&&console.log("LODGROUP",this.name,this.lodModels,this),!NI&&!this._lodsHandler&&this.gameObject&&this.lodModels&&Array.isArray(this.lodModels)){const e=[];for(const i of this.lodModels){const n=new $I(i);this._lods.push(n);for(const o of n.renderers)e.includes(o)||e.push(o)}this._lodsHandler=new Array;for(let i=0;i<e.length;i++){const n=new c.LOD;this._lodsHandler.push(n),this.gameObject.add(n)}const t=new c.Object3D;t.name="Cull "+this.name;for(let i=0;i<e.length;i++){const n=e[i],o=this._lodsHandler[i],r=n.gameObject;Vm&&console.log(i,r.name);for(const a of this._lods){const l=a.model.distance;let h=null;if(a.renderers.includes(n)?h=r:h=t,h.type==="Group"){console.warn(`LODGroup ${this.name}: Group or MultiMaterial object's are not supported as LOD object: ${h.name}`);continue}Vm&&console.log("LEVEL",h.name,l),o.autoUpdate=!1,this.onAddLodLevel(o,h,a.model.distance)}}}}onAfterRender(){if(!this.gameObject||!this._lodsHandler)return;const e=this.context.mainCamera;if(e)for(const t of this._lodsHandler){t.update(e);const i=t.getCurrentLevel(),n=t.levels[i];t.layers.mask=n.object.layers.mask}}onAddLodLevel(e,t,i){if(t===this.gameObject){console.warn("LODGroup component must be on parent object and not mesh directly at the moment",t.name,t);return}e.addLevel(t,i*this._distanceFactor,.01);const n={lod:e,levelIndex:e.levels.length-1,distance:i};this._settings.push(n)}_distanceFactor=1;distanceFactor(e){if(e!==this._distanceFactor){this._distanceFactor=e;for(const t of this._settings){const i=t.lod.levels[t.levelIndex];i.distance=t.distance*e}}}}xp([p(Ul)],Sp.prototype,"lodModels");var VI=Object.defineProperty,yb=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&VI(e,t,n),n};const nu=x("debugnestedgltf");class zl extends T{filePath;loaded=new Z;loadAssetInParent=!0;_isLoadingOrDoneLoading=!1;listenToProgress(e){this.filePath?.beginListenDownload(e)}preload(){return this.filePath?.preload()||null}async start(){if(this._isLoadingOrDoneLoading)return;nu&&console.log(this,this.guid);const e=this.gameObject.parent;if(e&&this.filePath){this._isLoadingOrDoneLoading=!0;const t=new hs;t.idProvider=new ot(this.hash(this.guid)),t.parent=this.loadAssetInParent!==!1?e:this.gameObject,this.gameObject.updateMatrix();const i=this.gameObject.matrix;nu&&console.log("Load nested:",this.filePath?.url??this.filePath,this.gameObject.position);const n=await this.filePath?.instantiate?.call(this.filePath,t);nu&&console.log("Nested loaded:",this.filePath?.url??this.filePath,n),n&&this.loadAssetInParent!==!1&&(n.matrixAutoUpdate=!1,n.matrix.identity(),n.applyMatrix4(i),n.matrixAutoUpdate=!0,n.layers.disableAll(),n.layers.set(this.layer),this.loaded.invoke({component:this,instance:n,asset:this.filePath})),nu&&console.log("Nested loading done:",this.filePath?.url??this.filePath,n)}}onDestroy(){this.filePath?.unload()}hash(e){let t=0;for(let i=0;i<e.length;i++)t=e.charCodeAt(i)+((t<<5)-t);return t}}yb([p(J)],zl.prototype,"filePath");yb([p(Z)],zl.prototype,"loaded");yb([p()],zl.prototype,"loadAssetInParent");var WI=Object.defineProperty,_b=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&WI(e,t,n),n};const GI=x("debugnet"),Cp=class py extends T{url=null;urlParameterName=null;localhost=null;awake(){GI&&console.log(this),this.context.connection.registerProvider(this)}getWebsocketUrl(){let e=this.url?py.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){const o=x(this.urlParameterName);o&&typeof o=="string"&&(e=o)}if(!e)return null;const i=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(e);return i?.groups?i?.groups.socket_prefix?e:"wss://"+i?.groups.url:null}static GetUrl(e,t){let i=e;const n=py.IsLocalNetwork()&&t;if(n&&(i=t),e?.startsWith("/")){const o=n?i:window.location.origin;o?.endsWith("/")&&e.startsWith("/")&&(e=e.substring(1)),i=o+e}return i}static IsLocalNetwork(e=window.location.hostname){return ki(e)}};_b([p()],Cp.prototype,"url");_b([p()],Cp.prototype,"urlParameterName");_b([p()],Cp.prototype,"localhost");let bb=Cp;var HI=Object.defineProperty,Pp=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&HI(e,t,n),n};class Jr extends T{referenceSpace;from;affectPosition=!1;affectRotation=!1;alignLookDirection=!1;levelLookDirection=!1;levelPosition=!1;positionOffset=new c.Vector3(0,0,0);rotationOffset=new c.Vector3(0,0,0);offset=new c.Vector3(0,0,0);update(){if(!this.from)return;var e=ie(this.from),t=Se(this.from);this.offset.copy(this.positionOffset);const i=this.offset.length();if(this.referenceSpace&&this.offset.transformDirection(this.referenceSpace.matrixWorld).multiplyScalar(i),e.add(this.offset),this.levelPosition&&this.referenceSpace){const a=new c.Plane(this.gameObject.up,0),l=ie(this.referenceSpace);a.setFromNormalAndCoplanarPoint(this.gameObject.up,l);const h=new c.Vector3(0,0,0);a.projectPoint(e,h),e.copy(h)}this.affectPosition&&Oi(this.gameObject,e);const n=new c.Euler(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),o=new c.Quaternion().setFromEuler(n);this.affectRotation&&vn(this.gameObject,t.multiply(o));const r=new c.Vector3;this.from.getWorldDirection(r).multiplyScalar(50),this.levelLookDirection&&(r.y=0),this.alignLookDirection&&this.gameObject.lookAt(r)}}Pp([p(P)],Jr.prototype,"referenceSpace");Pp([p(P)],Jr.prototype,"from");Pp([p(c.Vector3)],Jr.prototype,"positionOffset");Pp([p(c.Vector3)],Jr.prototype,"rotationOffset");var qI=Object.defineProperty,$o=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&qI(e,t,n),n};class ui{time=0;value=0;inTangent=1/0;inWeight;outTangent=1/0;outWeight;weightedMode;constructor(e=0,t=0){this.time=e,this.value=t}}$o([p()],ui.prototype,"time");$o([p()],ui.prototype,"value");$o([p()],ui.prototype,"inTangent");$o([p()],ui.prototype,"inWeight");$o([p()],ui.prototype,"outTangent");$o([p()],ui.prototype,"outWeight");$o([p()],ui.prototype,"weightedMode");const k1=class Ac{static linearFromTo(e,t,i){const n=new Ac,o=new ui;o.time=0,o.value=e;const r=new ui;return r.time=i,r.value=t,n.keys.push(o,r),n}static constant(e){const t=new Ac,i=new ui;return i.time=0,i.value=e,t.keys.push(i),t}keys=[];clone(){const e=new Ac;return e.keys=this.keys?.map(t=>{const i=new ui;return i.time=t.time,i.value=t.value,i.inTangent=t.inTangent,i.inWeight=t.inWeight,i.outTangent=t.outTangent,i.outWeight=t.outWeight,i.weightedMode=t.weightedMode,i})||[],e}get duration(){return!this.keys||this.keys.length==0?0:this.keys[this.keys.length-1].time}evaluate(e){if(!this.keys||this.keys.length==0)return 0;if(this.keys.length===1)return this.keys[0].value;if(this.keys[0].time>=e)return this.keys[0].value;for(let t=0;t<this.keys.length;t++){const i=this.keys[t];if(i.time<=e)if(t+1<this.keys.length){const o=this.keys[t+1];if(o.time<e)continue;return!isFinite(i.outTangent)||!isFinite(o.inTangent)?i.value:Ac.interpolateValue(e,i,o)}else return i.value}return this.keys[this.keys.length-1].value}static interpolateValue(e,t,i){const n=t.time,o=t.value,r=t.outTangent,a=i.time,l=i.value,h=i.inTangent,d=a-n,u=d*d,f=u*d,m=((r+h)*d-2*(l-o))/f,g=(3*(l-o)-(h+2*r)*d)/u,v=r,_=o,y=e-n,b=y*y,w=b*y;return m*w+g*b+v*y+_}};$o([p(ui)],k1.prototype,"keys");let Zh=k1;var XI=Object.defineProperty,S=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&XI(e,t,n),n};const su=x("debugparticles");var ks=(s=>(s[s.Billboard=0]="Billboard",s[s.Stretch=1]="Stretch",s[s.HorizontalBillboard=2]="HorizontalBillboard",s[s.VerticalBillboard=3]="VerticalBillboard",s[s.Mesh=4]="Mesh",s))(ks||{});class ea{alphaKeys=[];colorKeys=[];get duration(){return 1}evaluate(e,t){let i,n=0,o=null,r=0;for(let a=0;a<this.alphaKeys.length;a++){const l=this.alphaKeys[a];(l.time<e||!i)&&(i=l,n=a)}for(let a=0;a<this.colorKeys.length;a++){const l=this.colorKeys[a];(l.time<e||!o)&&(o=l,r=a)}if(o)if(r+1<this.colorKeys.length){const l=this.colorKeys[r+1],h=L.remap(e,o.time,l.time,0,1);t.r=L.lerp(o.color.r,l.color.r,h),t.g=L.lerp(o.color.g,l.color.g,h),t.b=L.lerp(o.color.b,l.color.b,h)}else t.r=o.color.r,t.g=o.color.g,t.b=o.color.b;if(i)if(n+1<this.alphaKeys.length){const l=this.alphaKeys[n+1],h=L.remap(e,i.time,l.time,0,1);t.alpha=L.lerp(i.alpha,l.alpha,h)}else t.alpha=i.alpha;return t}}S([p()],ea.prototype,"alphaKeys");S([p()],ea.prototype,"colorKeys");var bh=(s=>(s[s.Local=0]="Local",s[s.World=1]="World",s[s.Custom=2]="Custom",s))(bh||{}),vf=(s=>(s[s.Sphere=0]="Sphere",s[s.SphereShell=1]="SphereShell",s[s.Hemisphere=2]="Hemisphere",s[s.HemisphereShell=3]="HemisphereShell",s[s.Cone=4]="Cone",s[s.Box=5]="Box",s[s.Mesh=6]="Mesh",s[s.ConeShell=7]="ConeShell",s[s.ConeVolume=8]="ConeVolume",s[s.ConeVolumeShell=9]="ConeVolumeShell",s[s.Circle=10]="Circle",s[s.CircleEdge=11]="CircleEdge",s[s.SingleSidedEdge=12]="SingleSidedEdge",s[s.MeshRenderer=13]="MeshRenderer",s[s.SkinnedMeshRenderer=14]="SkinnedMeshRenderer",s[s.BoxShell=15]="BoxShell",s[s.BoxEdge=16]="BoxEdge",s[s.Donut=17]="Donut",s[s.Rectangle=18]="Rectangle",s[s.Sprite=19]="Sprite",s[s.SpriteRenderer=20]="SpriteRenderer",s))(vf||{});const Hs=class Dc{static constant(e){const t=new Dc;return t.setConstant(e),t}static betweenTwoConstants(e,t){const i=new Dc;return i.setMinMaxConstant(e,t),i}static curve(e,t=1){const i=new Dc;return i.setCurve(e,t),i}setConstant(e){this.mode=0,this.constant=e}setMinMaxConstant(e,t){this.mode=3,this.constantMin=e,this.constantMax=t}setCurve(e,t=1){this.mode=1,this.curve=e,this.curveMultiplier=t}mode="Constant";constant;constantMin;constantMax;curve;curveMin;curveMax;curveMultiplier;clone(){const e=new Dc;return e.mode=this.mode,e.constant=this.constant,e.constantMin=this.constantMin,e.constantMax=this.constantMax,e.curve=this.curve?.clone(),e.curveMin=this.curveMin?.clone(),e.curveMax=this.curveMax?.clone(),e.curveMultiplier=this.curveMultiplier,e}evaluate(e,t){const i=t===void 0?Math.random():t;switch(this.mode){case 0:case"Constant":return this.constant;case 1:case"Curve":return e=L.clamp01(e),this.curve.evaluate(e)*this.curveMultiplier;case 2:case"TwoCurves":const n=e*this.curveMin.duration,o=e*this.curveMax.duration;return L.lerp(this.curveMin.evaluate(n),this.curveMax.evaluate(o),i%1)*this.curveMultiplier;case 3:case"TwoConstants":return L.lerp(this.constantMin,this.constantMax,i%1);default:this.curveMax.evaluate(e)*this.curveMultiplier;break}return 0}getMax(){switch(this.mode){case 0:case"Constant":return this.constant;case 1:case"Curve":return this.getMaxFromCurve(this.curve)*this.curveMultiplier;case 2:case"TwoCurves":return Math.max(this.getMaxFromCurve(this.curveMin),this.getMaxFromCurve(this.curveMax))*this.curveMultiplier;case 3:case"TwoConstants":return Math.max(this.constantMin,this.constantMax);default:return 0}}getMaxFromCurve(e){if(!e)return 0;let t=Number.MIN_VALUE;for(let i=0;i<e.keys.length;i++){const n=e.keys[i];n.value>t&&(t=n.value)}return t}};S([p()],Hs.prototype,"mode");S([p()],Hs.prototype,"constant");S([p()],Hs.prototype,"constantMin");S([p()],Hs.prototype,"constantMax");S([p(Zh)],Hs.prototype,"curve");S([p(Zh)],Hs.prototype,"curveMin");S([p(Zh)],Hs.prototype,"curveMax");S([p()],Hs.prototype,"curveMultiplier");let Q=Hs;const Vo=class Tt{static constant(e){const t=new Tt;return t.constant(e),t}static betweenTwoColors(e,t){const i=new Tt;return i.betweenTwoColors(e,t),i}constant(e){return this.mode=0,this.color=e,this}betweenTwoColors(e,t){return this.mode=2,this.colorMin=e,this.colorMax=t,this}mode=0;color;colorMin;colorMax;gradient;gradientMin;gradientMax;static _temp=new oe(0,0,0,1);static _temp2=new oe(0,0,0,1);evaluate(e,t){const i=t===void 0?Math.random():t;switch(this.mode){case 0:case"Color":return this.color;case 1:case"Gradient":return this.gradient.evaluate(e,Tt._temp),Tt._temp;case 2:case"TwoColors":return Tt._temp.lerpColors(this.colorMin,this.colorMax,i);case 3:case"TwoGradients":return this.gradientMin.evaluate(e,Tt._temp),this.gradientMax.evaluate(e,Tt._temp2),Tt._temp.lerp(Tt._temp2,i);case 4:case"RandomColor":const o=Math.random();return this.gradientMin.evaluate(e,Tt._temp),this.gradientMax.evaluate(e,Tt._temp2),Tt._temp.lerp(Tt._temp2,o)}return Tt._temp.set(16777215),Tt._temp.alpha=1,Tt._temp}};S([p()],Vo.prototype,"mode");S([p(oe)],Vo.prototype,"color");S([p(oe)],Vo.prototype,"colorMin");S([p(oe)],Vo.prototype,"colorMax");S([p(ea)],Vo.prototype,"gradient");S([p(ea)],Vo.prototype,"gradientMin");S([p(ea)],Vo.prototype,"gradientMax");let ta=Vo;var my=(s=>(s[s.Hierarchy=0]="Hierarchy",s[s.Local=1]="Local",s[s.Shape=2]="Shape",s))(my||{});class $t{cullingMode;duration;emitterVelocityMode;flipRotation;gravityModifier;gravityModifierMultiplier;loop;maxParticles;playOnAwake;prewarm;ringBufferLoopRange;ringBufferMode;scalingMode;simulationSpace;simulationSpeed;startColor;startDelay;startDelayMultiplier;startLifetime;startLifetimeMultiplier;startRotation;startRotationMultiplier;startRotation3D;startRotationX;startRotationXMultiplier;startRotationY;startRotationYMultiplier;startRotationZ;startRotationZMultiplier;startSize;startSize3D;startSizeMultiplier;startSizeX;startSizeXMultiplier;startSizeY;startSizeYMultiplier;startSizeZ;startSizeZMultiplier;startSpeed;startSpeedMultiplier;stopAction;useUnscaledTime}S([p(Q)],$t.prototype,"gravityModifier");S([p(ta)],$t.prototype,"startColor");S([p(Q)],$t.prototype,"startDelay");S([p(Q)],$t.prototype,"startLifetime");S([p(Q)],$t.prototype,"startRotation");S([p(Q)],$t.prototype,"startRotationX");S([p(Q)],$t.prototype,"startRotationY");S([p(Q)],$t.prototype,"startRotationZ");S([p(Q)],$t.prototype,"startSize");S([p(Q)],$t.prototype,"startSizeX");S([p(Q)],$t.prototype,"startSizeY");S([p(Q)],$t.prototype,"startSizeZ");S([p(Q)],$t.prototype,"startSpeed");class wf{cycleCount;maxCount;minCount;probability;repeatInterval;time;count;_performed=0;reset(){this._performed=0}run(e){if(e<=this.time)return 0;let t=0;if(this.cycleCount===0||this._performed<this.cycleCount){const i=this.time+this.repeatInterval*this._performed;if(e>=i&&(this._performed+=1,Math.random()<this.probability))switch(this.count.mode){case 0:t=this.count.constant;break;case 3:t=L.lerp(this.count.constantMin,this.count.constantMax,Math.random());break;case 1:t=this.count.curve.evaluate(Math.random());break;case 2:const n=Math.random();t=L.lerp(this.count.curveMin.evaluate(n),this.count.curveMax.evaluate(n),Math.random());break}}return t}}class qs{enabled;get burstCount(){return this.bursts?.length??0}bursts;rateOverTime;rateOverTimeMultiplier;rateOverDistance;rateOverDistanceMultiplier;system;reset(){this.bursts?.forEach(e=>e.reset())}getBurst(){let e=0;if(this.burstCount>0)for(let t=0;t<this.burstCount;t++){const i=this.bursts[t];this.system.main.loop&&i.time>=this.system.time&&i.reset(),e+=Math.round(i.run(this.system.time))}return e}}S([p()],qs.prototype,"enabled");S([p()],qs.prototype,"bursts");S([p(Q)],qs.prototype,"rateOverTime");S([p()],qs.prototype,"rateOverTimeMultiplier");S([p(Q)],qs.prototype,"rateOverDistance");S([p()],qs.prototype,"rateOverDistanceMultiplier");class kp{enabled;color}S([p(ta)],kp.prototype,"color");class ia{enabled;separateAxes;size;sizeMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;_time=0;_temp=new c.Vector3;evaluate(e,t,i){if(t||(t=this._temp),!this.enabled)return t.x=t.y=t.z=1,t;if(this.separateAxes)t.x=this.x.evaluate(e,i)*this.xMultiplier,t.y=this.y.evaluate(e,i)*this.yMultiplier,t.z=this.z.evaluate(e,i)*this.zMultiplier;else{const n=this.size.evaluate(e,i)*this.sizeMultiplier;t.x=n}return t}}S([p(Q)],ia.prototype,"size");S([p(Q)],ia.prototype,"x");S([p(Q)],ia.prototype,"y");S([p(Q)],ia.prototype,"z");const lt=class Ic{get type(){return vf[this.shapeType]}initialize(e){this.onInitialize(e),e.position.x=this._vector.x,e.position.y=this._vector.y,e.position.z=this._vector.z}toJSON(){return this}clone(){return new Ic}shapeType=5;enabled=!0;alignToDirection=!1;angle=0;arc=360;arcSpread;arcSpeedMultiplier;arcMode;boxThickness;position;rotation;_rotation=new c.Euler;scale;radius;radiusThickness;sphericalDirectionAmount;randomDirectionAmount;randomPositionAmount;meshShapeType;meshRenderer;_meshObj;_meshGeometry;setMesh(e){this.meshRenderer=e,e?(this._meshObj=e.sharedMeshes[Math.floor(Math.random()*e.sharedMeshes.length)],this._meshGeometry=this._meshObj.geometry):(this._meshObj=void 0,this._meshGeometry=void 0)}system;_space;_worldSpaceMatrix=new c.Matrix4;_worldSpaceMatrixInverse=new c.Matrix4;constructor(){su&&console.log(this)}update(e,t){}onUpdate(e,t,i,n){this.system=e,this._space=i,i===1&&(this._worldSpaceMatrix.copy(n.matrixWorld),this._worldSpaceMatrix.elements[0]=1,this._worldSpaceMatrix.elements[5]=1,this._worldSpaceMatrix.elements[10]=1,this._worldSpaceMatrixInverse.copy(this._worldSpaceMatrix).invert())}applyRotation(e){const t=this.rotation.x!==0||this.rotation.y!==0||this.rotation.z!==0;return t&&(this._rotation.x=L.toRadians(this.rotation.x),this._rotation.y=L.toRadians(this.rotation.y),this._rotation.z=L.toRadians(this.rotation.z),this._rotation.order="ZYX",e.applyEuler(this._rotation)),t}_vector=new c.Vector3(0,0,0);_temp=new c.Vector3(0,0,0);_triangle=new c.Triangle;onInitialize(e){this._vector.set(0,0,0),e.mesh=void 0,e.mesh_geometry=void 0;const t=this._temp.copy(this.position),i=this._space===1;i&&t.applyQuaternion(this.system.worldQuaternion);let n=this.radius;if(i&&(n*=this.system.worldScale.x),this.enabled){switch(this.shapeType){case 5:su&&B.DrawWireBox(this.position,this.scale,14540253,1),this._vector.x=Math.random()*this.scale.x-this.scale.x/2,this._vector.y=Math.random()*this.scale.y-this.scale.y/2,this._vector.z=Math.random()*this.scale.z-this.scale.z/2,this._vector.add(t);break;case 4:this.randomConePoint(this.position,this.angle,n,this.radiusThickness,this.arc,this.arcMode,this._vector);break;case 0:this.randomSpherePoint(this.position,n,this.radiusThickness,this.arc,this._vector);break;case 10:this.randomCirclePoint(this.position,n,this.radiusThickness,this.arc,this._vector);break;case 13:const o=this.meshRenderer;o?.destroyed==!1&&this.setMesh(o);const r=e.mesh=this._meshObj,a=e.mesh_geometry=this._meshGeometry;if(r&&a)switch(this.meshShapeType){case 0:{const l=a.getAttribute("position"),h=Math.floor(Math.random()*l.count);this._vector.fromBufferAttribute(l,h),this._vector.applyMatrix4(r.matrixWorld),e.mesh_normal=h}break;case 1:break;case 2:{const l=a.index;if(l){let h=Math.random(),d=Math.random();h+d>1&&(h=1-h,d=1-d);const u=Math.floor(Math.random()*(l.count/3));let f=u*3,m=u*3+1,g=u*3+2;f=l.getX(f),m=l.getX(m),g=l.getX(g);const v=a.getAttribute("position");this._triangle.a.fromBufferAttribute(v,f),this._triangle.b.fromBufferAttribute(v,m),this._triangle.c.fromBufferAttribute(v,g),this._vector.set(0,0,0).addScaledVector(this._triangle.a,h).addScaledVector(this._triangle.b,d).addScaledVector(this._triangle.c,1-(h+d)),this._vector.applyMatrix4(r.matrixWorld),e.mesh_normal=u}}break}break;default:this._vector.set(0,0,0),E()&&!globalThis.__particlesystem_shapetype_unsupported&&(console.warn("ParticleSystem ShapeType is not supported:",vf[this.shapeType]),globalThis.__particlesystem_shapetype_unsupported=!0);break}this.randomizePosition(this._vector,this.randomPositionAmount)}this.applyRotation(this._vector),i&&(this._vector.applyQuaternion(this.system.worldQuaternion),this._vector.add(this.system.worldPos)),su&&B.DrawSphere(this._vector,.03,16711680,.5,!0)}_dir=new c.Vector3;getDirection(e,t){if(!this.enabled)return this._dir.set(0,0,1),this._dir;switch(this.shapeType){case 5:this._dir.set(0,0,1);break;case 4:this._dir.set(0,0,1);break;case 10:case 0:const i=t.x,n=t.y,o=t.z;this._dir.set(i,n,o),this.system?.worldspace?this._dir.sub(this.system.worldPos):this._dir.sub(this.position);break;case 13:const r=e.mesh,a=e.mesh_geometry;if(r&&a)switch(this.meshShapeType){case 0:{const l=a.getAttribute("normal"),h=e.mesh_normal;this._dir.fromBufferAttribute(l,h)}break;case 1:break;case 2:{const l=a.index;if(l){const h=e.mesh_normal,d=l.getX(h*3),u=l.getX(h*3+1),f=l.getX(h*3+2),m=a.getAttribute("position"),g=F(),v=F(),_=F();g.fromBufferAttribute(m,d),v.fromBufferAttribute(m,u),_.fromBufferAttribute(m,f),g.sub(v),_.sub(v),g.cross(_),this._dir.copy(g).multiplyScalar(-1);const y=Se(r);this._dir.applyQuaternion(y)}}break}break;default:this._dir.set(0,0,1);break}return this._space===1&&this._dir.applyQuaternion(this.system.worldQuaternion),this.applyRotation(this._dir),this._dir.normalize(),this.spherizeDirection(this._dir,this.sphericalDirectionAmount),this.randomizeDirection(this._dir,this.randomDirectionAmount),su&&(B.DrawSphere(t,.01,8925952,.5,!0),B.DrawDirection(t,this._dir,8925952,.5,!0)),this._dir}static _randomQuat=new c.Quaternion;static _tempVec=new c.Vector3;randomizePosition(e,t){if(t<=0)return;const i=Ic._tempVec;i.set(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1),i.x*=t*this.scale.x,i.y*=t*this.scale.y,i.z*=t*this.scale.z,e.add(i)}randomizeDirection(e,t){if(t===0)return;const i=Ic._randomQuat,n=Ic._tempVec;n.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).normalize(),i.setFromAxisAngle(n,t*Math.random()*Math.PI),e.applyQuaternion(i)}spherizeDirection(e,t){if(t===0)return;const i=Math.random()*Math.PI*2,n=Math.acos(1-Math.random()*2),o=Math.sin(n)*Math.cos(i),r=Math.sin(n)*Math.sin(i),a=Math.cos(n),l=new c.Vector3(o,r,a);e.lerp(l,t)}randomSpherePoint(e,t,i,n,o){const r=Math.random(),a=Math.random(),l=2*Math.PI*r*(n/360),h=Math.acos(2*a-1),d=L.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,u=e.x+this.scale.x*(-d*Math.sin(h)*Math.cos(l)),f=e.y+this.scale.y*(d*Math.sin(h)*Math.sin(l)),m=e.z+this.scale.z*(d*Math.cos(h));o.x=u,o.y=f,o.z=m}randomCirclePoint(e,t,i,n,o){const r=Math.random(),a=2*Math.PI*r*(n/360),l=L.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,h=e.x+this.scale.x*l*Math.cos(a),d=e.y+this.scale.y*l*Math.sin(a),u=e.z;o.x=h,o.y=d,o.z=u}_loopTime=0;_loopDirection=1;randomConePoint(e,t,i,n,o,r,a){let l=0,h=0;switch(r){case 0:l=Math.random(),h=Math.random();break;case 2:this._loopTime>1&&(this._loopDirection=-1),this._loopTime<0&&(this._loopDirection=1);case 1:l=.5,h=Math.random(),this._loopTime+=this.system.deltaTime*this._loopDirection;break}let d=2*Math.PI*l*(o/360);switch(r){case 2:case 1:d+=Math.PI+.5,d+=this._loopTime*Math.PI*2,d%=L.toRadians(o);break}const u=Math.acos(2*h-1),f=L.lerp(1,1-Math.pow(1-Math.random(),Math.PI),n)*i,m=e.x+-f*Math.sin(u)*Math.cos(d),g=e.y+f*Math.sin(u)*Math.sin(d),v=e.z;a.x=m*this.scale.x,a.y=g*this.scale.y,a.z=v*this.scale.z}};S([p()],lt.prototype,"shapeType");S([p()],lt.prototype,"enabled");S([p()],lt.prototype,"alignToDirection");S([p()],lt.prototype,"angle");S([p()],lt.prototype,"arc");S([p()],lt.prototype,"arcSpread");S([p()],lt.prototype,"arcSpeedMultiplier");S([p()],lt.prototype,"arcMode");S([p(c.Vector3)],lt.prototype,"boxThickness");S([p(c.Vector3)],lt.prototype,"position");S([p(c.Vector3)],lt.prototype,"rotation");S([p(c.Vector3)],lt.prototype,"scale");S([p()],lt.prototype,"radius");S([p()],lt.prototype,"radiusThickness");S([p()],lt.prototype,"sphericalDirectionAmount");S([p()],lt.prototype,"randomDirectionAmount");S([p()],lt.prototype,"randomPositionAmount");S([p()],lt.prototype,"meshShapeType");S([p(Vh)],lt.prototype,"meshRenderer");let vb=lt;class be{damping;enabled;frequency;octaveCount;octaveMultiplier;octaveScale;positionAmount;quality;remap;remapEnabled;remapMultiplier;remapX;remapXMultiplier;remapY;remapYMultiplier;remapZ;remapZMultiplier;scrollSpeedMultiplier;separateAxes;strengthMultiplier;strengthX;strengthXMultiplier;strengthY;strengthYMultiplier;strengthZ;strengthZMultiplier;_noise;_time=0;update(e){this._time+=e.time.deltaTime*this.scrollSpeedMultiplier}_temp=new c.Vector3;apply(e,t,i,n,o,r){if(!this.enabled)return;this._noise||(this._noise=ee.createNoise4D(()=>0));const a=this._temp.set(t.x,t.y,t.z).multiplyScalar(this.frequency),l=this._noise(a.x,a.y,a.z,this._time),h=this._noise(a.x,a.y,a.z,this._time+1e3*this.frequency),d=this._noise(a.x,a.y,a.z,this._time+2e3*this.frequency);this._temp.set(l,h,d).normalize();const u=o/r;let f=this.positionAmount.evaluate(u);this.separateAxes?(this._temp.x*=f*this.strengthXMultiplier,this._temp.y*=f*this.strengthYMultiplier,this._temp.z*=f*this.strengthZMultiplier):(this.strengthX&&(f*=this.strengthX.evaluate(u)*1.5),this._temp.multiplyScalar(f)),i.x+=this._temp.x,i.y+=this._temp.y,i.z+=this._temp.z}}S([p()],be.prototype,"damping");S([p()],be.prototype,"enabled");S([p()],be.prototype,"frequency");S([p()],be.prototype,"octaveCount");S([p()],be.prototype,"octaveMultiplier");S([p()],be.prototype,"octaveScale");S([p(Q)],be.prototype,"positionAmount");S([p()],be.prototype,"quality");S([p(Q)],be.prototype,"remap");S([p()],be.prototype,"remapEnabled");S([p()],be.prototype,"remapMultiplier");S([p(Q)],be.prototype,"remapX");S([p()],be.prototype,"remapXMultiplier");S([p(Q)],be.prototype,"remapY");S([p()],be.prototype,"remapYMultiplier");S([p(Q)],be.prototype,"remapZ");S([p()],be.prototype,"remapZMultiplier");S([p()],be.prototype,"scrollSpeedMultiplier");S([p()],be.prototype,"separateAxes");S([p()],be.prototype,"strengthMultiplier");S([p(Q)],be.prototype,"strengthX");S([p()],be.prototype,"strengthXMultiplier");S([p(Q)],be.prototype,"strengthY");S([p()],be.prototype,"strengthYMultiplier");S([p(Q)],be.prototype,"strengthZ");S([p()],be.prototype,"strengthZMultiplier");class ze{enabled;attachRibbonToTransform=!1;colorOverLifetime;colorOverTrail;dieWithParticles=!0;inheritParticleColor=!0;lifetime;lifetimeMultiplier;minVertexDistance=.2;mode=0;ratio=1;ribbonCount=1;shadowBias=0;sizeAffectsLifetime=!1;sizeAffectsWidth=!1;splitSubEmitterRibbons=!1;textureMode=0;widthOverTrail;widthOverTrailMultiplier;worldSpace=!1;getWidth(e,t,i,n){const o=this.widthOverTrail.evaluate(i,n);return e*=o,e}getColor(e,t,i){const n=this.colorOverTrail.evaluate(i),o=this.colorOverLifetime.evaluate(t);e.x*=n.r*o.r,e.y*=n.g*o.g,e.z*=n.b*o.b,"alpha"in n&&"alpha"in o&&(e.w*=n.alpha*o.alpha)}}S([p()],ze.prototype,"enabled");S([p()],ze.prototype,"attachRibbonToTransform");S([p(ta)],ze.prototype,"colorOverLifetime");S([p(ta)],ze.prototype,"colorOverTrail");S([p()],ze.prototype,"dieWithParticles");S([p()],ze.prototype,"inheritParticleColor");S([p(Q)],ze.prototype,"lifetime");S([p()],ze.prototype,"lifetimeMultiplier");S([p()],ze.prototype,"minVertexDistance");S([p()],ze.prototype,"mode");S([p()],ze.prototype,"ratio");S([p()],ze.prototype,"ribbonCount");S([p()],ze.prototype,"shadowBias");S([p()],ze.prototype,"sizeAffectsLifetime");S([p()],ze.prototype,"sizeAffectsWidth");S([p()],ze.prototype,"splitSubEmitterRibbons");S([p()],ze.prototype,"textureMode");S([p(Q)],ze.prototype,"widthOverTrail");S([p()],ze.prototype,"widthOverTrailMultiplier");S([p()],ze.prototype,"worldSpace");class We{enabled;space=0;orbitalX;orbitalY;orbitalZ;orbitalXMultiplier;orbitalYMultiplier;orbitalZMultiplier;orbitalOffsetX;orbitalOffsetY;orbitalOffsetZ;speedModifier;speedModifierMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;_system;update(e){this._system=e}_temp=new c.Vector3;_temp2=new c.Vector3;_temp3=new c.Vector3;_hasOrbital=!1;_index=0;_orbitalMatrix=new c.Matrix4;init(e){this._index==0&&(e.debug=!0),this._index+=1,e.orbitx=this.orbitalX.evaluate(Math.random()),e.orbity=this.orbitalY.evaluate(Math.random()),e.orbitz=this.orbitalZ.evaluate(Math.random()),this._hasOrbital=e.orbitx!=0||e.orbity!=0||e.orbitz!=0}apply(e,t,i,n,o,r,a){if(!this.enabled)return;const l=r/a,h=this.speedModifier.evaluate(l)*this.speedModifierMultiplier,d=this.x.evaluate(l),u=this.y.evaluate(l),f=this.z.evaluate(l);if(this._temp.set(-d,u,f),this._system&&this._system.main.simulationSpace===1&&this._temp.applyQuaternion(this._system.worldQuaternion),this._hasOrbital&&this._system?.worldPos){const g=this._temp2.set(i.x,i.y,i.z),v=this.orbitalXMultiplier,_=this.orbitalYMultiplier,y=this.orbitalZMultiplier,b=h*Math.PI*2*10,w=Math.cos(b*v),C=Math.sin(b*v),k=Math.cos(b*_),O=Math.sin(b*_),D=Math.cos(b*y),I=Math.sin(b*y),j=g.x*(k*D)+g.y*(k*I)+g.z*-O,$=g.x*(C*O*D-w*I)+g.y*(C*O*I+w*D)+g.z*(C*k),W=g.x*(w*O*D+C*I)+g.y*(w*O*I-C*D)+g.z*(w*k),R=this._temp3.set(g.x-j,g.y-$,g.z-W);R.normalize(),R.multiplyScalar(.2/o*Math.max(this.orbitalXMultiplier,this.orbitalYMultiplier,this.orbitalZMultiplier)),n.x+=R.x,n.y+=R.y,n.z+=R.z}n.x+=this._temp.x,n.y+=this._temp.y,n.z+=this._temp.z,n.x*=h,n.y*=h,n.z*=h}}S([p()],We.prototype,"enabled");S([p()],We.prototype,"space");S([p(Q)],We.prototype,"orbitalX");S([p(Q)],We.prototype,"orbitalY");S([p(Q)],We.prototype,"orbitalZ");S([p()],We.prototype,"orbitalXMultiplier");S([p()],We.prototype,"orbitalYMultiplier");S([p()],We.prototype,"orbitalZMultiplier");S([p()],We.prototype,"orbitalOffsetX");S([p()],We.prototype,"orbitalOffsetY");S([p()],We.prototype,"orbitalOffsetZ");S([p(Q)],We.prototype,"speedModifier");S([p()],We.prototype,"speedModifierMultiplier");S([p(Q)],We.prototype,"x");S([p()],We.prototype,"xMultiplier");S([p(Q)],We.prototype,"y");S([p()],We.prototype,"yMultiplier");S([p(Q)],We.prototype,"z");S([p()],We.prototype,"zMultiplier");class Vt{animation;enabled;cycleCount;frameOverTime;frameOverTimeMultiplier;numTilesX;numTilesY;startFrame;startFrameMultiplier;rowMode;rowIndex;spriteCount;timeMode;sampleOnceAtStart(){if(this.timeMode===0)switch(this.frameOverTime.mode){case 0:case 3:case 2:case 1:return!0}return!1}getStartIndex(){return this.sampleOnceAtStart()?Math.random()*(this.numTilesX*this.numTilesY):0}evaluate(e){if(!this.sampleOnceAtStart())return this.getIndex(e)}getIndex(e){const t=this.numTilesX*this.numTilesY;e=e*this.cycleCount;let i=this.frameOverTime.evaluate(e%1);return i*=this.frameOverTimeMultiplier,i*=t,i=i%t,i=Math.floor(i),i}}S([p()],Vt.prototype,"animation");S([p()],Vt.prototype,"enabled");S([p()],Vt.prototype,"cycleCount");S([p(Q)],Vt.prototype,"frameOverTime");S([p()],Vt.prototype,"frameOverTimeMultiplier");S([p()],Vt.prototype,"numTilesX");S([p()],Vt.prototype,"numTilesY");S([p(Q)],Vt.prototype,"startFrame");S([p()],Vt.prototype,"startFrameMultiplier");S([p()],Vt.prototype,"rowMode");S([p()],Vt.prototype,"rowIndex");S([p()],Vt.prototype,"spriteCount");S([p()],Vt.prototype,"timeMode");class Mn{enabled;separateAxes;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t){return this.enabled?this.separateAxes?0:this.z.evaluate(e,t)*-1:0}}S([p()],Mn.prototype,"enabled");S([p()],Mn.prototype,"separateAxes");S([p(Q)],Mn.prototype,"x");S([p()],Mn.prototype,"xMultiplier");S([p(Q)],Mn.prototype,"y");S([p()],Mn.prototype,"yMultiplier");S([p(Q)],Mn.prototype,"z");S([p()],Mn.prototype,"zMultiplier");class on{enabled;range;separateAxes;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t){if(!this.enabled)return 0;if(!this.separateAxes){const i=L.lerp(this.range.x,this.range.y,t);return this.z.evaluate(i)*-1}return 0}}S([p()],on.prototype,"enabled");S([p()],on.prototype,"range");S([p()],on.prototype,"separateAxes");S([p(Q)],on.prototype,"x");S([p()],on.prototype,"xMultiplier");S([p(Q)],on.prototype,"y");S([p()],on.prototype,"yMultiplier");S([p(Q)],on.prototype,"z");S([p()],on.prototype,"zMultiplier");class pt{enabled;dampen;drag;dragMultiplier;limit;limitMultiplier;separateAxes;limitX;limitXMultiplier;limitY;limitYMultiplier;limitZ;limitZMultiplier;multiplyDragByParticleSize=!1;multiplyDragByParticleVelocity=!1;space;_temp=new c.Vector3;_temp2=new c.Vector3;apply(e,t,i,n,o,r,a){if(this.enabled){const l=this.limit.evaluate(o)*this.limitMultiplier;if(t.length()>l){this._temp.copy(t).normalize().multiplyScalar(l);const d=this.dampen*.5;t.x=L.lerp(t.x,this._temp.x,d),t.y=L.lerp(t.y,this._temp.y,d),t.z=L.lerp(t.z,this._temp.z,d),i.x=L.lerp(i.x,this._temp.x,d),i.y=L.lerp(i.y,this._temp.y,d),i.z=L.lerp(i.z,this._temp.z,d)}}}}S([p()],pt.prototype,"enabled");S([p()],pt.prototype,"dampen");S([p(Q)],pt.prototype,"drag");S([p()],pt.prototype,"dragMultiplier");S([p(Q)],pt.prototype,"limit");S([p()],pt.prototype,"limitMultiplier");S([p()],pt.prototype,"separateAxes");S([p(Q)],pt.prototype,"limitX");S([p()],pt.prototype,"limitXMultiplier");S([p(Q)],pt.prototype,"limitY");S([p()],pt.prototype,"limitYMultiplier");S([p(Q)],pt.prototype,"limitZ");S([p()],pt.prototype,"limitZMultiplier");S([p()],pt.prototype,"multiplyDragByParticleSize");S([p()],pt.prototype,"multiplyDragByParticleVelocity");S([p()],pt.prototype,"space");const Jh=class M1{enabled;curve;curveMultiplier;mode;clone(){const e=new M1;return e.enabled=this.enabled,e.curve=this.curve?.clone(),e.curveMultiplier=this.curveMultiplier,e.mode=this.mode,e}system;get _lastWorldPosition(){return this.system._iv_lastWorldPosition||(this.system._iv_lastWorldPosition=new c.Vector3),this.system._iv_lastWorldPosition}get _velocity(){return this.system._iv_velocity||(this.system._iv_velocity=new c.Vector3),this.system._iv_velocity}_temp=new c.Vector3;_firstUpdate=!0;awake(e){this.system=e,this.reset()}reset(){this._firstUpdate=!0}update(e){this.enabled&&this.system.worldspace!==!1&&(this._firstUpdate?(this._firstUpdate=!1,this._velocity.set(0,0,0),this._lastWorldPosition.copy(this.system.worldPos)):this._lastWorldPosition&&(this._velocity.copy(this.system.worldPos).sub(this._lastWorldPosition).multiplyScalar(1/this.system.deltaTime),this._lastWorldPosition.copy(this.system.worldPos)))}applyInitial(e){if(this.enabled&&this.system.worldspace!==!1&&this.mode===0){const t=this.curve.evaluate(Math.random(),Math.random());this._temp.copy(this._velocity).multiplyScalar(t),e.x+=this._temp.x,e.y+=this._temp.y,e.z+=this._temp.z}}_frames=0;applyCurrent(e,t,i){if(this.enabled&&this.system&&this.system.worldspace!==!1&&this.mode===1){const n=this.curve.evaluate(t,i);this._temp.copy(this._velocity).multiplyScalar(n),e.x+=this._temp.x,e.y+=this._temp.y,e.z+=this._temp.z}}};S([p()],Jh.prototype,"enabled");S([p(Q)],Jh.prototype,"curve");S([p()],Jh.prototype,"curveMultiplier");S([p()],Jh.prototype,"mode");let wb=Jh;class _i{enabled;range;separateAxes;size;sizeMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t,i,n){const o=e.length(),r=L.remap(o,this.range.x,this.range.y,0,1),a=this.size.evaluate(r,i);return n.x*=a,n.y*=a,n.z*=a,n}}S([p()],_i.prototype,"enabled");S([p(c.Vector2)],_i.prototype,"range");S([p()],_i.prototype,"separateAxes");S([p(Q)],_i.prototype,"size");S([p()],_i.prototype,"sizeMultiplier");S([p(Q)],_i.prototype,"x");S([p()],_i.prototype,"xMultiplier");S([p(Q)],_i.prototype,"y");S([p()],_i.prototype,"yMultiplier");S([p(Q)],_i.prototype,"z");S([p()],_i.prototype,"zMultiplier");class Nl{enabled;range;color;evaluate(e,t,i){const n=e.length(),o=L.remap(n,this.range.x,this.range.y,0,1),r=this.color.evaluate(o,t);i.x*=r.r,i.y*=r.g,i.z*=r.b,"alpha"in r&&(i.w*=r.alpha)}}S([p()],Nl.prototype,"enabled");S([p(c.Vector2)],Nl.prototype,"range");S([p(ta)],Nl.prototype,"color");class xb{constructor(e,t,i,n){this.system=e,this.particleSystem=t,this.subSystem=i,this.subParticleSystem=n,this.subParticleSystem&&this.subParticleSystem&&(this.subParticleSystem.onlyUsedByOther=!0);const o=1e3;this._circularBuffer=new Mi(()=>new ee.Matrix4,o)}system;particleSystem;subSystem;subParticleSystem;type="NeedleParticleSubEmitter";emitterType;emitterProbability;q_=new c.Quaternion;v_=new c.Vector3;v2_=new c.Vector3;_emitterMatrix=new ee.Matrix4;_circularBuffer;clone(){throw new Error("Method not implemented.")}initialize(e){e.emissionState={burstIndex:0,burstWaveIndex:0,time:0,waitEmiting:0},this._emitterMatrix.copy(this.subSystem.matrixWorld).invert().premultiply(this.system.matrixWorld),this._emitterMatrix.setPosition(0,0,0),this.emitterType===gy.Birth&&this.run(e)}update(e,t){this.run(e)}frameUpdate(e){}toJSON(){}reset(){}run(e){if(this.subSystem.currentParticles>=this.subSystem.main.maxParticles||!this.subParticleSystem||!e.emissionState||this.emitterProbability&&Math.random()>this.emitterProbability)return;const t=this.system.deltaTime;if(this.emitterType===gy.Death){let n=e.life;if(e[Wa]!==void 0&&(n=e[Wa]),!(e.age+t*1.2>=n))return;const r=this.subSystem.main.maxParticles-this.subSystem.currentParticles;e.emissionState.waitEmiting=r}const i=new ee.Matrix4;i.set(1,0,0,e.position.x,0,1,0,e.position.y,0,0,1,e.position.z,0,0,0,1),this.particleSystem.worldSpace||i.multiplyMatrices(this._emitterMatrix,i),this.subParticleSystem.emit(t,e.emissionState,i)}}var QI=Object.defineProperty,Ne=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&QI(e,t,n),n};const po=x("debugparticles"),YI=x("noprogressive"),KI=x("debugprogressive");var gy=(s=>(s[s.Birth=0]="Birth",s[s.Collision=1]="Collision",s[s.Death=2]="Death",s[s.Trigger=3]="Trigger",s[s.Manual=4]="Manual",s))(gy||{});class rn extends T{renderMode;particleMaterial;trailMaterial;particleMesh;maxParticleSize;minParticleSize;velocityScale;cameraVelocityScale;lengthScale;start(){if(this.maxParticleSize!==.5&&this.minParticleSize!==0&&E()){const e=`ParticleSystem "${this.name}" has non-default min/max particle size. This may not render correctly. Please set min size to 0 and the max size to 0.5 and use the "StartSize" setting instead`;console.warn(e)}}get transparent(){return this.particleMaterial?.transparent??!1}getMaterial(e=!1){let t=e===!0&&this.trailMaterial?this.trailMaterial:this.particleMaterial;if(t){if(t.type==="MeshStandardMaterial"){po&&console.debug("ParticleSystemRenderer.getMaterial: MeshStandardMaterial detected, converting to MeshBasicMaterial. See https://github.com/Alchemist0823/three.quarks/issues/101"),"map"in t&&t.map&&(t.map.colorSpace=c.LinearSRGBColorSpace,t.map.premultiplyAlpha=!1);const i=new c.MeshBasicMaterial;i.copy(t),e?this.trailMaterial=i:this.particleMaterial=i}t.map&&(t.map.colorSpace=c.LinearSRGBColorSpace,t.map.premultiplyAlpha=!1),e&&t.side===c.FrontSide&&(t=t.clone(),t.side=c.BackSide,e?this.trailMaterial=t:this.particleMaterial=t)}return t&&!YI&&t._didRequestTextureLOD===void 0&&(t._didRequestTextureLOD=0,KI&&console.log("Load material LOD",t.name),re.NEEDLE_progressive.assignTextureLOD(t,0)),t}getMesh(e){let t=null;if(!t&&(this.particleMesh instanceof c.Mesh&&(t=this.particleMesh.geometry),t===null)){t=new c.PlaneGeometry(1,1);const n=t.attributes.uv;for(let o=0;o<n.count;o++)n.setX(o,1-n.getX(o))}return new c.Mesh(t,this.getMaterial())}}Ne([p()],rn.prototype,"renderMode");Ne([p(c.Material)],rn.prototype,"particleMaterial");Ne([p(c.Material)],rn.prototype,"trailMaterial");Ne([p()],rn.prototype,"maxParticleSize");Ne([p()],rn.prototype,"minParticleSize");Ne([p()],rn.prototype,"velocityScale");Ne([p()],rn.prototype,"cameraVelocityScale");Ne([p()],rn.prototype,"lengthScale");class ou{_curve;_factor;constructor(e,t=1){this._curve=e,this._factor=t}type="function";startGen(e){}genValue(e,t){return this._curve.evaluate(t,Math.random())*this._factor}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}}class Sb{type="value";toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}startGen(e){}system;constructor(e){this.system=e}}class ZI extends Sb{genValue(){return this.system.textureSheetAnimation.getStartIndex()}}class JI extends Sb{_lastPosition=new c.Vector3;_lastDistance=0;update(){const e=ie(this.system.gameObject);this._lastDistance=this._lastPosition.distanceTo(e),this._lastPosition.copy(e)}genValue(){if(!this.system.isPlaying||!this.system.emission.enabled||this.system.currentParticles>=this.system.maxParticles)return 0;let e=this.system.emission.rateOverTime.evaluate(this.system.time/this.system.duration,Math.random());if(this.system.deltaTime>0){const n=this.system.emission.rateOverDistance.evaluate(this.system.time/this.system.duration,Math.random());let r=this._lastDistance/this.system.deltaTime*n;Number.isFinite(r)||(r=0),e+=r}const t=this.system.emission.getBurst();t>0&&(e+=t/this.system.deltaTime);const i=this.system.maxParticles-this.system.currentParticles;return L.clamp(e,0,i/this.system.deltaTime)}}class eL extends Sb{genValue(){return this.system.isPlaying,0}}class Wo{system;get context(){return this.system.context}constructor(e){this.type=Object.getPrototypeOf(this).constructor.name||"ParticleSystemBaseBehaviour",e&&(this.system=e)}type;initialize(e){}update(e,t){}frameUpdate(e){}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}reset(){}}class tL extends Wo{type="NeedleTextureSheet";update(e,t){const i=this.system.textureSheetAnimation;if(i.enabled){const n=e.age/e.life,o=i.evaluate(n);o!==void 0&&(e.uvTile=o)}}}const rw=Symbol("particleRotation");class iL extends Wo{type="NeedleRotation";initialize(e){e[rw]=Math.random()}update(e,t){if(e.rotation===void 0)return;const i=e.age/e.life;if(typeof e.rotation=="number"&&(this.system.rotationOverLifetime.enabled?e.rotation+=this.system.rotationOverLifetime.evaluate(i,e[rw])*t:this.system.renderer.renderMode===ks.Billboard&&(e.rotation=Math.PI),this.system.rotationBySpeed.enabled)){const n=e.velocity.length();e.rotation+=this.system.rotationBySpeed.evaluate(i,n)*t}}}const aw=Symbol("sizeLerpFactor"),nL=new c.Vector3;class sL extends Wo{type="NeedleSize";_minSize=0;_maxSize=1;initialize(e){e[aw]=Math.random(),this._minSize=this.system.renderer.minParticleSize,this._maxSize=this.system.renderer.maxParticleSize}update(e,t){const i=e.age/e.life;let n=1;this.system.sizeOverLifetime.enabled&&(n*=this.system.sizeOverLifetime.evaluate(i,void 0,e[aw]).x);let o=1;this.system.renderer.renderMode!==ks.Mesh&&(o=this.system.worldScale.x/this.system.cameraScale);const r=F(e.startSize).multiplyScalar(n*o);if(e.size.set(r.x,r.y,r.z),this.system.localspace){const a=O1(this.system,nL);e.size.x*=a.x,e.size.y*=a.y,e.size.z*=a.z}}}const Wa=Symbol("particleLife"),Wm=Symbol("trailLifetime"),lw=Symbol("trailStartLength"),Gm=Symbol("trailWidthRandom");class oL extends Wo{type="NeedleTrail";initialize(e){e instanceof ee.TrailParticle&&(e[Wa]=e.life,this.system.trails.enabled&&this.system.trails.dieWithParticles===!1&&(e[Wm]=this.system.trails.lifetime.evaluate(Math.random(),Math.random()),e.life+=e[Wm]),e[lw]=e.length,e[Gm]=Math.random())}update(e){if(this.system.trails?.enabled&&e instanceof ee.TrailParticle){const t=e,i=e.age/e[Wa],n=e.previous.values(),o=e.previous.length;for(let r=0;r<o;r++){const l=n.next().value,h=1-r/(o-1),d=e.size;if(d.x<=0&&!this.system.trails.sizeAffectsWidth){const u=20*this.system.trails.widthOverTrail.evaluate(.5,t[Gm]);d.x=u,d.y=u,d.z=u}l.size=this.system.trails.getWidth(d.x,i,h,t[Gm]),l.color.copy(e.color),this.system.trails.getColor(l.color,i,h)}if(e.age>e[Wa]){e.velocity.set(0,0,0);const r=(e.age-e[Wa])/e[Wm];t.length=L.lerp(e[lw],0,r)}}}}const ru=Symbol("startVelocity"),cw=Symbol("gravityModifier"),Hm=Symbol("gravitySpeed"),au=Symbol("velocity lerp factor"),yy=new c.Vector3;class rL extends Wo{type="NeedleVelocity";_gravityDirection=new c.Vector3;initialize(e){const t=this.system.main.simulationSpeed;e.startSpeed=this.system.main.startSpeed.evaluate(Math.random(),Math.random());const i=this.system.shape.getDirection(e,e.position);e.velocity.x=i.x*e.startSpeed,e.velocity.y=i.y*e.startSpeed,e.velocity.z=i.z*e.startSpeed,this.system.inheritVelocity?.enabled&&this.system.inheritVelocity.applyInitial(e.velocity),e[ru]?e[ru].copy(e.velocity):e[ru]=e.velocity.clone();const n=this.system.main.gravityModifier.evaluate(Math.random(),Math.random());e[cw]=n*t,e[Hm]=n*t*.5,e[au]=Math.random(),this.system.velocityOverLifetime?.init(e),this._gravityDirection.set(0,-1,0),this.system.main.simulationSpace===bh.Local&&this._gravityDirection.applyQuaternion(this.system.worldQuaternionInverted).normalize()}update(e,t){const i=e[ru],n=e[cw];if(n!==0){const u=n*e[Hm];yy.copy(this._gravityDirection).multiplyScalar(u),e[Hm]+=t*.05,i.add(yy)}e.velocity.copy(i);const o=e.age/e.life;this.system.inheritVelocity?.enabled&&this.system.inheritVelocity.applyCurrent(e.velocity,o,e[au]);const r=this.system.noise;r.enabled&&r.apply(0,e.position,e.velocity,t,e.age,e.life);const a=this.system.sizeBySpeed;a?.enabled&&(e.size=a.evaluate(e.velocity,o,e[au],e.size));const l=this.system.colorBySpeed;l?.enabled&&l.evaluate(e.velocity,e[au],e.color);const h=this.system.velocityOverLifetime;h.enabled&&h.apply(e,0,e.position,e.velocity,t,e.age,e.life);const d=this.system.limitVelocityOverLifetime;if(d.enabled&&d.apply(e.position,i,e.velocity,e.size,o,t,1),this.system.worldspace){const u=this.system.worldScale;e.velocity.x*=u.x,e.velocity.y*=u.y,e.velocity.z*=u.z}}}const hw=Symbol("colorLerpFactor"),qm=new oe(1,1,1,1),nr=new oe(1,1,1,1);class aL extends Wo{type="NeedleColor";initialize(e){}_init(e){const t=this.system.renderer.particleMaterial;nr.copy(this.system.main.startColor.evaluate(Math.random())),t?.color&&(qm.copy(t.color),qm.alpha=t.opacity??1,nr.multiply(qm)),nr.convertLinearToSRGB(),e.startColor.set(nr.r,nr.g,nr.b,nr.alpha),e.color.copy(e.startColor),e[hw]=Math.random()}update(e,t){if(e.age===0&&this._init(e),this.system.colorOverLifetime.enabled){const i=e.age/e.life,n=this.system.colorOverLifetime.color.evaluate(i,e[hw]);e.color.set(n.r,n.g,n.b,"alpha"in n?n.alpha:1).multiply(e.startColor)}else e.color.copy(e.startColor)}}class lL{system;emission;get anim(){return this.system.textureSheetAnimation}constructor(e){this.system=e,this.emission=new JI(this.system)}get prewarm(){return!1}get material(){return this.system.renderer.getMaterial(this.system.trails.enabled)}get layers(){return this.system.gameObject.layers}update(){this.emission.update()}autoDestroy;get looping(){return this.system.main.loop}get duration(){return this.system.duration}get shape(){return this.system.shape}get startLife(){return new ou(this.system.main.startLifetime)}get startSpeed(){return new ou(this.system.main.startSpeed)}get startRotation(){return new ou(this.system.main.startRotation)}get startSize(){return new ou(this.system.main.startSize)}startLength;get startColor(){return new ee.ConstantColor(new ee.Vector4(1,1,1,1))}get emissionOverTime(){return this.emission}get emissionOverDistance(){return new eL(this.system)}emissionBursts;onlyUsedByOther;behaviors=[];get instancingGeometry(){return this.system.renderer.getMesh(this.system.renderer.renderMode).geometry}get renderMode(){if(this.system.trails.enabled===!0)return ee.RenderMode.Trail;switch(this.system.renderer.renderMode){case ks.Billboard:return ee.RenderMode.BillBoard;case ks.Stretch:return ee.RenderMode.StretchedBillBoard;case ks.HorizontalBillboard:return ee.RenderMode.HorizontalBillBoard;case ks.VerticalBillboard:return ee.RenderMode.VerticalBillBoard;case ks.Mesh:return ee.RenderMode.Mesh}return ee.RenderMode.BillBoard}rendererEmitterSettings={startLength:new ee.ConstantValue(220),followLocalOrigin:!1};get speedFactor(){let e=this.system.main.simulationSpeed;return this.system.renderer?.renderMode===ks.Stretch&&(e*=this.system.renderer.velocityScale??1),e}flatWhiteTexture;clonedTexture={original:void 0,clone:void 0};get texture(){const e=this.material;if(e&&e.map){const t=e.map;if(this.clonedTexture.original!==t||!this.clonedTexture.clone){const i=t.clone();i.premultiplyAlpha=!1,i.colorSpace=c.LinearSRGBColorSpace,this.clonedTexture.original=t,this.clonedTexture.clone=i}return this.clonedTexture.clone}return this.flatWhiteTexture||(this.flatWhiteTexture=Yy(new oe(1,1,1,1),1)),this.flatWhiteTexture}get startTileIndex(){return new ZI(this.system)}get uTileCount(){return this.anim.enabled?this.anim?.numTilesX:void 0}get vTileCount(){return this.anim.enabled?this.anim?.numTilesY:void 0}get renderOrder(){return 1}get blending(){return this.system.renderer.particleMaterial?.blending??c.NormalBlending}get transparent(){return this.system.renderer.transparent}get worldSpace(){return this.system.main.simulationSpace===bh.World}}class cL{burstParticleIndex=0;burstParticleCount=0;isBursting=!1;travelDistance=0;previousWorldPos;burstIndex=0;burstWaveIndex=0;time=0;waitEmiting=0}const Wt=class Lu extends T{play(e=!1){e&&P.foreachComponent(this.gameObject,t=>{t instanceof Lu&&t!==this&&t.play(!1)},!0),this._isPlaying=!0,this._particleSystem&&(this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1),this.emission?.reset()}pause(e=!0){e&&P.foreachComponent(this.gameObject,t=>{t instanceof Lu&&t!==this&&t.pause(!1)},!0),this._isPlaying=!1}stop(e=!0,t=!1){e&&P.foreachComponent(this.gameObject,i=>{i instanceof Lu&&i!==this&&i.stop(!1,t)},!0),this._isPlaying=!1,this._time=0,t&&this.reset()}reset(){this._time=0,this._particleSystem&&(this._particleSystem.particleNum=0,this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1,this.emission?.reset())}_state;emit(e){if(this._particleSystem){this.onUpdate(),e=Math.min(e,this.maxParticles-this.currentParticles),this._state||(this._state=new cL),this._state.waitEmiting=e,this._state.time=0;const t=this._particleSystem.emitEnded;this._particleSystem.emitEnded=!1,this._particleSystem.emit(this.deltaTime,this._state,this._particleSystem.emitter.matrixWorld),this._particleSystem.emitEnded=t}}get playOnAwake(){return this.main.playOnAwake}set playOnAwake(e){this.main.playOnAwake=e}colorOverLifetime;main;emission;sizeOverLifetime;shape;noise;trails;velocityOverLifetime;limitVelocityOverLifetime;inheritVelocity;colorBySpeed;textureSheetAnimation;rotationOverLifetime;rotationBySpeed;sizeBySpeed;get renderer(){return this._renderer}get isPlaying(){return this._isPlaying}get currentParticles(){return this._particleSystem?.particleNum??0}get maxParticles(){return this.main.maxParticles}get time(){return this._time}get duration(){return this.main.duration}get deltaTime(){return this.context.time.deltaTime*this.main.simulationSpeed}get scale(){return this.gameObject.scale.x}get cameraScale(){return this._cameraScale}_cameraScale=1;get container(){return this._container}get worldspace(){return this.main.simulationSpace===bh.World}get localspace(){return this.main.simulationSpace===bh.Local}__worldQuaternion=new c.Quaternion;get worldQuaternion(){return this.__worldQuaternion}_worldQuaternionInverted=new c.Quaternion;get worldQuaternionInverted(){return this._worldQuaternionInverted}_worldScale=new c.Vector3;get worldScale(){return this._worldScale}_worldPositionFrame=-1;_worldPos=new c.Vector3;get worldPos(){return this._worldPositionFrame!==this.context.time.frame&&(this._worldPositionFrame=this.context.time.frame,ie(this.gameObject,this._worldPos)),this._worldPos}get matrixWorld(){return this._container.matrixWorld}get isSubsystem(){return this._isUsedAsSubsystem}addBehaviour(e){return this._particleSystem?(e instanceof Wo&&(e.system=this),po&&console.debug("Add custom ParticleSystem Behaviour",e),this._particleSystem.addBehavior(e),!0):!1}removeBehaviour(e){if(!this._particleSystem)return!1;const t=this._particleSystem.behaviors,i=t.indexOf(e);return i!==-1&&((E()||po)&&console.debug("Remove custom ParticleSystem Behaviour",i,e),t.splice(i,1)),!0}removeAllBehaviours(){return this._particleSystem?(this._particleSystem.behaviors.length=0,!0):!1}get behaviours(){return this._particleSystem?this._particleSystem.behaviors:null}get particleSystem(){return this._particleSystem??null}_renderer;_batchSystem;_particleSystem;_interface;_container;_time=0;_isPlaying=!0;_isUsedAsSubsystem=!1;_didPreWarm=!1;set bursts(e){for(let t=0;t<e.length;t++){const i=e[t];if(!(i instanceof wf)){const n=new wf;cl(n,i),e[t]=n}}this._bursts=e}_bursts;set subEmitterSystems(e){for(let t=0;t<e.length;t++){const i=e[t];if(!(i instanceof xf)){const n=new xf;cl(n,i),e[t]=n}}po&&e.length>0&&console.log("SubEmitters: ",e,this),this._subEmitterSystems=e}_subEmitterSystems;onAfterDeserialize(e){if(this._subEmitterSystems&&Array.isArray(this._subEmitterSystems))for(const t of this._subEmitterSystems)t._deserialize(this.context,this.gameObject)}awake(){if(this._worldPositionFrame=-1,this._renderer=this.gameObject.getComponent(rn),!this.main)throw new Error("Not Supported: ParticleSystem needs a serialized MainModule. Creating new particle systems at runtime is currently not supported.");this._container=new c.Object3D,this._container.matrixAutoUpdate=!1,this.context.scene.add(this._container),this._batchSystem=new ee.BatchedParticleRenderer,this._batchSystem.name=this.gameObject.name,this._container.add(this._batchSystem),this._interface=new lL(this),this._particleSystem=new ee.ParticleSystem(this._interface),this._particleSystem.addBehavior(new sL(this)),this._particleSystem.addBehavior(new aL(this)),this._particleSystem.addBehavior(new tL(this)),this._particleSystem.addBehavior(new iL(this)),this._particleSystem.addBehavior(new rL(this)),this._particleSystem.addBehavior(new oL(this)),this._batchSystem.addSystem(this._particleSystem);const e=this._particleSystem.emitter;this.context.scene.add(e),this.inheritVelocity.system&&this.inheritVelocity.system!==this&&(this.inheritVelocity=this.inheritVelocity.clone()),this.inheritVelocity.awake(this),po&&(console.log(this),this.gameObject.add(new c.AxesHelper(1)))}start(){this.addSubParticleSystems(),this.updateLayers(),this.renderer.particleMesh instanceof c.Mesh&&this._interface.renderMode==ee.RenderMode.Mesh&&re.NEEDLE_progressive.assignMeshLOD(this.renderer.particleMesh,0).then(e=>{e&&this.particleSystem&&this._interface.renderMode==ee.RenderMode.Mesh&&(this.particleSystem.instancingGeometry=e)})}onDestroy(){this._container?.removeFromParent(),this._batchSystem?.removeFromParent(),this._particleSystem?.emitter.removeFromParent(),this._particleSystem?.dispose()}onEnable(){this.main&&(this.inheritVelocity&&(this.inheritVelocity.system=this),this._batchSystem&&(this._batchSystem.visible=!0),this.playOnAwake&&this.play(),this._isPlaying=this.playOnAwake)}onDisable(){this._batchSystem&&(this._batchSystem.visible=!1)}onBeforeRender(){this.main&&(this._didPreWarm===!1&&this.main?.prewarm===!0&&(this._didPreWarm=!0,this.preWarm()),this.onUpdate(),this.onSimulate(this.deltaTime))}preWarm(){if(!this.emission?.enabled||this.emission.rateOverTime.getMax()<=0)return;const t=1/60,i=this.main.duration,n=this.main.startLifetime.getMax(),r=Math.min(Math.max(i,n)/Math.max(.01,this.main.simulationSpeed),1e3),a=Math.ceil(r/t),l=Date.now();po&&console.log(`Particles ${this.name} - Prewarm for ${a} frames (${r} sec). Duration: ${i}, Lifetime: ${n}`);for(let h=0;h<a&&!(this.currentParticles>=this.maxParticles);h++){const d=Date.now()-l;if(d>2e3){console.warn(`Particles ${this.name} - Prewarm took too long. Aborting: ${d}`);break}this.onUpdate(),this.onSimulate(t)}}_lastBatchesCount=-1;onSimulate(e){if(this._batchSystem){let t=this.context.time.frameCount%60===0;this._lastBatchesCount!==this._batchSystem.batches.length&&(this._lastBatchesCount=this._batchSystem.batches.length,t=!0),t&&this.updateLayers(),this._batchSystem.update(e)}this._time+=e,this._time>this.duration&&(this._time=0)}updateLayers(){if(this._batchSystem)for(let e=0;e<this._batchSystem.batches.length;e++){const t=this._batchSystem.batches[e];t.layers.disableAll();const i=this.layer;t.layers.mask=1<<i}}onUpdate(){if(this._bursts&&(this.emission.bursts=this._bursts,delete this._bursts),!this._isPlaying)return;const e=this.context.mainCamera;if(e){const n=Ve(e);this._cameraScale=n.x}const t=!this.worldspace,i=this.gameObject;if(Se(i,this.__worldQuaternion),this._worldQuaternionInverted.copy(this.__worldQuaternion).invert(),Ve(this.gameObject,this._worldScale),t&&this._container&&this.gameObject?.parent){const n=O1(this,yy);this._container.matrix.makeScale(n.x,n.y,n.z),this._container.matrix.makeRotationFromQuaternion(this.__worldQuaternion),this._container.matrix.setPosition(this.worldPos),this._container.matrix.scale(this.gameObject.scale)}this.emission.system=this,this._interface.update(),this.shape.onUpdate(this,this.context,this.main.simulationSpace,this.gameObject),this.noise.update(this.context),this.inheritVelocity?.update(this.context),this.velocityOverLifetime.update(this)}addSubParticleSystems(){if(this._subEmitterSystems&&this._particleSystem)for(const e of this._subEmitterSystems){e.particleSystem&&(e.particleSystem.__internalAwake?e.particleSystem.__internalAwake():E()&&console.warn("SubParticleSystem serialization issue(?)",e.particleSystem,e));const t=e.particleSystem?._particleSystem;if(t){e.particleSystem._isUsedAsSubsystem=!0;const i=new xb(this,this._particleSystem,e.particleSystem,t);i.emitterType=e.type,i.emitterProbability=e.emitProbability,this._particleSystem.addBehavior(i)}else po&&console.warn("Could not add SubParticleSystem",e,this)}}};Ne([p(kp)],Wt.prototype,"colorOverLifetime");Ne([p($t)],Wt.prototype,"main");Ne([p(qs)],Wt.prototype,"emission");Ne([p(ia)],Wt.prototype,"sizeOverLifetime");Ne([p(vb)],Wt.prototype,"shape");Ne([p(be)],Wt.prototype,"noise");Ne([p(ze)],Wt.prototype,"trails");Ne([p(We)],Wt.prototype,"velocityOverLifetime");Ne([p(pt)],Wt.prototype,"limitVelocityOverLifetime");Ne([p(wb)],Wt.prototype,"inheritVelocity");Ne([p(Nl)],Wt.prototype,"colorBySpeed");Ne([p(Vt)],Wt.prototype,"textureSheetAnimation");Ne([p(Mn)],Wt.prototype,"rotationOverLifetime");Ne([p(on)],Wt.prototype,"rotationBySpeed");Ne([p(_i)],Wt.prototype,"sizeBySpeed");let vh=Wt;class xf{particleSystem;emitProbability=1;properties;type;_deserialize(e,t){const i=this.particleSystem;if(i instanceof vh)return;let n="";i&&typeof i.guid=="string"&&(n=i.guid,this.particleSystem=P.findByGuid(n,t)),po&&!(this.particleSystem instanceof vh)&&console.warn("Could not find particle system for sub emitter",n,t,this)}}function O1(s,e){if(e.set(1,1,1),s.gameObject.parent&&s.localspace)switch(s.main.scalingMode){case my.Local:e=Ve(s.gameObject.parent,e),e.x=1/e.x,e.y=1/e.y,e.z=1/e.z;break;default:if(!s.unsupported_scaling_mode){s.unsupported_scaling_mode=!0;const t="ParticleSystem scale mode "+my[s.main.scalingMode]+" is not supported";E()&&de(t),console.warn(t,s.name,s)}e=Ve(s.gameObject,e);break}return e}var hL=Object.defineProperty,Cb=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&hL(e,t,n),n};class $l extends T{strength=1;radius=2;targets=[];update(){const e=this.gameObject.worldPosition,t=-this.strength*this.context.time.deltaTime;this.targets?.forEach(i=>{if(!i)return;const n=i.gameObject.worldPosition.sub(e),o=n.length();if(o>this.radius)return;let r=t;o>1?r/=o*o:r/=Math.max(.05,o),i.applyImpulse(n.multiplyScalar(r))})}}Cb([p()],$l.prototype,"strength");Cb([p()],$l.prototype,"radius");Cb([p(Xe)],$l.prototype,"targets");class _l extends T{_didAssignPlayerColor=!1;onEnable(){this.context.connection.beginListen(te.JoinedRoom,this.tryAssignColor),this._didAssignPlayerColor||this.startCoroutine(this.waitForConnection())}onDisable(){this.context.connection.stopListen(te.JoinedRoom,this.tryAssignColor)}*waitForConnection(){for(;!this.destroyed&&this.activeAndEnabled&&(yield Hy(.2),!this.tryAssignColor()););}tryAssignColor=()=>{const e=P.getComponentInParent(this.gameObject,di);if(e&&e.owner)return this._didAssignPlayerColor=!0,this.assignUserColor(e.owner),!0;const t=P.getComponentInParent(this.gameObject,it);return t?.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(t.connectionId),!0):!1};assignUserColor(e){const t=_l.hashCode(e),i=_l.colorFromHashCode(t);if(this.gameObject.type==="Mesh"){const n=this.gameObject;this.assignColor(i,e,n)}else if(this.gameObject.children)for(const n of this.gameObject.children){const o=n;o.material&&o.material.color&&this.assignColor(i,e,o)}}assignColor(e,t,i){let n=i.material;n&&(n._playerMaterial!==t&&(n=n.clone(),n._playerMaterial=t,i.material=n),n.color=e)}static hashCode(e){var t=0,i,n;if(e.length===0)return t;for(i=0;i<e.length;i++)n=e.charCodeAt(i),t=(t<<5)-t+n,t|=0;return t}static colorFromHashCode(e){const t=(e&16711680)>>16,i=(e&65280)>>8,n=e&255;return new c.Color(t/255,i/255,n/255)}}var dL=Object.defineProperty,uL=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&dL(e,t,n),n};const Xm=x("debugpost");class rt extends T{get isPostProcessingEffect(){return!0}order=void 0;constructor(e=void 0){if(super(),e)for(const t of Object.keys(e)){const i=e[t],n=this[t];n instanceof z?n.initialize(i):n!==void 0&&(this[t]=i)}}active=!0;onEnable(){super.onEnable(),Xm&&console.warn("Enable",this.constructor.name+(this.__internalDidAwakeAndStart?"":" (awake)")),this.active=!0,this.context.postprocessing.addEffect(this)}onDisable(){super.onDisable(),Xm&&console.warn("Disable",this.constructor.name),this.context.postprocessing.removeEffect(this),this.active=!1}init(){}_result;_postprocessingContext=null;get postprocessingContext(){return this._postprocessingContext}apply(e){return this._postprocessingContext=e,this._result||(this.initParameters(),this._result=this.onCreateEffect?.call(this)),this._result&&this.initParameters(),this._result}unapply(){}dispose(){Xm&&console.warn("DISPOSE",this),this._result&&(Array.isArray(this._result)?this._result.forEach(e=>e.dispose()):this._result.dispose()),this._result=void 0}initParameters(){const e=Object.keys(this);for(const t of e){const i=this[t];i instanceof z&&i.__init()}}onEditorModification(e){const t=e.propertyName;if(this[t]instanceof z){const i=e.value;return this[t].value=i,!0}}}uL([p()],rt.prototype,"active");var fL=Object.defineProperty,pL=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&fL(e,t,n),n};const mL=x("debugpost"),_y={};function an(s,e){_y[s]=e}function gL(s){return s.__type in _y?_y[s.__type]:(mL&&s.__type&&console.warn("Unknown postprocessing type",s.__type,s),rt)}class Mp{components=[];__init(e){this.components?.forEach(t=>{t.gameObject===void 0&&e.gameObject.addComponent(t),t.init()})}addEffect(e){this.components.push(e)}removeEffect(e){const t=this.components.indexOf(e);t>=0&&this.components.splice(t,1)}}pL([Qe([s=>gL(s),rt])],Mp.prototype,"components");var yL=Object.defineProperty,_L=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&yL(e,t,n),n};const bL=x("debugpost");var E1=(s=>(s[s.LOW=0]="LOW",s[s.MEDIUM=1]="MEDIUM",s[s.HIGH=2]="HIGH",s[s.ULTRA=3]="ULTRA",s))(E1||{});class ed extends rt{get typeName(){return"Antialiasing"}preset=new z(2);onCreateEffect(){const e=new A.POSTPROCESSING.MODULE.SMAAEffect({preset:this.preset?.value??A.POSTPROCESSING.MODULE.SMAAPreset.HIGH,edgeDetectionMode:A.POSTPROCESSING.MODULE.EdgeDetectionMode.LUMA});return this.preset.onValueChanged=t=>{bL&&console.log("Antialiasing preset changed to",t),e.applyPreset(t)},e}}_L([p(z)],ed.prototype,"preset");an("Antialiasing",ed);var vL=Object.defineProperty,Pb=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&vL(e,t,n),n};const Op=class R1 extends rt{static useSelectiveBloom=!1;get typeName(){return"Bloom"}threshold=new z(.9);intensity=new z(1);scatter=new z(.7);selectiveBloom;init(){this.threshold.valueProcessor=e=>e,this.intensity.valueProcessor=e=>e,this.scatter.valueProcessor=e=>e}onCreateEffect(){let e;if(this.selectiveBloom==null&&(this.selectiveBloom=R1.useSelectiveBloom),this.selectiveBloom){const t=e=new A.POSTPROCESSING.MODULE.SelectiveBloomEffect(this.context.scene,this.context.mainCamera,{blendFunction:A.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});t.inverted=!0}else e=new A.POSTPROCESSING.MODULE.BloomEffect({blendFunction:A.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});return this.intensity.onValueChanged=t=>{e.intensity=t},this.threshold.onValueChanged=t=>{e.luminanceMaterial.threshold=Math.pow(t,2.2)},this.scatter.onValueChanged=t=>{e.luminancePass.enabled=!0,e.luminanceMaterial.smoothing=t,e.mipmapBlurPass&&(e.mipmapBlurPass.radius=c.MathUtils.lerp(.1,.9,t))},e}};Pb([p(z)],Op.prototype,"threshold");Pb([p(z)],Op.prototype,"intensity");Pb([p(z)],Op.prototype,"scatter");let Ep=Op;an("Bloom",Ep);var wL=Object.defineProperty,xL=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&wL(e,t,n),n};class td extends rt{get typeName(){return"ChromaticAberration"}intensity=new z(0);onCreateEffect(){const e=new A.POSTPROCESSING.MODULE.ChromaticAberrationEffect;return e.offset=new c.Vector2(0,0),e.radialModulation=!0,e.modulationOffset=.15,this.intensity.valueProcessor=t=>t*.02,this.intensity.onValueChanged=t=>{e.offset.x=-t,e.offset.y=t},e}}xL([p(z)],td.prototype,"intensity");an("ChromaticAberration",td);var Ga=(s=>(s[s.None=0]="None",s[s.Neutral=1]="Neutral",s[s.ACES=2]="ACES",s[s.AgX=3]="AgX",s[s.KhronosNeutral=4]="KhronosNeutral",s))(Ga||{});const dw=new Map;function Qm(s){switch(s){case 0:return c.LinearToneMapping;case 1:return c.ReinhardToneMapping;case 2:return c.ACESFilmicToneMapping;case 3:return c.AgXToneMapping;case 4:return c.NeutralToneMapping;default:return dw.has(s)||(dw.set(s,!0),console.warn("[Postprocessing] Unknown tone mapping mode",s)),c.NeutralToneMapping}}function SL(s){switch(s){case c.LinearToneMapping:return 0;case c.ACESFilmicToneMapping:return 2;case c.AgXToneMapping:return 3;case c.NeutralToneMapping:return 1;case c.ReinhardToneMapping:return 1;default:return 0}}function Bu(s){switch(s){case c.LinearToneMapping:return A.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR;case c.ACESFilmicToneMapping:return A.POSTPROCESSING.MODULE.ToneMappingMode.ACES_FILMIC;case c.AgXToneMapping:return A.POSTPROCESSING.MODULE.ToneMappingMode.AGX;case c.NeutralToneMapping:return A.POSTPROCESSING.MODULE.ToneMappingMode.NEUTRAL;case c.ReinhardToneMapping:return A.POSTPROCESSING.MODULE.ToneMappingMode.REINHARD;default:return A.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR}}var CL=Object.defineProperty,T1=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&CL(e,t,n),n};const Ym=x("debugpost");class na extends rt{get typeName(){return"ToneMapping"}mode=new z(void 0);exposure=new z(1);setMode(e){const t=Ga[e];return t===void 0?(console.error("[PostProcessing] Invalid ToneMapping mode",e),this):(this.mode.value=t,this)}get isToneMapping(){return!0}get threeToneMapping(){return this.mode.isInitialized&&this.mode.overrideState?Qm(this.mode.value):this.context.renderer.toneMapping}get toneMappingExposure(){return this.exposure.overrideState&&this.exposure.value!==void 0?Math.max(0,this.exposure.value):this.context.renderer.toneMappingExposure}_tonemappingEffect=null;onCreateEffect(){if(this.mode.isInitialized==!1){const i=SL(this.context.renderer.toneMapping);Ym&&console.log("[PostProcessing] Initializing ToneMapping mode to renderer.toneMapping",this.context.renderer.toneMapping+" → "+i),this.mode.initialize(i)}this._tonemappingEffect?.dispose();const e=Qm(this.mode.value),t=this._tonemappingEffect=new A.POSTPROCESSING.MODULE.ToneMappingEffect({mode:Bu(e)});return this.mode.onValueChanged=i=>{if(typeof i=="string")i=sS(i),t.mode=Bu(i);else{const n=Qm(i);t.mode=Bu(n)}t.name="ToneMapping ("+Ga[i]+")",Ym&&console.log("[PostProcessing] ToneMapping mode changed to",Ga[i],e,t.mode)},Ym&&console.log("[PostProcessing] Use ToneMapping",Ga[this.mode.value],e,t.mode,"renderer.tonemapping: "+this.context.renderer.toneMapping),t}}T1([p(z)],na.prototype,"mode");T1([p(z)],na.prototype,"exposure");an("Tonemapping",na);var PL=Object.defineProperty,Rp=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&PL(e,t,n),n};class Go extends rt{get typeName(){return"ColorAdjustments"}remap=!0;postExposure=new z(1);contrast=new z(0);hueShift=new z(0);saturation=new z(0);init(){this.postExposure.valueProcessor=e=>(this.remap&&(e=Math.pow(2,e)),e),this.contrast.valueProcessor=e=>{if(!this.remap)return e;let t=1;return e>0?t=200:e<0&&(t=100),e/t},this.contrast.defaultValue=0,this.hueShift.valueProcessor=e=>this.remap?Math.PI*e/180:e,this.hueShift.defaultValue=0,this.saturation.valueProcessor=e=>this.remap?e<0?e/100:e/(100*Math.PI):e,this.saturation.defaultValue=0}onCreateEffect(){const e=[],t=this.postprocessingContext?.components.find(r=>r instanceof na);let i=!1;this.postExposure.onValueChanged=r=>{if(this.postExposure.overrideState){if(!t){i||(i=!0,console.warn("[PostProcessing] ColorAdjustments.PostExposure has no effect: add a ToneMappingEffect to your postprocessing stack."));return}t.exposure.value=r}};const n=new A.POSTPROCESSING.MODULE.BrightnessContrastEffect;this.contrast.onValueChanged=r=>n.contrast=r;const o=new A.POSTPROCESSING.MODULE.HueSaturationEffect;return this.hueShift.onValueChanged=r=>o.hue=r,this.saturation.onValueChanged=r=>o.saturation=r,e.push(n),e.push(o),e}}Rp([p(z)],Go.prototype,"postExposure");Rp([p(z)],Go.prototype,"contrast");Rp([p(z)],Go.prototype,"hueShift");Rp([p(z)],Go.prototype,"saturation");an("ColorAdjustments",Go);var kL=Object.defineProperty,sa=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&kL(e,t,n),n},A1=(s=>(s[s.Off=0]="Off",s[s.Gaussian=1]="Gaussian",s[s.Bokeh=2]="Bokeh",s))(A1||{});const ML=x("debugpost");class On extends rt{get typeName(){return"DepthOfField"}mode;focusDistance=new z(1);focalLength=new z(.2);aperture=new z(20);gaussianMaxRadius=new z;resolutionScale=new z(1/window.devicePixelRatio);bokehScale=new z;init(){this.focalLength.valueProcessor=t=>{const i=t/300;return L.lerp(2,.01,i)};const e=20;this.aperture.valueProcessor=t=>{const i=1-t/32;return L.lerp(1,e,i)}}onCreateEffect(){if(this.mode===0){ML&&console.warn("DepthOfField: Mode is set to Off");return}const e=new A.POSTPROCESSING.MODULE.DepthOfFieldEffect(this.context.mainCamera,{worldFocusRange:this.focalLength.value,focalLength:1,bokehScale:this.aperture.value,resolutionScale:this.resolutionScale.value});return e.cocMaterial.worldFocusDistance=this.focusDistance.value,this.focusDistance.onValueChanged=t=>{e.cocMaterial.worldFocusDistance=t},this.focalLength.onValueChanged=t=>e.cocMaterial.worldFocusRange=t,this.aperture.onValueChanged=t=>e.bokehScale=t,this.resolutionScale&&(this.resolutionScale.onValueChanged=t=>e.resolution.scale=t),[e]}unapply(){}}sa([p()],On.prototype,"mode");sa([p(z)],On.prototype,"focusDistance");sa([p(z)],On.prototype,"focalLength");sa([p(z)],On.prototype,"aperture");sa([p(z)],On.prototype,"gaussianMaxRadius");sa([p(z)],On.prototype,"resolutionScale");sa([p(z)],On.prototype,"bokehScale");an("DepthOfField",On);class wh extends rt{effect;constructor(e){super(),this.effect=e}get typeName(){return this.effect.constructor.name}onCreateEffect(){return this.effect}}var OL=Object.defineProperty,EL=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&OL(e,t,n),n};const uw=x("debugpost");class id extends rt{get typeName(){return"PixelationEffect"}granularity=new z(10);_effect=null;_lastDpr=0;onCreateEffect(){const e=new A.POSTPROCESSING.MODULE.PixelationEffect;this._effect=e;const t=this.context.renderer.getPixelRatio();return this._lastDpr=t,e.granularity=this.granularity.value*t,this.granularity.onValueChanged=i=>{const n=this.context.renderer.getPixelRatio();e.granularity=i*n,uw&&console.debug(`[PixelationEffect] granularity changed: raw=${i}, dpr=${n}, effective=${e.granularity}`)},e}update(){if(!this._effect)return;const e=this.context.renderer.getPixelRatio();e!==this._lastDpr&&(this._lastDpr=e,this._effect.granularity=this.granularity.value*e,uw&&console.debug(`[PixelationEffect] DPR changed to ${e}, updating granularity: raw=${this.granularity.value}, effective=${this._effect.granularity}`))}}EL([p(z)],id.prototype,"granularity");an("PixelationEffect",id);var RL=Object.defineProperty,nd=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&RL(e,t,n),n};class Xs extends rt{get typeName(){return"ScreenSpaceAmbientOcclusion"}intensity=new z(2);falloff=new z(1);samples=new z(9);color=new z(new c.Color(0,0,0));luminanceInfluence=new z(.7);onBeforeRender(){if(this._ssao&&this.context.mainCamera instanceof c.PerspectiveCamera){const e=this.context.mainCamera.far-this.context.mainCamera.near;this._ssao.ssaoMaterial.worldDistanceFalloff=e*.01,this._ssao.ssaoMaterial.worldDistanceThreshold=this.context.mainCamera.far}}_ssao;onCreateEffect(){const e=this.context.mainCamera,t=new A.POSTPROCESSING.MODULE.NormalPass(this.context.scene,e),i=new A.POSTPROCESSING.MODULE.DepthDownsamplingPass({normalBuffer:t.texture,resolutionScale:.5}),n=this._ssao=new A.POSTPROCESSING.MODULE.SSAOEffect(e,t.texture,{normalDepthBuffer:i.texture,worldDistanceThreshold:1,worldDistanceFalloff:1,worldProximityThreshold:.1,worldProximityFalloff:2,intensity:1,blendFunction:A.POSTPROCESSING.MODULE.BlendFunction.MULTIPLY,luminanceInfluence:.5});this.intensity.onValueChanged=r=>{n.intensity=r},this.falloff.onValueChanged=r=>{n.ssaoMaterial.radius=r*.1},this.samples.onValueChanged=r=>{n.ssaoMaterial.samples=r},this.color.onValueChanged=r=>{n.color||(n.color=new c.Color),n.color.copy(r)},this.luminanceInfluence.onValueChanged=r=>{n.luminanceInfluence=r};const o=new Array;return o.push(t),o.push(i),o.push(n),o}}nd([p(z)],Xs.prototype,"intensity");nd([p(z)],Xs.prototype,"falloff");nd([p(z)],Xs.prototype,"samples");nd([p(z)],Xs.prototype,"color");nd([p(z)],Xs.prototype,"luminanceInfluence");an("ScreenSpaceAmbientOcclusion",Xs);var TL=Object.defineProperty,oa=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&TL(e,t,n),n};const AL=x("debugN8AO");var Sf=(s=>(s[s.Performance=0]="Performance",s[s.Low=1]="Low",s[s.Medium=2]="Medium",s[s.High=3]="High",s[s.Ultra=4]="Ultra",s))(Sf||{});class En extends rt{get typeName(){return"ScreenSpaceAmbientOcclusionN8"}get pass(){return this._ssao}gammaCorrection=!0;aoRadius=new z(1);falloff=new z(1);intensity=new z(1);color=new z(new c.Color(0,0,0));screenspaceRadius=!1;quality=2;_ssao;onValidate(){this._ssao&&(this._ssao.setQualityMode(Sf[this.quality]),this._ssao.configuration.gammaCorrection=this.gammaCorrection,this._ssao.configuration.screenSpaceRadius=this.screenspaceRadius)}onCreateEffect(){const e=this.context.mainCamera,t=this.context.domWidth,i=this.context.domHeight,n=this._ssao=new A.POSTPROCESSING_AO.MODULE.N8AOPostPass(this.context.scene,e,t,i);n.name="SSAO_N8";const o=Sf[this.quality];if(n.setQualityMode(o),n.configuration.transparencyAware=!1,n.configuration.halfRes=window.devicePixelRatio>1,n.effectCompositerQuad?.material){const a=n.effectCompositerQuad.material;a.fragmentShader=a.fragmentShader.replace(`if (depth == 1.0) {
1407
+ Please refer to the documentation on <a href="https://fwd.needle.tools/needle-engine/docs/local-server">https://docs.needle.tools</a> or ask for help in our <a href="https://discord.needle.tools">discord community</a>`;Re(t),console.warn(t)}}function AI(s,e){if("scenes"in e){for(const t of e.scenes)if(t&&!t.animations?.length)for(const i of e.animations)t.animations.includes(i)||t.animations.push(i)}if(s instanceof V.FBXLoader||s instanceof V.OBJLoader){let t=e;t instanceof c.Object3D||(t=e.scene||e.scenes.find(i=>i)),t.traverse(i=>{const n=i;n?.isMesh&&Dy(n,n.material)})}}var DI=Object.defineProperty,II=Object.getOwnPropertyDescriptor,wp=(s,e,t,i)=>{for(var n=II(e,t),o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&DI(e,t,n),n};class Kr extends T{set url(e){e!==this._url&&(this._url=e,e&&this.__internalDidAwake&&this.activeAndEnabled&&!this._loading&&this.load(e))}get url(){return this._url}_url;set opacity(e){this._opacity=e,this._splatMesh&&(this._splatMesh.opacity=e,this._splatMesh.updateVersion())}get opacity(){return this._opacity}_opacity=1;set raycastable(e){this._raycastable=e,this._splatMesh&&(this._splatMesh.raycastable=e)}get raycastable(){return this._raycastable}_raycastable=!0;set quality(e){e!==this._quality&&(this._quality=e,this._splatMesh&&Tg(this.context,this._splatMesh,e))}get quality(){return this._quality}_quality="auto";get splatMesh(){return this._splatMesh}get isLoaded(){return this._splatMesh?.isInitialized===!0}get initialized(){return this._initialized}_splatMesh=null;_initialized=Promise.resolve();_loading=!1;_loadGeneration=0;awake(){this._loadGeneration++,this._splatMesh=null,this._initialized=Promise.resolve(),this._loading=!1}onEnable(){this.url&&!this._splatMesh&&!this._loading&&this.load(this.url),this._splatMesh&&(this._splatMesh.visible=!0,this._splatMesh.updateVersion())}onDisable(){this._splatMesh&&(this._splatMesh.visible=!1,this._splatMesh.updateVersion())}onDestroy(){this._splatMesh&&(this._splatMesh.removeFromParent(),this._splatMesh.dispose(),this._splatMesh=null)}async load(e){const t=++this._loadGeneration;this._url=e,this._splatMesh&&(this._splatMesh.removeFromParent(),this._splatMesh.dispose(),this._splatMesh=null),this._loading=!0;const i=await C1(e,{context:this.context});if(t!==this._loadGeneration||this.destroyed)return i?.scene?.dispose(),null;const n=i?.scene;return n?(n.name="Gaussian Splat",n.hideFlags|=as.DontExport|as.DontInstantiate,n.opacity=this._opacity,n.raycastable=this.raycastable,this._splatMesh=n,this.gameObject.add(n),this.activeAndEnabled||(n.visible=!1),this._initialized=n.initialized.then(()=>{t===this._loadGeneration&&(this._loading=!1)}),await this._initialized,t!==this._loadGeneration||this.destroyed?null:(Tg(this.context,n,this._quality),n)):(this._loading=!1,null)}}wp([p(URL)],Kr.prototype,"url");wp([p()],Kr.prototype,"opacity");wp([p()],Kr.prototype,"raycastable");wp([p()],Kr.prototype,"quality");var LI=Object.defineProperty,ub=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&LI(e,t,n),n};class Zr extends T{objectBounds=!1;color;isGizmo=!0;_gizmoObject=null;_boxHelper=null;onEnable(){this.isGizmo&&!Oh||(this._gizmoObject||(this.objectBounds?this._gizmoObject=new c.BoxHelper(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=s_(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),Ce.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){for(;this._boxHelper;)this._boxHelper?.update(),yield}}ub([p()],Zr.prototype,"objectBounds");ub([p(c.Color)],Zr.prototype,"color");ub([p()],Zr.prototype,"isGizmo");var BI=Object.defineProperty,fb=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&BI(e,t,n),n};class jl extends T{isGizmo=!1;color0;color1;gridHelper;size;divisions;offset;onEnable(){if(this.isGizmo&&!Oh)return;const e=this.size,t=this.divisions;this.gridHelper||(this.gridHelper=new c.GridHelper(e,t,this.color0??new c.Color(.4,.4,.4),this.color1??new c.Color(.6,.6,.6)),this.offset!==void 0&&(this.gridHelper.position.y+=this.offset)),this.gridHelper&&this.gameObject.add(this.gridHelper)}onDisable(){this.gridHelper&&(this.gameObject.remove(this.gridHelper),this.gridHelper=null)}}fb([p()],jl.prototype,"isGizmo");fb([p(c.Color)],jl.prototype,"color0");fb([p(c.Color)],jl.prototype,"color1");var FI=Object.defineProperty,pb=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&FI(e,t,n),n};class mb extends T{connectedBody;get rigidBody(){return this._rigidBody}_rigidBody=null;_jointHandle=null;onEnable(){this._rigidBody||(this._rigidBody=this.gameObject.getComponent(Xe)),this.rigidBody&&this.connectedBody&&this.startCoroutine(this.create())}onDisable(){this._jointHandle&&(this.context.physics.engine?.removeJoint(this._jointHandle),this._jointHandle=null)}*create(){if(yield,!this._jointHandle&&this.rigidBody&&this.connectedBody&&this.activeAndEnabled){const e=this.createJoint(this.rigidBody,this.connectedBody);e instanceof Promise?yield e.then(t=>this._jointHandle=t):this._jointHandle=e}}}pb([p(Xe)],mb.prototype,"connectedBody");class gb extends mb{createJoint(e,t){return this.context.physics.engine?.addFixedJoint(e,t)??null}}class Kh extends mb{anchor;axis;createJoint(e,t){return this.axis&&this.anchor?this.context.physics.engine?.addHingeJoint(e,t,this.anchor,this.axis)??null:null}}pb([p(c.Vector3)],Kh.prototype,"anchor");pb([p(c.Vector3)],Kh.prototype,"axis");var jI=Object.defineProperty,UI=Object.getOwnPropertyDescriptor,Bi=(s,e,t,i)=>{for(var n=i>1?void 0:i?UI(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&jI(e,t,n),n};function Pa(s){return s*Math.PI/180}const ow=300,Bn=x("debuglights");var fy=(s=>(s[s.Spot=0]="Spot",s[s.Directional=1]="Directional",s[s.Point=2]="Point",s[s.Area=3]="Area",s[s.Rectangle=3]="Rectangle",s[s.Disc=4]="Disc",s))(fy||{});class Lt extends T{get type(){return this._type}set type(e){if(this.light&&this.__didAwake)throw new Error("Changing the light type at runtime is not supported");switch(e){case 1:this._type="directional";break;case 2:this._type="point";break;case 0:this._type="spot";break;case"directional":case"point":case"spot":this._type=e;break;default:(Bn||E())&&console.warn(`[Light] Unsupported light type: ${fy[e]} (${e}) on '${this.name}'`),this._type="unsupported";break}}_type="point";get range(){return this._range}set range(e){this._range=e,this.light&&(this.light.type==="SpotLight"||this.light.type==="PointLight")&&"distance"in this.light&&(this.light.distance=e)}_range=1;get spotAngle(){return this._spotAngle}set spotAngle(e){this._spotAngle=e,this.light&&this.light.type==="SpotLight"&&"angle"in this.light&&(this.light.angle=Pa(e/2))}_spotAngle=30;get innerSpotAngle(){return this._innerSpotAngle}set innerSpotAngle(e){if(this._innerSpotAngle=e,this.light&&this.light.type==="SpotLight"&&"penumbra"in this.light){const t=this.spotAngle,n=1-Pa(e/2)/Pa(t/2);this.light.penumbra=n}}_innerSpotAngle=10;set color(e){this._color=e,this.light!==void 0&&(this.light.color=e)}get color(){return this.light?this.light.color:this._color}_color=new c.Color(16777215);set shadowNearPlane(e){if(e!==this._shadowNearPlane&&(this._shadowNearPlane=e,this.shadowLight?.shadow?.camera!==void 0)){const t=this.shadowLight.shadow.camera;t.near=e}}get shadowNearPlane(){return this._shadowNearPlane}_shadowNearPlane=.1;set shadowBias(e){e!==this._shadowBias&&(this._shadowBias=e,this.shadowLight?.shadow?.bias!==void 0&&(this.shadowLight.shadow.bias=e,this.shadowLight.shadow.needsUpdate=!0))}get shadowBias(){return this._shadowBias}_shadowBias=0;set shadowNormalBias(e){e!==this._shadowNormalBias&&(this._shadowNormalBias=e,this.shadowLight?.shadow?.normalBias!==void 0&&(this.shadowLight.shadow.normalBias=e,this.shadowLight.shadow.needsUpdate=!0))}get shadowNormalBias(){return this._shadowNormalBias}_shadowNormalBias=0;_overrideShadowBiasSettings=!1;set shadows(e){this._shadows=e,this.light&&(this.light.castShadow=e!==0,this.updateShadowSoftHard())}get shadows(){return this._shadows}_shadows=1;lightmapBakeType=4;set intensity(e){this._intensity=e,this.light&&(this.light.intensity=e),Bn&&console.log("Set light intensity to "+this._intensity,e,this)}get intensity(){return this._intensity}_intensity=-1;get shadowDistance(){const e=this.shadowLight;return e?.shadow?e.shadow.camera.far:-1}set shadowDistance(e){this._shadowDistance=e;const t=this.shadowLight;if(t?.shadow){const i=t.shadow.camera;i.far=e,i.updateProjectionMatrix()}}_shadowDistance;shadowWidth;shadowHeight;get shadowResolution(){const e=this.shadowLight;return e?.shadow?e.shadow.mapSize.x:-1}set shadowResolution(e){if(e===this._shadowResolution)return;this._shadowResolution=e;const t=this.shadowLight;t?.shadow&&(t.shadow.mapSize.set(e,e),t.shadow.needsUpdate=!0)}_shadowResolution=void 0;get isBaked(){return this.lightmapBakeType===2}get selfIsLight(){if(this.gameObject.isLight===!0)return!0;switch(this.gameObject.type){case"SpotLight":case"PointLight":case"DirectionalLight":return!0}return!1}light=void 0;get shadowLight(){const e=this.light;if(e&&"shadow"in e)return e}getWorldPosition(e){return this.light?this.type==="directional"?this.light.getWorldPosition(e).multiplyScalar(1):this.light.getWorldPosition(e):e}awake(){this.color=new c.Color(this.color??16777215),Bn&&console.log(this.name,this)}onEnable(){Bn&&console.log("ENABLE LIGHT",this.name),this.createLight(),!this.isBaked&&(this.light&&(this.light.visible=!0,this.light.intensity=this._intensity,Bn&&console.log("Set light intensity to "+this.light.intensity,this.name),this.selfIsLight||this.light.parent!==this.gameObject&&this.gameObject.add(this.light)),this.context.lights.push(this))}onDisable(){Bn&&console.log("DISABLE LIGHT",this.name);const e=this.context.lights.indexOf(this);e!==-1&&this.context.lights.splice(e,1),this.light&&(this.selfIsLight?this.light.intensity=0:this.light.visible=!1)}createLight(){const e=this.selfIsLight;if(e&&!this.light)this.light=this.gameObject,this.light.name=this.name,this._intensity=this.light.intensity,this.type==="directional"&&this.setDirectionalLight(this.light);else if(!this.light)switch(this.type){case"directional":const t=new c.DirectionalLight(this.color,this.intensity*Math.PI);if(t.position.set(0,0,-ow*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(t.target),Ar(t.target,0,0,0),this.light=t,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),Bn){const r=new c.DirectionalLightHelper(this.light,.2,this.color);this.context.scene.add(r)}break;case"spot":const i=new c.SpotLight(this.color,this.intensity*Math.PI,this.range,Pa(this.spotAngle/2),1-Pa(this.innerSpotAngle/2)/Pa(this.spotAngle/2),2);i.position.set(0,0,0),i.rotation.set(0,0,0),this.light=i;const n=i.target;i.add(n),n.position.set(0,0,this.range),n.rotation.set(0,0,0);break;case"point":const o=new c.PointLight(this.color,this.intensity*Math.PI,this.range);this.light=o;break;default:Bn&&console.warn(`[Light] Unsupported light type: ${fy[this.type]} (${this.type}) on '${this.name}'`);break}if(this.light){if(this._intensity>=0?this.light.intensity=this._intensity:this._intensity=this.light.intensity,this.shadows!==0?this.light.castShadow=!0:this.light.castShadow=!1,this.shadowLight?.shadow){this._shadowResolution!==void 0&&this._shadowResolution>4?(this.shadowLight.shadow.mapSize.width=this._shadowResolution,this.shadowLight.shadow.mapSize.height=this._shadowResolution):(this.shadowLight.shadow.mapSize.width=2048,this.shadowLight.shadow.mapSize.height=2048),Bn&&console.log("Override shadow bias?",this._overrideShadowBiasSettings,this.shadowBias,this.shadowNormalBias),this.shadowLight.shadow.bias=this.shadowBias,this.shadowLight.shadow.normalBias=this.shadowNormalBias,this.updateShadowSoftHard();const t=this.shadowLight.shadow.camera;if(t.near=this.shadowNearPlane,this._shadowDistance!==void 0&&typeof this._shadowDistance=="number"?t.far=this._shadowDistance:t.far=ow*Math.abs(this.gameObject.scale.z),this.gameObject.scale.set(1,1,1),this.shadowWidth!==void 0)t.left=-this.shadowWidth/2,t.right=this.shadowWidth/2;else{const i=this.gameObject.scale.x;t.left*=i,t.right*=i}if(this.shadowHeight!==void 0)t.top=this.shadowHeight/2,t.bottom=-this.shadowHeight/2;else{const i=this.gameObject.scale.y;t.top*=i,t.bottom*=i}this.shadowLight.shadow.needsUpdate=!0,Bn&&this.context.scene.add(new c.CameraHelper(t))}this.isBaked?this.light.removeFromParent():e||this.gameObject.add(this.light)}}static allowChangingRendererShadowMapType=!0;updateShadowSoftHard(){this.light&&this.shadowLight.shadow&&(this.shadows===2||(this.shadowLight.shadow.radius=1,this.shadowLight.shadow.blurSamples=1))}onEnterXR(e){this.applyXRScale(e.xr.rigScale)}onUpdateXR(e){this.applyXRScale(e.xr.rigScale)}onLeaveXR(e){this.applyXRScale(1)}applyXRScale(e){this.light&&("distance"in this.light?(this.light.intensity=this._intensity/e,this.light.distance=this._range/e):this.light.intensity=this._intensity)}setDirectionalLight(e){e.add(e.target),e.target.position.set(0,0,-1)}}Bi([p()],Lt.prototype,"type",1);Bi([p()],Lt.prototype,"range",1);Bi([p()],Lt.prototype,"spotAngle",1);Bi([p()],Lt.prototype,"innerSpotAngle",1);Bi([p(c.Color)],Lt.prototype,"color",1);Bi([p()],Lt.prototype,"shadowNearPlane",1);Bi([p()],Lt.prototype,"shadowBias",1);Bi([p()],Lt.prototype,"shadowNormalBias",1);Bi([p()],Lt.prototype,"shadows",1);Bi([p()],Lt.prototype,"lightmapBakeType",2);Bi([p()],Lt.prototype,"intensity",1);Bi([p()],Lt.prototype,"shadowDistance",1);Bi([p()],Lt.prototype,"shadowResolution",1);var zI=Object.defineProperty,xp=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&zI(e,t,n),n};const Vm=x("debuglods"),NI=x("nolods");class Ul{screenRelativeTransitionHeight;distance;renderers}xp([p()],Ul.prototype,"screenRelativeTransitionHeight");xp([p()],Ul.prototype,"distance");xp([p(ti)],Ul.prototype,"renderers");class $I{model;get renderers(){return this.model.renderers}constructor(e){this.model=e}}class Sp extends T{lodModels=[];_lods=[];_settings=[];_lodsHandler;start(){if(Vm&&console.log("LODGROUP",this.name,this.lodModels,this),!NI&&!this._lodsHandler&&this.gameObject&&this.lodModels&&Array.isArray(this.lodModels)){const e=[];for(const i of this.lodModels){const n=new $I(i);this._lods.push(n);for(const o of n.renderers)e.includes(o)||e.push(o)}this._lodsHandler=new Array;for(let i=0;i<e.length;i++){const n=new c.LOD;this._lodsHandler.push(n),this.gameObject.add(n)}const t=new c.Object3D;t.name="Cull "+this.name;for(let i=0;i<e.length;i++){const n=e[i],o=this._lodsHandler[i],r=n.gameObject;Vm&&console.log(i,r.name);for(const a of this._lods){const l=a.model.distance;let h=null;if(a.renderers.includes(n)?h=r:h=t,h.type==="Group"){console.warn(`LODGroup ${this.name}: Group or MultiMaterial object's are not supported as LOD object: ${h.name}`);continue}Vm&&console.log("LEVEL",h.name,l),o.autoUpdate=!1,this.onAddLodLevel(o,h,a.model.distance)}}}}onAfterRender(){if(!this.gameObject||!this._lodsHandler)return;const e=this.context.mainCamera;if(e)for(const t of this._lodsHandler){t.update(e);const i=t.getCurrentLevel(),n=t.levels[i];t.layers.mask=n.object.layers.mask}}onAddLodLevel(e,t,i){if(t===this.gameObject){console.warn("LODGroup component must be on parent object and not mesh directly at the moment",t.name,t);return}e.addLevel(t,i*this._distanceFactor,.01);const n={lod:e,levelIndex:e.levels.length-1,distance:i};this._settings.push(n)}_distanceFactor=1;distanceFactor(e){if(e!==this._distanceFactor){this._distanceFactor=e;for(const t of this._settings){const i=t.lod.levels[t.levelIndex];i.distance=t.distance*e}}}}xp([p(Ul)],Sp.prototype,"lodModels");var VI=Object.defineProperty,yb=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&VI(e,t,n),n};const nu=x("debugnestedgltf");class zl extends T{filePath;loaded=new Z;loadAssetInParent=!0;_isLoadingOrDoneLoading=!1;listenToProgress(e){this.filePath?.beginListenDownload(e)}preload(){return this.filePath?.preload()||null}async start(){if(this._isLoadingOrDoneLoading)return;nu&&console.log(this,this.guid);const e=this.gameObject.parent;if(e&&this.filePath){this._isLoadingOrDoneLoading=!0;const t=new hs;t.idProvider=new ot(this.hash(this.guid)),t.parent=this.loadAssetInParent!==!1?e:this.gameObject,this.gameObject.updateMatrix();const i=this.gameObject.matrix;nu&&console.log("Load nested:",this.filePath?.url??this.filePath,this.gameObject.position);const n=await this.filePath?.instantiate?.call(this.filePath,t);nu&&console.log("Nested loaded:",this.filePath?.url??this.filePath,n),n&&this.loadAssetInParent!==!1&&(n.matrixAutoUpdate=!1,n.matrix.identity(),n.applyMatrix4(i),n.matrixAutoUpdate=!0,n.layers.disableAll(),n.layers.set(this.layer),this.loaded.invoke({component:this,instance:n,asset:this.filePath})),nu&&console.log("Nested loading done:",this.filePath?.url??this.filePath,n)}}onDestroy(){this.filePath?.unload()}hash(e){let t=0;for(let i=0;i<e.length;i++)t=e.charCodeAt(i)+((t<<5)-t);return t}}yb([p(J)],zl.prototype,"filePath");yb([p(Z)],zl.prototype,"loaded");yb([p()],zl.prototype,"loadAssetInParent");var WI=Object.defineProperty,_b=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&WI(e,t,n),n};const GI=x("debugnet"),Cp=class py extends T{url=null;urlParameterName=null;localhost=null;awake(){GI&&console.log(this),this.context.connection.registerProvider(this)}getWebsocketUrl(){let e=this.url?py.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){const o=x(this.urlParameterName);o&&typeof o=="string"&&(e=o)}if(!e)return null;const i=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(e);return i?.groups?i?.groups.socket_prefix?e:"wss://"+i?.groups.url:null}static GetUrl(e,t){let i=e;const n=py.IsLocalNetwork()&&t;if(n&&(i=t),e?.startsWith("/")){const o=n?i:window.location.origin;o?.endsWith("/")&&e.startsWith("/")&&(e=e.substring(1)),i=o+e}return i}static IsLocalNetwork(e=window.location.hostname){return ki(e)}};_b([p()],Cp.prototype,"url");_b([p()],Cp.prototype,"urlParameterName");_b([p()],Cp.prototype,"localhost");let bb=Cp;var HI=Object.defineProperty,Pp=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&HI(e,t,n),n};class Jr extends T{referenceSpace;from;affectPosition=!1;affectRotation=!1;alignLookDirection=!1;levelLookDirection=!1;levelPosition=!1;positionOffset=new c.Vector3(0,0,0);rotationOffset=new c.Vector3(0,0,0);offset=new c.Vector3(0,0,0);update(){if(!this.from)return;var e=ie(this.from),t=Se(this.from);this.offset.copy(this.positionOffset);const i=this.offset.length();if(this.referenceSpace&&this.offset.transformDirection(this.referenceSpace.matrixWorld).multiplyScalar(i),e.add(this.offset),this.levelPosition&&this.referenceSpace){const a=new c.Plane(this.gameObject.up,0),l=ie(this.referenceSpace);a.setFromNormalAndCoplanarPoint(this.gameObject.up,l);const h=new c.Vector3(0,0,0);a.projectPoint(e,h),e.copy(h)}this.affectPosition&&Oi(this.gameObject,e);const n=new c.Euler(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),o=new c.Quaternion().setFromEuler(n);this.affectRotation&&vn(this.gameObject,t.multiply(o));const r=new c.Vector3;this.from.getWorldDirection(r).multiplyScalar(50),this.levelLookDirection&&(r.y=0),this.alignLookDirection&&this.gameObject.lookAt(r)}}Pp([p(P)],Jr.prototype,"referenceSpace");Pp([p(P)],Jr.prototype,"from");Pp([p(c.Vector3)],Jr.prototype,"positionOffset");Pp([p(c.Vector3)],Jr.prototype,"rotationOffset");var qI=Object.defineProperty,$o=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&qI(e,t,n),n};class ui{time=0;value=0;inTangent=1/0;inWeight;outTangent=1/0;outWeight;weightedMode;constructor(e=0,t=0){this.time=e,this.value=t}}$o([p()],ui.prototype,"time");$o([p()],ui.prototype,"value");$o([p()],ui.prototype,"inTangent");$o([p()],ui.prototype,"inWeight");$o([p()],ui.prototype,"outTangent");$o([p()],ui.prototype,"outWeight");$o([p()],ui.prototype,"weightedMode");const k1=class Ac{static linearFromTo(e,t,i){const n=new Ac,o=new ui;o.time=0,o.value=e;const r=new ui;return r.time=i,r.value=t,n.keys.push(o,r),n}static constant(e){const t=new Ac,i=new ui;return i.time=0,i.value=e,t.keys.push(i),t}keys=[];clone(){const e=new Ac;return e.keys=this.keys?.map(t=>{const i=new ui;return i.time=t.time,i.value=t.value,i.inTangent=t.inTangent,i.inWeight=t.inWeight,i.outTangent=t.outTangent,i.outWeight=t.outWeight,i.weightedMode=t.weightedMode,i})||[],e}get duration(){return!this.keys||this.keys.length==0?0:this.keys[this.keys.length-1].time}evaluate(e){if(!this.keys||this.keys.length==0)return 0;if(this.keys.length===1)return this.keys[0].value;if(this.keys[0].time>=e)return this.keys[0].value;for(let t=0;t<this.keys.length;t++){const i=this.keys[t];if(i.time<=e)if(t+1<this.keys.length){const o=this.keys[t+1];if(o.time<e)continue;return!isFinite(i.outTangent)||!isFinite(o.inTangent)?i.value:Ac.interpolateValue(e,i,o)}else return i.value}return this.keys[this.keys.length-1].value}static interpolateValue(e,t,i){const n=t.time,o=t.value,r=t.outTangent,a=i.time,l=i.value,h=i.inTangent,d=a-n,u=d*d,f=u*d,m=((r+h)*d-2*(l-o))/f,g=(3*(l-o)-(h+2*r)*d)/u,v=r,_=o,y=e-n,b=y*y,w=b*y;return m*w+g*b+v*y+_}};$o([p(ui)],k1.prototype,"keys");let Zh=k1;var XI=Object.defineProperty,S=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&XI(e,t,n),n};const su=x("debugparticles");var ks=(s=>(s[s.Billboard=0]="Billboard",s[s.Stretch=1]="Stretch",s[s.HorizontalBillboard=2]="HorizontalBillboard",s[s.VerticalBillboard=3]="VerticalBillboard",s[s.Mesh=4]="Mesh",s))(ks||{});class ea{alphaKeys=[];colorKeys=[];get duration(){return 1}evaluate(e,t){let i,n=0,o=null,r=0;for(let a=0;a<this.alphaKeys.length;a++){const l=this.alphaKeys[a];(l.time<e||!i)&&(i=l,n=a)}for(let a=0;a<this.colorKeys.length;a++){const l=this.colorKeys[a];(l.time<e||!o)&&(o=l,r=a)}if(o)if(r+1<this.colorKeys.length){const l=this.colorKeys[r+1],h=L.remap(e,o.time,l.time,0,1);t.r=L.lerp(o.color.r,l.color.r,h),t.g=L.lerp(o.color.g,l.color.g,h),t.b=L.lerp(o.color.b,l.color.b,h)}else t.r=o.color.r,t.g=o.color.g,t.b=o.color.b;if(i)if(n+1<this.alphaKeys.length){const l=this.alphaKeys[n+1],h=L.remap(e,i.time,l.time,0,1);t.alpha=L.lerp(i.alpha,l.alpha,h)}else t.alpha=i.alpha;return t}}S([p()],ea.prototype,"alphaKeys");S([p()],ea.prototype,"colorKeys");var bh=(s=>(s[s.Local=0]="Local",s[s.World=1]="World",s[s.Custom=2]="Custom",s))(bh||{}),vf=(s=>(s[s.Sphere=0]="Sphere",s[s.SphereShell=1]="SphereShell",s[s.Hemisphere=2]="Hemisphere",s[s.HemisphereShell=3]="HemisphereShell",s[s.Cone=4]="Cone",s[s.Box=5]="Box",s[s.Mesh=6]="Mesh",s[s.ConeShell=7]="ConeShell",s[s.ConeVolume=8]="ConeVolume",s[s.ConeVolumeShell=9]="ConeVolumeShell",s[s.Circle=10]="Circle",s[s.CircleEdge=11]="CircleEdge",s[s.SingleSidedEdge=12]="SingleSidedEdge",s[s.MeshRenderer=13]="MeshRenderer",s[s.SkinnedMeshRenderer=14]="SkinnedMeshRenderer",s[s.BoxShell=15]="BoxShell",s[s.BoxEdge=16]="BoxEdge",s[s.Donut=17]="Donut",s[s.Rectangle=18]="Rectangle",s[s.Sprite=19]="Sprite",s[s.SpriteRenderer=20]="SpriteRenderer",s))(vf||{});const Hs=class Dc{static constant(e){const t=new Dc;return t.setConstant(e),t}static betweenTwoConstants(e,t){const i=new Dc;return i.setMinMaxConstant(e,t),i}static curve(e,t=1){const i=new Dc;return i.setCurve(e,t),i}setConstant(e){this.mode=0,this.constant=e}setMinMaxConstant(e,t){this.mode=3,this.constantMin=e,this.constantMax=t}setCurve(e,t=1){this.mode=1,this.curve=e,this.curveMultiplier=t}mode="Constant";constant;constantMin;constantMax;curve;curveMin;curveMax;curveMultiplier;clone(){const e=new Dc;return e.mode=this.mode,e.constant=this.constant,e.constantMin=this.constantMin,e.constantMax=this.constantMax,e.curve=this.curve?.clone(),e.curveMin=this.curveMin?.clone(),e.curveMax=this.curveMax?.clone(),e.curveMultiplier=this.curveMultiplier,e}evaluate(e,t){const i=t===void 0?Math.random():t;switch(this.mode){case 0:case"Constant":return this.constant;case 1:case"Curve":return e=L.clamp01(e),this.curve.evaluate(e)*this.curveMultiplier;case 2:case"TwoCurves":const n=e*this.curveMin.duration,o=e*this.curveMax.duration;return L.lerp(this.curveMin.evaluate(n),this.curveMax.evaluate(o),i%1)*this.curveMultiplier;case 3:case"TwoConstants":return L.lerp(this.constantMin,this.constantMax,i%1);default:this.curveMax.evaluate(e)*this.curveMultiplier;break}return 0}getMax(){switch(this.mode){case 0:case"Constant":return this.constant;case 1:case"Curve":return this.getMaxFromCurve(this.curve)*this.curveMultiplier;case 2:case"TwoCurves":return Math.max(this.getMaxFromCurve(this.curveMin),this.getMaxFromCurve(this.curveMax))*this.curveMultiplier;case 3:case"TwoConstants":return Math.max(this.constantMin,this.constantMax);default:return 0}}getMaxFromCurve(e){if(!e)return 0;let t=Number.MIN_VALUE;for(let i=0;i<e.keys.length;i++){const n=e.keys[i];n.value>t&&(t=n.value)}return t}};S([p()],Hs.prototype,"mode");S([p()],Hs.prototype,"constant");S([p()],Hs.prototype,"constantMin");S([p()],Hs.prototype,"constantMax");S([p(Zh)],Hs.prototype,"curve");S([p(Zh)],Hs.prototype,"curveMin");S([p(Zh)],Hs.prototype,"curveMax");S([p()],Hs.prototype,"curveMultiplier");let Q=Hs;const Vo=class Tt{static constant(e){const t=new Tt;return t.constant(e),t}static betweenTwoColors(e,t){const i=new Tt;return i.betweenTwoColors(e,t),i}constant(e){return this.mode=0,this.color=e,this}betweenTwoColors(e,t){return this.mode=2,this.colorMin=e,this.colorMax=t,this}mode=0;color;colorMin;colorMax;gradient;gradientMin;gradientMax;static _temp=new oe(0,0,0,1);static _temp2=new oe(0,0,0,1);evaluate(e,t){const i=t===void 0?Math.random():t;switch(this.mode){case 0:case"Color":return this.color;case 1:case"Gradient":return this.gradient.evaluate(e,Tt._temp),Tt._temp;case 2:case"TwoColors":return Tt._temp.lerpColors(this.colorMin,this.colorMax,i);case 3:case"TwoGradients":return this.gradientMin.evaluate(e,Tt._temp),this.gradientMax.evaluate(e,Tt._temp2),Tt._temp.lerp(Tt._temp2,i);case 4:case"RandomColor":const o=Math.random();return this.gradientMin.evaluate(e,Tt._temp),this.gradientMax.evaluate(e,Tt._temp2),Tt._temp.lerp(Tt._temp2,o)}return Tt._temp.set(16777215),Tt._temp.alpha=1,Tt._temp}};S([p()],Vo.prototype,"mode");S([p(oe)],Vo.prototype,"color");S([p(oe)],Vo.prototype,"colorMin");S([p(oe)],Vo.prototype,"colorMax");S([p(ea)],Vo.prototype,"gradient");S([p(ea)],Vo.prototype,"gradientMin");S([p(ea)],Vo.prototype,"gradientMax");let ta=Vo;var my=(s=>(s[s.Hierarchy=0]="Hierarchy",s[s.Local=1]="Local",s[s.Shape=2]="Shape",s))(my||{});class $t{cullingMode;duration;emitterVelocityMode;flipRotation;gravityModifier;gravityModifierMultiplier;loop;maxParticles;playOnAwake;prewarm;ringBufferLoopRange;ringBufferMode;scalingMode;simulationSpace;simulationSpeed;startColor;startDelay;startDelayMultiplier;startLifetime;startLifetimeMultiplier;startRotation;startRotationMultiplier;startRotation3D;startRotationX;startRotationXMultiplier;startRotationY;startRotationYMultiplier;startRotationZ;startRotationZMultiplier;startSize;startSize3D;startSizeMultiplier;startSizeX;startSizeXMultiplier;startSizeY;startSizeYMultiplier;startSizeZ;startSizeZMultiplier;startSpeed;startSpeedMultiplier;stopAction;useUnscaledTime}S([p(Q)],$t.prototype,"gravityModifier");S([p(ta)],$t.prototype,"startColor");S([p(Q)],$t.prototype,"startDelay");S([p(Q)],$t.prototype,"startLifetime");S([p(Q)],$t.prototype,"startRotation");S([p(Q)],$t.prototype,"startRotationX");S([p(Q)],$t.prototype,"startRotationY");S([p(Q)],$t.prototype,"startRotationZ");S([p(Q)],$t.prototype,"startSize");S([p(Q)],$t.prototype,"startSizeX");S([p(Q)],$t.prototype,"startSizeY");S([p(Q)],$t.prototype,"startSizeZ");S([p(Q)],$t.prototype,"startSpeed");class wf{cycleCount;maxCount;minCount;probability;repeatInterval;time;count;_performed=0;reset(){this._performed=0}run(e){if(e<=this.time)return 0;let t=0;if(this.cycleCount===0||this._performed<this.cycleCount){const i=this.time+this.repeatInterval*this._performed;if(e>=i&&(this._performed+=1,Math.random()<this.probability))switch(this.count.mode){case 0:t=this.count.constant;break;case 3:t=L.lerp(this.count.constantMin,this.count.constantMax,Math.random());break;case 1:t=this.count.curve.evaluate(Math.random());break;case 2:const n=Math.random();t=L.lerp(this.count.curveMin.evaluate(n),this.count.curveMax.evaluate(n),Math.random());break}}return t}}class qs{enabled;get burstCount(){return this.bursts?.length??0}bursts;rateOverTime;rateOverTimeMultiplier;rateOverDistance;rateOverDistanceMultiplier;system;reset(){this.bursts?.forEach(e=>e.reset())}getBurst(){let e=0;if(this.burstCount>0)for(let t=0;t<this.burstCount;t++){const i=this.bursts[t];this.system.main.loop&&i.time>=this.system.time&&i.reset(),e+=Math.round(i.run(this.system.time))}return e}}S([p()],qs.prototype,"enabled");S([p()],qs.prototype,"bursts");S([p(Q)],qs.prototype,"rateOverTime");S([p()],qs.prototype,"rateOverTimeMultiplier");S([p(Q)],qs.prototype,"rateOverDistance");S([p()],qs.prototype,"rateOverDistanceMultiplier");class kp{enabled;color}S([p(ta)],kp.prototype,"color");class ia{enabled;separateAxes;size;sizeMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;_time=0;_temp=new c.Vector3;evaluate(e,t,i){if(t||(t=this._temp),!this.enabled)return t.x=t.y=t.z=1,t;if(this.separateAxes)t.x=this.x.evaluate(e,i)*this.xMultiplier,t.y=this.y.evaluate(e,i)*this.yMultiplier,t.z=this.z.evaluate(e,i)*this.zMultiplier;else{const n=this.size.evaluate(e,i)*this.sizeMultiplier;t.x=n}return t}}S([p(Q)],ia.prototype,"size");S([p(Q)],ia.prototype,"x");S([p(Q)],ia.prototype,"y");S([p(Q)],ia.prototype,"z");const lt=class Ic{get type(){return vf[this.shapeType]}initialize(e){this.onInitialize(e),e.position.x=this._vector.x,e.position.y=this._vector.y,e.position.z=this._vector.z}toJSON(){return this}clone(){return new Ic}shapeType=5;enabled=!0;alignToDirection=!1;angle=0;arc=360;arcSpread;arcSpeedMultiplier;arcMode;boxThickness;position;rotation;_rotation=new c.Euler;scale;radius;radiusThickness;sphericalDirectionAmount;randomDirectionAmount;randomPositionAmount;meshShapeType;meshRenderer;_meshObj;_meshGeometry;setMesh(e){this.meshRenderer=e,e?(this._meshObj=e.sharedMeshes[Math.floor(Math.random()*e.sharedMeshes.length)],this._meshGeometry=this._meshObj.geometry):(this._meshObj=void 0,this._meshGeometry=void 0)}system;_space;_worldSpaceMatrix=new c.Matrix4;_worldSpaceMatrixInverse=new c.Matrix4;constructor(){su&&console.log(this)}update(e,t){}onUpdate(e,t,i,n){this.system=e,this._space=i,i===1&&(this._worldSpaceMatrix.copy(n.matrixWorld),this._worldSpaceMatrix.elements[0]=1,this._worldSpaceMatrix.elements[5]=1,this._worldSpaceMatrix.elements[10]=1,this._worldSpaceMatrixInverse.copy(this._worldSpaceMatrix).invert())}applyRotation(e){const t=this.rotation.x!==0||this.rotation.y!==0||this.rotation.z!==0;return t&&(this._rotation.x=L.toRadians(this.rotation.x),this._rotation.y=L.toRadians(this.rotation.y),this._rotation.z=L.toRadians(this.rotation.z),this._rotation.order="ZYX",e.applyEuler(this._rotation)),t}_vector=new c.Vector3(0,0,0);_temp=new c.Vector3(0,0,0);_triangle=new c.Triangle;onInitialize(e){this._vector.set(0,0,0),e.mesh=void 0,e.mesh_geometry=void 0;const t=this._temp.copy(this.position),i=this._space===1;i&&t.applyQuaternion(this.system.worldQuaternion);let n=this.radius;if(i&&(n*=this.system.worldScale.x),this.enabled){switch(this.shapeType){case 5:su&&B.DrawWireBox(this.position,this.scale,14540253,1),this._vector.x=Math.random()*this.scale.x-this.scale.x/2,this._vector.y=Math.random()*this.scale.y-this.scale.y/2,this._vector.z=Math.random()*this.scale.z-this.scale.z/2,this._vector.add(t);break;case 4:this.randomConePoint(this.position,this.angle,n,this.radiusThickness,this.arc,this.arcMode,this._vector);break;case 0:this.randomSpherePoint(this.position,n,this.radiusThickness,this.arc,this._vector);break;case 10:this.randomCirclePoint(this.position,n,this.radiusThickness,this.arc,this._vector);break;case 13:const o=this.meshRenderer;o?.destroyed==!1&&this.setMesh(o);const r=e.mesh=this._meshObj,a=e.mesh_geometry=this._meshGeometry;if(r&&a)switch(this.meshShapeType){case 0:{const l=a.getAttribute("position"),h=Math.floor(Math.random()*l.count);this._vector.fromBufferAttribute(l,h),this._vector.applyMatrix4(r.matrixWorld),e.mesh_normal=h}break;case 1:break;case 2:{const l=a.index;if(l){let h=Math.random(),d=Math.random();h+d>1&&(h=1-h,d=1-d);const u=Math.floor(Math.random()*(l.count/3));let f=u*3,m=u*3+1,g=u*3+2;f=l.getX(f),m=l.getX(m),g=l.getX(g);const v=a.getAttribute("position");this._triangle.a.fromBufferAttribute(v,f),this._triangle.b.fromBufferAttribute(v,m),this._triangle.c.fromBufferAttribute(v,g),this._vector.set(0,0,0).addScaledVector(this._triangle.a,h).addScaledVector(this._triangle.b,d).addScaledVector(this._triangle.c,1-(h+d)),this._vector.applyMatrix4(r.matrixWorld),e.mesh_normal=u}}break}break;default:this._vector.set(0,0,0),E()&&!globalThis.__particlesystem_shapetype_unsupported&&(console.warn("ParticleSystem ShapeType is not supported:",vf[this.shapeType]),globalThis.__particlesystem_shapetype_unsupported=!0);break}this.randomizePosition(this._vector,this.randomPositionAmount)}this.applyRotation(this._vector),i&&(this._vector.applyQuaternion(this.system.worldQuaternion),this._vector.add(this.system.worldPos)),su&&B.DrawSphere(this._vector,.03,16711680,.5,!0)}_dir=new c.Vector3;getDirection(e,t){if(!this.enabled)return this._dir.set(0,0,1),this._dir;switch(this.shapeType){case 5:this._dir.set(0,0,1);break;case 4:this._dir.set(0,0,1);break;case 10:case 0:const i=t.x,n=t.y,o=t.z;this._dir.set(i,n,o),this.system?.worldspace?this._dir.sub(this.system.worldPos):this._dir.sub(this.position);break;case 13:const r=e.mesh,a=e.mesh_geometry;if(r&&a)switch(this.meshShapeType){case 0:{const l=a.getAttribute("normal"),h=e.mesh_normal;this._dir.fromBufferAttribute(l,h)}break;case 1:break;case 2:{const l=a.index;if(l){const h=e.mesh_normal,d=l.getX(h*3),u=l.getX(h*3+1),f=l.getX(h*3+2),m=a.getAttribute("position"),g=F(),v=F(),_=F();g.fromBufferAttribute(m,d),v.fromBufferAttribute(m,u),_.fromBufferAttribute(m,f),g.sub(v),_.sub(v),g.cross(_),this._dir.copy(g).multiplyScalar(-1);const y=Se(r);this._dir.applyQuaternion(y)}}break}break;default:this._dir.set(0,0,1);break}return this._space===1&&this._dir.applyQuaternion(this.system.worldQuaternion),this.applyRotation(this._dir),this._dir.normalize(),this.spherizeDirection(this._dir,this.sphericalDirectionAmount),this.randomizeDirection(this._dir,this.randomDirectionAmount),su&&(B.DrawSphere(t,.01,8925952,.5,!0),B.DrawDirection(t,this._dir,8925952,.5,!0)),this._dir}static _randomQuat=new c.Quaternion;static _tempVec=new c.Vector3;randomizePosition(e,t){if(t<=0)return;const i=Ic._tempVec;i.set(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1),i.x*=t*this.scale.x,i.y*=t*this.scale.y,i.z*=t*this.scale.z,e.add(i)}randomizeDirection(e,t){if(t===0)return;const i=Ic._randomQuat,n=Ic._tempVec;n.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).normalize(),i.setFromAxisAngle(n,t*Math.random()*Math.PI),e.applyQuaternion(i)}spherizeDirection(e,t){if(t===0)return;const i=Math.random()*Math.PI*2,n=Math.acos(1-Math.random()*2),o=Math.sin(n)*Math.cos(i),r=Math.sin(n)*Math.sin(i),a=Math.cos(n),l=new c.Vector3(o,r,a);e.lerp(l,t)}randomSpherePoint(e,t,i,n,o){const r=Math.random(),a=Math.random(),l=2*Math.PI*r*(n/360),h=Math.acos(2*a-1),d=L.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,u=e.x+this.scale.x*(-d*Math.sin(h)*Math.cos(l)),f=e.y+this.scale.y*(d*Math.sin(h)*Math.sin(l)),m=e.z+this.scale.z*(d*Math.cos(h));o.x=u,o.y=f,o.z=m}randomCirclePoint(e,t,i,n,o){const r=Math.random(),a=2*Math.PI*r*(n/360),l=L.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,h=e.x+this.scale.x*l*Math.cos(a),d=e.y+this.scale.y*l*Math.sin(a),u=e.z;o.x=h,o.y=d,o.z=u}_loopTime=0;_loopDirection=1;randomConePoint(e,t,i,n,o,r,a){let l=0,h=0;switch(r){case 0:l=Math.random(),h=Math.random();break;case 2:this._loopTime>1&&(this._loopDirection=-1),this._loopTime<0&&(this._loopDirection=1);case 1:l=.5,h=Math.random(),this._loopTime+=this.system.deltaTime*this._loopDirection;break}let d=2*Math.PI*l*(o/360);switch(r){case 2:case 1:d+=Math.PI+.5,d+=this._loopTime*Math.PI*2,d%=L.toRadians(o);break}const u=Math.acos(2*h-1),f=L.lerp(1,1-Math.pow(1-Math.random(),Math.PI),n)*i,m=e.x+-f*Math.sin(u)*Math.cos(d),g=e.y+f*Math.sin(u)*Math.sin(d),v=e.z;a.x=m*this.scale.x,a.y=g*this.scale.y,a.z=v*this.scale.z}};S([p()],lt.prototype,"shapeType");S([p()],lt.prototype,"enabled");S([p()],lt.prototype,"alignToDirection");S([p()],lt.prototype,"angle");S([p()],lt.prototype,"arc");S([p()],lt.prototype,"arcSpread");S([p()],lt.prototype,"arcSpeedMultiplier");S([p()],lt.prototype,"arcMode");S([p(c.Vector3)],lt.prototype,"boxThickness");S([p(c.Vector3)],lt.prototype,"position");S([p(c.Vector3)],lt.prototype,"rotation");S([p(c.Vector3)],lt.prototype,"scale");S([p()],lt.prototype,"radius");S([p()],lt.prototype,"radiusThickness");S([p()],lt.prototype,"sphericalDirectionAmount");S([p()],lt.prototype,"randomDirectionAmount");S([p()],lt.prototype,"randomPositionAmount");S([p()],lt.prototype,"meshShapeType");S([p(Vh)],lt.prototype,"meshRenderer");let vb=lt;class ve{damping;enabled;frequency;octaveCount;octaveMultiplier;octaveScale;positionAmount;quality;remap;remapEnabled;remapMultiplier;remapX;remapXMultiplier;remapY;remapYMultiplier;remapZ;remapZMultiplier;scrollSpeedMultiplier;separateAxes;strengthMultiplier;strengthX;strengthXMultiplier;strengthY;strengthYMultiplier;strengthZ;strengthZMultiplier;_noise;_time=0;update(e){this._time+=e.time.deltaTime*this.scrollSpeedMultiplier}_temp=new c.Vector3;apply(e,t,i,n,o,r){if(!this.enabled)return;this._noise||(this._noise=ee.createNoise4D(()=>0));const a=this._temp.set(t.x,t.y,t.z).multiplyScalar(this.frequency),l=this._noise(a.x,a.y,a.z,this._time),h=this._noise(a.x,a.y,a.z,this._time+1e3*this.frequency),d=this._noise(a.x,a.y,a.z,this._time+2e3*this.frequency);this._temp.set(l,h,d).normalize();const u=o/r;let f=this.positionAmount.evaluate(u);this.separateAxes?(this._temp.x*=f*this.strengthXMultiplier,this._temp.y*=f*this.strengthYMultiplier,this._temp.z*=f*this.strengthZMultiplier):(this.strengthX&&(f*=this.strengthX.evaluate(u)*1.5),this._temp.multiplyScalar(f)),i.x+=this._temp.x,i.y+=this._temp.y,i.z+=this._temp.z}}S([p()],ve.prototype,"damping");S([p()],ve.prototype,"enabled");S([p()],ve.prototype,"frequency");S([p()],ve.prototype,"octaveCount");S([p()],ve.prototype,"octaveMultiplier");S([p()],ve.prototype,"octaveScale");S([p(Q)],ve.prototype,"positionAmount");S([p()],ve.prototype,"quality");S([p(Q)],ve.prototype,"remap");S([p()],ve.prototype,"remapEnabled");S([p()],ve.prototype,"remapMultiplier");S([p(Q)],ve.prototype,"remapX");S([p()],ve.prototype,"remapXMultiplier");S([p(Q)],ve.prototype,"remapY");S([p()],ve.prototype,"remapYMultiplier");S([p(Q)],ve.prototype,"remapZ");S([p()],ve.prototype,"remapZMultiplier");S([p()],ve.prototype,"scrollSpeedMultiplier");S([p()],ve.prototype,"separateAxes");S([p()],ve.prototype,"strengthMultiplier");S([p(Q)],ve.prototype,"strengthX");S([p()],ve.prototype,"strengthXMultiplier");S([p(Q)],ve.prototype,"strengthY");S([p()],ve.prototype,"strengthYMultiplier");S([p(Q)],ve.prototype,"strengthZ");S([p()],ve.prototype,"strengthZMultiplier");class ze{enabled;attachRibbonToTransform=!1;colorOverLifetime;colorOverTrail;dieWithParticles=!0;inheritParticleColor=!0;lifetime;lifetimeMultiplier;minVertexDistance=.2;mode=0;ratio=1;ribbonCount=1;shadowBias=0;sizeAffectsLifetime=!1;sizeAffectsWidth=!1;splitSubEmitterRibbons=!1;textureMode=0;widthOverTrail;widthOverTrailMultiplier;worldSpace=!1;getWidth(e,t,i,n){const o=this.widthOverTrail.evaluate(i,n);return e*=o,e}getColor(e,t,i){const n=this.colorOverTrail.evaluate(i),o=this.colorOverLifetime.evaluate(t);e.x*=n.r*o.r,e.y*=n.g*o.g,e.z*=n.b*o.b,"alpha"in n&&"alpha"in o&&(e.w*=n.alpha*o.alpha)}}S([p()],ze.prototype,"enabled");S([p()],ze.prototype,"attachRibbonToTransform");S([p(ta)],ze.prototype,"colorOverLifetime");S([p(ta)],ze.prototype,"colorOverTrail");S([p()],ze.prototype,"dieWithParticles");S([p()],ze.prototype,"inheritParticleColor");S([p(Q)],ze.prototype,"lifetime");S([p()],ze.prototype,"lifetimeMultiplier");S([p()],ze.prototype,"minVertexDistance");S([p()],ze.prototype,"mode");S([p()],ze.prototype,"ratio");S([p()],ze.prototype,"ribbonCount");S([p()],ze.prototype,"shadowBias");S([p()],ze.prototype,"sizeAffectsLifetime");S([p()],ze.prototype,"sizeAffectsWidth");S([p()],ze.prototype,"splitSubEmitterRibbons");S([p()],ze.prototype,"textureMode");S([p(Q)],ze.prototype,"widthOverTrail");S([p()],ze.prototype,"widthOverTrailMultiplier");S([p()],ze.prototype,"worldSpace");class We{enabled;space=0;orbitalX;orbitalY;orbitalZ;orbitalXMultiplier;orbitalYMultiplier;orbitalZMultiplier;orbitalOffsetX;orbitalOffsetY;orbitalOffsetZ;speedModifier;speedModifierMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;_system;update(e){this._system=e}_temp=new c.Vector3;_temp2=new c.Vector3;_temp3=new c.Vector3;_hasOrbital=!1;_index=0;_orbitalMatrix=new c.Matrix4;init(e){this._index==0&&(e.debug=!0),this._index+=1,e.orbitx=this.orbitalX.evaluate(Math.random()),e.orbity=this.orbitalY.evaluate(Math.random()),e.orbitz=this.orbitalZ.evaluate(Math.random()),this._hasOrbital=e.orbitx!=0||e.orbity!=0||e.orbitz!=0}apply(e,t,i,n,o,r,a){if(!this.enabled)return;const l=r/a,h=this.speedModifier.evaluate(l)*this.speedModifierMultiplier,d=this.x.evaluate(l),u=this.y.evaluate(l),f=this.z.evaluate(l);if(this._temp.set(-d,u,f),this._system&&this._system.main.simulationSpace===1&&this._temp.applyQuaternion(this._system.worldQuaternion),this._hasOrbital&&this._system?.worldPos){const g=this._temp2.set(i.x,i.y,i.z),v=this.orbitalXMultiplier,_=this.orbitalYMultiplier,y=this.orbitalZMultiplier,b=h*Math.PI*2*10,w=Math.cos(b*v),C=Math.sin(b*v),k=Math.cos(b*_),O=Math.sin(b*_),D=Math.cos(b*y),I=Math.sin(b*y),j=g.x*(k*D)+g.y*(k*I)+g.z*-O,$=g.x*(C*O*D-w*I)+g.y*(C*O*I+w*D)+g.z*(C*k),W=g.x*(w*O*D+C*I)+g.y*(w*O*I-C*D)+g.z*(w*k),R=this._temp3.set(g.x-j,g.y-$,g.z-W);R.normalize(),R.multiplyScalar(.2/o*Math.max(this.orbitalXMultiplier,this.orbitalYMultiplier,this.orbitalZMultiplier)),n.x+=R.x,n.y+=R.y,n.z+=R.z}n.x+=this._temp.x,n.y+=this._temp.y,n.z+=this._temp.z,n.x*=h,n.y*=h,n.z*=h}}S([p()],We.prototype,"enabled");S([p()],We.prototype,"space");S([p(Q)],We.prototype,"orbitalX");S([p(Q)],We.prototype,"orbitalY");S([p(Q)],We.prototype,"orbitalZ");S([p()],We.prototype,"orbitalXMultiplier");S([p()],We.prototype,"orbitalYMultiplier");S([p()],We.prototype,"orbitalZMultiplier");S([p()],We.prototype,"orbitalOffsetX");S([p()],We.prototype,"orbitalOffsetY");S([p()],We.prototype,"orbitalOffsetZ");S([p(Q)],We.prototype,"speedModifier");S([p()],We.prototype,"speedModifierMultiplier");S([p(Q)],We.prototype,"x");S([p()],We.prototype,"xMultiplier");S([p(Q)],We.prototype,"y");S([p()],We.prototype,"yMultiplier");S([p(Q)],We.prototype,"z");S([p()],We.prototype,"zMultiplier");class Vt{animation;enabled;cycleCount;frameOverTime;frameOverTimeMultiplier;numTilesX;numTilesY;startFrame;startFrameMultiplier;rowMode;rowIndex;spriteCount;timeMode;sampleOnceAtStart(){if(this.timeMode===0)switch(this.frameOverTime.mode){case 0:case 3:case 2:case 1:return!0}return!1}getStartIndex(){return this.sampleOnceAtStart()?Math.random()*(this.numTilesX*this.numTilesY):0}evaluate(e){if(!this.sampleOnceAtStart())return this.getIndex(e)}getIndex(e){const t=this.numTilesX*this.numTilesY;e=e*this.cycleCount;let i=this.frameOverTime.evaluate(e%1);return i*=this.frameOverTimeMultiplier,i*=t,i=i%t,i=Math.floor(i),i}}S([p()],Vt.prototype,"animation");S([p()],Vt.prototype,"enabled");S([p()],Vt.prototype,"cycleCount");S([p(Q)],Vt.prototype,"frameOverTime");S([p()],Vt.prototype,"frameOverTimeMultiplier");S([p()],Vt.prototype,"numTilesX");S([p()],Vt.prototype,"numTilesY");S([p(Q)],Vt.prototype,"startFrame");S([p()],Vt.prototype,"startFrameMultiplier");S([p()],Vt.prototype,"rowMode");S([p()],Vt.prototype,"rowIndex");S([p()],Vt.prototype,"spriteCount");S([p()],Vt.prototype,"timeMode");class Mn{enabled;separateAxes;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t){return this.enabled?this.separateAxes?0:this.z.evaluate(e,t)*-1:0}}S([p()],Mn.prototype,"enabled");S([p()],Mn.prototype,"separateAxes");S([p(Q)],Mn.prototype,"x");S([p()],Mn.prototype,"xMultiplier");S([p(Q)],Mn.prototype,"y");S([p()],Mn.prototype,"yMultiplier");S([p(Q)],Mn.prototype,"z");S([p()],Mn.prototype,"zMultiplier");class on{enabled;range;separateAxes;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t){if(!this.enabled)return 0;if(!this.separateAxes){const i=L.lerp(this.range.x,this.range.y,t);return this.z.evaluate(i)*-1}return 0}}S([p()],on.prototype,"enabled");S([p()],on.prototype,"range");S([p()],on.prototype,"separateAxes");S([p(Q)],on.prototype,"x");S([p()],on.prototype,"xMultiplier");S([p(Q)],on.prototype,"y");S([p()],on.prototype,"yMultiplier");S([p(Q)],on.prototype,"z");S([p()],on.prototype,"zMultiplier");class pt{enabled;dampen;drag;dragMultiplier;limit;limitMultiplier;separateAxes;limitX;limitXMultiplier;limitY;limitYMultiplier;limitZ;limitZMultiplier;multiplyDragByParticleSize=!1;multiplyDragByParticleVelocity=!1;space;_temp=new c.Vector3;_temp2=new c.Vector3;apply(e,t,i,n,o,r,a){if(this.enabled){const l=this.limit.evaluate(o)*this.limitMultiplier;if(t.length()>l){this._temp.copy(t).normalize().multiplyScalar(l);const d=this.dampen*.5;t.x=L.lerp(t.x,this._temp.x,d),t.y=L.lerp(t.y,this._temp.y,d),t.z=L.lerp(t.z,this._temp.z,d),i.x=L.lerp(i.x,this._temp.x,d),i.y=L.lerp(i.y,this._temp.y,d),i.z=L.lerp(i.z,this._temp.z,d)}}}}S([p()],pt.prototype,"enabled");S([p()],pt.prototype,"dampen");S([p(Q)],pt.prototype,"drag");S([p()],pt.prototype,"dragMultiplier");S([p(Q)],pt.prototype,"limit");S([p()],pt.prototype,"limitMultiplier");S([p()],pt.prototype,"separateAxes");S([p(Q)],pt.prototype,"limitX");S([p()],pt.prototype,"limitXMultiplier");S([p(Q)],pt.prototype,"limitY");S([p()],pt.prototype,"limitYMultiplier");S([p(Q)],pt.prototype,"limitZ");S([p()],pt.prototype,"limitZMultiplier");S([p()],pt.prototype,"multiplyDragByParticleSize");S([p()],pt.prototype,"multiplyDragByParticleVelocity");S([p()],pt.prototype,"space");const Jh=class M1{enabled;curve;curveMultiplier;mode;clone(){const e=new M1;return e.enabled=this.enabled,e.curve=this.curve?.clone(),e.curveMultiplier=this.curveMultiplier,e.mode=this.mode,e}system;get _lastWorldPosition(){return this.system._iv_lastWorldPosition||(this.system._iv_lastWorldPosition=new c.Vector3),this.system._iv_lastWorldPosition}get _velocity(){return this.system._iv_velocity||(this.system._iv_velocity=new c.Vector3),this.system._iv_velocity}_temp=new c.Vector3;_firstUpdate=!0;awake(e){this.system=e,this.reset()}reset(){this._firstUpdate=!0}update(e){this.enabled&&this.system.worldspace!==!1&&(this._firstUpdate?(this._firstUpdate=!1,this._velocity.set(0,0,0),this._lastWorldPosition.copy(this.system.worldPos)):this._lastWorldPosition&&(this._velocity.copy(this.system.worldPos).sub(this._lastWorldPosition).multiplyScalar(1/this.system.deltaTime),this._lastWorldPosition.copy(this.system.worldPos)))}applyInitial(e){if(this.enabled&&this.system.worldspace!==!1&&this.mode===0){const t=this.curve.evaluate(Math.random(),Math.random());this._temp.copy(this._velocity).multiplyScalar(t),e.x+=this._temp.x,e.y+=this._temp.y,e.z+=this._temp.z}}_frames=0;applyCurrent(e,t,i){if(this.enabled&&this.system&&this.system.worldspace!==!1&&this.mode===1){const n=this.curve.evaluate(t,i);this._temp.copy(this._velocity).multiplyScalar(n),e.x+=this._temp.x,e.y+=this._temp.y,e.z+=this._temp.z}}};S([p()],Jh.prototype,"enabled");S([p(Q)],Jh.prototype,"curve");S([p()],Jh.prototype,"curveMultiplier");S([p()],Jh.prototype,"mode");let wb=Jh;class _i{enabled;range;separateAxes;size;sizeMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t,i,n){const o=e.length(),r=L.remap(o,this.range.x,this.range.y,0,1),a=this.size.evaluate(r,i);return n.x*=a,n.y*=a,n.z*=a,n}}S([p()],_i.prototype,"enabled");S([p(c.Vector2)],_i.prototype,"range");S([p()],_i.prototype,"separateAxes");S([p(Q)],_i.prototype,"size");S([p()],_i.prototype,"sizeMultiplier");S([p(Q)],_i.prototype,"x");S([p()],_i.prototype,"xMultiplier");S([p(Q)],_i.prototype,"y");S([p()],_i.prototype,"yMultiplier");S([p(Q)],_i.prototype,"z");S([p()],_i.prototype,"zMultiplier");class Nl{enabled;range;color;evaluate(e,t,i){const n=e.length(),o=L.remap(n,this.range.x,this.range.y,0,1),r=this.color.evaluate(o,t);i.x*=r.r,i.y*=r.g,i.z*=r.b,"alpha"in r&&(i.w*=r.alpha)}}S([p()],Nl.prototype,"enabled");S([p(c.Vector2)],Nl.prototype,"range");S([p(ta)],Nl.prototype,"color");class xb{constructor(e,t,i,n){this.system=e,this.particleSystem=t,this.subSystem=i,this.subParticleSystem=n,this.subParticleSystem&&this.subParticleSystem&&(this.subParticleSystem.onlyUsedByOther=!0);const o=1e3;this._circularBuffer=new Mi(()=>new ee.Matrix4,o)}system;particleSystem;subSystem;subParticleSystem;type="NeedleParticleSubEmitter";emitterType;emitterProbability;q_=new c.Quaternion;v_=new c.Vector3;v2_=new c.Vector3;_emitterMatrix=new ee.Matrix4;_circularBuffer;clone(){throw new Error("Method not implemented.")}initialize(e){e.emissionState={burstIndex:0,burstWaveIndex:0,time:0,waitEmiting:0},this._emitterMatrix.copy(this.subSystem.matrixWorld).invert().premultiply(this.system.matrixWorld),this._emitterMatrix.setPosition(0,0,0),this.emitterType===gy.Birth&&this.run(e)}update(e,t){this.run(e)}frameUpdate(e){}toJSON(){}reset(){}run(e){if(this.subSystem.currentParticles>=this.subSystem.main.maxParticles||!this.subParticleSystem||!e.emissionState||this.emitterProbability&&Math.random()>this.emitterProbability)return;const t=this.system.deltaTime;if(this.emitterType===gy.Death){let n=e.life;if(e[Wa]!==void 0&&(n=e[Wa]),!(e.age+t*1.2>=n))return;const r=this.subSystem.main.maxParticles-this.subSystem.currentParticles;e.emissionState.waitEmiting=r}const i=new ee.Matrix4;i.set(1,0,0,e.position.x,0,1,0,e.position.y,0,0,1,e.position.z,0,0,0,1),this.particleSystem.worldSpace||i.multiplyMatrices(this._emitterMatrix,i),this.subParticleSystem.emit(t,e.emissionState,i)}}var QI=Object.defineProperty,Ne=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&QI(e,t,n),n};const po=x("debugparticles"),YI=x("noprogressive"),KI=x("debugprogressive");var gy=(s=>(s[s.Birth=0]="Birth",s[s.Collision=1]="Collision",s[s.Death=2]="Death",s[s.Trigger=3]="Trigger",s[s.Manual=4]="Manual",s))(gy||{});class rn extends T{renderMode;particleMaterial;trailMaterial;particleMesh;maxParticleSize;minParticleSize;velocityScale;cameraVelocityScale;lengthScale;start(){if(this.maxParticleSize!==.5&&this.minParticleSize!==0&&E()){const e=`ParticleSystem "${this.name}" has non-default min/max particle size. This may not render correctly. Please set min size to 0 and the max size to 0.5 and use the "StartSize" setting instead`;console.warn(e)}}get transparent(){return this.particleMaterial?.transparent??!1}getMaterial(e=!1){let t=e===!0&&this.trailMaterial?this.trailMaterial:this.particleMaterial;if(t){if(t.type==="MeshStandardMaterial"){po&&console.debug("ParticleSystemRenderer.getMaterial: MeshStandardMaterial detected, converting to MeshBasicMaterial. See https://github.com/Alchemist0823/three.quarks/issues/101"),"map"in t&&t.map&&(t.map.colorSpace=c.LinearSRGBColorSpace,t.map.premultiplyAlpha=!1);const i=new c.MeshBasicMaterial;i.copy(t),e?this.trailMaterial=i:this.particleMaterial=i}t.map&&(t.map.colorSpace=c.LinearSRGBColorSpace,t.map.premultiplyAlpha=!1),e&&t.side===c.FrontSide&&(t=t.clone(),t.side=c.BackSide,e?this.trailMaterial=t:this.particleMaterial=t)}return t&&!YI&&t._didRequestTextureLOD===void 0&&(t._didRequestTextureLOD=0,KI&&console.log("Load material LOD",t.name),re.NEEDLE_progressive.assignTextureLOD(t,0)),t}getMesh(e){let t=null;if(!t&&(this.particleMesh instanceof c.Mesh&&(t=this.particleMesh.geometry),t===null)){t=new c.PlaneGeometry(1,1);const n=t.attributes.uv;for(let o=0;o<n.count;o++)n.setX(o,1-n.getX(o))}return new c.Mesh(t,this.getMaterial())}}Ne([p()],rn.prototype,"renderMode");Ne([p(c.Material)],rn.prototype,"particleMaterial");Ne([p(c.Material)],rn.prototype,"trailMaterial");Ne([p()],rn.prototype,"maxParticleSize");Ne([p()],rn.prototype,"minParticleSize");Ne([p()],rn.prototype,"velocityScale");Ne([p()],rn.prototype,"cameraVelocityScale");Ne([p()],rn.prototype,"lengthScale");class ou{_curve;_factor;constructor(e,t=1){this._curve=e,this._factor=t}type="function";startGen(e){}genValue(e,t){return this._curve.evaluate(t,Math.random())*this._factor}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}}class Sb{type="value";toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}startGen(e){}system;constructor(e){this.system=e}}class ZI extends Sb{genValue(){return this.system.textureSheetAnimation.getStartIndex()}}class JI extends Sb{_lastPosition=new c.Vector3;_lastDistance=0;update(){const e=ie(this.system.gameObject);this._lastDistance=this._lastPosition.distanceTo(e),this._lastPosition.copy(e)}genValue(){if(!this.system.isPlaying||!this.system.emission.enabled||this.system.currentParticles>=this.system.maxParticles)return 0;let e=this.system.emission.rateOverTime.evaluate(this.system.time/this.system.duration,Math.random());if(this.system.deltaTime>0){const n=this.system.emission.rateOverDistance.evaluate(this.system.time/this.system.duration,Math.random());let r=this._lastDistance/this.system.deltaTime*n;Number.isFinite(r)||(r=0),e+=r}const t=this.system.emission.getBurst();t>0&&(e+=t/this.system.deltaTime);const i=this.system.maxParticles-this.system.currentParticles;return L.clamp(e,0,i/this.system.deltaTime)}}class eL extends Sb{genValue(){return this.system.isPlaying,0}}class Wo{system;get context(){return this.system.context}constructor(e){this.type=Object.getPrototypeOf(this).constructor.name||"ParticleSystemBaseBehaviour",e&&(this.system=e)}type;initialize(e){}update(e,t){}frameUpdate(e){}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}reset(){}}class tL extends Wo{type="NeedleTextureSheet";update(e,t){const i=this.system.textureSheetAnimation;if(i.enabled){const n=e.age/e.life,o=i.evaluate(n);o!==void 0&&(e.uvTile=o)}}}const rw=Symbol("particleRotation");class iL extends Wo{type="NeedleRotation";initialize(e){e[rw]=Math.random()}update(e,t){if(e.rotation===void 0)return;const i=e.age/e.life;if(typeof e.rotation=="number"&&(this.system.rotationOverLifetime.enabled?e.rotation+=this.system.rotationOverLifetime.evaluate(i,e[rw])*t:this.system.renderer.renderMode===ks.Billboard&&(e.rotation=Math.PI),this.system.rotationBySpeed.enabled)){const n=e.velocity.length();e.rotation+=this.system.rotationBySpeed.evaluate(i,n)*t}}}const aw=Symbol("sizeLerpFactor"),nL=new c.Vector3;class sL extends Wo{type="NeedleSize";_minSize=0;_maxSize=1;initialize(e){e[aw]=Math.random(),this._minSize=this.system.renderer.minParticleSize,this._maxSize=this.system.renderer.maxParticleSize}update(e,t){const i=e.age/e.life;let n=1;this.system.sizeOverLifetime.enabled&&(n*=this.system.sizeOverLifetime.evaluate(i,void 0,e[aw]).x);let o=1;this.system.renderer.renderMode!==ks.Mesh&&(o=this.system.worldScale.x/this.system.cameraScale);const r=F(e.startSize).multiplyScalar(n*o);if(e.size.set(r.x,r.y,r.z),this.system.localspace){const a=O1(this.system,nL);e.size.x*=a.x,e.size.y*=a.y,e.size.z*=a.z}}}const Wa=Symbol("particleLife"),Wm=Symbol("trailLifetime"),lw=Symbol("trailStartLength"),Gm=Symbol("trailWidthRandom");class oL extends Wo{type="NeedleTrail";initialize(e){e instanceof ee.TrailParticle&&(e[Wa]=e.life,this.system.trails.enabled&&this.system.trails.dieWithParticles===!1&&(e[Wm]=this.system.trails.lifetime.evaluate(Math.random(),Math.random()),e.life+=e[Wm]),e[lw]=e.length,e[Gm]=Math.random())}update(e){if(this.system.trails?.enabled&&e instanceof ee.TrailParticle){const t=e,i=e.age/e[Wa],n=e.previous.values(),o=e.previous.length;for(let r=0;r<o;r++){const l=n.next().value,h=1-r/(o-1),d=e.size;if(d.x<=0&&!this.system.trails.sizeAffectsWidth){const u=20*this.system.trails.widthOverTrail.evaluate(.5,t[Gm]);d.x=u,d.y=u,d.z=u}l.size=this.system.trails.getWidth(d.x,i,h,t[Gm]),l.color.copy(e.color),this.system.trails.getColor(l.color,i,h)}if(e.age>e[Wa]){e.velocity.set(0,0,0);const r=(e.age-e[Wa])/e[Wm];t.length=L.lerp(e[lw],0,r)}}}}const ru=Symbol("startVelocity"),cw=Symbol("gravityModifier"),Hm=Symbol("gravitySpeed"),au=Symbol("velocity lerp factor"),yy=new c.Vector3;class rL extends Wo{type="NeedleVelocity";_gravityDirection=new c.Vector3;initialize(e){const t=this.system.main.simulationSpeed;e.startSpeed=this.system.main.startSpeed.evaluate(Math.random(),Math.random());const i=this.system.shape.getDirection(e,e.position);e.velocity.x=i.x*e.startSpeed,e.velocity.y=i.y*e.startSpeed,e.velocity.z=i.z*e.startSpeed,this.system.inheritVelocity?.enabled&&this.system.inheritVelocity.applyInitial(e.velocity),e[ru]?e[ru].copy(e.velocity):e[ru]=e.velocity.clone();const n=this.system.main.gravityModifier.evaluate(Math.random(),Math.random());e[cw]=n*t,e[Hm]=n*t*.5,e[au]=Math.random(),this.system.velocityOverLifetime?.init(e),this._gravityDirection.set(0,-1,0),this.system.main.simulationSpace===bh.Local&&this._gravityDirection.applyQuaternion(this.system.worldQuaternionInverted).normalize()}update(e,t){const i=e[ru],n=e[cw];if(n!==0){const u=n*e[Hm];yy.copy(this._gravityDirection).multiplyScalar(u),e[Hm]+=t*.05,i.add(yy)}e.velocity.copy(i);const o=e.age/e.life;this.system.inheritVelocity?.enabled&&this.system.inheritVelocity.applyCurrent(e.velocity,o,e[au]);const r=this.system.noise;r.enabled&&r.apply(0,e.position,e.velocity,t,e.age,e.life);const a=this.system.sizeBySpeed;a?.enabled&&(e.size=a.evaluate(e.velocity,o,e[au],e.size));const l=this.system.colorBySpeed;l?.enabled&&l.evaluate(e.velocity,e[au],e.color);const h=this.system.velocityOverLifetime;h.enabled&&h.apply(e,0,e.position,e.velocity,t,e.age,e.life);const d=this.system.limitVelocityOverLifetime;if(d.enabled&&d.apply(e.position,i,e.velocity,e.size,o,t,1),this.system.worldspace){const u=this.system.worldScale;e.velocity.x*=u.x,e.velocity.y*=u.y,e.velocity.z*=u.z}}}const hw=Symbol("colorLerpFactor"),qm=new oe(1,1,1,1),nr=new oe(1,1,1,1);class aL extends Wo{type="NeedleColor";initialize(e){}_init(e){const t=this.system.renderer.particleMaterial;nr.copy(this.system.main.startColor.evaluate(Math.random())),t?.color&&(qm.copy(t.color),qm.alpha=t.opacity??1,nr.multiply(qm)),nr.convertLinearToSRGB(),e.startColor.set(nr.r,nr.g,nr.b,nr.alpha),e.color.copy(e.startColor),e[hw]=Math.random()}update(e,t){if(e.age===0&&this._init(e),this.system.colorOverLifetime.enabled){const i=e.age/e.life,n=this.system.colorOverLifetime.color.evaluate(i,e[hw]);e.color.set(n.r,n.g,n.b,"alpha"in n?n.alpha:1).multiply(e.startColor)}else e.color.copy(e.startColor)}}class lL{system;emission;get anim(){return this.system.textureSheetAnimation}constructor(e){this.system=e,this.emission=new JI(this.system)}get prewarm(){return!1}get material(){return this.system.renderer.getMaterial(this.system.trails.enabled)}get layers(){return this.system.gameObject.layers}update(){this.emission.update()}autoDestroy;get looping(){return this.system.main.loop}get duration(){return this.system.duration}get shape(){return this.system.shape}get startLife(){return new ou(this.system.main.startLifetime)}get startSpeed(){return new ou(this.system.main.startSpeed)}get startRotation(){return new ou(this.system.main.startRotation)}get startSize(){return new ou(this.system.main.startSize)}startLength;get startColor(){return new ee.ConstantColor(new ee.Vector4(1,1,1,1))}get emissionOverTime(){return this.emission}get emissionOverDistance(){return new eL(this.system)}emissionBursts;onlyUsedByOther;behaviors=[];get instancingGeometry(){return this.system.renderer.getMesh(this.system.renderer.renderMode).geometry}get renderMode(){if(this.system.trails.enabled===!0)return ee.RenderMode.Trail;switch(this.system.renderer.renderMode){case ks.Billboard:return ee.RenderMode.BillBoard;case ks.Stretch:return ee.RenderMode.StretchedBillBoard;case ks.HorizontalBillboard:return ee.RenderMode.HorizontalBillBoard;case ks.VerticalBillboard:return ee.RenderMode.VerticalBillBoard;case ks.Mesh:return ee.RenderMode.Mesh}return ee.RenderMode.BillBoard}rendererEmitterSettings={startLength:new ee.ConstantValue(220),followLocalOrigin:!1};get speedFactor(){let e=this.system.main.simulationSpeed;return this.system.renderer?.renderMode===ks.Stretch&&(e*=this.system.renderer.velocityScale??1),e}flatWhiteTexture;clonedTexture={original:void 0,clone:void 0};get texture(){const e=this.material;if(e&&e.map){const t=e.map;if(this.clonedTexture.original!==t||!this.clonedTexture.clone){const i=t.clone();i.premultiplyAlpha=!1,i.colorSpace=c.LinearSRGBColorSpace,this.clonedTexture.original=t,this.clonedTexture.clone=i}return this.clonedTexture.clone}return this.flatWhiteTexture||(this.flatWhiteTexture=Yy(new oe(1,1,1,1),1)),this.flatWhiteTexture}get startTileIndex(){return new ZI(this.system)}get uTileCount(){return this.anim.enabled?this.anim?.numTilesX:void 0}get vTileCount(){return this.anim.enabled?this.anim?.numTilesY:void 0}get renderOrder(){return 1}get blending(){return this.system.renderer.particleMaterial?.blending??c.NormalBlending}get transparent(){return this.system.renderer.transparent}get worldSpace(){return this.system.main.simulationSpace===bh.World}}class cL{burstParticleIndex=0;burstParticleCount=0;isBursting=!1;travelDistance=0;previousWorldPos;burstIndex=0;burstWaveIndex=0;time=0;waitEmiting=0}const Wt=class Lu extends T{play(e=!1){e&&P.foreachComponent(this.gameObject,t=>{t instanceof Lu&&t!==this&&t.play(!1)},!0),this._isPlaying=!0,this._particleSystem&&(this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1),this.emission?.reset()}pause(e=!0){e&&P.foreachComponent(this.gameObject,t=>{t instanceof Lu&&t!==this&&t.pause(!1)},!0),this._isPlaying=!1}stop(e=!0,t=!1){e&&P.foreachComponent(this.gameObject,i=>{i instanceof Lu&&i!==this&&i.stop(!1,t)},!0),this._isPlaying=!1,this._time=0,t&&this.reset()}reset(){this._time=0,this._particleSystem&&(this._particleSystem.particleNum=0,this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1,this.emission?.reset())}_state;emit(e){if(this._particleSystem){this.onUpdate(),e=Math.min(e,this.maxParticles-this.currentParticles),this._state||(this._state=new cL),this._state.waitEmiting=e,this._state.time=0;const t=this._particleSystem.emitEnded;this._particleSystem.emitEnded=!1,this._particleSystem.emit(this.deltaTime,this._state,this._particleSystem.emitter.matrixWorld),this._particleSystem.emitEnded=t}}get playOnAwake(){return this.main.playOnAwake}set playOnAwake(e){this.main.playOnAwake=e}colorOverLifetime;main;emission;sizeOverLifetime;shape;noise;trails;velocityOverLifetime;limitVelocityOverLifetime;inheritVelocity;colorBySpeed;textureSheetAnimation;rotationOverLifetime;rotationBySpeed;sizeBySpeed;get renderer(){return this._renderer}get isPlaying(){return this._isPlaying}get currentParticles(){return this._particleSystem?.particleNum??0}get maxParticles(){return this.main.maxParticles}get time(){return this._time}get duration(){return this.main.duration}get deltaTime(){return this.context.time.deltaTime*this.main.simulationSpeed}get scale(){return this.gameObject.scale.x}get cameraScale(){return this._cameraScale}_cameraScale=1;get container(){return this._container}get worldspace(){return this.main.simulationSpace===bh.World}get localspace(){return this.main.simulationSpace===bh.Local}__worldQuaternion=new c.Quaternion;get worldQuaternion(){return this.__worldQuaternion}_worldQuaternionInverted=new c.Quaternion;get worldQuaternionInverted(){return this._worldQuaternionInverted}_worldScale=new c.Vector3;get worldScale(){return this._worldScale}_worldPositionFrame=-1;_worldPos=new c.Vector3;get worldPos(){return this._worldPositionFrame!==this.context.time.frame&&(this._worldPositionFrame=this.context.time.frame,ie(this.gameObject,this._worldPos)),this._worldPos}get matrixWorld(){return this._container.matrixWorld}get isSubsystem(){return this._isUsedAsSubsystem}addBehaviour(e){return this._particleSystem?(e instanceof Wo&&(e.system=this),po&&console.debug("Add custom ParticleSystem Behaviour",e),this._particleSystem.addBehavior(e),!0):!1}removeBehaviour(e){if(!this._particleSystem)return!1;const t=this._particleSystem.behaviors,i=t.indexOf(e);return i!==-1&&((E()||po)&&console.debug("Remove custom ParticleSystem Behaviour",i,e),t.splice(i,1)),!0}removeAllBehaviours(){return this._particleSystem?(this._particleSystem.behaviors.length=0,!0):!1}get behaviours(){return this._particleSystem?this._particleSystem.behaviors:null}get particleSystem(){return this._particleSystem??null}_renderer;_batchSystem;_particleSystem;_interface;_container;_time=0;_isPlaying=!0;_isUsedAsSubsystem=!1;_didPreWarm=!1;set bursts(e){for(let t=0;t<e.length;t++){const i=e[t];if(!(i instanceof wf)){const n=new wf;cl(n,i),e[t]=n}}this._bursts=e}_bursts;set subEmitterSystems(e){for(let t=0;t<e.length;t++){const i=e[t];if(!(i instanceof xf)){const n=new xf;cl(n,i),e[t]=n}}po&&e.length>0&&console.log("SubEmitters: ",e,this),this._subEmitterSystems=e}_subEmitterSystems;onAfterDeserialize(e){if(this._subEmitterSystems&&Array.isArray(this._subEmitterSystems))for(const t of this._subEmitterSystems)t._deserialize(this.context,this.gameObject)}awake(){if(this._worldPositionFrame=-1,this._renderer=this.gameObject.getComponent(rn),!this.main)throw new Error("Not Supported: ParticleSystem needs a serialized MainModule. Creating new particle systems at runtime is currently not supported.");this._container=new c.Object3D,this._container.matrixAutoUpdate=!1,this.context.scene.add(this._container),this._batchSystem=new ee.BatchedParticleRenderer,this._batchSystem.name=this.gameObject.name,this._container.add(this._batchSystem),this._interface=new lL(this),this._particleSystem=new ee.ParticleSystem(this._interface),this._particleSystem.addBehavior(new sL(this)),this._particleSystem.addBehavior(new aL(this)),this._particleSystem.addBehavior(new tL(this)),this._particleSystem.addBehavior(new iL(this)),this._particleSystem.addBehavior(new rL(this)),this._particleSystem.addBehavior(new oL(this)),this._batchSystem.addSystem(this._particleSystem);const e=this._particleSystem.emitter;this.context.scene.add(e),this.inheritVelocity.system&&this.inheritVelocity.system!==this&&(this.inheritVelocity=this.inheritVelocity.clone()),this.inheritVelocity.awake(this),po&&(console.log(this),this.gameObject.add(new c.AxesHelper(1)))}start(){this.addSubParticleSystems(),this.updateLayers(),this.renderer.particleMesh instanceof c.Mesh&&this._interface.renderMode==ee.RenderMode.Mesh&&re.NEEDLE_progressive.assignMeshLOD(this.renderer.particleMesh,0).then(e=>{e&&this.particleSystem&&this._interface.renderMode==ee.RenderMode.Mesh&&(this.particleSystem.instancingGeometry=e)})}onDestroy(){this._container?.removeFromParent(),this._batchSystem?.removeFromParent(),this._particleSystem?.emitter.removeFromParent(),this._particleSystem?.dispose()}onEnable(){this.main&&(this.inheritVelocity&&(this.inheritVelocity.system=this),this._batchSystem&&(this._batchSystem.visible=!0),this.playOnAwake&&this.play(),this._isPlaying=this.playOnAwake)}onDisable(){this._batchSystem&&(this._batchSystem.visible=!1)}onBeforeRender(){this.main&&(this._didPreWarm===!1&&this.main?.prewarm===!0&&(this._didPreWarm=!0,this.preWarm()),this.onUpdate(),this.onSimulate(this.deltaTime))}preWarm(){if(!this.emission?.enabled||this.emission.rateOverTime.getMax()<=0)return;const t=1/60,i=this.main.duration,n=this.main.startLifetime.getMax(),r=Math.min(Math.max(i,n)/Math.max(.01,this.main.simulationSpeed),1e3),a=Math.ceil(r/t),l=Date.now();po&&console.log(`Particles ${this.name} - Prewarm for ${a} frames (${r} sec). Duration: ${i}, Lifetime: ${n}`);for(let h=0;h<a&&!(this.currentParticles>=this.maxParticles);h++){const d=Date.now()-l;if(d>2e3){console.warn(`Particles ${this.name} - Prewarm took too long. Aborting: ${d}`);break}this.onUpdate(),this.onSimulate(t)}}_lastBatchesCount=-1;onSimulate(e){if(this._batchSystem){let t=this.context.time.frameCount%60===0;this._lastBatchesCount!==this._batchSystem.batches.length&&(this._lastBatchesCount=this._batchSystem.batches.length,t=!0),t&&this.updateLayers(),this._batchSystem.update(e)}this._time+=e,this._time>this.duration&&(this._time=0)}updateLayers(){if(this._batchSystem)for(let e=0;e<this._batchSystem.batches.length;e++){const t=this._batchSystem.batches[e];t.layers.disableAll();const i=this.layer;t.layers.mask=1<<i}}onUpdate(){if(this._bursts&&(this.emission.bursts=this._bursts,delete this._bursts),!this._isPlaying)return;const e=this.context.mainCamera;if(e){const n=Ve(e);this._cameraScale=n.x}const t=!this.worldspace,i=this.gameObject;if(Se(i,this.__worldQuaternion),this._worldQuaternionInverted.copy(this.__worldQuaternion).invert(),Ve(this.gameObject,this._worldScale),t&&this._container&&this.gameObject?.parent){const n=O1(this,yy);this._container.matrix.makeScale(n.x,n.y,n.z),this._container.matrix.makeRotationFromQuaternion(this.__worldQuaternion),this._container.matrix.setPosition(this.worldPos),this._container.matrix.scale(this.gameObject.scale)}this.emission.system=this,this._interface.update(),this.shape.onUpdate(this,this.context,this.main.simulationSpace,this.gameObject),this.noise.update(this.context),this.inheritVelocity?.update(this.context),this.velocityOverLifetime.update(this)}addSubParticleSystems(){if(this._subEmitterSystems&&this._particleSystem)for(const e of this._subEmitterSystems){e.particleSystem&&(e.particleSystem.__internalAwake?e.particleSystem.__internalAwake():E()&&console.warn("SubParticleSystem serialization issue(?)",e.particleSystem,e));const t=e.particleSystem?._particleSystem;if(t){e.particleSystem._isUsedAsSubsystem=!0;const i=new xb(this,this._particleSystem,e.particleSystem,t);i.emitterType=e.type,i.emitterProbability=e.emitProbability,this._particleSystem.addBehavior(i)}else po&&console.warn("Could not add SubParticleSystem",e,this)}}};Ne([p(kp)],Wt.prototype,"colorOverLifetime");Ne([p($t)],Wt.prototype,"main");Ne([p(qs)],Wt.prototype,"emission");Ne([p(ia)],Wt.prototype,"sizeOverLifetime");Ne([p(vb)],Wt.prototype,"shape");Ne([p(ve)],Wt.prototype,"noise");Ne([p(ze)],Wt.prototype,"trails");Ne([p(We)],Wt.prototype,"velocityOverLifetime");Ne([p(pt)],Wt.prototype,"limitVelocityOverLifetime");Ne([p(wb)],Wt.prototype,"inheritVelocity");Ne([p(Nl)],Wt.prototype,"colorBySpeed");Ne([p(Vt)],Wt.prototype,"textureSheetAnimation");Ne([p(Mn)],Wt.prototype,"rotationOverLifetime");Ne([p(on)],Wt.prototype,"rotationBySpeed");Ne([p(_i)],Wt.prototype,"sizeBySpeed");let vh=Wt;class xf{particleSystem;emitProbability=1;properties;type;_deserialize(e,t){const i=this.particleSystem;if(i instanceof vh)return;let n="";i&&typeof i.guid=="string"&&(n=i.guid,this.particleSystem=P.findByGuid(n,t)),po&&!(this.particleSystem instanceof vh)&&console.warn("Could not find particle system for sub emitter",n,t,this)}}function O1(s,e){if(e.set(1,1,1),s.gameObject.parent&&s.localspace)switch(s.main.scalingMode){case my.Local:e=Ve(s.gameObject.parent,e),e.x=1/e.x,e.y=1/e.y,e.z=1/e.z;break;default:if(!s.unsupported_scaling_mode){s.unsupported_scaling_mode=!0;const t="ParticleSystem scale mode "+my[s.main.scalingMode]+" is not supported";E()&&de(t),console.warn(t,s.name,s)}e=Ve(s.gameObject,e);break}return e}var hL=Object.defineProperty,Cb=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&hL(e,t,n),n};class $l extends T{strength=1;radius=2;targets=[];update(){const e=this.gameObject.worldPosition,t=-this.strength*this.context.time.deltaTime;this.targets?.forEach(i=>{if(!i)return;const n=i.gameObject.worldPosition.sub(e),o=n.length();if(o>this.radius)return;let r=t;o>1?r/=o*o:r/=Math.max(.05,o),i.applyImpulse(n.multiplyScalar(r))})}}Cb([p()],$l.prototype,"strength");Cb([p()],$l.prototype,"radius");Cb([p(Xe)],$l.prototype,"targets");class _l extends T{_didAssignPlayerColor=!1;onEnable(){this.context.connection.beginListen(te.JoinedRoom,this.tryAssignColor),this._didAssignPlayerColor||this.startCoroutine(this.waitForConnection())}onDisable(){this.context.connection.stopListen(te.JoinedRoom,this.tryAssignColor)}*waitForConnection(){for(;!this.destroyed&&this.activeAndEnabled&&(yield Hy(.2),!this.tryAssignColor()););}tryAssignColor=()=>{const e=P.getComponentInParent(this.gameObject,di);if(e&&e.owner)return this._didAssignPlayerColor=!0,this.assignUserColor(e.owner),!0;const t=P.getComponentInParent(this.gameObject,it);return t?.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(t.connectionId),!0):!1};assignUserColor(e){const t=_l.hashCode(e),i=_l.colorFromHashCode(t);if(this.gameObject.type==="Mesh"){const n=this.gameObject;this.assignColor(i,e,n)}else if(this.gameObject.children)for(const n of this.gameObject.children){const o=n;o.material&&o.material.color&&this.assignColor(i,e,o)}}assignColor(e,t,i){let n=i.material;n&&(n._playerMaterial!==t&&(n=n.clone(),n._playerMaterial=t,i.material=n),n.color=e)}static hashCode(e){var t=0,i,n;if(e.length===0)return t;for(i=0;i<e.length;i++)n=e.charCodeAt(i),t=(t<<5)-t+n,t|=0;return t}static colorFromHashCode(e){const t=(e&16711680)>>16,i=(e&65280)>>8,n=e&255;return new c.Color(t/255,i/255,n/255)}}var dL=Object.defineProperty,uL=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&dL(e,t,n),n};const Xm=x("debugpost");class rt extends T{get isPostProcessingEffect(){return!0}order=void 0;constructor(e=void 0){if(super(),e)for(const t of Object.keys(e)){const i=e[t],n=this[t];n instanceof z?n.initialize(i):n!==void 0&&(this[t]=i)}}active=!0;onEnable(){super.onEnable(),Xm&&console.warn("Enable",this.constructor.name+(this.__internalDidAwakeAndStart?"":" (awake)")),this.active=!0,this.context.postprocessing.addEffect(this)}onDisable(){super.onDisable(),Xm&&console.warn("Disable",this.constructor.name),this.context.postprocessing.removeEffect(this),this.active=!1}init(){}_result;_postprocessingContext=null;get postprocessingContext(){return this._postprocessingContext}apply(e){return this._postprocessingContext=e,this._result||(this.initParameters(),this._result=this.onCreateEffect?.call(this)),this._result&&this.initParameters(),this._result}unapply(){}dispose(){Xm&&console.warn("DISPOSE",this),this._result&&(Array.isArray(this._result)?this._result.forEach(e=>e.dispose()):this._result.dispose()),this._result=void 0}initParameters(){const e=Object.keys(this);for(const t of e){const i=this[t];i instanceof z&&i.__init()}}onEditorModification(e){const t=e.propertyName;if(this[t]instanceof z){const i=e.value;return this[t].value=i,!0}}}uL([p()],rt.prototype,"active");var fL=Object.defineProperty,pL=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&fL(e,t,n),n};const mL=x("debugpost"),_y={};function an(s,e){_y[s]=e}function gL(s){return s.__type in _y?_y[s.__type]:(mL&&s.__type&&console.warn("Unknown postprocessing type",s.__type,s),rt)}class Mp{components=[];__init(e){this.components?.forEach(t=>{t.gameObject===void 0&&e.gameObject.addComponent(t),t.init()})}addEffect(e){this.components.push(e)}removeEffect(e){const t=this.components.indexOf(e);t>=0&&this.components.splice(t,1)}}pL([Qe([s=>gL(s),rt])],Mp.prototype,"components");var yL=Object.defineProperty,_L=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&yL(e,t,n),n};const bL=x("debugpost");var E1=(s=>(s[s.LOW=0]="LOW",s[s.MEDIUM=1]="MEDIUM",s[s.HIGH=2]="HIGH",s[s.ULTRA=3]="ULTRA",s))(E1||{});class ed extends rt{get typeName(){return"Antialiasing"}preset=new z(2);onCreateEffect(){const e=new A.POSTPROCESSING.MODULE.SMAAEffect({preset:this.preset?.value??A.POSTPROCESSING.MODULE.SMAAPreset.HIGH,edgeDetectionMode:A.POSTPROCESSING.MODULE.EdgeDetectionMode.LUMA});return this.preset.onValueChanged=t=>{bL&&console.log("Antialiasing preset changed to",t),e.applyPreset(t)},e}}_L([p(z)],ed.prototype,"preset");an("Antialiasing",ed);var vL=Object.defineProperty,Pb=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&vL(e,t,n),n};const Op=class R1 extends rt{static useSelectiveBloom=!1;get typeName(){return"Bloom"}threshold=new z(.9);intensity=new z(1);scatter=new z(.7);selectiveBloom;init(){this.threshold.valueProcessor=e=>e,this.intensity.valueProcessor=e=>e,this.scatter.valueProcessor=e=>e}onCreateEffect(){let e;if(this.selectiveBloom==null&&(this.selectiveBloom=R1.useSelectiveBloom),this.selectiveBloom){const t=e=new A.POSTPROCESSING.MODULE.SelectiveBloomEffect(this.context.scene,this.context.mainCamera,{blendFunction:A.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});t.inverted=!0}else e=new A.POSTPROCESSING.MODULE.BloomEffect({blendFunction:A.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});return this.intensity.onValueChanged=t=>{e.intensity=t},this.threshold.onValueChanged=t=>{e.luminanceMaterial.threshold=Math.pow(t,2.2)},this.scatter.onValueChanged=t=>{e.luminancePass.enabled=!0,e.luminanceMaterial.smoothing=t,e.mipmapBlurPass&&(e.mipmapBlurPass.radius=c.MathUtils.lerp(.1,.9,t))},e}};Pb([p(z)],Op.prototype,"threshold");Pb([p(z)],Op.prototype,"intensity");Pb([p(z)],Op.prototype,"scatter");let Ep=Op;an("Bloom",Ep);var wL=Object.defineProperty,xL=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&wL(e,t,n),n};class td extends rt{get typeName(){return"ChromaticAberration"}intensity=new z(0);onCreateEffect(){const e=new A.POSTPROCESSING.MODULE.ChromaticAberrationEffect;return e.offset=new c.Vector2(0,0),e.radialModulation=!0,e.modulationOffset=.15,this.intensity.valueProcessor=t=>t*.02,this.intensity.onValueChanged=t=>{e.offset.x=-t,e.offset.y=t},e}}xL([p(z)],td.prototype,"intensity");an("ChromaticAberration",td);var Ga=(s=>(s[s.None=0]="None",s[s.Neutral=1]="Neutral",s[s.ACES=2]="ACES",s[s.AgX=3]="AgX",s[s.KhronosNeutral=4]="KhronosNeutral",s))(Ga||{});const dw=new Map;function Qm(s){switch(s){case 0:return c.LinearToneMapping;case 1:return c.ReinhardToneMapping;case 2:return c.ACESFilmicToneMapping;case 3:return c.AgXToneMapping;case 4:return c.NeutralToneMapping;default:return dw.has(s)||(dw.set(s,!0),console.warn("[Postprocessing] Unknown tone mapping mode",s)),c.NeutralToneMapping}}function SL(s){switch(s){case c.LinearToneMapping:return 0;case c.ACESFilmicToneMapping:return 2;case c.AgXToneMapping:return 3;case c.NeutralToneMapping:return 1;case c.ReinhardToneMapping:return 1;default:return 0}}function Bu(s){switch(s){case c.LinearToneMapping:return A.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR;case c.ACESFilmicToneMapping:return A.POSTPROCESSING.MODULE.ToneMappingMode.ACES_FILMIC;case c.AgXToneMapping:return A.POSTPROCESSING.MODULE.ToneMappingMode.AGX;case c.NeutralToneMapping:return A.POSTPROCESSING.MODULE.ToneMappingMode.NEUTRAL;case c.ReinhardToneMapping:return A.POSTPROCESSING.MODULE.ToneMappingMode.REINHARD;default:return A.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR}}var CL=Object.defineProperty,T1=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&CL(e,t,n),n};const Ym=x("debugpost");class na extends rt{get typeName(){return"ToneMapping"}mode=new z(void 0);exposure=new z(1);setMode(e){const t=Ga[e];return t===void 0?(console.error("[PostProcessing] Invalid ToneMapping mode",e),this):(this.mode.value=t,this)}get isToneMapping(){return!0}get threeToneMapping(){return this.mode.isInitialized&&this.mode.overrideState?Qm(this.mode.value):this.context.renderer.toneMapping}get toneMappingExposure(){return this.exposure.overrideState&&this.exposure.value!==void 0?Math.max(0,this.exposure.value):this.context.renderer.toneMappingExposure}_tonemappingEffect=null;onCreateEffect(){if(this.mode.isInitialized==!1){const i=SL(this.context.renderer.toneMapping);Ym&&console.log("[PostProcessing] Initializing ToneMapping mode to renderer.toneMapping",this.context.renderer.toneMapping+" → "+i),this.mode.initialize(i)}this._tonemappingEffect?.dispose();const e=Qm(this.mode.value),t=this._tonemappingEffect=new A.POSTPROCESSING.MODULE.ToneMappingEffect({mode:Bu(e)});return this.mode.onValueChanged=i=>{if(typeof i=="string")i=sS(i),t.mode=Bu(i);else{const n=Qm(i);t.mode=Bu(n)}t.name="ToneMapping ("+Ga[i]+")",Ym&&console.log("[PostProcessing] ToneMapping mode changed to",Ga[i],e,t.mode)},Ym&&console.log("[PostProcessing] Use ToneMapping",Ga[this.mode.value],e,t.mode,"renderer.tonemapping: "+this.context.renderer.toneMapping),t}}T1([p(z)],na.prototype,"mode");T1([p(z)],na.prototype,"exposure");an("Tonemapping",na);var PL=Object.defineProperty,Rp=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&PL(e,t,n),n};class Go extends rt{get typeName(){return"ColorAdjustments"}remap=!0;postExposure=new z(1);contrast=new z(0);hueShift=new z(0);saturation=new z(0);init(){this.postExposure.valueProcessor=e=>(this.remap&&(e=Math.pow(2,e)),e),this.contrast.valueProcessor=e=>{if(!this.remap)return e;let t=1;return e>0?t=200:e<0&&(t=100),e/t},this.contrast.defaultValue=0,this.hueShift.valueProcessor=e=>this.remap?Math.PI*e/180:e,this.hueShift.defaultValue=0,this.saturation.valueProcessor=e=>this.remap?e<0?e/100:e/(100*Math.PI):e,this.saturation.defaultValue=0}onCreateEffect(){const e=[],t=this.postprocessingContext?.components.find(r=>r instanceof na);let i=!1;this.postExposure.onValueChanged=r=>{if(this.postExposure.overrideState){if(!t){i||(i=!0,console.warn("[PostProcessing] ColorAdjustments.PostExposure has no effect: add a ToneMappingEffect to your postprocessing stack."));return}t.exposure.value=r}};const n=new A.POSTPROCESSING.MODULE.BrightnessContrastEffect;this.contrast.onValueChanged=r=>n.contrast=r;const o=new A.POSTPROCESSING.MODULE.HueSaturationEffect;return this.hueShift.onValueChanged=r=>o.hue=r,this.saturation.onValueChanged=r=>o.saturation=r,e.push(n),e.push(o),e}}Rp([p(z)],Go.prototype,"postExposure");Rp([p(z)],Go.prototype,"contrast");Rp([p(z)],Go.prototype,"hueShift");Rp([p(z)],Go.prototype,"saturation");an("ColorAdjustments",Go);var kL=Object.defineProperty,sa=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&kL(e,t,n),n},A1=(s=>(s[s.Off=0]="Off",s[s.Gaussian=1]="Gaussian",s[s.Bokeh=2]="Bokeh",s))(A1||{});const ML=x("debugpost");class On extends rt{get typeName(){return"DepthOfField"}mode;focusDistance=new z(1);focalLength=new z(.2);aperture=new z(20);gaussianMaxRadius=new z;resolutionScale=new z(1/window.devicePixelRatio);bokehScale=new z;init(){this.focalLength.valueProcessor=t=>{const i=t/300;return L.lerp(2,.01,i)};const e=20;this.aperture.valueProcessor=t=>{const i=1-t/32;return L.lerp(1,e,i)}}onCreateEffect(){if(this.mode===0){ML&&console.warn("DepthOfField: Mode is set to Off");return}const e=new A.POSTPROCESSING.MODULE.DepthOfFieldEffect(this.context.mainCamera,{worldFocusRange:this.focalLength.value,focalLength:1,bokehScale:this.aperture.value,resolutionScale:this.resolutionScale.value});return e.cocMaterial.worldFocusDistance=this.focusDistance.value,this.focusDistance.onValueChanged=t=>{e.cocMaterial.worldFocusDistance=t},this.focalLength.onValueChanged=t=>e.cocMaterial.worldFocusRange=t,this.aperture.onValueChanged=t=>e.bokehScale=t,this.resolutionScale&&(this.resolutionScale.onValueChanged=t=>e.resolution.scale=t),[e]}unapply(){}}sa([p()],On.prototype,"mode");sa([p(z)],On.prototype,"focusDistance");sa([p(z)],On.prototype,"focalLength");sa([p(z)],On.prototype,"aperture");sa([p(z)],On.prototype,"gaussianMaxRadius");sa([p(z)],On.prototype,"resolutionScale");sa([p(z)],On.prototype,"bokehScale");an("DepthOfField",On);class wh extends rt{effect;constructor(e){super(),this.effect=e}get typeName(){return this.effect.constructor.name}onCreateEffect(){return this.effect}}var OL=Object.defineProperty,EL=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&OL(e,t,n),n};const uw=x("debugpost");class id extends rt{get typeName(){return"PixelationEffect"}granularity=new z(10);_effect=null;_lastDpr=0;onCreateEffect(){const e=new A.POSTPROCESSING.MODULE.PixelationEffect;this._effect=e;const t=this.context.renderer.getPixelRatio();return this._lastDpr=t,e.granularity=this.granularity.value*t,this.granularity.onValueChanged=i=>{const n=this.context.renderer.getPixelRatio();e.granularity=i*n,uw&&console.debug(`[PixelationEffect] granularity changed: raw=${i}, dpr=${n}, effective=${e.granularity}`)},e}update(){if(!this._effect)return;const e=this.context.renderer.getPixelRatio();e!==this._lastDpr&&(this._lastDpr=e,this._effect.granularity=this.granularity.value*e,uw&&console.debug(`[PixelationEffect] DPR changed to ${e}, updating granularity: raw=${this.granularity.value}, effective=${this._effect.granularity}`))}}EL([p(z)],id.prototype,"granularity");an("PixelationEffect",id);var RL=Object.defineProperty,nd=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&RL(e,t,n),n};class Xs extends rt{get typeName(){return"ScreenSpaceAmbientOcclusion"}intensity=new z(2);falloff=new z(1);samples=new z(9);color=new z(new c.Color(0,0,0));luminanceInfluence=new z(.7);onBeforeRender(){if(this._ssao&&this.context.mainCamera instanceof c.PerspectiveCamera){const e=this.context.mainCamera.far-this.context.mainCamera.near;this._ssao.ssaoMaterial.worldDistanceFalloff=e*.01,this._ssao.ssaoMaterial.worldDistanceThreshold=this.context.mainCamera.far}}_ssao;onCreateEffect(){const e=this.context.mainCamera,t=new A.POSTPROCESSING.MODULE.NormalPass(this.context.scene,e),i=new A.POSTPROCESSING.MODULE.DepthDownsamplingPass({normalBuffer:t.texture,resolutionScale:.5}),n=this._ssao=new A.POSTPROCESSING.MODULE.SSAOEffect(e,t.texture,{normalDepthBuffer:i.texture,worldDistanceThreshold:1,worldDistanceFalloff:1,worldProximityThreshold:.1,worldProximityFalloff:2,intensity:1,blendFunction:A.POSTPROCESSING.MODULE.BlendFunction.MULTIPLY,luminanceInfluence:.5});this.intensity.onValueChanged=r=>{n.intensity=r},this.falloff.onValueChanged=r=>{n.ssaoMaterial.radius=r*.1},this.samples.onValueChanged=r=>{n.ssaoMaterial.samples=r},this.color.onValueChanged=r=>{n.color||(n.color=new c.Color),n.color.copy(r)},this.luminanceInfluence.onValueChanged=r=>{n.luminanceInfluence=r};const o=new Array;return o.push(t),o.push(i),o.push(n),o}}nd([p(z)],Xs.prototype,"intensity");nd([p(z)],Xs.prototype,"falloff");nd([p(z)],Xs.prototype,"samples");nd([p(z)],Xs.prototype,"color");nd([p(z)],Xs.prototype,"luminanceInfluence");an("ScreenSpaceAmbientOcclusion",Xs);var TL=Object.defineProperty,oa=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&TL(e,t,n),n};const AL=x("debugN8AO");var Sf=(s=>(s[s.Performance=0]="Performance",s[s.Low=1]="Low",s[s.Medium=2]="Medium",s[s.High=3]="High",s[s.Ultra=4]="Ultra",s))(Sf||{});class En extends rt{get typeName(){return"ScreenSpaceAmbientOcclusionN8"}get pass(){return this._ssao}gammaCorrection=!0;aoRadius=new z(1);falloff=new z(1);intensity=new z(1);color=new z(new c.Color(0,0,0));screenspaceRadius=!1;quality=2;_ssao;onValidate(){this._ssao&&(this._ssao.setQualityMode(Sf[this.quality]),this._ssao.configuration.gammaCorrection=this.gammaCorrection,this._ssao.configuration.screenSpaceRadius=this.screenspaceRadius)}onCreateEffect(){const e=this.context.mainCamera,t=this.context.domWidth,i=this.context.domHeight,n=this._ssao=new A.POSTPROCESSING_AO.MODULE.N8AOPostPass(this.context.scene,e,t,i);n.name="SSAO_N8";const o=Sf[this.quality];if(n.setQualityMode(o),n.configuration.transparencyAware=!1,n.configuration.halfRes=window.devicePixelRatio>1,n.effectCompositerQuad?.material){const a=n.effectCompositerQuad.material;a.fragmentShader=a.fragmentShader.replace(`if (depth == 1.0) {
1408
1408
  texel = vec4(0.0, 0.0, 0.0, 1.0);`,`if (depth == 1.0) {
1409
1409
  gl_FragColor = sceneTexel;
1410
1410
  return;`),a.needsUpdate=!0}const r=new c.WebGLRenderTarget(t,i);return n.configuration.beautyRenderTarget=r,n.configuration.autoRenderBeauty=!1,n.configuration.gammaCorrection=this.gammaCorrection,n.configuration.screenSpaceRadius=this.screenspaceRadius,AL&&(n.enableDebugMode(),console.log(n),setInterval(()=>{console.log("SSAO",n.lastTime)},1e3),setInterval(()=>{console.log("SSAO",n.enabled,{ssao:n,autoRenderBeauty:n.configuration.autoRenderBeauty})},4e3)),this.intensity.onValueChanged=a=>{n.configuration.intensity=a},this.falloff.onValueChanged=a=>{n.configuration.distanceFalloff=a},this.aoRadius.onValueChanged=a=>{n.configuration.aoRadius=a},this.color.onValueChanged=a=>{n.color||(n.color=new c.Color),n.configuration.color.copy(a)},n}}oa([je(),p()],En.prototype,"gammaCorrection");oa([p(z)],En.prototype,"aoRadius");oa([p(z)],En.prototype,"falloff");oa([p(z)],En.prototype,"intensity");oa([p(z)],En.prototype,"color");oa([je(),p()],En.prototype,"screenspaceRadius");oa([je(),p()],En.prototype,"quality");an("ScreenSpaceAmbientOcclusionN8",En);const lu=x("debugpost"),dt={AT_START:-1e4,NormalPass:0,DepthDownsamplingPass:10,SSAO:20,SMAA:30,TiltShift:40,DepthOfField:50,ChromaticAberration:60,Bloom:70,Vignette:80,Pixelation:90,ToneMapping:100,HueSaturation:110,BrightnessContrast:120,Sharpening:130,AT_END:1e4};let Ke=null;function DL(s){if(lu==="verbose"&&console.debug("Before ordering effects",[...s]),!Ke){Ke=new Map,Ke.set(A.POSTPROCESSING.MODULE.NormalPass,dt.NormalPass),Ke.set(A.POSTPROCESSING.MODULE.DepthDownsamplingPass,dt.DepthDownsamplingPass),Ke.set(A.POSTPROCESSING.MODULE.SMAAEffect,dt.SMAA),Ke.set(A.POSTPROCESSING.MODULE.SSAOEffect,dt.SSAO);const e=A.POSTPROCESSING_AO.MAYBEMODULE;e&&(Ke.set(e.N8AOPostPass,dt.SSAO),Ke.set(e.N8AOPass,dt.SSAO)),Ke.set(A.POSTPROCESSING.MODULE.TiltShiftEffect,dt.TiltShift),Ke.set(A.POSTPROCESSING.MODULE.DepthOfFieldEffect,dt.DepthOfField),Ke.set(A.POSTPROCESSING.MODULE.ChromaticAberrationEffect,dt.ChromaticAberration),Ke.set(A.POSTPROCESSING.MODULE.BloomEffect,dt.Bloom),Ke.set(A.POSTPROCESSING.MODULE.SelectiveBloomEffect,dt.Bloom),Ke.set(A.POSTPROCESSING.MODULE.VignetteEffect,dt.Vignette),Ke.set(A.POSTPROCESSING.MODULE.PixelationEffect,dt.Pixelation),Ke.set(A.POSTPROCESSING.MODULE.ToneMappingEffect,dt.ToneMapping),Ke.set(A.POSTPROCESSING.MODULE.HueSaturationEffect,dt.HueSaturation),Ke.set(A.POSTPROCESSING.MODULE.BrightnessContrastEffect,dt.BrightnessContrast)}s.sort((e,t)=>{const i=typeof e.priority=="number"?e.priority:Ke.get(e.effect.constructor)??Number.NEGATIVE_INFINITY,n=typeof t.priority=="number"?t.priority:Ke.get(t.effect.constructor)??Number.NEGATIVE_INFINITY;return i===Number.NEGATIVE_INFINITY?(lu&&console.warn("Unknown effect found: ",e.constructor.name,e),1):n===Number.NEGATIVE_INFINITY?(lu&&console.warn("Unknown effect found: ",t.constructor.name,t),-1):i-n}),lu==="verbose"&&console.debug("After ordering effects",[...s])}var IL=Object.defineProperty,LL=Object.getOwnPropertyDescriptor,D1=(s,e,t,i)=>{for(var n=LL(e,t),o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&IL(e,t,n),n};class sd extends rt{get typeName(){return"Sharpening"}order=dt.Sharpening;_effect;onCreateEffect(){return this._effect??=new(BL()),this.effect}get effect(){return this._effect}set amount(e){this._amount=e,this._effect&&(this._effect.uniforms.get("amount").value=e)}get amount(){return this._effect?this._effect.uniforms.get("amount").value:this._amount}_amount=1;set radius(e){this._radius=e,this._effect&&(this._effect.uniforms.get("radius").value=e)}get radius(){return this._effect?this._effect.uniforms.get("radius").value:this._radius}_radius=1}D1([p()],sd.prototype,"amount");D1([p()],sd.prototype,"radius");function BL(){const s=`
@@ -1857,4 +1857,4 @@ Needle Engine: finished loading `+i+`
1857
1857
  ---------------------------------
1858
1858
  • `+r.passes.map(u=>u.name||u.constructor.name+"*").join(`
1859
1859
  • `)+`
1860
- `),si&&this._onCreateEffectsDebug(this._composer,o)}createPassForMergeableEffects(e,t,i,n){if(e.length>0){const o=new A.POSTPROCESSING.MODULE.EffectPass(i,...e);o.name=e.map(r=>r.name).join(", "),o.mainScene=n,o.enabled=!0,o.renderToScreen=!1,t.addPass(o),e.length=0}}handleDevicePixelRatio(){typeof this.context.devicePixelRatio=="number"&&this.context.requestSizeUpdate()}_menuEntry=null;_passIndices=null;_onCreateEffectsDebug(e,t){if(si==="passes"){const i=new A.POSTPROCESSING.MODULE.DepthEffect({blendFunction:A.POSTPROCESSING.MODULE.BlendFunction.NORMAL,inverted:!0});i.name="Depth Effect";const n=new A.POSTPROCESSING.MODULE.EffectPass(t,i);if(n.name="Depth Effect Pass",n.enabled=!1,e.passes.push(n),this._passIndices!==null){const r=[e.passes[0]];this._passIndices.length>0&&r.push(...this._passIndices.filter(a=>a!==0).map(a=>e.passes[a]).filter(a=>a)),r.length>0&&console.log("[PostProcessing] Passes (selected) →",r),e.passes.length=0;for(const a of r)a.enabled=!0,a.renderToScreen=!1,e.addPass(a)}const o=this.context.menu;if(o&&this._passIndices===null){this._menuEntry&&this._menuEntry.remove();const r=document.createElement("select");r.multiple=!0;const a=document.createElement("option");a.innerText="Final Output",a.value="-1",r.appendChild(a);for(const l of e.passes){const h=document.createElement("option");h.innerText=l.name,h.value=`${e.passes.indexOf(l)}`,h.title=l.name,r.appendChild(h)}o.appendChild(r),this._menuEntry=r,r.addEventListener("change",()=>{const l=Array.from(r.selectedOptions).map(h=>parseInt(h.value));l.length===1&&l[0]===-1?this._passIndices=null:this._passIndices=l,this.applyEffects(this.context)})}}}}const F3=Object.freeze(Object.defineProperty({__proto__:null,PostProcessingHandler:vl},Symbol.toStringTag,{value:"Module"}));class Wp{_name;_tracks=[];_currentTrack=null;_pendingSignals=[];_idProvider;constructor(e,t){this._name=e,this._idProvider=new ot(t??Date.now())}static create(e,t){return new Wp(e??"Timeline",t)}animationTrack(e,t){return this.commitInlineTracks(),this._currentTrack=this.pushTrack(e,ve.Animation,t??null),this}audioTrack(e,t,i){return this.commitInlineTracks(),this._currentTrack=this.pushTrack(e,ve.Audio,t??null),this._currentTrack.volume=i,this}activationTrack(e,t){return this.commitInlineTracks(),this._currentTrack=this.pushTrack(e,ve.Activation,t??null),this}controlTrack(e){return this.commitInlineTracks(),this._currentTrack=this.pushTrack(e,ve.Control,null),this}signalTrack(e,t){return this.commitInlineTracks(),this._currentTrack=this.pushTrack(e,ve.Signal,t??null),this}markerTrack(e){return this.commitInlineTracks(),this._currentTrack=this.pushTrack(e,ve.Marker,null),this}clip(e,t){if(!this._currentTrack)throw new Error("TimelineBuilder: .clip() must be called after a track method (e.g. .animationTrack())");this.commitInlineTracks();const i=this._currentTrack;switch(i.type){case ve.Animation:{let n;if(e instanceof c.AnimationClip)n=e;else{const d=Array.isArray(e)?e:[e],u=i.outputs[0],f=u instanceof c.Object3D?u:u!=null&&"gameObject"in u?u.gameObject:void 0;n=dh(d,f)}const o=t??{},r=o.duration??n.duration,a=o.start??i.cursor,l=a+r,h={start:a,end:l,duration:r,timeScale:o.speed??1,clipIn:o.clipIn??0,easeInDuration:o.easeIn??0,easeOutDuration:o.easeOut??0,preExtrapolationMode:o.preExtrapolation??et.None,postExtrapolationMode:o.postExtrapolation??et.None,reversed:o.reversed,asset:{clip:n,loop:o.loop??!1,duration:n.duration,removeStartOffset:o.removeStartOffset??!1}};i.clips.push(h),i.cursor=l;break}case ve.Audio:{const n=e,o=t??{},r=o.duration,a=o.start??i.cursor,l=a+r,h={start:a,end:l,duration:r,timeScale:o.speed??1,clipIn:0,easeInDuration:o.easeIn??0,easeOutDuration:o.easeOut??0,preExtrapolationMode:et.None,postExtrapolationMode:et.None,asset:{clip:n,loop:o.loop??!1,volume:o.volume??1}};i.clips.push(h),i.cursor=l;break}case ve.Activation:{const n=e,o=n.start??i.cursor,r=o+n.duration,a={start:o,end:r,duration:n.duration,timeScale:1,clipIn:0,easeInDuration:n.easeIn??0,easeOutDuration:n.easeOut??0,preExtrapolationMode:et.None,postExtrapolationMode:et.None,asset:{}};i.clips.push(a),i.cursor=r;break}case ve.Control:{const n=e,o=t??{},r=o.start??i.cursor,a=o.duration,l=r+a,h={start:r,end:l,duration:a,timeScale:1,clipIn:0,easeInDuration:0,easeOutDuration:0,preExtrapolationMode:et.None,postExtrapolationMode:et.None,asset:{sourceObject:n,controlActivation:o.controlActivation??!0,updateDirector:o.updateDirector??!0}};i.clips.push(h),i.cursor=l;break}default:throw new Error(`TimelineBuilder: .clip() is not supported on track type "${i.type}"`)}return this}marker(e,t,i){if(!this._currentTrack)throw new Error("TimelineBuilder: .marker() must be called after a track method");if(this._currentTrack.type!==ve.Signal&&this._currentTrack.type!==ve.Marker)throw new Error(`TimelineBuilder: .marker() is only supported on signal and marker tracks, not "${this._currentTrack.type}"`);const n={type:mh.Signal,time:e,retroActive:i?.retroActive??!1,emitOnce:i?.emitOnce??!1,asset:t};return this._currentTrack.markers.push(n),e>this._currentTrack.cursor&&(this._currentTrack.cursor=e),this}signal(e,t,i){if(!this._currentTrack)throw new Error("TimelineBuilder: .signal() must be called after a track method");if(this._currentTrack.type!==ve.Signal&&this._currentTrack.type!==ve.Marker)throw new Error(`TimelineBuilder: .signal() is only supported on signal and marker tracks, not "${this._currentTrack.type}"`);const n=this._idProvider.generateUUID(),o=this._tracks.indexOf(this._currentTrack),r={type:mh.Signal,time:e,retroActive:i?.retroActive??!1,emitOnce:i?.emitOnce??!1,asset:n};return this._currentTrack.markers.push(r),this._pendingSignals.push({trackIndex:o,guid:n,callback:t}),e>this._currentTrack.cursor&&(this._currentTrack.cursor=e),this}muted(e=!0){if(!this._currentTrack)throw new Error("TimelineBuilder: .muted() must be called after a track method");return this._currentTrack.muted=e,this}track(e,t,i,n){if(!this._currentTrack)throw new Error("TimelineBuilder: .track() must be called after .animationTrack()");if(this._currentTrack.type!==ve.Animation)throw new Error("TimelineBuilder: .track() is only supported on animation tracks");return this._currentTrack.inlineTracks.push(u_(e,t,i,n)),this}build(){this.commitInlineTracks();const e=this._tracks.map(t=>{const i={name:t.name,type:t.type,muted:t.muted,outputs:t.outputs};return t.clips.length>0&&(i.clips=t.clips),t.markers.length>0&&(i.markers=t.markers),t.volume!==void 0&&(i.volume=t.volume),t.trackOffset!==void 0&&(i.trackOffset=t.trackOffset),i});return{name:this._name,tracks:e}}install(e){const t=this.build();if(this._pendingSignals.length>0){const i=e.gameObject;let n=P.getComponent(i,Lr);n||(n=P.addComponent(i,Lr)),n.events||(n.events=[]);for(const o of this._pendingSignals){const r=new Lh;r.guid=o.guid;const a=new Ml;a.signal=r,a.reaction=new Z([o.callback]),n.events.push(a);const l=t.tracks[o.trackIndex];l&&!l.outputs.includes(n)&&l.outputs.push(n)}}return e.playableAsset=t,t}pushTrack(e,t,i){const n={name:e,type:t,muted:!1,outputs:i?[i]:[],clips:[],markers:[],cursor:0,inlineTracks:[]};return this._tracks.push(n),n}commitInlineTracks(){if(!this._currentTrack||this._currentTrack.inlineTracks.length===0)return;const e=this._currentTrack,t=e.outputs[0],i=t instanceof c.Object3D?t:t!=null&&"gameObject"in t?t.gameObject:void 0,n=dh(e.inlineTracks,i),o=e.cursor,r=n.duration,a={start:o,end:o+r,duration:r,timeScale:1,clipIn:0,easeInDuration:0,easeOutDuration:0,preExtrapolationMode:et.None,postExtrapolationMode:et.None,asset:{clip:n,loop:!1,duration:n.duration,removeStartOffset:!1}};e.clips.push(a),e.cursor=o+r,e.inlineTracks=[]}}class hP{}const j3=Object.freeze(Object.defineProperty({__proto__:null,ActionBuilder:pe,ActionCollection:JC,ActionModel:li,AlignmentConstraint:jh,Animation:Ut,AnimationBuilder:Hf,AnimationCurve:Zh,AnimationExtension:up,Animator:vt,AnimatorController:Jn,Antialiasing:ed,Attractor:$l,AudioExtension:qr,AudioListener:Ms,AudioSource:Ei,Avatar:Io,AvatarMarker:it,AxesHelper:Ol,AxisRotationConstraint:O_,BaseUIComponent:en,BasicIKConstraint:x_,BehaviorExtension:tb,BehaviorModel:Dt,BloomEffect:Ep,BoxCollider:np,BoxGizmo:Zr,BoxHelperComponent:At,Button:Ys,CallInfo:vi,Camera:Jt,CameraTargetReachedEvent:ph,Canvas:yl,CanvasGroup:Lo,CapsuleCollider:Fs,ChangeMaterialOnClick:X_,ChangeTransformOnClick:Xr,CharacterController:Gr,CharacterControllerInput:Ns,ChromaticAberration:td,ClickThrough:zp,ColorAdjustments:Go,ColorBySpeedModule:Nl,ColorOverLifetimeModule:kp,ContactShadows:Uh,CursorFollow:ha,CustomBranding:Yr,Deletable:k_,DeleteBox:Oo,DepthOfField:On,DeviceFlag:sp,DocumentExtension:cP,DragControls:vr,DragProfile:uf,DropListener:Vs,Duplicatable:U_,EffectWrapper:wh,EmissionModule:qs,EmphasizeOnClick:Al,EnvironmentScene:ip,EventList:Z,EventListEvent:f_,EventSystem:ei,EventTrigger:hp,FieldWithDefault:TC,FixedJoint:gb,FixedRotationAxesConstraint:vC,Fog:Fl,GaussianSplat:Kr,GltfExport:W_,GltfExportBox:$_,GrabPointPlaneConstraint:Nh,Gradient:ea,Graphic:Qh,GraphicRaycaster:Yf,GridHelper:jl,GridLayoutGroup:ab,GridSnapConstraint:op,GroundProjectedEnv:ds,GroupActionModel:wr,HideOnStart:Gi,HingeJoint:Kh,HorizontalLayoutGroup:rb,get HoverAnimation(){return exports.HoverAnimation},Image:ql,InheritVelocityModule:wb,InputField:Db,InstanceHandle:Rr,InstancingHandler:jr,Interactable:P_,KeepRotationConstraint:rp,KeepScaleConstraint:bC,Keyframe:ui,LODGroup:Sp,LODModel:Ul,Light:Lt,LimitVelocityOverLifetimeModule:pt,LogStats:C_,LookAt:Ib,LookAtConstraint:Vr,MainModule:$t,MaskableGraphic:Yh,MeshCollider:Uo,MeshRenderer:Vh,MinMaxCurve:Q,MinMaxGradient:ta,NeedleMenu:fs,NestedGltf:zl,Networking:bb,NoiseModule:be,ObjectRaycaster:Ji,OffsetConstraint:Jr,OpenURL:Xl,OrbitControls:ue,Outline:Bl,Padding:Qr,ParticleBurst:wf,ParticleSubEmitter:xb,ParticleSystem:vh,ParticleSystemRenderer:rn,PhysicsExtension:ib,PixelationEffect:id,PlaneHeightLockConstraint:E_,PlayAnimationOnClick:_h,PlayAudioOnClick:Do,PlayableDirector:ml,PlayerColor:_l,PointerEventData:Ih,PostProcessingHandler:vl,PreliminaryAction:Dl,PreliminaryTrigger:Gh,RawImage:Fp,Rect:l1,RectTransform:Cn,ReflectionProbe:Ps,RegisteredAnimationInfo:Co,RemoteSkybox:v_,Renderer:ti,RendererLightmap:B_,Rigidbody:Xe,RotationBySpeedModule:on,RotationOverLifetimeModule:Mn,ScaleLimitConstraint:M_,SceneSwitcher:Ye,ScreenCapture:Ho,ScreenSpaceAmbientOcclusion:Xs,ScreenSpaceAmbientOcclusionN8:En,ScrollFollow:gs,SeeThrough:Ob,SetActiveOnClick:Q_,ShadowCatcher:ld,ShapeModule:vb,SharpeningEffect:sd,SignalAsset:Lh,SignalReceiver:Lr,SignalReceiverEvent:Ml,SignalTrackHandler:yh,Size:a1,SizeBySpeedModule:_i,SizeOverLifetimeModule:ia,SkinnedMeshRenderer:F_,SmoothFollow:Ap,SnapToSurfaceConstraint:ap,SpatialGrabRaycaster:Ir,SpatialHtml:ud,SpatialTrigger:Dp,SpatialTriggerReceiver:rs,SpectatorCamera:Ip,SphereCollider:El,SplineContainer:la,SplineData:ls,SplineWalker:ln,Sprite:Ws,SpriteData:nl,SpriteRenderer:gi,SpriteSheet:gl,SubEmitterSystem:xf,SyncedCamera:Eb,SyncedRoom:Rn,SyncedTransform:Sn,TapGestureTrigger:K_,TeleportTarget:yp,TestRunner:Rb,TestSimulateUserData:Tb,Text:Nt,TextBuilder:sb,TextExtension:bp,TextureSheetAnimationModule:Vt,TiltShiftEffect:ms,TimelineActivationTrack:Jf,TimelineAnimationTrack:gh,TimelineAudioTrack:Os,TimelineBuilder:Wp,TimelineControlTrack:ep,TimelineMarkerTrack:Zf,ToneMappingEffect:na,TrailModule:ze,TransformData:Fe,TransformGizmo:ca,TriggerBuilder:jt,TriggerModel:Eo,UIRaycastUtils:m_,UIRootComponent:qh,USDZExporter:os,USDZText:Va,USDZUIExtension:cb,UsageMarker:zh,VariantAction:q_,VelocityOverLifetimeModule:We,VerticalLayoutGroup:ob,VideoPlayer:ut,get ViewBox(){return exports.ViewBox},Vignette:ra,VisibilityAction:Hh,Voip:Qs,Volume:od,VolumeParameter:z,VolumeProfile:Mp,WebARCameraBackground:pd,WebARSessionRoot:Qi,WebXR:_p,WebXRImageTracking:Kl,WebXRImageTrackingModel:Zi,WebXRPlaneTracking:Js,WebXRTrackedImage:bl,XRControllerFollow:Ks,XRControllerModel:js,XRControllerMovement:Ti,XRFlag:_n,XRRig:Vp,XRState:Kt,__Ignore:hP},Symbol.toStringTag,{value:"Module"}));exports.SplineUtils=void 0;(s=>{function e(t,i=!1,n=.75){const o=new la,r=1-L.clamp(n,0,1);return t.forEach((a,l)=>{const h=new c.Vector3;l<t.length-1?h.subVectors(t[l+1],a).normalize().multiplyScalar(r):i&&t.length>1&&h.subVectors(t[0],a).normalize().multiplyScalar(r);const d=new ls;d.position.copy(a),d.tangentIn.copy(h),d.tangentOut.copy(h),o.addKnot(d)}),o.closed=i,o}s.createFromPoints=e})(exports.SplineUtils||(exports.SplineUtils={}));class U3 extends ee.WorkerBase{constructor(){super(new Worker(new URL("/generateMeshBVH.worker-Be19n6m6.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:Ha&&Ha.tagName.toUpperCase()==="SCRIPT"&&Ha.src||new URL("needle-engine.bundle-BuUj9B4K.umd.cjs",document.baseURI).href),{type:"module"})),this.name="GenerateMeshBVHWorker"}runTask(e,t,i={}){return new Promise((n,o)=>{if(t.getAttribute("position").isInterleavedBufferAttribute||t.index&&t.index.isInterleavedBufferAttribute)throw new Error("GenerateMeshBVHWorker: InterleavedBufferAttribute are not supported for the geometry attributes.");e.onerror=h=>{o(new Error(`[GenerateMeshBVHWorker] ${h.message||"Could not load worker."}`))},e.onmessage=h=>{const{data:d}=h;if(d.error)o(new Error(d.error)),e.onmessage=null;else if(d.serialized){const{serialized:u,position:f}=d,m=ee.MeshBVH.deserialize(u,t,{setIndex:!1}),g=Object.assign({setBoundingBox:!0},i);if(t.attributes.position.array=f,u.index)if(t.index)t.index.array=u.index;else{const v=new c.BufferAttribute(u.index,1,!1);t.setIndex(v)}g.setBoundingBox&&(t.boundingBox=m.getBoundingBox(new c.Box3)),i.onProgress&&i.onProgress(d.progress),n(m),e.onmessage=null}else i.onProgress&&i.onProgress(d.progress)};const r=t.index?t.index.array:null,a=t.attributes.position.array,l=[a];r&&l.push(r),e.postMessage({index:r,position:a,options:{...i,onProgress:null,includedProgressCallback:!!i.onProgress,groups:[...t.groups]}},l.map(h=>h.buffer).filter(h=>typeof SharedArrayBuffer>"u"||!(h instanceof SharedArrayBuffer)))}).finally(()=>{e.onmessage=null,e.onerror=null})}}const z3=Object.freeze(Object.defineProperty({__proto__:null,GenerateMeshBVHWorker:U3},Symbol.toStringTag,{value:"Module"}));exports.$TNE=kh;exports.$componentName=Gu;exports.$physicsKey=qk;exports.$vnStLM=ns;exports.ActionBuilder=pe;exports.ActionCollection=JC;exports.ActionModel=li;exports.Addressables=Lx;exports.AlignmentConstraint=jh;exports.AmbientMode=Ya;exports.Animation=Ut;exports.AnimationBuilder=Hf;exports.AnimationCurve=Zh;exports.AnimationExtension=up;exports.Animator=vt;exports.AnimatorConditionMode=hi;exports.AnimatorController=Jn;exports.AnimatorControllerBuilder=qf;exports.AnimatorControllerParameterType=br;exports.AnimatorStateInfo=Pc;exports.Antialiasing=ed;exports.Application=wn;exports.AssetDatabase=CS;exports.AssetReference=J;exports.Attractor=$l;exports.AudioClip=Yg;exports.AudioExtension=qr;exports.AudioListener=Ms;exports.AudioRolloffMode=hC;exports.AudioSource=Ei;exports.Avatar=Io;exports.AvatarMarker=it;exports.Axes=$a;exports.AxesHelper=Ol;exports.AxisRotationConstraint=O_;exports.BUILD_TIME=Zc;exports.BaseUIComponent=en;exports.BasicIKConstraint=x_;exports.BehaviorExtension=tb;exports.BehaviorModel=Dt;exports.BloomEffect=Ep;exports.BoxCollider=np;exports.BoxGizmo=Zr;exports.BoxHelperComponent=At;exports.Button=Ys;exports.ButtonsFactory=Xi;exports.CallDirection=B1;exports.CallInfo=vi;exports.Camera=Jt;exports.CameraTargetReachedEvent=ph;exports.Canvas=yl;exports.CanvasGroup=Lo;exports.CapsuleCollider=Fs;exports.ChangeMaterialOnClick=X_;exports.ChangeTransformOnClick=Xr;exports.CharacterController=Gr;exports.CharacterControllerInput=Ns;exports.ChromaticAberration=td;exports.CircularBuffer=Mi;exports.ClearFlags=Or;exports.ClickThrough=zp;exports.ClipExtrapolation=et;exports.Collider=Ii;exports.Collision=fx;exports.CollisionDetectionMode=Qf;exports.ColorAdjustments=Go;exports.ColorBySpeedModule=Nl;exports.ColorOverLifetimeModule=kp;exports.Component=sR;exports.Component$1=T;exports.ComponentLifecycleEvents=Rf;exports.Components=j3;exports.ConnectionEvents=qx;exports.ContactPoint=ux;exports.ContactShadows=Uh;exports.Context=X;exports.ContextArgs=dE;exports.ContextEvent=ae;exports.ContextRegistry=se;exports.CursorFollow=ha;exports.CustomBranding=Yr;exports.CustomShader=Me;exports.DefaultReflectionMode=Ju;exports.Deletable=k_;exports.DeleteBox=Oo;exports.DepthOfField=On;exports.DepthOfFieldMode=A1;exports.DeviceFlag=sp;exports.DirectorWrapMode=uC;exports.DisposableStore=Ou;exports.DocumentExtension=cP;exports.DragControls=vr;exports.DragMode=R_;exports.DragProfile=uf;exports.DropListener=Vs;exports.Duplicatable=U_;exports.EffectWrapper=wh;exports.EmissionModule=qs;exports.EmphasizeOnClick=Al;exports.EngineLoadingView=Tr;exports.EnvironmentScene=ip;exports.EventBus=Og;exports.EventList=Z;exports.EventListEvent=f_;exports.EventSystem=ei;exports.EventTrigger=hp;exports.FieldWithDefault=TC;exports.FileReference=qn;exports.FileReferenceSerializer=Fx;exports.FileSpawnModel=lA;exports.File_Event=xC;exports.FixedJoint=gb;exports.FixedRotationAxesConstraint=vC;exports.Fog=Fl;exports.FontStyle=bf;exports.FrameEvent=Ce;exports.GENERATOR=al;exports.GameObject=P;exports.GaussianSplat=Kr;exports.Gizmos=B;exports.GltfExport=W_;exports.GltfExportBox=$_;exports.GrabPointPlaneConstraint=Nh;exports.Gradient=ea;exports.Graphic=Qh;exports.GraphicRaycaster=Yf;exports.Graphics=To;exports.GridHelper=jl;exports.GridLayoutGroup=ab;exports.GridSnapConstraint=op;exports.GroundProjectedEnv=ds;exports.GroupActionModel=wr;exports.HideFlags=as;exports.HideOnStart=Gi;exports.HingeJoint=Kh;exports.HorizontalLayoutGroup=rb;exports.HorizontalWrapMode=f1;exports.HostData=gM;exports.Image=ql;exports.ImageReference=Hn;exports.ImageReferenceSerializer=Bx;exports.InheritVelocityModule=wb;exports.Input=Nx;exports.InputEventQueue=xo;exports.InputEvents=xe;exports.InputField=Db;exports.InstanceHandle=Rr;exports.InstancingHandler=jr;exports.InstancingUtil=Ki;exports.InstantiateEvent=wx;exports.InstantiateIdProvider=ot;exports.InstantiateOptions=hs;exports.Interactable=P_;exports.JoinedRoomResponse=QM;exports.KeepRotationConstraint=rp;exports.KeepScaleConstraint=bC;exports.KeyEventArgs=NM;exports.Keyframe=ui;exports.LODGroup=Sp;exports.LODModel=Ul;exports.LODsManager=$x;exports.LeftRoomResponse=YM;exports.Light=Lt;exports.LightData=tS;exports.LimitVelocityOverLifetimeModule=pt;exports.LoadingElementOptions=y3;exports.LogStats=C_;exports.LogType=Ci;exports.LookAt=Ib;exports.LookAtConstraint=Vr;exports.MODULES=A;exports.MainModule=$t;exports.MarkerType=mh;exports.MaskableGraphic=Yh;exports.MaterialPropertyBlock=As;exports.Mathf=L;exports.MeshCollider=Uo;exports.MeshRenderer=Vh;exports.MinMaxCurve=Q;exports.MinMaxGradient=ta;exports.NEEDLE_ENGINE_FEATURE_FLAGS=By;exports.NEKeyboardEvent=xc;exports.NEPointerEvent=Cs;exports.NEToneMappingMode=Ga;exports.NeedleButtonElement=eP;exports.NeedleEngineWebComponent=Ub;exports.NeedleMenu=fs;exports.NeedlePatchesKey=gu;exports.NeedleXRController=Jy;exports.NeedleXRSession=N;exports.NeedleXRSync=hS;exports.NeedleXRUtils=wS;exports.NestedGltf=zl;exports.NetworkConnection=th;exports.NetworkedStreamEvents=is;exports.NetworkedStreams=rd;exports.Networking=bb;exports.NewInstanceModel=Sx;exports.NoiseModule=be;exports.ObjectRaycaster=Ji;exports.ObjectUtils=jo;exports.OffsetConstraint=Jr;exports.OneEuroFilter=pu;exports.OneEuroFilterXYZ=My;exports.OpenURL=Xl;exports.OrbitControls=ue;exports.Outline=Bl;exports.OwnershipEvent=Xx;exports.OwnershipModel=Qx;exports.PUBLIC_KEY=wo;exports.Padding=Qr;exports.ParticleBurst=wf;exports.ParticleSubEmitter=xb;exports.ParticleSystem=vh;exports.ParticleSystemBaseBehaviour=Wo;exports.ParticleSystemRenderer=rn;exports.ParticleSystemShapeType=vf;exports.PeerHandle=sl;exports.PeerNetworking=Hx;exports.Physics=pl;exports.PhysicsExtension=ib;exports.PhysicsMaterialCombine=mt;exports.PixelationEffect=id;exports.PlaneHeightLockConstraint=E_;exports.PlayAnimationOnClick=_h;exports.PlayAudioOnClick=Do;exports.PlayableDirector=ml;exports.PlayerColor=_l;exports.PlayerState=di;exports.PlayerStateEvent=i1;exports.PlayerSync=J_;exports.PlayerView=Yx;exports.PlayerViewManager=Kx;exports.PointerEventData=Ih;exports.PointerType=Lf;exports.PostProcessing=oS;exports.PostProcessingEffect=rt;exports.PostProcessingEffectOrder=dt;exports.PostProcessingHandler=vl;exports.Prefabs=ll;exports.PreliminaryAction=Dl;exports.PreliminaryTrigger=Gh;exports.PrimitiveType=xl;exports.Progress=he;exports.PromiseAllWithErrors=Py;exports.PromiseErrorResult=hg;exports.QualityLevel=E1;exports.RGBAColor=oe;exports.RapierPhysics=ol;exports.RawImage=Fp;exports.RaycastOptions=zr;exports.Rect=l1;exports.RectTransform=Cn;exports.ReflectionProbe=Ps;exports.ReflectionProbeUsage=RC;exports.RegisteredAnimationInfo=Co;exports.RemoteSkybox=v_;exports.RenderTexture=es;exports.RenderTextureSerializer=nC;exports.Renderer=ti;exports.RendererData=eS;exports.RendererLightmap=B_;exports.Rigidbody=Xe;exports.RigidbodyConstraints=qe;exports.RoomEvents=te;exports.RotationBySpeedModule=on;exports.RotationOverLifetimeModule=Mn;exports.ScaleLimitConstraint=M_;exports.SceneLightSettings=ff;exports.SceneSwitcher=Ye;exports.ScreenCapture=Ho;exports.ScreenSpaceAmbientOcclusion=Xs;exports.ScreenSpaceAmbientOcclusionN8=En;exports.ScreenSpaceAmbientOcclusionN8QualityMode=Sf;exports.ScrollFollow=gs;exports.SeeThrough=Ob;exports.SendQueue=yn;exports.SerializationContext=Eh;exports.SetActiveOnClick=Q_;exports.ShadowCastingMode=gf;exports.ShadowCatcher=ld;exports.ShapeModule=vb;exports.ShapeOverlapResult=px;exports.SharpeningEffect=sd;exports.SignalAsset=Lh;exports.SignalReceiver=Lr;exports.SignalReceiverEvent=Ml;exports.SignalTrackHandler=yh;exports.Size=a1;exports.SizeBySpeedModule=_i;exports.SizeOverLifetimeModule=ia;exports.SkinnedMeshRenderer=F_;exports.SmoothFollow=Ap;exports.SnapToSurfaceConstraint=ap;exports.SpatialGrabRaycaster=Ir;exports.SpatialHtml=ud;exports.SpatialTrigger=Dp;exports.SpatialTriggerReceiver=rs;exports.SpectatorCamera=Ip;exports.SphereCollider=El;exports.SphereIntersection=o_;exports.SplineContainer=la;exports.SplineData=ls;exports.SplineWalker=ln;exports.Sprite=Ws;exports.SpriteData=nl;exports.SpriteRenderer=gi;exports.SpriteSheet=gl;exports.StateMachineBehaviour=cR;exports.StreamEndedEvent=Mb;exports.StreamReceivedEvent=L1;exports.SubEmitterSystem=xf;exports.SyncedCamera=Eb;exports.SyncedRoom=Rn;exports.SyncedTransform=Sn;exports.TapGestureTrigger=K_;exports.TeleportTarget=yp;exports.TestRunner=Rb;exports.TestSimulateUserData=Tb;exports.Text=Nt;exports.TextAnchor=Je;exports.TextBuilder=sb;exports.TextExtension=bp;exports.TextureSheetAnimationModule=Vt;exports.TiltShiftEffect=ms;exports.Time=iS;exports.TimelineActivationTrack=Jf;exports.TimelineAnimationTrack=gh;exports.TimelineAudioTrack=Os;exports.TimelineBuilder=Wp;exports.TimelineControlTrack=ep;exports.TimelineMarkerTrack=Zf;exports.TimelineTrackHandler=Wr;exports.ToneMappingEffect=na;exports.TrackType=ve;exports.TrailModule=ze;exports.TransformData=Fe;exports.TransformGizmo=ca;exports.TriggerBuilder=jt;exports.TriggerModel=Eo;exports.TypeStore=M;exports.UIRaycastUtils=m_;exports.UIRootComponent=qh;exports.USDDocument=G_;exports.USDObject=nt;exports.USDWriter=WC;exports.USDZExporter=GC;exports.USDZExporter$1=os;exports.USDZText=Va;exports.USDZUIExtension=cb;exports.UriSerializer=sC;exports.UsageMarker=zh;exports.UserJoinedOrLeftRoomModel=KM;exports.VERSION=Zt;exports.VariantAction=q_;exports.VelocityOverLifetimeModule=We;exports.VerticalLayoutGroup=ob;exports.VerticalWrapMode=u1;exports.VideoPlayer=ut;exports.ViewDevice=Ts;exports.Vignette=ra;exports.VisibilityAction=Hh;exports.Voip=Qs;exports.Volume=od;exports.VolumeParameter=z;exports.VolumeProfile=Mp;exports.WaitForFrames=FM;exports.WaitForPromise=zx;exports.WaitForSeconds=Hy;exports.Watch=Es;exports.WebARCameraBackground=pd;exports.WebARSessionRoot=Qi;exports.WebXR=_p;exports.WebXRButtonFactory=Ro;exports.WebXRImageTracking=Kl;exports.WebXRImageTrackingModel=Zi;exports.WebXRPlaneTracking=Js;exports.WebXRTrackedImage=bl;exports.XRControllerFollow=Ks;exports.XRControllerModel=js;exports.XRControllerMovement=Ti;exports.XRFlag=_n;exports.XRRig=Vp;exports.XRState=Kt;exports.XRStateFlag=Yn;exports._$IqaqwY=Yi;exports.__Ignore=hP;exports.__internalNotifyObjectDestroyed=vE;exports.__internalStepGaussianSplatAdaptation=rS;exports.activeInHierarchyFieldName=Zn;exports.adaptGaussianSplatQuality=Ky;exports.addAttributeChangeCallback=ju;exports.addComponent=ss;exports.addCustomExtensionPlugin=LA;exports.addNewComponent=kr;exports.addPatch=Tf;exports.apply=lh;exports.applyDef=aP;exports.applyGaussianSplatQuality=Tg;exports.applyHMRChanges=nR;exports.applyOver=lP;exports.applyPrototypeExtensions=DS;exports.beginListenDestroy=xx;exports.beginListenInstantiate=kx;exports.binaryIdentifierCasts=qy;exports.build_scene_functions=hE;exports.builtinComponentKeyName=cr;exports.calculateProgress01=jb;exports.clearMessages=NP;exports.compareAssociation=Ex;exports.copyTexture=Kw;exports.createDefSerializationContext=zb;exports.createMotion=eC;exports.debugNet=oi;exports.debugOwner=Oa;exports.decompressGpuTexture=QC;exports.deepClone=Sh;exports.delay=Ds;exports.delayForFrames=kf;exports.deserializeObject=Jc;exports.destroy=fi;exports.destroyComponentInstance=XS;exports.determineMimeTypeFromExtension=T_;exports.disposeObjectResources=Oe;exports.disposeStream=Hi;exports.editorGuidKeyName=Rs;exports.enableSpatialConsole=qa;exports.evaluateProjectDocument=rP;exports.exportAsGLTF=I3;exports.findByGuid=l_;exports.findObjectOfType=kl;exports.findObjectsOfType=YS;exports.findResourceUsers=r_;exports.fitCamera=aC;exports.fitObjectIntoVolume=Jw;exports.foreachComponent=xn;exports.foreachComponentEnumerator=c_;exports.forward=ak;exports.generateQRCode=yS;exports.generateSeed=Px;exports.getBoundingBox=pi;exports.getCameraController=Vw;exports.getComponent=Bs;exports.getComponentInChildren=Ah;exports.getComponentInParent=ch;exports.getComponents=Cl;exports.getComponentsInChildren=Pl;exports.getComponentsInParent=Gf;exports.getContextResetBehaviors=Ux;exports.getFormattedDate=zC;exports.getGaussianSplatQualityInfo=fO;exports.getIconElement=bt;exports.getIconTexture=Dg;exports.getLoader=Is;exports.getOrAddComponent=Th;exports.getParam=x;exports.getParentHierarchyPath=hk;exports.getPath=bP;exports.getPeerOptions=GM;exports.getPeerjsInstance=Gx;exports.getResourceUserCount=xE;exports.getSceneData=Jx;exports.getTempColor=qw;exports.getTempQuaternion=ci;exports.getTempVector=F;exports.getUrlParams=xh;exports.getVisibleInCustomShadowRendering=Zw;exports.getWorldDirection=Xw;exports.getWorldEuler=Ry;exports.getWorldPosition=ie;exports.getWorldQuaternion=Se;exports.getWorldRotation=Of;exports.getWorldScale=Ve;exports.hasPointerEventComponent=hf;exports.hideDebugConsole=sx;exports.imageToCanvas=YC;exports.initAddressableSerializers=jx;exports.initBuiltinSerializers=oC;exports.initEngine=O3;exports.initPhysics=J1;exports.initVolumeParameterSerializer=pC;exports.instantiate=Ls;exports.invokeLoadedImportPluginHooks=OC;exports.invokeXRSessionEnd=gS;exports.invokeXRSessionStart=mS;exports.isActiveInHierarchy=IS;exports.isActiveSelf=Sl;exports.isAndroidDevice=PP;exports.isAnimationAction=Yw;exports.isComponent=Af;exports.isDebugMode=pP;exports.isDesktop=wP;exports.isDestroyed=Ao;exports.isDevEnvironment=E;exports.isDisposable=JE;exports.isDisposed=bE;exports.isExporting=A3;exports.isGLTFModel=dx;exports.isHostedOnGlitch=Rw;exports.isHotReloadEnabled=Xg;exports.isHotReloading=tR;exports.isIPad=SP;exports.isIconElement=_S;exports.isLocalNetwork=ki;exports.isMacOS=MP;exports.isMobileDevice=xP;exports.isMozillaXR=kP;exports.isQuest=RP;exports.isResourceTrackingEnabled=kS;exports.isSafari=EP;exports.isTrackModel=mT;exports.isUsingInstancing=$f;exports.isiOS=OP;exports.isiPad=CP;exports.isolateChildrenDuring=Fg;exports.loadAsset=C1;exports.loadPMREM=Bh;exports.loadSync=db;exports.logHierarchy=$u;exports.lookAtInverse=JP;exports.lookAtObject=Ch;exports.lookAtScreenPoint=ek;exports.makeId=gP;exports.makeIdFromRandomWords=Dw;exports.makeNameSafe=Ri;exports.markAsInstancedRendered=LS;exports.maxGaussianSplatAdaptationLevel=hr;exports.microphonePermissionsGranted=TP;exports.nameof=fP;exports.nameofFactory=Tw;exports.needle=JM;exports.offBeforeXRSession=pS;exports.offXRSessionEnd=fS;exports.offXRSessionStart=t_;exports.on=eR;exports.onAfterRender=eM;exports.onBeforeRender=Jk;exports.onBeforeXRSession=ZO;exports.onClear=Kk;exports.onDestroy=Zk;exports.onInitialized=Uy;exports.onStart=If;exports.onSyncDestroy=mM;exports.onSyncInstantiate=Cx;exports.onUpdate=_x;exports.onXRSessionEnd=i_;exports.onXRSessionStart=jf;exports.originalComponentNameKey=ah;exports.parseSync=vp;exports.placeOnSurface=ex;exports.postprocessFBXMaterials=Dy;exports.prefix=QR;exports.pushState=Aw;exports.randomNumber=yP;exports.registerBinaryType=Xy;exports.registerComponent=zf;exports.registerComponentExtension=I_;exports.registerCustomEffectType=an;exports.registerExportExtensions=L_;exports.registerExtensions=mf;exports.registerHotReloadType=KS;exports.registerLoader=gx;exports.registerPrefabProvider=Mx;exports.registerPrototypeExtensions=a_;exports.registerType=Ly;exports.relativePathPrefix=Lw;exports.removeAttributeChangeCallback=Fw;exports.removeComponent=Wf;exports.removeCustomImportExtensionType=BA;exports.removePatch=Wk;exports.resolveGaussianSplatQuality=Ff;exports.resolveUrl=cs;exports.sanitizeString=Iw;exports.saveImage=K1;exports.screenshot=Z2;exports.screenshot2=Fb;exports.sendDestroyed=$y;exports.serializable=p;exports.serializeObject=Ax;exports.serializeable=Qe;exports.setActive=Pr;exports.setAllowBalloonMessages=zw;exports.setAllowOverlayMessages=FP;exports.setAutoFitEnabled=zu;exports.setCameraController=fg;exports.setDestroyed=FS;exports.setDevEnvironment=HP;exports.setDisposable=OS;exports.setDontDestroy=Ea;exports.setOrAddParamsToUrl=cg;exports.setParam=mP;exports.setParamWithoutReload=Yc;exports.setPeerOptions=HM;exports.setPhysicsEngineFactory=SS;exports.setResourceTrackingEnabled=_E;exports.setState=Sy;exports.setVisibleInCustomShadowRendering=Ay;exports.setWorldEuler=Ty;exports.setWorldPosition=Oi;exports.setWorldPositionXYZ=Ar;exports.setWorldQuaternion=vn;exports.setWorldQuaternionXYZW=Ey;exports.setWorldRotation=Qw;exports.setWorldRotationXYZ=Ph;exports.setWorldScale=rl;exports.showBalloonError=wl;exports.showBalloonMessage=Re;exports.showBalloonWarning=de;exports.showDebugConsole=Iy;exports.slerp=Gw;exports.syncDestroy=Mh;exports.syncField=b_;exports.syncInstantiate=Vy;exports.textureToCanvas=dk;exports.toSourceId=Bw;exports.tryCastBinary=Vx;exports.tryDetermineMimetypeFromBinary=PC;exports.tryDetermineMimetypeFromURL=CC;exports.tryFindObject=Kc;exports.tryGetExtensionFromUrl=SC;exports.tryGetGuid=Wx;exports.unregisterHotReloadType=ZS;exports.unregisterPrefabProvider=_M;exports.unwatchWrite=Cy;exports.useForAutoFit=Ww;exports.validate=je;exports.watchWrite=Mf;
1860
+ `),si&&this._onCreateEffectsDebug(this._composer,o)}createPassForMergeableEffects(e,t,i,n){if(e.length>0){const o=new A.POSTPROCESSING.MODULE.EffectPass(i,...e);o.name=e.map(r=>r.name).join(", "),o.mainScene=n,o.enabled=!0,o.renderToScreen=!1,t.addPass(o),e.length=0}}handleDevicePixelRatio(){typeof this.context.devicePixelRatio=="number"&&this.context.requestSizeUpdate()}_menuEntry=null;_passIndices=null;_onCreateEffectsDebug(e,t){if(si==="passes"){const i=new A.POSTPROCESSING.MODULE.DepthEffect({blendFunction:A.POSTPROCESSING.MODULE.BlendFunction.NORMAL,inverted:!0});i.name="Depth Effect";const n=new A.POSTPROCESSING.MODULE.EffectPass(t,i);if(n.name="Depth Effect Pass",n.enabled=!1,e.passes.push(n),this._passIndices!==null){const r=[e.passes[0]];this._passIndices.length>0&&r.push(...this._passIndices.filter(a=>a!==0).map(a=>e.passes[a]).filter(a=>a)),r.length>0&&console.log("[PostProcessing] Passes (selected) →",r),e.passes.length=0;for(const a of r)a.enabled=!0,a.renderToScreen=!1,e.addPass(a)}const o=this.context.menu;if(o&&this._passIndices===null){this._menuEntry&&this._menuEntry.remove();const r=document.createElement("select");r.multiple=!0;const a=document.createElement("option");a.innerText="Final Output",a.value="-1",r.appendChild(a);for(const l of e.passes){const h=document.createElement("option");h.innerText=l.name,h.value=`${e.passes.indexOf(l)}`,h.title=l.name,r.appendChild(h)}o.appendChild(r),this._menuEntry=r,r.addEventListener("change",()=>{const l=Array.from(r.selectedOptions).map(h=>parseInt(h.value));l.length===1&&l[0]===-1?this._passIndices=null:this._passIndices=l,this.applyEffects(this.context)})}}}}const F3=Object.freeze(Object.defineProperty({__proto__:null,PostProcessingHandler:vl},Symbol.toStringTag,{value:"Module"}));class Wp{_name;_tracks=[];_currentTrack=null;_pendingSignals=[];_idProvider;constructor(e,t){this._name=e,this._idProvider=new ot(t??Date.now())}static create(e,t){return new Wp(e??"Timeline",t)}animationTrack(e,t){return this.commitInlineTracks(),this._currentTrack=this.pushTrack(e,we.Animation,t??null),this}audioTrack(e,t,i){return this.commitInlineTracks(),this._currentTrack=this.pushTrack(e,we.Audio,t??null),this._currentTrack.volume=i,this}activationTrack(e,t){return this.commitInlineTracks(),this._currentTrack=this.pushTrack(e,we.Activation,t??null),this}controlTrack(e){return this.commitInlineTracks(),this._currentTrack=this.pushTrack(e,we.Control,null),this}signalTrack(e,t){return this.commitInlineTracks(),this._currentTrack=this.pushTrack(e,we.Signal,t??null),this}markerTrack(e){return this.commitInlineTracks(),this._currentTrack=this.pushTrack(e,we.Marker,null),this}clip(e,t){if(!this._currentTrack)throw new Error("TimelineBuilder: .clip() must be called after a track method (e.g. .animationTrack())");this.commitInlineTracks();const i=this._currentTrack;switch(i.type){case we.Animation:{let n;if(e instanceof c.AnimationClip)n=e;else{const d=Array.isArray(e)?e:[e],u=i.outputs[0],f=u instanceof c.Object3D?u:u!=null&&"gameObject"in u?u.gameObject:void 0;n=dh(d,f)}const o=t??{},r=o.duration??n.duration,a=o.start??i.cursor,l=a+r,h={start:a,end:l,duration:r,timeScale:o.speed??1,clipIn:o.clipIn??0,easeInDuration:o.easeIn??0,easeOutDuration:o.easeOut??0,preExtrapolationMode:o.preExtrapolation??et.None,postExtrapolationMode:o.postExtrapolation??et.None,reversed:o.reversed,asset:{clip:n,loop:o.loop??!1,duration:n.duration,removeStartOffset:o.removeStartOffset??!1}};i.clips.push(h),i.cursor=l;break}case we.Audio:{const n=e,o=t??{},r=o.duration,a=o.start??i.cursor,l=a+r,h={start:a,end:l,duration:r,timeScale:o.speed??1,clipIn:0,easeInDuration:o.easeIn??0,easeOutDuration:o.easeOut??0,preExtrapolationMode:et.None,postExtrapolationMode:et.None,asset:{clip:n,loop:o.loop??!1,volume:o.volume??1}};i.clips.push(h),i.cursor=l;break}case we.Activation:{const n=e,o=n.start??i.cursor,r=o+n.duration,a={start:o,end:r,duration:n.duration,timeScale:1,clipIn:0,easeInDuration:n.easeIn??0,easeOutDuration:n.easeOut??0,preExtrapolationMode:et.None,postExtrapolationMode:et.None,asset:{}};i.clips.push(a),i.cursor=r;break}case we.Control:{const n=e,o=t??{},r=o.start??i.cursor,a=o.duration,l=r+a,h={start:r,end:l,duration:a,timeScale:1,clipIn:0,easeInDuration:0,easeOutDuration:0,preExtrapolationMode:et.None,postExtrapolationMode:et.None,asset:{sourceObject:n,controlActivation:o.controlActivation??!0,updateDirector:o.updateDirector??!0}};i.clips.push(h),i.cursor=l;break}default:throw new Error(`TimelineBuilder: .clip() is not supported on track type "${i.type}"`)}return this}marker(e,t,i){if(!this._currentTrack)throw new Error("TimelineBuilder: .marker() must be called after a track method");if(this._currentTrack.type!==we.Signal&&this._currentTrack.type!==we.Marker)throw new Error(`TimelineBuilder: .marker() is only supported on signal and marker tracks, not "${this._currentTrack.type}"`);const n={type:mh.Signal,time:e,retroActive:i?.retroActive??!1,emitOnce:i?.emitOnce??!1,asset:t};return this._currentTrack.markers.push(n),e>this._currentTrack.cursor&&(this._currentTrack.cursor=e),this}signal(e,t,i){if(!this._currentTrack)throw new Error("TimelineBuilder: .signal() must be called after a track method");if(this._currentTrack.type!==we.Signal&&this._currentTrack.type!==we.Marker)throw new Error(`TimelineBuilder: .signal() is only supported on signal and marker tracks, not "${this._currentTrack.type}"`);const n=this._idProvider.generateUUID(),o=this._tracks.indexOf(this._currentTrack),r={type:mh.Signal,time:e,retroActive:i?.retroActive??!1,emitOnce:i?.emitOnce??!1,asset:n};return this._currentTrack.markers.push(r),this._pendingSignals.push({trackIndex:o,guid:n,callback:t}),e>this._currentTrack.cursor&&(this._currentTrack.cursor=e),this}muted(e=!0){if(!this._currentTrack)throw new Error("TimelineBuilder: .muted() must be called after a track method");return this._currentTrack.muted=e,this}track(e,t,i,n){if(!this._currentTrack)throw new Error("TimelineBuilder: .track() must be called after .animationTrack()");if(this._currentTrack.type!==we.Animation)throw new Error("TimelineBuilder: .track() is only supported on animation tracks");return this._currentTrack.inlineTracks.push(u_(e,t,i,n)),this}build(){this.commitInlineTracks();const e=this._tracks.map(t=>{const i={name:t.name,type:t.type,muted:t.muted,outputs:t.outputs};return t.clips.length>0&&(i.clips=t.clips),t.markers.length>0&&(i.markers=t.markers),t.volume!==void 0&&(i.volume=t.volume),t.trackOffset!==void 0&&(i.trackOffset=t.trackOffset),i});return{name:this._name,tracks:e}}install(e){const t=this.build();if(this._pendingSignals.length>0){const i=e.gameObject;let n=P.getComponent(i,Lr);n||(n=P.addComponent(i,Lr)),n.events||(n.events=[]);for(const o of this._pendingSignals){const r=new Lh;r.guid=o.guid;const a=new Ml;a.signal=r,a.reaction=new Z([o.callback]),n.events.push(a);const l=t.tracks[o.trackIndex];l&&!l.outputs.includes(n)&&l.outputs.push(n)}}return e.playableAsset=t,t}pushTrack(e,t,i){const n={name:e,type:t,muted:!1,outputs:i?[i]:[],clips:[],markers:[],cursor:0,inlineTracks:[]};return this._tracks.push(n),n}commitInlineTracks(){if(!this._currentTrack||this._currentTrack.inlineTracks.length===0)return;const e=this._currentTrack,t=e.outputs[0],i=t instanceof c.Object3D?t:t!=null&&"gameObject"in t?t.gameObject:void 0,n=dh(e.inlineTracks,i),o=e.cursor,r=n.duration,a={start:o,end:o+r,duration:r,timeScale:1,clipIn:0,easeInDuration:0,easeOutDuration:0,preExtrapolationMode:et.None,postExtrapolationMode:et.None,asset:{clip:n,loop:!1,duration:n.duration,removeStartOffset:!1}};e.clips.push(a),e.cursor=o+r,e.inlineTracks=[]}}class hP{}const j3=Object.freeze(Object.defineProperty({__proto__:null,ActionBuilder:pe,ActionCollection:JC,ActionModel:li,AlignmentConstraint:jh,Animation:Ut,AnimationBuilder:Hf,AnimationCurve:Zh,AnimationExtension:up,Animator:vt,AnimatorController:Jn,Antialiasing:ed,Attractor:$l,AudioExtension:qr,AudioListener:Ms,AudioSource:Ei,Avatar:Io,AvatarMarker:it,AxesHelper:Ol,AxisRotationConstraint:O_,BaseUIComponent:en,BasicIKConstraint:x_,BehaviorExtension:tb,BehaviorModel:Dt,BloomEffect:Ep,BoxCollider:np,BoxGizmo:Zr,BoxHelperComponent:At,Button:Ys,CallInfo:vi,Camera:Jt,CameraTargetReachedEvent:ph,Canvas:yl,CanvasGroup:Lo,CapsuleCollider:Fs,ChangeMaterialOnClick:X_,ChangeTransformOnClick:Xr,CharacterController:Gr,CharacterControllerInput:Ns,ChromaticAberration:td,ClickThrough:zp,ColorAdjustments:Go,ColorBySpeedModule:Nl,ColorOverLifetimeModule:kp,ContactShadows:Uh,CursorFollow:ha,CustomBranding:Yr,Deletable:k_,DeleteBox:Oo,DepthOfField:On,DeviceFlag:sp,DocumentExtension:cP,DragControls:vr,DragProfile:uf,DropListener:Vs,Duplicatable:U_,EffectWrapper:wh,EmissionModule:qs,EmphasizeOnClick:Al,EnvironmentScene:ip,EventList:Z,EventListEvent:f_,EventSystem:ei,EventTrigger:hp,FieldWithDefault:TC,FixedJoint:gb,FixedRotationAxesConstraint:vC,Fog:Fl,GaussianSplat:Kr,GltfExport:W_,GltfExportBox:$_,GrabPointPlaneConstraint:Nh,Gradient:ea,Graphic:Qh,GraphicRaycaster:Yf,GridHelper:jl,GridLayoutGroup:ab,GridSnapConstraint:op,GroundProjectedEnv:ds,GroupActionModel:wr,HideOnStart:Gi,HingeJoint:Kh,HorizontalLayoutGroup:rb,get HoverAnimation(){return exports.HoverAnimation},Image:ql,InheritVelocityModule:wb,InputField:Db,InstanceHandle:Rr,InstancingHandler:jr,Interactable:P_,KeepRotationConstraint:rp,KeepScaleConstraint:bC,Keyframe:ui,LODGroup:Sp,LODModel:Ul,Light:Lt,LimitVelocityOverLifetimeModule:pt,LogStats:C_,LookAt:Ib,LookAtConstraint:Vr,MainModule:$t,MaskableGraphic:Yh,MeshCollider:Uo,MeshRenderer:Vh,MinMaxCurve:Q,MinMaxGradient:ta,NeedleMenu:fs,NestedGltf:zl,Networking:bb,NoiseModule:ve,ObjectRaycaster:Ji,OffsetConstraint:Jr,OpenURL:Xl,OrbitControls:ue,Outline:Bl,Padding:Qr,ParticleBurst:wf,ParticleSubEmitter:xb,ParticleSystem:vh,ParticleSystemRenderer:rn,PhysicsExtension:ib,PixelationEffect:id,PlaneHeightLockConstraint:E_,PlayAnimationOnClick:_h,PlayAudioOnClick:Do,PlayableDirector:ml,PlayerColor:_l,PointerEventData:Ih,PostProcessingHandler:vl,PreliminaryAction:Dl,PreliminaryTrigger:Gh,RawImage:Fp,Rect:l1,RectTransform:Cn,ReflectionProbe:Ps,RegisteredAnimationInfo:Co,RemoteSkybox:v_,Renderer:ti,RendererLightmap:B_,Rigidbody:Xe,RotationBySpeedModule:on,RotationOverLifetimeModule:Mn,ScaleLimitConstraint:M_,SceneSwitcher:Ye,ScreenCapture:Ho,ScreenSpaceAmbientOcclusion:Xs,ScreenSpaceAmbientOcclusionN8:En,ScrollFollow:gs,SeeThrough:Ob,SetActiveOnClick:Q_,ShadowCatcher:ld,ShapeModule:vb,SharpeningEffect:sd,SignalAsset:Lh,SignalReceiver:Lr,SignalReceiverEvent:Ml,SignalTrackHandler:yh,Size:a1,SizeBySpeedModule:_i,SizeOverLifetimeModule:ia,SkinnedMeshRenderer:F_,SmoothFollow:Ap,SnapToSurfaceConstraint:ap,SpatialGrabRaycaster:Ir,SpatialHtml:ud,SpatialTrigger:Dp,SpatialTriggerReceiver:rs,SpectatorCamera:Ip,SphereCollider:El,SplineContainer:la,SplineData:ls,SplineWalker:ln,Sprite:Ws,SpriteData:nl,SpriteRenderer:gi,SpriteSheet:gl,SubEmitterSystem:xf,SyncedCamera:Eb,SyncedRoom:Rn,SyncedTransform:Sn,TapGestureTrigger:K_,TeleportTarget:yp,TestRunner:Rb,TestSimulateUserData:Tb,Text:Nt,TextBuilder:sb,TextExtension:bp,TextureSheetAnimationModule:Vt,TiltShiftEffect:ms,TimelineActivationTrack:Jf,TimelineAnimationTrack:gh,TimelineAudioTrack:Os,TimelineBuilder:Wp,TimelineControlTrack:ep,TimelineMarkerTrack:Zf,ToneMappingEffect:na,TrailModule:ze,TransformData:Fe,TransformGizmo:ca,TriggerBuilder:jt,TriggerModel:Eo,UIRaycastUtils:m_,UIRootComponent:qh,USDZExporter:os,USDZText:Va,USDZUIExtension:cb,UsageMarker:zh,VariantAction:q_,VelocityOverLifetimeModule:We,VerticalLayoutGroup:ob,VideoPlayer:ut,get ViewBox(){return exports.ViewBox},Vignette:ra,VisibilityAction:Hh,Voip:Qs,Volume:od,VolumeParameter:z,VolumeProfile:Mp,WebARCameraBackground:pd,WebARSessionRoot:Qi,WebXR:_p,WebXRImageTracking:Kl,WebXRImageTrackingModel:Zi,WebXRPlaneTracking:Js,WebXRTrackedImage:bl,XRControllerFollow:Ks,XRControllerModel:js,XRControllerMovement:Ti,XRFlag:_n,XRRig:Vp,XRState:Kt,__Ignore:hP},Symbol.toStringTag,{value:"Module"}));exports.SplineUtils=void 0;(s=>{function e(t,i=!1,n=.75){const o=new la,r=1-L.clamp(n,0,1);return t.forEach((a,l)=>{const h=new c.Vector3;l<t.length-1?h.subVectors(t[l+1],a).normalize().multiplyScalar(r):i&&t.length>1&&h.subVectors(t[0],a).normalize().multiplyScalar(r);const d=new ls;d.position.copy(a),d.tangentIn.copy(h),d.tangentOut.copy(h),o.addKnot(d)}),o.closed=i,o}s.createFromPoints=e})(exports.SplineUtils||(exports.SplineUtils={}));class U3 extends ee.WorkerBase{constructor(){super(new Worker(new URL("/generateMeshBVH.worker-Be19n6m6.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:Ha&&Ha.tagName.toUpperCase()==="SCRIPT"&&Ha.src||new URL("needle-engine.bundle-D3nBMgfk.umd.cjs",document.baseURI).href),{type:"module"})),this.name="GenerateMeshBVHWorker"}runTask(e,t,i={}){return new Promise((n,o)=>{if(t.getAttribute("position").isInterleavedBufferAttribute||t.index&&t.index.isInterleavedBufferAttribute)throw new Error("GenerateMeshBVHWorker: InterleavedBufferAttribute are not supported for the geometry attributes.");e.onerror=h=>{o(new Error(`[GenerateMeshBVHWorker] ${h.message||"Could not load worker."}`))},e.onmessage=h=>{const{data:d}=h;if(d.error)o(new Error(d.error)),e.onmessage=null;else if(d.serialized){const{serialized:u,position:f}=d,m=ee.MeshBVH.deserialize(u,t,{setIndex:!1}),g=Object.assign({setBoundingBox:!0},i);if(t.attributes.position.array=f,u.index)if(t.index)t.index.array=u.index;else{const v=new c.BufferAttribute(u.index,1,!1);t.setIndex(v)}g.setBoundingBox&&(t.boundingBox=m.getBoundingBox(new c.Box3)),i.onProgress&&i.onProgress(d.progress),n(m),e.onmessage=null}else i.onProgress&&i.onProgress(d.progress)};const r=t.index?t.index.array:null,a=t.attributes.position.array,l=[a];r&&l.push(r),e.postMessage({index:r,position:a,options:{...i,onProgress:null,includedProgressCallback:!!i.onProgress,groups:[...t.groups]}},l.map(h=>h.buffer).filter(h=>typeof SharedArrayBuffer>"u"||!(h instanceof SharedArrayBuffer)))}).finally(()=>{e.onmessage=null,e.onerror=null})}}const z3=Object.freeze(Object.defineProperty({__proto__:null,GenerateMeshBVHWorker:U3},Symbol.toStringTag,{value:"Module"}));exports.$componentName=Gu;exports.$physicsKey=qk;exports.ActionBuilder=pe;exports.ActionCollection=JC;exports.ActionModel=li;exports.Addressables=Lx;exports.AlignmentConstraint=jh;exports.AmbientMode=Ya;exports.Animation=Ut;exports.AnimationBuilder=Hf;exports.AnimationCurve=Zh;exports.AnimationExtension=up;exports.Animator=vt;exports.AnimatorConditionMode=hi;exports.AnimatorController=Jn;exports.AnimatorControllerBuilder=qf;exports.AnimatorControllerParameterType=br;exports.AnimatorStateInfo=Pc;exports.Antialiasing=ed;exports.Application=wn;exports.AssetDatabase=CS;exports.AssetReference=J;exports.Attractor=$l;exports.AudioClip=Yg;exports.AudioExtension=qr;exports.AudioListener=Ms;exports.AudioRolloffMode=hC;exports.AudioSource=Ei;exports.Avatar=Io;exports.AvatarMarker=it;exports.Axes=$a;exports.AxesHelper=Ol;exports.AxisRotationConstraint=O_;exports.BUILD_TIME=Zc;exports.BaseUIComponent=en;exports.BasicIKConstraint=x_;exports.BehaviorExtension=tb;exports.BehaviorModel=Dt;exports.BloomEffect=Ep;exports.BoxCollider=np;exports.BoxGizmo=Zr;exports.BoxHelperComponent=At;exports.Button=Ys;exports.ButtonsFactory=Xi;exports.CallDirection=B1;exports.CallInfo=vi;exports.Camera=Jt;exports.CameraTargetReachedEvent=ph;exports.Canvas=yl;exports.CanvasGroup=Lo;exports.CapsuleCollider=Fs;exports.ChangeMaterialOnClick=X_;exports.ChangeTransformOnClick=Xr;exports.CharacterController=Gr;exports.CharacterControllerInput=Ns;exports.ChromaticAberration=td;exports.CircularBuffer=Mi;exports.ClearFlags=Or;exports.ClickThrough=zp;exports.ClipExtrapolation=et;exports.Collider=Ii;exports.Collision=fx;exports.CollisionDetectionMode=Qf;exports.ColorAdjustments=Go;exports.ColorBySpeedModule=Nl;exports.ColorOverLifetimeModule=kp;exports.Component=sR;exports.Component$1=T;exports.ComponentLifecycleEvents=Rf;exports.Components=j3;exports.ConnectionEvents=qx;exports.ContactPoint=ux;exports.ContactShadows=Uh;exports.Context=X;exports.ContextArgs=dE;exports.ContextEvent=ae;exports.ContextRegistry=se;exports.CursorFollow=ha;exports.CustomBranding=Yr;exports.CustomShader=Me;exports.DefaultReflectionMode=Ju;exports.Deletable=k_;exports.DeleteBox=Oo;exports.DepthOfField=On;exports.DepthOfFieldMode=A1;exports.DeviceFlag=sp;exports.DirectorWrapMode=uC;exports.DisposableStore=Ou;exports.DocumentExtension=cP;exports.DragControls=vr;exports.DragMode=R_;exports.DragProfile=uf;exports.DropListener=Vs;exports.Duplicatable=U_;exports.EffectWrapper=wh;exports.EmissionModule=qs;exports.EmphasizeOnClick=Al;exports.EngineLoadingView=Tr;exports.EnvironmentScene=ip;exports.EventBus=Og;exports.EventList=Z;exports.EventListEvent=f_;exports.EventSystem=ei;exports.EventTrigger=hp;exports.FieldWithDefault=TC;exports.FileReference=qn;exports.FileReferenceSerializer=Fx;exports.FileSpawnModel=lA;exports.File_Event=xC;exports.FixedJoint=gb;exports.FixedRotationAxesConstraint=vC;exports.Fog=Fl;exports.FontStyle=bf;exports.FrameEvent=Ce;exports.GENERATOR=al;exports.GameObject=P;exports.GaussianSplat=Kr;exports.Gizmos=B;exports.GltfExport=W_;exports.GltfExportBox=$_;exports.GrabPointPlaneConstraint=Nh;exports.Gradient=ea;exports.Graphic=Qh;exports.GraphicRaycaster=Yf;exports.Graphics=To;exports.GridHelper=jl;exports.GridLayoutGroup=ab;exports.GridSnapConstraint=op;exports.GroundProjectedEnv=ds;exports.GroupActionModel=wr;exports.HideFlags=as;exports.HideOnStart=Gi;exports.HingeJoint=Kh;exports.HorizontalLayoutGroup=rb;exports.HorizontalWrapMode=f1;exports.HostData=gM;exports.Image=ql;exports.ImageReference=Hn;exports.ImageReferenceSerializer=Bx;exports.InheritVelocityModule=wb;exports.Input=Nx;exports.InputEventQueue=xo;exports.InputEvents=xe;exports.InputField=Db;exports.InstanceHandle=Rr;exports.InstancingHandler=jr;exports.InstancingUtil=Ki;exports.InstantiateEvent=wx;exports.InstantiateIdProvider=ot;exports.InstantiateOptions=hs;exports.Interactable=P_;exports.JoinedRoomResponse=QM;exports.KeepRotationConstraint=rp;exports.KeepScaleConstraint=bC;exports.KeyEventArgs=NM;exports.Keyframe=ui;exports.LODGroup=Sp;exports.LODModel=Ul;exports.LODsManager=$x;exports.LeftRoomResponse=YM;exports.Light=Lt;exports.LightData=tS;exports.LimitVelocityOverLifetimeModule=pt;exports.LoadingElementOptions=y3;exports.LogStats=C_;exports.LogType=Ci;exports.LookAt=Ib;exports.LookAtConstraint=Vr;exports.MODULES=A;exports.MainModule=$t;exports.MarkerType=mh;exports.MaskableGraphic=Yh;exports.MaterialPropertyBlock=As;exports.Mathf=L;exports.MeshCollider=Uo;exports.MeshRenderer=Vh;exports.MinMaxCurve=Q;exports.MinMaxGradient=ta;exports.NEEDLE_ENGINE_FEATURE_FLAGS=By;exports.NEKeyboardEvent=xc;exports.NEPointerEvent=Cs;exports.NEToneMappingMode=Ga;exports.NeedleButtonElement=eP;exports.NeedleEngineWebComponent=Ub;exports.NeedleMenu=fs;exports.NeedlePatchesKey=gu;exports.NeedleXRController=Jy;exports.NeedleXRSession=N;exports.NeedleXRSync=hS;exports.NeedleXRUtils=wS;exports.NestedGltf=zl;exports.NetworkConnection=th;exports.NetworkedStreamEvents=is;exports.NetworkedStreams=rd;exports.Networking=bb;exports.NewInstanceModel=Sx;exports.NoiseModule=ve;exports.ObjectRaycaster=Ji;exports.ObjectUtils=jo;exports.OffsetConstraint=Jr;exports.OneEuroFilter=pu;exports.OneEuroFilterXYZ=My;exports.OpenURL=Xl;exports.OrbitControls=ue;exports.Outline=Bl;exports.OwnershipEvent=Xx;exports.OwnershipModel=Qx;exports.PUBLIC_KEY=wo;exports.Padding=Qr;exports.ParticleBurst=wf;exports.ParticleSubEmitter=xb;exports.ParticleSystem=vh;exports.ParticleSystemBaseBehaviour=Wo;exports.ParticleSystemRenderer=rn;exports.ParticleSystemShapeType=vf;exports.PeerHandle=sl;exports.PeerNetworking=Hx;exports.Physics=pl;exports.PhysicsExtension=ib;exports.PhysicsMaterialCombine=mt;exports.PixelationEffect=id;exports.PlaneHeightLockConstraint=E_;exports.PlayAnimationOnClick=_h;exports.PlayAudioOnClick=Do;exports.PlayableDirector=ml;exports.PlayerColor=_l;exports.PlayerState=di;exports.PlayerStateEvent=i1;exports.PlayerSync=J_;exports.PlayerView=Yx;exports.PlayerViewManager=Kx;exports.PointerEventData=Ih;exports.PointerType=Lf;exports.PostProcessing=oS;exports.PostProcessingEffect=rt;exports.PostProcessingEffectOrder=dt;exports.PostProcessingHandler=vl;exports.Prefabs=ll;exports.PreliminaryAction=Dl;exports.PreliminaryTrigger=Gh;exports.PrimitiveType=xl;exports.Progress=he;exports.PromiseAllWithErrors=Py;exports.PromiseErrorResult=hg;exports.QualityLevel=E1;exports.RGBAColor=oe;exports.RapierPhysics=ol;exports.RawImage=Fp;exports.RaycastOptions=zr;exports.Rect=l1;exports.RectTransform=Cn;exports.ReflectionProbe=Ps;exports.ReflectionProbeUsage=RC;exports.RegisteredAnimationInfo=Co;exports.RemoteSkybox=v_;exports.RenderTexture=es;exports.RenderTextureSerializer=nC;exports.Renderer=ti;exports.RendererData=eS;exports.RendererLightmap=B_;exports.Rigidbody=Xe;exports.RigidbodyConstraints=qe;exports.RoomEvents=te;exports.RotationBySpeedModule=on;exports.RotationOverLifetimeModule=Mn;exports.ScaleLimitConstraint=M_;exports.SceneLightSettings=ff;exports.SceneSwitcher=Ye;exports.ScreenCapture=Ho;exports.ScreenSpaceAmbientOcclusion=Xs;exports.ScreenSpaceAmbientOcclusionN8=En;exports.ScreenSpaceAmbientOcclusionN8QualityMode=Sf;exports.ScrollFollow=gs;exports.SeeThrough=Ob;exports.SendQueue=yn;exports.SerializationContext=Eh;exports.SetActiveOnClick=Q_;exports.ShadowCastingMode=gf;exports.ShadowCatcher=ld;exports.ShapeModule=vb;exports.ShapeOverlapResult=px;exports.SharpeningEffect=sd;exports.SignalAsset=Lh;exports.SignalReceiver=Lr;exports.SignalReceiverEvent=Ml;exports.SignalTrackHandler=yh;exports.Size=a1;exports.SizeBySpeedModule=_i;exports.SizeOverLifetimeModule=ia;exports.SkinnedMeshRenderer=F_;exports.SmoothFollow=Ap;exports.SnapToSurfaceConstraint=ap;exports.SpatialGrabRaycaster=Ir;exports.SpatialHtml=ud;exports.SpatialTrigger=Dp;exports.SpatialTriggerReceiver=rs;exports.SpectatorCamera=Ip;exports.SphereCollider=El;exports.SphereIntersection=o_;exports.SplineContainer=la;exports.SplineData=ls;exports.SplineWalker=ln;exports.Sprite=Ws;exports.SpriteData=nl;exports.SpriteRenderer=gi;exports.SpriteSheet=gl;exports.StateMachineBehaviour=cR;exports.StreamEndedEvent=Mb;exports.StreamReceivedEvent=L1;exports.SubEmitterSystem=xf;exports.SyncedCamera=Eb;exports.SyncedRoom=Rn;exports.SyncedTransform=Sn;exports.TapGestureTrigger=K_;exports.TeleportTarget=yp;exports.TestRunner=Rb;exports.TestSimulateUserData=Tb;exports.Text=Nt;exports.TextAnchor=Je;exports.TextBuilder=sb;exports.TextExtension=bp;exports.TextureSheetAnimationModule=Vt;exports.TiltShiftEffect=ms;exports.Time=iS;exports.TimelineActivationTrack=Jf;exports.TimelineAnimationTrack=gh;exports.TimelineAudioTrack=Os;exports.TimelineBuilder=Wp;exports.TimelineControlTrack=ep;exports.TimelineMarkerTrack=Zf;exports.TimelineTrackHandler=Wr;exports.ToneMappingEffect=na;exports.TrackType=we;exports.TrailModule=ze;exports.TransformData=Fe;exports.TransformGizmo=ca;exports.TriggerBuilder=jt;exports.TriggerModel=Eo;exports.TypeStore=M;exports.UIRaycastUtils=m_;exports.UIRootComponent=qh;exports.USDDocument=G_;exports.USDObject=nt;exports.USDWriter=WC;exports.USDZExporter=GC;exports.USDZExporter$1=os;exports.USDZText=Va;exports.USDZUIExtension=cb;exports.UriSerializer=sC;exports.UsageMarker=zh;exports.UserJoinedOrLeftRoomModel=KM;exports.VERSION=Zt;exports.VariantAction=q_;exports.VelocityOverLifetimeModule=We;exports.VerticalLayoutGroup=ob;exports.VerticalWrapMode=u1;exports.VideoPlayer=ut;exports.ViewDevice=Ts;exports.Vignette=ra;exports.VisibilityAction=Hh;exports.Voip=Qs;exports.Volume=od;exports.VolumeParameter=z;exports.VolumeProfile=Mp;exports.WaitForFrames=FM;exports.WaitForPromise=zx;exports.WaitForSeconds=Hy;exports.Watch=Es;exports.WebARCameraBackground=pd;exports.WebARSessionRoot=Qi;exports.WebXR=_p;exports.WebXRButtonFactory=Ro;exports.WebXRImageTracking=Kl;exports.WebXRImageTrackingModel=Zi;exports.WebXRPlaneTracking=Js;exports.WebXRTrackedImage=bl;exports.XRControllerFollow=Ks;exports.XRControllerModel=js;exports.XRControllerMovement=Ti;exports.XRFlag=_n;exports.XRRig=Vp;exports.XRState=Kt;exports.XRStateFlag=Yn;exports.__Ignore=hP;exports.__Pekxq=Yi;exports.__internalNotifyObjectDestroyed=vE;exports.__internalStepGaussianSplatAdaptation=rS;exports._fncZ=ns;exports.activeInHierarchyFieldName=Zn;exports.adaptGaussianSplatQuality=Ky;exports.addAttributeChangeCallback=ju;exports.addComponent=ss;exports.addCustomExtensionPlugin=LA;exports.addNewComponent=kr;exports.addPatch=Tf;exports.apply=lh;exports.applyDef=aP;exports.applyGaussianSplatQuality=Tg;exports.applyHMRChanges=nR;exports.applyOver=lP;exports.applyPrototypeExtensions=DS;exports.beginListenDestroy=xx;exports.beginListenInstantiate=kx;exports.binaryIdentifierCasts=qy;exports.build_scene_functions=hE;exports.builtinComponentKeyName=cr;exports.calculateProgress01=jb;exports.clearMessages=NP;exports.compareAssociation=Ex;exports.copyTexture=Kw;exports.createDefSerializationContext=zb;exports.createMotion=eC;exports.debugNet=oi;exports.debugOwner=Oa;exports.decompressGpuTexture=QC;exports.deepClone=Sh;exports.delay=Ds;exports.delayForFrames=kf;exports.deserializeObject=Jc;exports.destroy=fi;exports.destroyComponentInstance=XS;exports.determineMimeTypeFromExtension=T_;exports.disposeObjectResources=Oe;exports.disposeStream=Hi;exports.editorGuidKeyName=Rs;exports.enableSpatialConsole=qa;exports.evaluateProjectDocument=rP;exports.exportAsGLTF=I3;exports.findByGuid=l_;exports.findObjectOfType=kl;exports.findObjectsOfType=YS;exports.findResourceUsers=r_;exports.fitCamera=aC;exports.fitObjectIntoVolume=Jw;exports.foreachComponent=xn;exports.foreachComponentEnumerator=c_;exports.forward=ak;exports.generateQRCode=yS;exports.generateSeed=Px;exports.getBoundingBox=pi;exports.getCameraController=Vw;exports.getComponent=Bs;exports.getComponentInChildren=Ah;exports.getComponentInParent=ch;exports.getComponents=Cl;exports.getComponentsInChildren=Pl;exports.getComponentsInParent=Gf;exports.getContextResetBehaviors=Ux;exports.getFormattedDate=zC;exports.getGaussianSplatQualityInfo=fO;exports.getIconElement=bt;exports.getIconTexture=Dg;exports.getLoader=Is;exports.getOrAddComponent=Th;exports.getParam=x;exports.getParentHierarchyPath=hk;exports.getPath=bP;exports.getPeerOptions=GM;exports.getPeerjsInstance=Gx;exports.getResourceUserCount=xE;exports.getSceneData=Jx;exports.getTempColor=qw;exports.getTempQuaternion=ci;exports.getTempVector=F;exports.getUrlParams=xh;exports.getVisibleInCustomShadowRendering=Zw;exports.getWorldDirection=Xw;exports.getWorldEuler=Ry;exports.getWorldPosition=ie;exports.getWorldQuaternion=Se;exports.getWorldRotation=Of;exports.getWorldScale=Ve;exports.hasPointerEventComponent=hf;exports.hideDebugConsole=sx;exports.imageToCanvas=YC;exports.initAddressableSerializers=jx;exports.initBuiltinSerializers=oC;exports.initEngine=O3;exports.initPhysics=J1;exports.initVolumeParameterSerializer=pC;exports.instantiate=Ls;exports.invokeLoadedImportPluginHooks=OC;exports.invokeXRSessionEnd=gS;exports.invokeXRSessionStart=mS;exports.isActiveInHierarchy=IS;exports.isActiveSelf=Sl;exports.isAndroidDevice=PP;exports.isAnimationAction=Yw;exports.isComponent=Af;exports.isDebugMode=pP;exports.isDesktop=wP;exports.isDestroyed=Ao;exports.isDevEnvironment=E;exports.isDisposable=JE;exports.isDisposed=bE;exports.isExporting=A3;exports.isGLTFModel=dx;exports.isHostedOnGlitch=Rw;exports.isHotReloadEnabled=Xg;exports.isHotReloading=tR;exports.isIPad=SP;exports.isIconElement=_S;exports.isLocalNetwork=ki;exports.isMacOS=MP;exports.isMobileDevice=xP;exports.isMozillaXR=kP;exports.isQuest=RP;exports.isResourceTrackingEnabled=kS;exports.isSafari=EP;exports.isTrackModel=mT;exports.isUsingInstancing=$f;exports.isiOS=OP;exports.isiPad=CP;exports.isolateChildrenDuring=Fg;exports.loadAsset=C1;exports.loadPMREM=Bh;exports.loadSync=db;exports.logHierarchy=$u;exports.lookAtInverse=JP;exports.lookAtObject=Ch;exports.lookAtScreenPoint=ek;exports.makeId=gP;exports.makeIdFromRandomWords=Dw;exports.makeNameSafe=Ri;exports.markAsInstancedRendered=LS;exports.maxGaussianSplatAdaptationLevel=hr;exports.microphonePermissionsGranted=TP;exports.nameof=fP;exports.nameofFactory=Tw;exports.needle=JM;exports.offBeforeXRSession=pS;exports.offXRSessionEnd=fS;exports.offXRSessionStart=t_;exports.on=eR;exports.onAfterRender=eM;exports.onBeforeRender=Jk;exports.onBeforeXRSession=ZO;exports.onClear=Kk;exports.onDestroy=Zk;exports.onInitialized=Uy;exports.onStart=If;exports.onSyncDestroy=mM;exports.onSyncInstantiate=Cx;exports.onUpdate=_x;exports.onXRSessionEnd=i_;exports.onXRSessionStart=jf;exports.originalComponentNameKey=ah;exports.parseSync=vp;exports.placeOnSurface=ex;exports.postprocessFBXMaterials=Dy;exports.prefix=QR;exports.pushState=Aw;exports.randomNumber=yP;exports.registerBinaryType=Xy;exports.registerComponent=zf;exports.registerComponentExtension=I_;exports.registerCustomEffectType=an;exports.registerExportExtensions=L_;exports.registerExtensions=mf;exports.registerHotReloadType=KS;exports.registerLoader=gx;exports.registerPrefabProvider=Mx;exports.registerPrototypeExtensions=a_;exports.registerType=Ly;exports.relativePathPrefix=Lw;exports.removeAttributeChangeCallback=Fw;exports.removeComponent=Wf;exports.removeCustomImportExtensionType=BA;exports.removePatch=Wk;exports.resolveGaussianSplatQuality=Ff;exports.resolveUrl=cs;exports.sUknx=kh;exports.sanitizeString=Iw;exports.saveImage=K1;exports.screenshot=Z2;exports.screenshot2=Fb;exports.sendDestroyed=$y;exports.serializable=p;exports.serializeObject=Ax;exports.serializeable=Qe;exports.setActive=Pr;exports.setAllowBalloonMessages=zw;exports.setAllowOverlayMessages=FP;exports.setAutoFitEnabled=zu;exports.setCameraController=fg;exports.setDestroyed=FS;exports.setDevEnvironment=HP;exports.setDisposable=OS;exports.setDontDestroy=Ea;exports.setOrAddParamsToUrl=cg;exports.setParam=mP;exports.setParamWithoutReload=Yc;exports.setPeerOptions=HM;exports.setPhysicsEngineFactory=SS;exports.setResourceTrackingEnabled=_E;exports.setState=Sy;exports.setVisibleInCustomShadowRendering=Ay;exports.setWorldEuler=Ty;exports.setWorldPosition=Oi;exports.setWorldPositionXYZ=Ar;exports.setWorldQuaternion=vn;exports.setWorldQuaternionXYZW=Ey;exports.setWorldRotation=Qw;exports.setWorldRotationXYZ=Ph;exports.setWorldScale=rl;exports.showBalloonError=wl;exports.showBalloonMessage=Re;exports.showBalloonWarning=de;exports.showDebugConsole=Iy;exports.slerp=Gw;exports.syncDestroy=Mh;exports.syncField=b_;exports.syncInstantiate=Vy;exports.textureToCanvas=dk;exports.toSourceId=Bw;exports.tryCastBinary=Vx;exports.tryDetermineMimetypeFromBinary=PC;exports.tryDetermineMimetypeFromURL=CC;exports.tryFindObject=Kc;exports.tryGetExtensionFromUrl=SC;exports.tryGetGuid=Wx;exports.unregisterHotReloadType=ZS;exports.unregisterPrefabProvider=_M;exports.unwatchWrite=Cy;exports.useForAutoFit=Ww;exports.validate=je;exports.watchWrite=Mf;