@needle-tools/engine 6.0.0-alpha.4 → 6.0.0-alpha.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +8 -0
- package/README.md +11 -1
- package/dist/{gltf-progressive-CcSfG2Ja.js → gltf-progressive-B7lOWdLe.js} +117 -115
- package/dist/gltf-progressive-BpT9M5Mt.umd.cjs +10 -0
- package/dist/gltf-progressive-D0rzvhNG.min.js +10 -0
- package/dist/{materialx-B3qY8vPU.js → materialx-Bd9BE6LR.js} +1 -1
- package/dist/{materialx-BwYvA-4x.umd.cjs → materialx-CzRx9AGf.umd.cjs} +2 -2
- package/dist/{materialx-CTPhpPxI.min.js → materialx-x1m4IJd1.min.js} +1 -1
- package/dist/{needle-engine.bundle-Bmcb5t3w.min.js → needle-engine.bundle-D6mZl1dR.min.js} +29 -29
- package/dist/{needle-engine.bundle-BuUj9B4K.umd.cjs → needle-engine.bundle-DOHf03pR.umd.cjs} +14 -14
- package/dist/{needle-engine.bundle-0tD9EcNs.js → needle-engine.bundle-Hu7ZAxEI.js} +75 -69
- package/dist/needle-engine.d.ts +5 -5
- package/dist/needle-engine.js +192 -192
- package/dist/needle-engine.min.js +1 -1
- package/dist/needle-engine.umd.cjs +1 -1
- package/dist/{vendor-BQUQwut5.js → vendor-BatPc34p.js} +50 -41
- package/dist/{vendor-BJviq-Oq.umd.cjs → vendor-CDN1hirK.umd.cjs} +1 -1
- package/dist/{vendor-CdNldo8c.min.js → vendor-T07c_9f_.min.js} +1 -1
- package/lib/engine/api.d.ts +1 -1
- package/lib/engine/api.js +1 -1
- package/lib/engine/api.js.map +1 -1
- package/lib/engine/engine_init.js +2 -2
- package/lib/engine/engine_init.js.map +1 -1
- package/lib/engine/engine_license.d.ts +7 -7
- package/lib/engine/engine_license.js +98 -78
- package/lib/engine/engine_license.js.map +1 -1
- package/lib/engine/engine_networking_blob.js +3 -3
- package/lib/engine/engine_networking_blob.js.map +1 -1
- package/lib/engine/engine_utils_qrcode.js +2 -2
- package/lib/engine/engine_utils_qrcode.js.map +1 -1
- package/lib/engine/webcomponents/needle menu/needle-menu-spatial.js +2 -2
- package/lib/engine/webcomponents/needle menu/needle-menu-spatial.js.map +1 -1
- package/lib/engine/webcomponents/needle menu/needle-menu.js +5 -5
- package/lib/engine/webcomponents/needle menu/needle-menu.js.map +1 -1
- package/lib/engine/webcomponents/needle-engine.js +2 -2
- package/lib/engine/webcomponents/needle-engine.js.map +1 -1
- package/lib/engine/webcomponents/needle-engine.loading.js +2 -2
- package/lib/engine/webcomponents/needle-engine.loading.js.map +1 -1
- package/lib/engine/xr/TempXRContext.js +2 -2
- package/lib/engine/xr/TempXRContext.js.map +1 -1
- package/lib/engine-components/Renderer.d.ts +1 -1
- package/lib/engine-components/Renderer.js +2 -11
- package/lib/engine-components/Renderer.js.map +1 -1
- package/lib/engine-components/export/usdz/USDZExporter.js +4 -4
- package/lib/engine-components/export/usdz/USDZExporter.js.map +1 -1
- package/package.json +6 -3
- package/plugins/common/license.js +4 -4
- package/plugins/license/README.md +38 -0
- package/plugins/license/cli.js +46 -0
- package/plugins/license/index.js +24 -0
- package/plugins/vite/license.js +4 -4
- package/src/engine/api.ts +1 -1
- package/src/engine/engine_init.ts +2 -2
- package/src/engine/engine_license.ts +93 -76
- package/src/engine/engine_networking_blob.ts +3 -3
- package/src/engine/engine_utils_qrcode.ts +2 -2
- package/src/engine/webcomponents/needle menu/needle-menu-spatial.ts +2 -2
- package/src/engine/webcomponents/needle menu/needle-menu.ts +5 -5
- package/src/engine/webcomponents/needle-engine.loading.ts +2 -2
- package/src/engine/webcomponents/needle-engine.ts +2 -2
- package/src/engine/xr/TempXRContext.ts +2 -2
- package/src/engine-components/Renderer.ts +4 -13
- package/src/engine-components/export/usdz/USDZExporter.ts +4 -4
- package/dist/gltf-progressive-BYG9UH7O.min.js +0 -10
- package/dist/gltf-progressive-sK--FWg7.umd.cjs +0 -10
package/dist/{needle-engine.bundle-BuUj9B4K.umd.cjs → needle-engine.bundle-DOHf03pR.umd.cjs}
RENAMED
|
@@ -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-
|
|
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-CDN1hirK.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.6";');Bo('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";');Bo('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Tue Oct 06 2026 10:27:28 GMT+0000 (Coordinated Universal Time)";');Bo('globalThis["__NEEDLE_PUBLIC_KEY__"] = "'+NEEDLE_PUBLIC_KEY+'";');const Zt="6.0.0-alpha.6",al="undefined",Zc="Tue Oct 06 2026 10:27:28 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
|
|
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)
|
|
@@ -271,7 +271,7 @@ TEX `+i.texture_lod;if(sm=="density"&&(v+=`
|
|
|
271
271
|
`+(g/n.lastScreenCoverage).toFixed(0)+` dens
|
|
272
272
|
`+(n.lastScreenCoverage*100).toFixed(1)+`% cov
|
|
273
273
|
`+(n.lastCentrality*100).toFixed(1)+`% centr
|
|
274
|
-
`+(Sd.min.x.toFixed(2)+"-"+Sd.max.x.toFixed(2)+"x"+Sd.min.y.toFixed(2)+"-"+Sd.max.y.toFixed(2))+" scr"),n.lastScreenCoverage>.1){const _=e,y=_.worldForward,b=_.worldPosition,C=F(y).multiplyScalar(h*.7).add(l),k=C.distanceTo(b),O=d[Math.min(d.length-1,Math.max(0,o))]+"88",D=this.context.domHeight>0?screen.height/this.context.domHeight:1,I=e.isPerspectiveCamera?Math.tan(e.fov*Math.PI/180/2):1;B.DrawLabel(C,v,k*.012*D*I,void 0,16777215,O)}}}}}const qy={};function Xy(s,e){qy[s]=e}function Vx(s){const e=s.getBufferIdentifier(),t=qy[e];return t(s)}function Wx(s){return typeof s.guid=="function"?s.guid():null}class WM{_url;_ws;onOpen=null;onClose=null;onError=null;onMessage=null;get url(){return this._ws?.url??this._url}constructor(e){this._url=e}async start(){const e=await Promise.resolve().then(()=>require("./vendor-BJviq-Oq.umd.cjs")).then(o=>o.index),t=e.default?.WebsocketBuilder??e.WebsocketBuilder,i=e.default?.ExponentialBackoff??e.ExponentialBackoff,n=new t(this._url).withMaxRetries(10).withBackoff(new i(2e3,4)).onOpen(()=>{this._ws=n,this.onOpen?.()}).onClose(()=>{this.onClose?.()}).onError(()=>{this.onError?.(new Error("Websocket connection failed"))}).onRetry(()=>{console.log("Retry connecting to networking websocket")}).build();n.addEventListener(e.WebsocketEvent.message,(o,r)=>{this.onMessage?.(r.data)})}send(e){this._ws?.send(e)}close(){this._ws?.close(),this._ws=void 0}}function sc(s){const e=[],t={MODULE:void 0,MAYBEMODULE:null,ready(){return t.MODULE?Promise.resolve(t.MODULE):new Promise(i=>{e.push(i)})},async load(){if(t.MODULE)return t.MODULE;const i=await s();t.MODULE=i,t.MAYBEMODULE=i;for(const n of e)n(i);return e.length=0,i}};return t}const A={MaterialX:sc(()=>Promise.resolve().then(()=>require("./materialx-BwYvA-4x.umd.cjs"))),RAPIER_PHYSICS:sc(()=>Promise.resolve().then(()=>require("./rapier-DQltNJbN.umd.cjs"))),POSTPROCESSING:sc(()=>Promise.resolve().then(()=>require("./postprocessing-DwcCsALK.umd.cjs")).then(s=>s.index)),POSTPROCESSING_AO:sc(()=>Promise.resolve().then(()=>require("./postprocessing-DwcCsALK.umd.cjs")).then(s=>s.N8AO)),PEERJS:sc(()=>Promise.resolve().then(()=>require("./vendor-BJviq-Oq.umd.cjs")).then(s=>s.bundler))};let Qy;const yo=x("debugpeer")!==void 0;function GM(){return Qy}function HM(s){Qy=s}async function Gx(s,e){const i=(await A.PEERJS.load()).default;return e||(e={}),e={...Qy,...e},s?new i(s,e):new i(e)}async function Cv(){const s=await A.PEERJS.load();return s.default===void 0?s:s.default}class Hx{get isHost(){return this._host!==void 0}_host;_client;_clientData;constructor(){this.onEnable()}onEnable(){this.trySetupHost("HOST-5980e65c-8438-453e-8b35-f13c736dcd81")}async trySetupHost(e){const t=await Cv(),i=new t(e);i.on("error",n=>{yo&&console.error(n),this._host=void 0,this.trySetupClient(e)}),i.on("open",n=>{this._host=new XM(i)})}async trySetupClient(e){const t=await Cv();this._client=new t,this._client.on("error",i=>{yo&&console.error("Client error",i)}),this._client.on("open",i=>{yo&&console.debug("client connected",i),this._clientData=this._client.connect(e,{metadata:{id:i}}),this._clientData.on("open",()=>{yo&&console.debug("Connected to host")}),this._clientData.on("data",n=>{yo&&console.debug("<<",n)})})}}class qM{_peer;constructor(e){this._peer=e}}class XM extends qM{get isHost(){return!0}_connections=[];constructor(e){super(e),this._peer?.on("connection",this.onConnection.bind(this)),this._peer.on("close",()=>{this.broadcast("bye")})}onConnection(e){yo&&console.debug("host connection",e),e.on("open",()=>{this._connections.push(e),this.broadcastConnection(e)})}broadcastConnection(e){const t=this._connections.map(i=>i.metadata?.id).filter(i=>i!==void 0);this.broadcast({type:"connection-list",connections:t})}broadcast(e){if(e!=null){yo&&console.debug(">>",e);for(const t in this._peer.connections){const i=this._peer.connections[t];if(i)if(Array.isArray(i))for(const n of i)n&&n.send(e);else yo&&console.warn(i)}}}}const Pv="https://urls.needle.tools/default-networking-backend/index";let ys="wss://networking-2.needle.tools/socket";const Pd=Symbol("originalCallback"),oi=!!x("debugnet"),Oa=!!(oi||x("debugowner")),kd=x("debugnetbin");var qx=(s=>(s.ConnectionInfo="connection-start-info",s))(qx||{}),te=(s=>(s.Join="join-room",s.Leave="leave-room",s.JoinedRoom="joined-room",s.LeftRoom="left-room",s.UserJoinedRoom="user-joined-room",s.UserLeftRoom="user-left-room",s.RoomStateSent="room-state-sent",s))(te||{});class QM{room;viewId;allowEditing;inRoom}class YM{room}class KM{userId}var Xx=(s=>(s.RequestHasOwner="request-has-owner",s.ResponseHasOwner="response-has-owner",s.RequestIsOwner="request-is-owner",s.ResponseIsOwner="response-is-owner",s.RequestOwnership="request-ownership",s.GainedOwnership="gained-ownership",s.RemoveOwnership="remove-ownership",s.LostOwnership="lost-ownership",s.GainedOwnershipBroadcast="gained-ownership-broadcast",s.LostOwnershipBroadcast="lost-ownership-broadcast",s))(Xx||{});class Qx{guid;connection;get hasOwnership(){return this._hasOwnership}get isOwned(){return this._isOwned}get isConnected(){return this.connection.isConnected}_hasOwnership=!1;_isOwned=void 0;_gainSubscription;_lostSubscription;_hasOwnerResponse;_pendingOwnershipResolve=null;constructor(e,t){this.connection=e,this.guid=t,this._gainSubscription=this.onGainedOwnership.bind(this),this._lostSubscription=this.onLostOwnership.bind(this),e.beginListen("lost-ownership",this._lostSubscription),e.beginListen("gained-ownership-broadcast",this._gainSubscription),this._hasOwnerResponse=this.onHasOwnerResponse.bind(this),e.beginListen("response-has-owner",this._hasOwnerResponse)}_isWaitingForOwnershipResponseCallback=null;updateIsOwned(){this.connection.send("request-has-owner",{guid:this.guid})}onHasOwnerResponse(e){e.guid===this.guid&&(this._isOwned=e.value)}requestOwnershipIfNotOwned(){return this._isWaitingForOwnershipResponseCallback!==null?this:(this._isWaitingForOwnershipResponseCallback=this.waitForHasOwnershipRequestResponse.bind(this),this.connection.beginListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this.connection.send("request-has-owner",{guid:this.guid}),this)}waitForHasOwnershipRequestResponse(e){e.guid===this.guid&&(this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this._isOwned=e.value,e.value||(Oa&&console.log("request ownership",this.guid),this.connection.send("request-ownership",{guid:this.guid})))}requestOwnership(){return this._hasOwnership?Promise.resolve(!0):(this._pendingOwnershipResolve?.(!1),this._pendingOwnershipResolve=null,Oa&&console.log("Request ownership",this.guid),this.connection.send("request-ownership",{guid:this.guid}),new Promise(e=>{this._pendingOwnershipResolve=e,setTimeout(()=>{this._pendingOwnershipResolve===e&&(this._pendingOwnershipResolve=null,e(!1))},2e3)}))}async requestOwnershipAsync(){return Oa&&console.log("Request ownership",this.guid),this.connection.send("request-ownership",{guid:this.guid}),this}freeOwnership(){return this._hasOwnership?(this._hasOwnership=!1,this.connection.send("remove-ownership",{guid:this.guid}),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this):this}destroy(){this.connection.stopListen("gained-ownership",this._gainSubscription),this.connection.stopListen("lost-ownership",this._lostSubscription),this.connection.stopListen("response-has-owner",this._hasOwnerResponse),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this._pendingOwnershipResolve?.(!1),this._pendingOwnershipResolve=null}onGainedOwnership(e){e.guid===this.guid&&(this._isOwned=!0,this.connection.connectionId===e.owner?(Oa&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0,this._pendingOwnershipResolve&&(this._pendingOwnershipResolve(!0),this._pendingOwnershipResolve=null)):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(Oa&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1,this._pendingOwnershipResolve&&(this._pendingOwnershipResolve(!1),this._pendingOwnershipResolve=null))}}class th{context;_peer=null;constructor(e){this.context=e}get peer(){return this._peer||(this._peer=new Hx),this._peer}tryGetState(e){return e==="invalid"?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return oi}get isConnected(){return this.connected}get currentRoomName(){return this._currentRoomName}get allowEditing(){return this._currentRoomAllowEditing}get currentRoomViewId(){return this._currentRoomViewId}getViewOnlyUrl(){if(this.currentRoomViewId===null)return null;const e=new URL(window.location.href);return e.searchParams.set("view",this.currentRoomViewId),e.href}get isInRoom(){return this._isInRoom}get currentLatency(){return this._currentDelay}get currentServerUrl(){return this._transport?.url??null}sendPing(){this.send("ping",{time:this.context.time.time})}userIsInRoom(e){return this._currentInRoom.indexOf(e)!==-1}_usersInRoomCopy=[];usersInRoom(e=null){e||(e=this._usersInRoomCopy),e.length=0;for(const t of this._currentInRoom)e.push(t);return e}joinRoom(e,t=!1){return e?e.length>1024?(console.error('Room name too long, can not join: "'+e+'". Max length is 1024 characters.'),!1):(this.isInRoom&&this.currentRoomName!==e&&console.warn("Needle Engine is already connected to a networking room. Connecting to multiple rooms is not supported"),this.connect(),oi&&console.log("join: "+e),this.send("join-room",{room:e,viewOnly:t},yn.OnConnection),!0):(console.error('Missing room name, can not join: "'+e+'"'),!1)}leaveRoom(e=null){return e||(e=this.currentRoomName),e?(this.send("leave-room",{room:e}),!0):(console.error('Missing room name, can not join: "'+e+'"'),!1)}send(e,t,i=yn.Queued){if(i===yn.Queued){this._defaultMessagesBuffer.push({key:e,value:t});return}return this.sendWithWebsocket(e,t,i)}sendDeleteRemoteState(e){this.send("delete-state",{guid:e,dontSave:!0}),delete this._state[e]}sendDeleteRemoteStateAll(){this.send("delete-all-state"),this._state={}}sendBinary(e){kd&&console.log("<< send binary",this.context.time.frame,e.length/1024+" KB"),this._transport?.send(e)}_defaultMessagesBuffer=[];_defaultMessagesBufferArray=[];sendBufferedMessagesNow(){if(!this._transport)return;this._defaultMessagesBufferArray.length=0;const e=Object.keys(this._defaultMessagesBuffer).length;for(const i in this._defaultMessagesBuffer){const n=this._defaultMessagesBuffer[i];if(e<=1){this.sendWithWebsocket(n.key,n.value,yn.Immediate);break}const o=this.toMessage(n.key,n.value);this._defaultMessagesBufferArray.push(o)}if(this._defaultMessagesBuffer.length=0,this._defaultMessagesBufferArray.length>0&&oi&&console.log("SEND BUFFERED",this._defaultMessagesBufferArray.length),this._defaultMessagesBufferArray.length<=0)return;const t=JSON.stringify(this._defaultMessagesBufferArray);this._transport?.send(t)}beginListen(e,t){this._listeners[e]||(this._listeners[e]=[]),this._listeners[e].push(t);const i=()=>this.stopListen(e,t);return i[Pd]=t,i}stopListening(e,t){return this.stopListen(e,t)}static _didLogStopListenHint=!1;stopListen(e,t){if(!t||!this._listeners[e])return;const i=t[Pd]??t;i!==t&&E()&&!th._didLogStopListenHint&&(th._didLogStopListenHint=!0,console.warn("[Needle Engine] Tip: beginListen() returns an unsubscribe function — you can call it directly instead of using stopListen()."));const n=this._listeners[e].indexOf(i);n>=0&&this._listeners[e].splice(n,1)}beginListenBinary(e,t){this._listenersBinary[e]||(this._listenersBinary[e]=[]),this._listenersBinary[e].push(t);const i=()=>this.stopListenBinary(e,t);return i[Pd]=t,i}stopListenBinary(e,t){if(!this._listenersBinary[e])return;const i=t?.[Pd]??t,n=this._listenersBinary[e].indexOf(i);n>=0&&this._listenersBinary[e].splice(n,1)}netWebSocketUrlProvider;registerProvider(e){this.netWebSocketUrlProvider=e}async connect(e,t){if(this.connected&&e&&e!==ys)return Promise.reject("Can not connect to different server url. Please disconnect first.");if(this.connected)return Promise.resolve(!0);if(t)return this.connectTransport(t);e&&console.debug("Connecting to user provided url "+e);const i=e||this.netWebSocketUrlProvider?.getWebsocketUrl();return i?ys=i:Rw()&&(ys="wss://"+window.location.host+"/socket"),this.connectWebsocket()}disconnect(){this._transport&&(this._transport.onOpen=null,this._transport.onClose=null,this._transport.onError=null,this._transport.onMessage=null,this._transport.close(),this._transport=void 0),ys=void 0,this.connected=!1,this._connectionId=null,this._currentRoomAllowEditing=!0,this._currentRoomName=null,this._currentRoomViewId=null,this._isInRoom=!1,this._currentInRoom.length=0,this._state={},this._currentDelay=-1,this._connectingToWebsocketPromise=null}dispose(){this.disconnect(),this._listeners={},this._listenersBinary={},this._waitingForSocket={},this._peer=null}_listeners={};_listenersBinary={};connected=!1;_connectionId=null;_transport;_waitingForSocket={};_isInRoom=!1;_currentRoomName=null;_currentRoomViewId=null;_currentRoomAllowEditing=!0;_currentInRoom=[];_state={};_currentDelay=-1;_connectingToWebsocketPromise=null;connectTransport(e){return this._connectingToWebsocketPromise?this._connectingToWebsocketPromise:this._connectingToWebsocketPromise=new Promise(t=>{let i=!1;const n=o=>{i||(i=!0,t(o))};e.onOpen=()=>{this._connectingToWebsocketPromise=null,this._transport=e,this.connected=!0,E()||oi?console.log(`Connected to networking backend
|
|
274
|
+
`+(Sd.min.x.toFixed(2)+"-"+Sd.max.x.toFixed(2)+"x"+Sd.min.y.toFixed(2)+"-"+Sd.max.y.toFixed(2))+" scr"),n.lastScreenCoverage>.1){const _=e,y=_.worldForward,b=_.worldPosition,C=F(y).multiplyScalar(h*.7).add(l),k=C.distanceTo(b),O=d[Math.min(d.length-1,Math.max(0,o))]+"88",D=this.context.domHeight>0?screen.height/this.context.domHeight:1,I=e.isPerspectiveCamera?Math.tan(e.fov*Math.PI/180/2):1;B.DrawLabel(C,v,k*.012*D*I,void 0,16777215,O)}}}}}const qy={};function Xy(s,e){qy[s]=e}function Vx(s){const e=s.getBufferIdentifier(),t=qy[e];return t(s)}function Wx(s){return typeof s.guid=="function"?s.guid():null}class WM{_url;_ws;onOpen=null;onClose=null;onError=null;onMessage=null;get url(){return this._ws?.url??this._url}constructor(e){this._url=e}async start(){const e=await Promise.resolve().then(()=>require("./vendor-CDN1hirK.umd.cjs")).then(o=>o.index),t=e.default?.WebsocketBuilder??e.WebsocketBuilder,i=e.default?.ExponentialBackoff??e.ExponentialBackoff,n=new t(this._url).withMaxRetries(10).withBackoff(new i(2e3,4)).onOpen(()=>{this._ws=n,this.onOpen?.()}).onClose(()=>{this.onClose?.()}).onError(()=>{this.onError?.(new Error("Websocket connection failed"))}).onRetry(()=>{console.log("Retry connecting to networking websocket")}).build();n.addEventListener(e.WebsocketEvent.message,(o,r)=>{this.onMessage?.(r.data)})}send(e){this._ws?.send(e)}close(){this._ws?.close(),this._ws=void 0}}function sc(s){const e=[],t={MODULE:void 0,MAYBEMODULE:null,ready(){return t.MODULE?Promise.resolve(t.MODULE):new Promise(i=>{e.push(i)})},async load(){if(t.MODULE)return t.MODULE;const i=await s();t.MODULE=i,t.MAYBEMODULE=i;for(const n of e)n(i);return e.length=0,i}};return t}const A={MaterialX:sc(()=>Promise.resolve().then(()=>require("./materialx-CzRx9AGf.umd.cjs"))),RAPIER_PHYSICS:sc(()=>Promise.resolve().then(()=>require("./rapier-DQltNJbN.umd.cjs"))),POSTPROCESSING:sc(()=>Promise.resolve().then(()=>require("./postprocessing-DwcCsALK.umd.cjs")).then(s=>s.index)),POSTPROCESSING_AO:sc(()=>Promise.resolve().then(()=>require("./postprocessing-DwcCsALK.umd.cjs")).then(s=>s.N8AO)),PEERJS:sc(()=>Promise.resolve().then(()=>require("./vendor-CDN1hirK.umd.cjs")).then(s=>s.bundler))};let Qy;const yo=x("debugpeer")!==void 0;function GM(){return Qy}function HM(s){Qy=s}async function Gx(s,e){const i=(await A.PEERJS.load()).default;return e||(e={}),e={...Qy,...e},s?new i(s,e):new i(e)}async function Cv(){const s=await A.PEERJS.load();return s.default===void 0?s:s.default}class Hx{get isHost(){return this._host!==void 0}_host;_client;_clientData;constructor(){this.onEnable()}onEnable(){this.trySetupHost("HOST-5980e65c-8438-453e-8b35-f13c736dcd81")}async trySetupHost(e){const t=await Cv(),i=new t(e);i.on("error",n=>{yo&&console.error(n),this._host=void 0,this.trySetupClient(e)}),i.on("open",n=>{this._host=new XM(i)})}async trySetupClient(e){const t=await Cv();this._client=new t,this._client.on("error",i=>{yo&&console.error("Client error",i)}),this._client.on("open",i=>{yo&&console.debug("client connected",i),this._clientData=this._client.connect(e,{metadata:{id:i}}),this._clientData.on("open",()=>{yo&&console.debug("Connected to host")}),this._clientData.on("data",n=>{yo&&console.debug("<<",n)})})}}class qM{_peer;constructor(e){this._peer=e}}class XM extends qM{get isHost(){return!0}_connections=[];constructor(e){super(e),this._peer?.on("connection",this.onConnection.bind(this)),this._peer.on("close",()=>{this.broadcast("bye")})}onConnection(e){yo&&console.debug("host connection",e),e.on("open",()=>{this._connections.push(e),this.broadcastConnection(e)})}broadcastConnection(e){const t=this._connections.map(i=>i.metadata?.id).filter(i=>i!==void 0);this.broadcast({type:"connection-list",connections:t})}broadcast(e){if(e!=null){yo&&console.debug(">>",e);for(const t in this._peer.connections){const i=this._peer.connections[t];if(i)if(Array.isArray(i))for(const n of i)n&&n.send(e);else yo&&console.warn(i)}}}}const Pv="https://urls.needle.tools/default-networking-backend/index";let ys="wss://networking-2.needle.tools/socket";const Pd=Symbol("originalCallback"),oi=!!x("debugnet"),Oa=!!(oi||x("debugowner")),kd=x("debugnetbin");var qx=(s=>(s.ConnectionInfo="connection-start-info",s))(qx||{}),te=(s=>(s.Join="join-room",s.Leave="leave-room",s.JoinedRoom="joined-room",s.LeftRoom="left-room",s.UserJoinedRoom="user-joined-room",s.UserLeftRoom="user-left-room",s.RoomStateSent="room-state-sent",s))(te||{});class QM{room;viewId;allowEditing;inRoom}class YM{room}class KM{userId}var Xx=(s=>(s.RequestHasOwner="request-has-owner",s.ResponseHasOwner="response-has-owner",s.RequestIsOwner="request-is-owner",s.ResponseIsOwner="response-is-owner",s.RequestOwnership="request-ownership",s.GainedOwnership="gained-ownership",s.RemoveOwnership="remove-ownership",s.LostOwnership="lost-ownership",s.GainedOwnershipBroadcast="gained-ownership-broadcast",s.LostOwnershipBroadcast="lost-ownership-broadcast",s))(Xx||{});class Qx{guid;connection;get hasOwnership(){return this._hasOwnership}get isOwned(){return this._isOwned}get isConnected(){return this.connection.isConnected}_hasOwnership=!1;_isOwned=void 0;_gainSubscription;_lostSubscription;_hasOwnerResponse;_pendingOwnershipResolve=null;constructor(e,t){this.connection=e,this.guid=t,this._gainSubscription=this.onGainedOwnership.bind(this),this._lostSubscription=this.onLostOwnership.bind(this),e.beginListen("lost-ownership",this._lostSubscription),e.beginListen("gained-ownership-broadcast",this._gainSubscription),this._hasOwnerResponse=this.onHasOwnerResponse.bind(this),e.beginListen("response-has-owner",this._hasOwnerResponse)}_isWaitingForOwnershipResponseCallback=null;updateIsOwned(){this.connection.send("request-has-owner",{guid:this.guid})}onHasOwnerResponse(e){e.guid===this.guid&&(this._isOwned=e.value)}requestOwnershipIfNotOwned(){return this._isWaitingForOwnershipResponseCallback!==null?this:(this._isWaitingForOwnershipResponseCallback=this.waitForHasOwnershipRequestResponse.bind(this),this.connection.beginListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this.connection.send("request-has-owner",{guid:this.guid}),this)}waitForHasOwnershipRequestResponse(e){e.guid===this.guid&&(this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this._isOwned=e.value,e.value||(Oa&&console.log("request ownership",this.guid),this.connection.send("request-ownership",{guid:this.guid})))}requestOwnership(){return this._hasOwnership?Promise.resolve(!0):(this._pendingOwnershipResolve?.(!1),this._pendingOwnershipResolve=null,Oa&&console.log("Request ownership",this.guid),this.connection.send("request-ownership",{guid:this.guid}),new Promise(e=>{this._pendingOwnershipResolve=e,setTimeout(()=>{this._pendingOwnershipResolve===e&&(this._pendingOwnershipResolve=null,e(!1))},2e3)}))}async requestOwnershipAsync(){return Oa&&console.log("Request ownership",this.guid),this.connection.send("request-ownership",{guid:this.guid}),this}freeOwnership(){return this._hasOwnership?(this._hasOwnership=!1,this.connection.send("remove-ownership",{guid:this.guid}),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this):this}destroy(){this.connection.stopListen("gained-ownership",this._gainSubscription),this.connection.stopListen("lost-ownership",this._lostSubscription),this.connection.stopListen("response-has-owner",this._hasOwnerResponse),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this._pendingOwnershipResolve?.(!1),this._pendingOwnershipResolve=null}onGainedOwnership(e){e.guid===this.guid&&(this._isOwned=!0,this.connection.connectionId===e.owner?(Oa&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0,this._pendingOwnershipResolve&&(this._pendingOwnershipResolve(!0),this._pendingOwnershipResolve=null)):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(Oa&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1,this._pendingOwnershipResolve&&(this._pendingOwnershipResolve(!1),this._pendingOwnershipResolve=null))}}class th{context;_peer=null;constructor(e){this.context=e}get peer(){return this._peer||(this._peer=new Hx),this._peer}tryGetState(e){return e==="invalid"?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return oi}get isConnected(){return this.connected}get currentRoomName(){return this._currentRoomName}get allowEditing(){return this._currentRoomAllowEditing}get currentRoomViewId(){return this._currentRoomViewId}getViewOnlyUrl(){if(this.currentRoomViewId===null)return null;const e=new URL(window.location.href);return e.searchParams.set("view",this.currentRoomViewId),e.href}get isInRoom(){return this._isInRoom}get currentLatency(){return this._currentDelay}get currentServerUrl(){return this._transport?.url??null}sendPing(){this.send("ping",{time:this.context.time.time})}userIsInRoom(e){return this._currentInRoom.indexOf(e)!==-1}_usersInRoomCopy=[];usersInRoom(e=null){e||(e=this._usersInRoomCopy),e.length=0;for(const t of this._currentInRoom)e.push(t);return e}joinRoom(e,t=!1){return e?e.length>1024?(console.error('Room name too long, can not join: "'+e+'". Max length is 1024 characters.'),!1):(this.isInRoom&&this.currentRoomName!==e&&console.warn("Needle Engine is already connected to a networking room. Connecting to multiple rooms is not supported"),this.connect(),oi&&console.log("join: "+e),this.send("join-room",{room:e,viewOnly:t},yn.OnConnection),!0):(console.error('Missing room name, can not join: "'+e+'"'),!1)}leaveRoom(e=null){return e||(e=this.currentRoomName),e?(this.send("leave-room",{room:e}),!0):(console.error('Missing room name, can not join: "'+e+'"'),!1)}send(e,t,i=yn.Queued){if(i===yn.Queued){this._defaultMessagesBuffer.push({key:e,value:t});return}return this.sendWithWebsocket(e,t,i)}sendDeleteRemoteState(e){this.send("delete-state",{guid:e,dontSave:!0}),delete this._state[e]}sendDeleteRemoteStateAll(){this.send("delete-all-state"),this._state={}}sendBinary(e){kd&&console.log("<< send binary",this.context.time.frame,e.length/1024+" KB"),this._transport?.send(e)}_defaultMessagesBuffer=[];_defaultMessagesBufferArray=[];sendBufferedMessagesNow(){if(!this._transport)return;this._defaultMessagesBufferArray.length=0;const e=Object.keys(this._defaultMessagesBuffer).length;for(const i in this._defaultMessagesBuffer){const n=this._defaultMessagesBuffer[i];if(e<=1){this.sendWithWebsocket(n.key,n.value,yn.Immediate);break}const o=this.toMessage(n.key,n.value);this._defaultMessagesBufferArray.push(o)}if(this._defaultMessagesBuffer.length=0,this._defaultMessagesBufferArray.length>0&&oi&&console.log("SEND BUFFERED",this._defaultMessagesBufferArray.length),this._defaultMessagesBufferArray.length<=0)return;const t=JSON.stringify(this._defaultMessagesBufferArray);this._transport?.send(t)}beginListen(e,t){this._listeners[e]||(this._listeners[e]=[]),this._listeners[e].push(t);const i=()=>this.stopListen(e,t);return i[Pd]=t,i}stopListening(e,t){return this.stopListen(e,t)}static _didLogStopListenHint=!1;stopListen(e,t){if(!t||!this._listeners[e])return;const i=t[Pd]??t;i!==t&&E()&&!th._didLogStopListenHint&&(th._didLogStopListenHint=!0,console.warn("[Needle Engine] Tip: beginListen() returns an unsubscribe function — you can call it directly instead of using stopListen()."));const n=this._listeners[e].indexOf(i);n>=0&&this._listeners[e].splice(n,1)}beginListenBinary(e,t){this._listenersBinary[e]||(this._listenersBinary[e]=[]),this._listenersBinary[e].push(t);const i=()=>this.stopListenBinary(e,t);return i[Pd]=t,i}stopListenBinary(e,t){if(!this._listenersBinary[e])return;const i=t?.[Pd]??t,n=this._listenersBinary[e].indexOf(i);n>=0&&this._listenersBinary[e].splice(n,1)}netWebSocketUrlProvider;registerProvider(e){this.netWebSocketUrlProvider=e}async connect(e,t){if(this.connected&&e&&e!==ys)return Promise.reject("Can not connect to different server url. Please disconnect first.");if(this.connected)return Promise.resolve(!0);if(t)return this.connectTransport(t);e&&console.debug("Connecting to user provided url "+e);const i=e||this.netWebSocketUrlProvider?.getWebsocketUrl();return i?ys=i:Rw()&&(ys="wss://"+window.location.host+"/socket"),this.connectWebsocket()}disconnect(){this._transport&&(this._transport.onOpen=null,this._transport.onClose=null,this._transport.onError=null,this._transport.onMessage=null,this._transport.close(),this._transport=void 0),ys=void 0,this.connected=!1,this._connectionId=null,this._currentRoomAllowEditing=!0,this._currentRoomName=null,this._currentRoomViewId=null,this._isInRoom=!1,this._currentInRoom.length=0,this._state={},this._currentDelay=-1,this._connectingToWebsocketPromise=null}dispose(){this.disconnect(),this._listeners={},this._listenersBinary={},this._waitingForSocket={},this._peer=null}_listeners={};_listenersBinary={};connected=!1;_connectionId=null;_transport;_waitingForSocket={};_isInRoom=!1;_currentRoomName=null;_currentRoomViewId=null;_currentRoomAllowEditing=!0;_currentInRoom=[];_state={};_currentDelay=-1;_connectingToWebsocketPromise=null;connectTransport(e){return this._connectingToWebsocketPromise?this._connectingToWebsocketPromise:this._connectingToWebsocketPromise=new Promise(t=>{let i=!1;const n=o=>{i||(i=!0,t(o))};e.onOpen=()=>{this._connectingToWebsocketPromise=null,this._transport=e,this.connected=!0,E()||oi?console.log(`Connected to networking backend
|
|
275
275
|
`+(e.url??"")):console.debug("Connected to networking backend",e.url??""),n(!0),this.onSendQueued(yn.OnConnection)},e.onClose=()=>{this._connectingToWebsocketPromise=null,this.connected=!1,this._isInRoom=!1,n(!1);let o="Websocket connection closed...";e.url?.includes("/socket")||(o+=' Do you perhaps mean to connect to "/socket"?'),console.error(o)},e.onError=()=>{console.error("Websocket connection failed..."),n(!1),st.sendEvent(this.context,"networking",{event:"connection_error"})},e.onMessage=o=>{this.onMessage(o)},e.start()})}async connectWebsocket(){if(this._connectingToWebsocketPromise)return this._connectingToWebsocketPromise;if(ys===void 0&&(console.log("Fetch default backend url: "+Pv),ys=await(await fetch(Pv)).text()),ys===void 0)return!1;console.debug(`Connecting to networking backend on
|
|
276
276
|
`+ys);const e=new WM(ys);return this.connectTransport(e)}onMessage(e){const t=e;try{if(typeof t!="string"){t.size&&this.handleIncomingBinaryMessage(t);return}const i=JSON.parse(t);if(Array.isArray(i))for(const n of i)this.handleIncomingStringMessage(n);else this.handleIncomingStringMessage(i);return}catch(i){oi&&t==="pong"?console.log("<<",t):E()&&console.error("Failed to parse message",i)}}async handleIncomingBinaryMessage(e){kd&&console.log("<< bin",this.context.time.frame);const t=await e.arrayBuffer();var i=new Uint8Array(t);const n=new ee.ByteBuffer(i),o=n.getBufferIdentifier(),r=this._listenersBinary[o],a=Vx(n),l=Wx(a);if(l&&typeof l=="string"&&(this._state[l]=a),!r)return;const h=a??n;for(const d of r)d(h)}handleIncomingStringMessage(e){if(oi&&console.log("<<",e.key??e),e.key)switch(e.key){case"connection-start-info":if(e.data){const r=e.data;r&&(console.assert(r.id!==void 0&&r.id!==null&&r.id.length>0,"server did not send connection id",r.id),console.debug("Your id is: "+r.id,this.context.alias??""),this._connectionId=r.id,st.sendEvent(this.context,"networking",{event:"connected"}))}else console.warn("Expected connection id in "+e.key);break;case"joined-room":if(oi&&console.log(e),e){this._isInRoom=!0;const r=e;this._currentRoomName=r.room,this._currentRoomViewId=r.viewId,this._currentRoomAllowEditing=r.allowEditing??!0,this._currentInRoom.length=0,this._currentInRoom.push(...r.inRoom),(kd||E())&&console.debug("Joined Needle Engine Room: "+r.room);const a=new URL(window.location.href);a.searchParams.has("room")&&a.searchParams.delete("room"),a.searchParams.set("view",this._currentRoomViewId),console.debug(`Room view id: ${this._currentRoomViewId}
|
|
277
277
|
${a.href}`)}this.onSendQueued(yn.OnRoomJoin),st.sendEvent(this.context,"networking",{event:"joined_room",room:this._currentRoomName});break;case"left-room":const n=e;n.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentRoomAllowEditing=!0,this._currentInRoom.length=0,(kd||E())&&console.debug("Left Needle Engine Room: "+n.room)),st.sendEvent(this.context,"networking",{event:"left_room",room:n.room});break;case"user-joined-room":if(e.data){const r=e.data;this._currentInRoom.push(r.userId),oi&&console.log(r.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(e.data){const r=e.data,a=this._currentInRoom.indexOf(r.userId);a>=0&&(oi&&console.log(r.userId+" left","now in room:",this._currentInRoom),this._currentInRoom.splice(a,1)),r.userId===this.connectionId&&console.log("you left the room")}break;case"all-room-state-deleted":oi&&console.log("RECEIVED all-room-state-deleted"),this._state={};break;case"ping":case"pong":const o=e.data?.time;o&&(this._currentDelay=this.context.time.time-o),oi&&console.log(`Current latency: ${(this._currentDelay*1e3).toFixed()} ms`,"Clients in room: "+this._currentInRoom?.length);break}const t=e.data;t&&(this._state[t.guid]=t);let i=this._listeners[e.key];if(i){i=[...i];for(const n of i)try{n(e.data)}catch(o){console.error('Error invoking callback for "'+e.key+'"',o)}}}toMessage(e,t){return{key:e,data:t}}sendWithWebsocket(e,t,i=yn.OnRoomJoin){if(!this._transport){const o=this._waitingForSocket[i]||[];o.push(()=>this.sendWithWebsocket(e,t,i)),this._waitingForSocket[i]=o;return}const n=JSON.stringify(this.toMessage(e,t));oi&&console.log(">>",e),this._transport.send(n)}onSendQueued(e){const t=this._waitingForSocket[e];if(t){for(const i of t)i();t.length=0}}}const ZM=x("debugplayerview");var Ts=(s=>(s.Browser="browser",s.Headset="headset",s.Handheld="handheld",s))(Ts||{});class Yx{userId;context;viewDevice="browser";get currentObject(){return this._object}set currentObject(e){this._object=e}get isConnected(){return this.context.connection.userIsInRoom(this.userId)}removed=!1;_object;constructor(e,t){this.userId=e,this.context=t}}class Kx{context;playerViews=new Map;constructor(e){this.context=e}setPlayerView(e,t,i){let n=this.playerViews.get(e);n||(n=new Yx(e,this.context),this.playerViews.set(e,n)),n.viewDevice=i,n.currentObject=t,n.removed=!1}getPlayerView(e){if(!e)return;if(!this.context.connection.userIsInRoom(e)){this.playerViews.delete(e);return}return this.playerViews.get(e)}removePlayerView(e,t){const i=this.playerViews.get(e);i?.viewDevice===t&&(ZM&&console.log("REMOVE",e),i.removed=!0,this.playerViews.delete(e))}}const JM=new Proxy({},{get(s,e){if(e==="then")return;const t=se.Current;if(!t)return(E()?console.error:console.warn)(`[needle] needle.${e} was accessed before the scene started. Use "needle" inside event handlers or callbacks, not at module top-level. For setup code use: onStart(ctx => { ... })`),Qa("needle not ready — scene hasn't started yet");const i=t[e];return typeof i=="function"?i.bind(t):i},set(s,e,t){const i=se.Current;return i?(i[e]=t,!0):((E()?console.error:console.warn)(`[needle] needle.${e} was set before the scene started. Use "needle" inside event handlers or callbacks, not at module top-level. For setup code use: onStart(ctx => { ... })`),!0)}}),kv=new WeakMap;function Qa(s){const e={get(t,i){return i==="then"||typeof i=="symbol"?void 0:((E()?console.error:console.warn)(`[SceneData] ${s}`),Qa(s))},set(t,i){return typeof i=="symbol"||(E()?console.error:console.warn)(`[SceneData] ${s} (tried to set "${i}")`),!0}};return new Proxy({},e)}function Zx(s,e){return new Proxy({},{get(t,i){if(i==="$object")return e;if(i==="$components")return new Proxy({},{get(o,r){if(r==="then")return;const a=M.get(r);if(!a)return Qa(`Component type "${r}" not registered (node "${e.name}")`);const l=Bs(e,a);return l||Qa(`Component "${r}" not found on node "${e.name}"`)}});if(i==="then")return;const n=e.children.find(o=>o.name===i)??null;return n?Zx(s,n):((E()?console.error:console.warn)(`[SceneData] "${i}" is not a child of "${e.name}". Use .$object to get the Three.js object or .$components.Name to access a component.`),Qa(`"${i}" not found on node "${e.name}"`))}})}function Jx(s){let e=kv.get(s);return e||(e=new Proxy({},{get(t,i){return new Proxy({},{get(n,o){if(o==="then")return;const r=s.scene.getObjectByName(o)??null;return r?Zx(s,r):Qa(`Node "${o}" not found in scene`)}})}}),kv.set(s,e)),e}const Rh=new Uint8Array(4);Rh[0]=255;Rh[1]=255;Rh[2]=255;Rh[3]=255;const eO=new c.DataTexture(Rh,1,1,c.RGBAFormat);function Yy(s,e=1){const t="alpha"in s,i=e*e,n=new Uint8Array(4*i),o=Math.floor(s.r*255),r=Math.floor(s.g*255),a=Math.floor(s.b*255);for(let h=0;h<i;h++){const d=h*4;n[d+0]=o,n[d+1]=r,n[d+2]=a,t?n[d+3]=Math.floor(s.alpha*255):n[d+3]=255}const l=new c.DataTexture(n,e,e);return l.needsUpdate=!0,l}function tO(s,e,t,i=1,n=3){const r=i*n,a=[s,e,t],l=a.length,h=new Uint8Array(4*l*r),d=new c.Color;for(let f=0;f<n;f++){const m=Math.floor(f/n*l),g=L.clamp(m+1,0,l-1),v=a[m],_=a[g],y=f/n*l%1;d.lerpColors(v,_,y);const b=Math.floor(d.r*255),w=Math.floor(d.g*255),C=Math.floor(d.b*255);for(let k=0;k<i;k++){const O=(f*i+k)*4;h[O+0]=b,h[O+1]=w,h[O+2]=C,h[O+3]=255}}const u=new c.DataTexture(h,i,n);return u.needsUpdate=!0,u}function Zu(s,e){const t=s.elements;e||(e=[]),e.length=0;for(let i=0;i<16;i+=4){const n=t[i],o=t[i+1],r=t[i+2],a=t[i+3],l=new c.Vector4(n,o,r,a);e.push(l)}return e}const om=[],Mv=[];function iO(s,e){if(om.length===0)for(let t=0;t<27;t++)om.push(0);e||(e=om);for(let t=0;t<27;t++)Mv[t]=e[t];e=Mv,s.unity_SHAr={value:new c.Vector4(e[9],e[3],e[6],e[0])},s.unity_SHBr={value:new c.Vector4(e[12],e[15],e[18],e[21])},s.unity_SHAg={value:new c.Vector4(e[10],e[4],e[7],e[1])},s.unity_SHBg={value:new c.Vector4(e[13],e[16],e[19],e[22])},s.unity_SHAb={value:new c.Vector4(e[11],e[5],e[8],e[2])},s.unity_SHBb={value:new c.Vector4(e[14],e[17],e[20],e[23])},s.unity_SHC={value:new c.Vector4(e[24],e[25],e[26],1)}}class nO{vertexShader;fragmentShader;technique;constructor(e,t,i){this.vertexShader=e,this.fragmentShader=t,this.technique=i}}async function sO(s,e){if(!s)return console.error("Can not find technique: no shader data"),null;const t=s.programs[e],i=t.vertexShader,n=t.fragmentShader;if(i!==void 0&&n!==void 0){const o=s.shaders[i],r=s.shaders[n];if(o.uri&&r.uri||o.code&&r.code){if(!o.code&&o.uri&&await Ov(o),!r.code&&r.uri&&await Ov(r),!o.code||!r.code)return null;const a=s.techniques[e];return new nO(o.code,r.code,a)}}return console.error("Shader technique not found",e),null}async function Ov(s){const e=s.uri;if(e)if(e.endsWith(".glsl")){const i=await new c.FileLoader().loadAsync(e);s.code=i.toString()}else s.code=oO(s.uri)}function oO(s){return decodeURIComponent(Array.prototype.map.call(atob(s),function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)}).join(""))}const dn=x("debugenvlight");var Ya=(s=>(s[s.Skybox=0]="Skybox",s[s.Trilight=1]="Trilight",s[s.Flat=3]="Flat",s[s.Custom=4]="Custom",s))(Ya||{}),Ju=(s=>(s[s.Skybox=0]="Skybox",s[s.Custom=1]="Custom",s))(Ju||{});class eS{context;constructor(e){this.context=e,this.context.pre_update_callbacks.push(this.preUpdate.bind(this))}_currentLightSettingsId;_sceneLightSettings;get currentLightSettingsId(){return this._currentLightSettingsId}preUpdate(){const e=this.context.time;this._timevec4.x=e.time,this._timevec4.y=Math.sin(e.time),this._timevec4.z=Math.cos(e.time),this._timevec4.w=e.deltaTime}_timevec4=new c.Vector4;get timeVec4(){return this._timevec4}get environmentIntensity(){if(!this._sceneLightSettings||!this._currentLightSettingsId)return 1;const e=this._sceneLightSettings.get(this._currentLightSettingsId);return e?e.ambientIntensity:1}get sceneLightSettings(){return this._sceneLightSettings?.values()}enable(e){e instanceof J&&(e=e.url);const t=this._sceneLightSettings?.get(e);return t?(dn&&console.log("Enable scene light settings",e,t),e!==this._currentLightSettingsId&&this._currentLightSettingsId&&this.disable(this._currentLightSettingsId),this._currentLightSettingsId=e,t.enabled=!0,!0):(dn&&console.warn("No light settings found for",e),!1)}disable(e){if(e instanceof J&&(e=e.url),e==null)return!1;const t=this._sceneLightSettings?.get(e);return t?(dn&&console.log("Disable scene light settings",e,t),t.enabled=!1,!0):!1}enableCurrent(){return this._currentLightSettingsId?(this.enable(this._currentLightSettingsId),this._currentLightSettingsId??null):null}disableCurrent(){if(this._currentLightSettingsId){const e=this._currentLightSettingsId;return this.disable(this._currentLightSettingsId),e}return null}internalRegisterSceneLightSettings(e){const t=e.sourceId;if(!t){console.error("Missing source id for scene light settings, can not register:",e);return}dn&&console.log("Register "+e?.sourceId+" lighting",e),this._sceneLightSettings||(this._sceneLightSettings=new Map),this._sceneLightSettings.set(t,e)}internalUnregisterSceneLightSettings(e){const t=e.sourceId;if(!t){console.error("Missing source id for scene light settings, can not unregister:",e);return}dn&&console.log("Unregister "+e?.sourceId+" lighting",e),this._sceneLightSettings&&this._sceneLightSettings.delete(t)}internalRegisterReflection(e,t){dn&&console.log("Register reflection",e,t);const i=new tS(this.context,t,1);this._lighting[e]=i}internalGetReflection(e){return this._lighting[e]}__currentReflectionId=null;internalEnableReflection(e){this.__currentReflectionId=e;const t=this._sceneLightSettings?.get(e);switch(dn&&console.log("Enable reflection",e,t?Ya[t.ambientMode]:"Unknown ambient mode",t),t?.ambientMode){case 0:case 4:const i=this.internalGetReflection(e);if(i&&i.Source){dn&&console.log("Setting environment reflection",i);const n=this.context.scene,o=i.Source;return o.mapping!==c.CubeUVReflectionMapping&&(o.mapping=c.EquirectangularReflectionMapping),n.environment=o,n.environmentIntensity=this.environmentIntensity||1,o}else dn&&console.warn("Could not find reflection for source",e);break}if(t?.environmentReflectionSource===1)switch(t?.ambientMode){case 1:if(t.ambientTrilight){const i=t.ambientTrilight,n=tO(i[0],i[1],i[2],64,64);return n.colorSpace=c.SRGBColorSpace,n.mapping=c.EquirectangularReflectionMapping,this.context.scene.environment=n,n}else console.error("Missing ambient trilight",t.sourceId);case 3:if(t.ambientLight){const i=Yy(t.ambientLight,64);return i.colorSpace=c.SRGBColorSpace,i.mapping=c.EquirectangularReflectionMapping,this.context.scene.environment=i,i}else console.error("Missing ambientlight",t.sourceId)}return null}internalDisableReflection(e){if(e&&e!==this.__currentReflectionId){dn&&console.log("Not disabling reflection for",e,"because it is not the current light settings id",this.__currentReflectionId);return}dn&&console.log("Disable reflection",e);const t=this.context.scene;t.environment=null}_lighting={}}class tS{get Source(){return this._source}_source;constructor(e,t,i=1){this._source=t,t.mapping!==c.CubeUVReflectionMapping&&(t.mapping=c.EquirectangularReflectionMapping)}}let Eg;function rO(s){Eg=s}function aO(s){return s.isWebGPURenderer===!0&&Eg?new Eg(s):new c.PMREMGenerator(s)}const Ev=x("timescale");let Rg=1;typeof Ev=="number"&&(Rg=Ev);class iS{get time(){return this._time}set time(e){this._time=e}_time=0;get deltaTime(){return this._deltaTime}set deltaTime(e){this._deltaTime=e}_deltaTime=0;get deltaTimeUnscaled(){return this._deltaTimeUnscaled}_deltaTimeUnscaled=0;timeScale=1;get frame(){return this._frame}set frame(e){this._frame=e}_frame=0;get frameCount(){return this.frame}get realtimeSinceStartup(){return this._elapsedUnscaled}get fps(){return 1/this.deltaTime}get smoothedFps(){return this._smoothedFps}get smoothedDeltaTime(){return 1/this._smoothedFps}_clockStartTime=performance.now();_lastUpdateTime=this._clockStartTime;_elapsedUnscaled=0;_smoothedFps=0;_smoothedDeltaTime=0;_fpsSamples=[];_fpsSampleIndex=0;constructor(){typeof Rg=="number"&&(this.timeScale=Rg)}update(){const e=performance.now();this.deltaTime=(e-this._lastUpdateTime)/1e3,this._lastUpdateTime=e,this._elapsedUnscaled+=this.deltaTime,this.deltaTime=Math.min(.1,this.deltaTime),this._deltaTimeUnscaled=this.deltaTime,this.deltaTime<=0&&(this.deltaTime=1e-12),this.deltaTime*=this.timeScale,this.frame+=1,this.time+=this.deltaTime,this._fpsSamples.length<60?this._fpsSamples.push(this.deltaTime):this._fpsSamples[this._fpsSampleIndex++%60]=this.deltaTime;let t=0;for(let i=0;i<this._fpsSamples.length;i++)t+=this._fpsSamples[i];this._smoothedDeltaTime=t/this._fpsSamples.length,this._smoothedFps=1/this._smoothedDeltaTime}}let Rv=!1;function nS(s){Rv||(Rv=!0,lO(),cO())}function lO(){const s=`
|
|
@@ -408,7 +408,7 @@ vec3 AgXToneMapping( vec3 color ) {
|
|
|
408
408
|
return color;
|
|
409
409
|
`,e="vec3 AgXToneMapping( vec3 color ) {",t="return color;",i=c.ShaderChunk.tonemapping_pars_fragment.indexOf(e),n=c.ShaderChunk.tonemapping_pars_fragment.indexOf(t,i);if(i>=0&&n>=0){const o=c.ShaderChunk.tonemapping_pars_fragment.substring(i,n+t.length);c.ShaderChunk.tonemapping_pars_fragment=c.ShaderChunk.tonemapping_pars_fragment.replace(o,s)}else E()&&console.error("Couldn't find AgXToneMapping in ShaderChunk.tonemapping_pars_fragment")}function sS(s){if(typeof s=="string")switch(s=s.toLowerCase(),s){case"none":return c.NoToneMapping;case"neutral":return c.NeutralToneMapping;case"aces":return c.ACESFilmicToneMapping;case"agx":return c.AgXToneMapping;case"khronos_neutral":return c.NeutralToneMapping;default:console.warn("[PostProcessing] Unknown tone mapping mode",s);return}}const Zo=x("debugpost");class oS{_context;_handler=null;_effects=[];_isDirty=!1;get effects(){return this._effects}get dirty(){return this._isDirty}set dirty(e){this._isDirty=e}_enabled=!0;get enabled(){return this._enabled}set enabled(e){e!==this._enabled&&(this._enabled=e,this.markDirty())}get handler(){return this._handler}get composer(){return this._composer}set composer(e){this._composer=e}_composer=null;multisampling="auto";adaptiveResolution=!1;constructor(e){this._context=e}addEffect(e){this._effects.includes(e)||(this._effects.push(e),this._isDirty=!0)}removeEffect(e){const t=this._effects.indexOf(e);t!==-1&&(this._effects.splice(t,1),this._isDirty=!0)}markDirty(){this._isDirty=!0}_enabledTime=-1;_multisampleAutoChangeTime=0;_multisampleAutoDecreaseTime=0;update(){const e=this._context;if(e.isInXR)return;if(this._isDirty&&e.mainCamera&&this.apply(),this._tonemappingOnlyActive){const i=this._effects.filter(n=>n.active&&n.enabled&&n.isToneMapping===!0);if(i.length>0){const n=i[i.length-1];e.renderer.toneMapping=n.threeToneMapping,e.renderer.toneMappingExposure=n.toneMappingExposure}return}if(!this._handler||!this._composer||this._handler.composer!==this._composer)return;const t=this._composer;if(e.renderer.getContext().isContextLost()&&e.renderer.forceContextRestore(),t.getRenderer()!==e.renderer&&t.setRenderer(e.renderer),t.setMainScene(e.scene),this.multisampling==="auto")if(this._handler.hasSmaaEffect)this._handler.multisampling!==0&&(this._handler.multisampling=0,(Zo||E())&&console.log(`[PostProcessing] multisampling is disabled because it's set to 'auto' and there is an SMAA effect.
|
|
410
410
|
|
|
411
|
-
If you need multisampling consider changing 'auto' to a fixed value (e.g. 4).`));else{const i=e.time.realtimeSinceStartup-this._multisampleAutoChangeTime;if(e.time.realtimeSinceStartup-this._enabledTime>2&&i>.5){const n=this._handler.multisampling;if(this._handler.multisampling>0&&e.time.smoothedFps<=50){this._multisampleAutoChangeTime=e.time.realtimeSinceStartup,this._multisampleAutoDecreaseTime=e.time.realtimeSinceStartup;let o=this._handler.multisampling*.5;o=Math.floor(o),o!=this._handler.multisampling&&(this._handler.multisampling=o),Zo&&console.debug(`[PostProcessing] Reduced multisampling from ${n} to ${this._handler.multisampling}`)}else if(i>1&&e.time.smoothedFps>=59&&this._handler.multisampling<e.renderer.capabilities.maxSamples&&e.time.realtimeSinceStartup-this._multisampleAutoDecreaseTime>10){this._multisampleAutoChangeTime=e.time.realtimeSinceStartup;let o=this._handler.multisampling<=0?1:this._handler.multisampling*2;o=Math.floor(o),o!==this._handler.multisampling&&(this._handler.multisampling=o),Zo&&console.debug(`[PostProcessing] Increased multisampling from ${n} to ${this._handler.multisampling}`)}}}else{const i=Math.max(0,Math.min(this.multisampling,e.renderer.capabilities.maxSamples));i!==this._handler.multisampling&&(this._handler.multisampling=i)}if(this._handler.adaptivePixelRatio=this.adaptiveResolution,this._handler.updateAdaptivePixelRatio(),e.mainCamera){const i=t.passes;for(const n of i)if(n.mainCamera&&n.mainCamera!==e.mainCamera){t.setMainCamera(e.mainCamera);break}}}_lastApplyTime;_rapidApplyCount=0;_tonemappingOnlyActive=!1;_previousToneMapping;_previousToneMappingExposure;apply(){Zo&&console.log(`[PostProcessing] Apply stack (${this._effects.length} effects)`),E()&&(this._lastApplyTime!==void 0&&Date.now()-this._lastApplyTime<100&&(this._rapidApplyCount++,this._rapidApplyCount===5&&console.warn("[PostProcessing] Detected rapid post processing modifications - this might be a bug")),this._lastApplyTime=Date.now()),this._isDirty=!1;const e=this._enabled?this._effects.filter(i=>i.active&&i.enabled):[];if(e.length<=0){this.restoreTonemapping(),this._handler?.unapply(!1);return}if(e.every(i=>i.isToneMapping===!0)){const i=e[e.length-1];Zo&&console.log("[PostProcessing] Only tonemapping effects in stack — applying directly to renderer"),this._tonemappingOnlyActive||(this._previousToneMapping=this._context.renderer.toneMapping,this._previousToneMappingExposure=this._context.renderer.toneMappingExposure,this._tonemappingOnlyActive=!0),this._context.renderer.toneMapping=i.threeToneMapping,this._context.renderer.toneMappingExposure=i.toneMappingExposure,this._handler?.unapply(!1);return}this.restoreTonemapping(),this.ensureHandler().then(i=>{if(i)return i.apply(e)}).then(()=>{this._handler&&(this.multisampling==="auto"?this._handler.multisampling=exports.DeviceUtilities.isMobileDevice()?2:4:this._handler.multisampling=Math.max(0,Math.min(this.multisampling,this._context.renderer.capabilities.maxSamples)),Zo&&console.debug(`[PostProcessing] Set multisampling to ${this._handler.multisampling} (Is Mobile: ${exports.DeviceUtilities.isMobileDevice()})`))}).catch(i=>{console.error("[PostProcessing] Failed to build/apply the postprocessing pipeline",i)}),this._enabledTime=this._context.time.realtimeSinceStartup}restoreTonemapping(){this._tonemappingOnlyActive&&(this._previousToneMapping!==void 0&&(this._context.renderer.toneMapping=this._previousToneMapping),this._previousToneMappingExposure!==void 0&&(this._context.renderer.toneMappingExposure=this._previousToneMappingExposure),this._tonemappingOnlyActive=!1,this._previousToneMapping=void 0,this._previousToneMappingExposure=void 0,Zo&&console.log("[PostProcessing] Restored renderer tonemapping"))}async ensureHandler(){if(!this._handler){const{PostProcessingHandler:e}=await Promise.resolve().then(()=>F3);this._handler||(this._handler=new e(this._context))}return this._handler}dispose(){this.restoreTonemapping(),this._handler?.dispose(),this._handler=null,this._composer=null,this._effects.length=0}}const mr=[],Su=[];exports.NeedleEngineModelLoader=void 0;(s=>{function e(i,n){const o={name:n?.name,priority:n?.priority??0,callback:i};return mr.push(o),mr.sort((r,a)=>r.priority===a.priority?0:r.priority>a.priority?-1:1),()=>{const r=mr.indexOf(o);r>=0&&mr.splice(r,1)}}s.onCreateCustomModelLoader=e;function t(i){return Su.push(i),()=>{const n=Su.indexOf(i);n>=0&&Su.splice(n,1)}}s.onDetermineModelMimetype=t})(exports.NeedleEngineModelLoader||(exports.NeedleEngineModelLoader={}));const rm="Gaussian Splat Loader",hO=x("debugsplats")||x("debugsplatsort")||x("debugspatsort"),dO=(()=>{const s=x("splatcull"),e=typeof s=="number"?s:typeof s=="string"?parseFloat(s):NaN;return Number.isFinite(e)&&e>0?Math.min(Math.PI,e*(Math.PI/180)):void 0})(),uO={high:{maxSh:3,minSortIntervalMs:150,fetchers:3,lodRenderScale:1,lodSplatScale:1,maxStdDev:Math.sqrt(8),maxPixelRadius:512,coneFoveate:.4,behindFoveate:.2,xrFramebufferScale:1,maxPagedSplats:0,minAlpha:.5/255,resolutionScale:1,sortCullHalfAngle:Math.PI,xrMaxFps:0},medium:{maxSh:2,minSortIntervalMs:200,fetchers:2,lodRenderScale:1,lodSplatScale:1,maxStdDev:Math.sqrt(8),maxPixelRadius:384,coneFoveate:.3,behindFoveate:.15,xrFramebufferScale:.9,maxPagedSplats:0,minAlpha:.5/255,resolutionScale:1,sortCullHalfAngle:120/180*Math.PI,xrMaxFps:0},low:{maxSh:1,minSortIntervalMs:250,fetchers:1,lodRenderScale:1,lodSplatScale:1,maxStdDev:Math.sqrt(7),maxPixelRadius:320,coneFoveate:.25,behindFoveate:.1,xrFramebufferScale:.8,maxPagedSplats:48*65536,minAlpha:.5/255,resolutionScale:1,sortCullHalfAngle:110/180*Math.PI,xrMaxFps:30}};function Ff(s,e=exports.DeviceUtilities.isMobileDevice()){return{...uO[s==="auto"?e?"low":"high":s]}}function Tg(s,e,t){const i=Ff(t),n=gr.get(s);n&&(n.quality=t,t!=="auto"&&(n.level=0,n.fpsBeforeStep=null,n.downBackoffUntil=0,n.goodStreak=0,n.stepFromLevel=null,n.jumpBackoffUntil=0,n.fpsBeforeProbe=null,n.upBackoffUntil=0,n.stableStreak=0),Zy(n));const o=e;if(o){typeof o.maxSh=="number"&&(o.maxSh=i.maxSh);const r=o.paged;r&&(r.setMaxSh(i.maxSh),r.pager&&(r.pager.numFetchers=i.fetchers))}return i}const ef=[{lodRenderScale:1,lodSplatScale:1,maxPixelRadius:1,maxStdDevCap:Number.POSITIVE_INFINITY,foveate:1,minAlphaFloor:0,resolutionScale:1},{lodRenderScale:1.5,lodSplatScale:.75,maxPixelRadius:1,maxStdDevCap:Number.POSITIVE_INFINITY,foveate:.8,minAlphaFloor:0,resolutionScale:1},{lodRenderScale:2.25,lodSplatScale:.5,maxPixelRadius:.75,maxStdDevCap:Math.sqrt(7),foveate:.6,minAlphaFloor:0,resolutionScale:1},{lodRenderScale:3.5,lodSplatScale:.35,maxPixelRadius:.5,maxStdDevCap:Math.sqrt(6),foveate:.45,minAlphaFloor:0,resolutionScale:1},{lodRenderScale:3.5,lodSplatScale:.35,maxPixelRadius:.5,maxStdDevCap:Math.sqrt(6),foveate:.45,minAlphaFloor:4/255,resolutionScale:1},{lodRenderScale:3.5,lodSplatScale:.35,maxPixelRadius:.5,maxStdDevCap:Math.sqrt(6),foveate:.45,minAlphaFloor:10/255,resolutionScale:1},{lodRenderScale:3.5,lodSplatScale:.35,maxPixelRadius:.5,maxStdDevCap:Math.sqrt(6),foveate:.45,minAlphaFloor:10/255,resolutionScale:.75},{lodRenderScale:3.5,lodSplatScale:.35,maxPixelRadius:.5,maxStdDevCap:Math.sqrt(6),foveate:.45,minAlphaFloor:10/255,resolutionScale:.6}],hr=ef.length-1;function Ky(s,e){const t=Math.max(0,Math.min(hr,Math.round(e))),i=ef[t];return{...s,lodRenderScale:s.lodRenderScale*i.lodRenderScale,lodSplatScale:s.lodSplatScale*i.lodSplatScale,maxPixelRadius:Math.round(s.maxPixelRadius*i.maxPixelRadius),maxStdDev:Math.min(s.maxStdDev,i.maxStdDevCap),coneFoveate:Math.max(.05,s.coneFoveate*i.foveate),behindFoveate:Math.max(.05,s.behindFoveate*i.foveate),minAlpha:Math.max(s.minAlpha,i.minAlphaFloor),resolutionScale:s.resolutionScale*i.resolutionScale}}const gr=new WeakMap;function fO(s){const e=gr.get(s);return e?{quality:e.quality,adaptationLevel:e.level,effective:Ky(Ff(e.quality),e.level)}:null}const pO=1,mO=2,gO=.8,yO=.95,_O=4,Tv=3,bO=1.1,oc=30,Av=2,vO=10,Dv=.8,wO=8,xO=.9,Iv=.5;function rS(s,e,t){const i=gr.get(s);if(!i||i.quality!=="auto")return;let n=i.level;e.streaming&&(i.lastStreamingTime=Math.max(i.lastStreamingTime,t));const o=t-i.lastStreamingTime>=Av||t-i.lastChangeTime>=vO;i.fpsBeforeStep!==null&&t-i.lastChangeTime>=Tv&&o&&(e.smoothedFps<i.fpsBeforeStep*Dv?E()&&console.debug(`[SplatQuality] conditions collapsed since the degradation (${i.fpsBeforeStep.toFixed(1)} → ${e.smoothedFps.toFixed(1)}) — discarding the measurement, keeping level ${n}`):e.smoothedFps<i.fpsBeforeStep*bO?(n=i.stepFromLevel??Math.max(0,n-1),i.downBackoffUntil=t+oc,i.stepFromLevel!==null&&i.level-i.stepFromLevel>1&&(i.jumpBackoffUntil=t+oc),E()&&console.debug(`[SplatQuality] degradation bought no fps (${i.fpsBeforeStep.toFixed(1)} → ${e.smoothedFps.toFixed(1)}) — reverting to level ${n}, backing off ${oc}s`)):E()&&console.debug(`[SplatQuality] degradation bought fps (${i.fpsBeforeStep.toFixed(1)} → ${e.smoothedFps.toFixed(1)}) — keeping level ${n}`),i.fpsBeforeStep=null,i.stepFromLevel=null),i.fpsBeforeProbe!==null&&t-i.lastChangeTime>=Tv&&o&&(e.smoothedFps<i.fpsBeforeProbe*Dv?(n=Math.min(hr,n+1),E()&&console.debug(`[SplatQuality] conditions collapsed during recovery probe (${i.fpsBeforeProbe.toFixed(1)} → ${e.smoothedFps.toFixed(1)}) — restoring level ${n}`)):e.smoothedFps<i.fpsBeforeProbe*xO?(n=Math.min(hr,n+1),i.upBackoffUntil=t+oc,E()&&console.debug(`[SplatQuality] recovery probe cost fps (${i.fpsBeforeProbe.toFixed(1)} → ${e.smoothedFps.toFixed(1)}) — restoring level ${n}, backing off ${oc}s`)):E()&&console.debug(`[SplatQuality] recovery probe kept (fps ${i.fpsBeforeProbe.toFixed(1)} → ${e.smoothedFps.toFixed(1)}), level ${n}`),i.fpsBeforeProbe=null);const r=e.smoothedFps<e.targetFps*gO,a=e.smoothedFps>=e.targetFps*yO,l=t-i.lastChangeTime>=mO;r?(i.goodStreak=0,l&&t>=i.downBackoffUntil&&n===i.level&&i.fpsBeforeStep===null&&i.fpsBeforeProbe===null&&n<hr?(!(ef[n+1].resolutionScale<ef[n].resolutionScale)||e.smoothedFps<e.targetFps*Iv)&&(i.fpsBeforeStep=e.smoothedFps,i.stepFromLevel=n,n++):l&&t<i.downBackoffUntil&&t>=i.jumpBackoffUntil&&e.smoothedFps<e.targetFps*Iv&&n===i.level&&i.fpsBeforeStep===null&&i.fpsBeforeProbe===null&&n<hr&&(i.fpsBeforeStep=e.smoothedFps,i.stepFromLevel=n,n=hr)):a?(i.goodStreak++,i.goodStreak>=_O&&l&&i.fpsBeforeProbe===null&&n>0&&(n--,i.goodStreak=0)):i.goodStreak=0;const h=n===i.level&&i.fpsBeforeStep===null&&i.fpsBeforeProbe===null;i.stableStreak=h?i.stableStreak+1:0,h&&!r&&n>0&&i.stableStreak>=wO&&l&&t>=i.upBackoffUntil&&t-i.lastStreamingTime>=Av&&(i.fpsBeforeProbe=e.smoothedFps,i.stableStreak=0,n--),n!==i.level&&(E()&&console.debug(`[SplatQuality] adaptation level ${i.level} → ${n} (fps ${e.smoothedFps.toFixed(1)}/${e.targetFps}${n>i.level?", verifying fps gain":i.fpsBeforeProbe!==null?", probing recovery":""})`),i.level=n,i.lastChangeTime=t,Zy(i))}const za=new WeakMap;function aS(s,e){if((za.get(s)??0)>0)return!0;const t=e.renderer.pager;return!!t&&((t.fetchers?.length??0)>0||(t.fetched?.length??0)>0)}const SO=1500;function CO(s,e){e.resumeQuietUntil!==0&&performance.now()>=e.resumeQuietUntil&&(e.renderer.pauseWork=!1,e.resumeQuietUntil=0,E()&&console.debug("[SplatQuality] calm resume over — splat work resumed"));const t=s.time.time,i=aS(s,e);if(i&&(e.lastStreamingTime=Math.max(e.lastStreamingTime,t)),t-e.lastEvalTime<pO||(e.lastEvalTime=t,hO&&PO(s,e),s.time.frameCount<60))return;const n=s.isInXR;let o=(n?s.xrSession?.frameRate:void 0)??60;n&&s.xrFrameRateLimit>0&&(o=Math.min(o,s.xrFrameRateLimit)),rS(s,{smoothedFps:s.time.smoothedFps,targetFps:o,streaming:i},t)}function PO(s,e){const t=e.renderer;if(!t.sortedCenter)return;const i=(a,l)=>{const h=l.getWorldPosition(kO),d=l.getWorldScale(MO),u=(d.x+d.y+d.z)/3,f=t.sortedCenter?h.distanceTo(t.sortedCenter):-1,m=t.lastLod?t.lastLod.pos.distanceTo(h):-1;console.debug(`[SplatSort] ${a} pos=(${h.x.toFixed(4)}, ${h.y.toFixed(4)}, ${h.z.toFixed(4)}) scale=${u.toFixed(4)} sortedCenterDist=${f.toFixed(5)} threshold=${(.001*u).toFixed(5)} lodPosDist=${m.toFixed(4)} activeSplats=${t.activeSplats}`)};if(s.mainCamera){i("mainCamera",s.mainCamera);let a="";for(let l=s.mainCamera.parent;l;l=l.parent)a+=`${l.name||l.type}(s=${l.scale.x.toFixed(2)}) > `;console.debug(`[SplatSort] mainCamera parents: ${a||"none"}`)}if(s.isInXR){const a=s.renderer.xr.getCamera();a&&(i("xrCamera",a),a.cameras?.[0]&&i("xrCamera.eye0",a.cameras[0]))}let n=0;s.scene.traverse(a=>{a.constructor?.name?.includes("SplatMesh")&&n++});const o=(t.pager?.pageLru?.size??0)*(t.pager?.pageSplats??0),r=aS(s,e);console.debug(`[SplatSort] fps=${s.time.smoothedFps.toFixed(1)} splatMeshes=${n} resident=${o}/${t.pager?.maxSplats??0} streaming=${r}(f=${t.pager?.fetchers?.length??0},q=${t.pager?.fetched?.length??0},l=${za.get(s)??0}) lod renderScale=${t.lodRenderScale} splatScale=${t.lodSplatScale} pixelScaleLimit=${t.lastLod?.pixelScaleLimit?.toExponential(3)} maxSplats=${t.lastLod?.maxSplats} adaptLevel=${e.level}`)}const kO=new c.Vector3,MO=new c.Vector3;function OO(s,e){s.minSortIntervalMs=e.minSortIntervalMs,s.numLodFetchers=e.fetchers,s.lodRenderScale=e.lodRenderScale;const t=exports.DeviceUtilities.isiOS()?2/3:1;s.lodSplatScale=e.lodSplatScale*t,s.sortCullHalfAngle=dO??e.sortCullHalfAngle,s.maxStdDev=e.maxStdDev,s.maxPixelRadius=e.maxPixelRadius,s.coneFoveate=e.coneFoveate,s.behindFoveate=e.behindFoveate,s.minAlpha=e.minAlpha,e.maxPagedSplats>0&&!s.pager&&(s.maxPagedSplats=e.maxPagedSplats),s.pager&&(s.pager.numFetchers=e.fetchers),lS=e.xrFramebufferScale}let lS;function Lv(){return lS}let cS=1;function EO(){return cS}function Zy(s){const e=Ky(Ff(s.quality),s.level);if(OO(s.renderer,e),e.resolutionScale!==s.appliedResolutionScale){const t=s.context.resolutionScaleFactor/s.appliedResolutionScale;s.context.resolutionScaleFactor=t*e.resolutionScale,s.appliedResolutionScale=e.resolutionScale,cS=e.resolutionScale,s.context.xr?.setDynamicResolutionScale(e.resolutionScale)}s.context.xr?.refreshRenderResolution(),e.xrMaxFps!==s.appliedXrMaxFps&&(s.context.xrFrameRateLimit===s.appliedXrMaxFps&&(s.context.xrFrameRateLimit=e.xrMaxFps),s.appliedXrMaxFps=e.xrMaxFps),s.context.scene.traverse(t=>t.updateVersion?.())}function RO(s,e){let t;if(s.scene.traverse(i=>{i instanceof e&&(t=i)}),t||(t=new e({renderer:s.renderer}),s.scene.add(t)),gr.has(s))gr.get(s).renderer=t;else{const i={context:s,renderer:t,quality:"auto",level:0,lastChangeTime:0,lastEvalTime:0,goodStreak:0,fpsBeforeStep:null,downBackoffUntil:0,lastStreamingTime:-1/0,stepFromLevel:null,jumpBackoffUntil:0,fpsBeforeProbe:null,upBackoffUntil:0,stableStreak:0,appliedResolutionScale:1,appliedXrMaxFps:0,resumeQuietUntil:0};gr.set(s,i),Zy(i),s.pre_render_callbacks.push(()=>CO(s,i)),typeof document<"u"&&document.addEventListener("visibilitychange",()=>{const n=gr.get(s);if(!n)return;const o=n.renderer;document.visibilityState==="hidden"?(o.pauseWork=!0,n.resumeQuietUntil=Number.POSITIVE_INFINITY):n.resumeQuietUntil=performance.now()+SO})}return t}function TO(s){return!/^(blob:|data:)/i.test(s)}function AO(){mr.some(s=>s.name===rm)||exports.NeedleEngineModelLoader.onCreateCustomModelLoader(s=>{switch(s.mimetype){case"model/ply":case"model/spz":case"model/splat":case"model/ksplat":case"model/sog":case"model/rad":{const e=s.mimetype,t=s.context,i={name:rm,loadAsync:async(n,o)=>{const r=await Promise.resolve().then(()=>require("./vendor-BJviq-Oq.umd.cjs")).then(m=>m.spark_module);if(RO(t,r.SparkRenderer),e==="model/rad"&&TO(n))return new r.SplatMesh({url:n,paged:!0});za.set(t,(za.get(t)??0)+1);const a=()=>za.set(t,Math.max(0,(za.get(t)??1)-1)),l=new r.SplatLoader,h={"model/ply":r.SplatFileType.PLY,"model/spz":r.SplatFileType.SPZ,"model/splat":r.SplatFileType.SPLAT,"model/ksplat":r.SplatFileType.KSPLAT,"model/sog":r.SplatFileType.PCSOGSZIP,"model/rad":r.SplatFileType.RAD}[e];let d;try{d=await new Promise((m,g)=>{l.loadInternal({url:n,fileType:h,onLoad:m,onError:g,onProgress:v=>{if(o&&v.type==="progress"){const _=v;o(new ProgressEvent("progress",{loaded:_.loaded??0,total:_.total??0,lengthComputable:_.total!=null&&_.total>0}))}}})})}catch(m){throw a(),m}const u=d instanceof r.PackedSplats?{packedSplats:d,lod:!0}:{extSplats:d,lod:!0},f=new r.SplatMesh(u);return f.createLodSplats().catch(m=>console.warn("[Needle Engine] Building the splat LOD tree failed — rendering without LOD",m)).finally(a),(e==="model/ply"||e==="model/sog")&&f.quaternion.set(1,0,0,0),f},parse:n=>{const o=typeof n=="string"?new TextEncoder().encode(n):n,r=URL.createObjectURL(new Blob([o]));return i.loadAsync(r).finally(()=>URL.revokeObjectURL(r))}};return i}}return null},{name:rm})}const Ka=new c.Matrix4().makeRotationY(Math.PI),Wi=new c.Quaternion().setFromAxisAngle(new c.Vector3(0,1,0),Math.PI),DO=x("debugwebxr");class IO{priority=-1e5;gameObject;isXRRig(){return!0}get isActive(){return this.gameObject.visible}constructor(){if(this.gameObject=new c.Object3D,this.gameObject.name="Implicit XR Rig",DO){const e=s_(16733661);e.position.y+=.5,this.gameObject.add(e)}}}const _s=x("debugwebxr"),Md=x("debugcustomgesture"),LO="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",BO="generic-trigger",FO=new c.Quaternion().setFromEuler(new c.Euler(c.MathUtils.degToRad(0),c.MathUtils.degToRad(-90),c.MathUtils.degToRad(-90))),jO=new c.Vector3(.04,-.04,0);class Jy{xr;get context(){return this.xr.context}inputSource;index=0;emitEvents=!0;get connected(){return this._connected}_connected=!0;get isTracking(){return this._isTracking}_isTracking=!1;get gamepad(){return this.__gamepad??=this.inputSource.gamepad}__gamepad;get isHand(){return this.hand!=null}get hand(){return this.__hand??=this.inputSource.hand}__hand;get handObject(){return this.context.renderer.xr.getHand(this.index)}get profiles(){return this.inputSource.profiles}get layout(){return this._layout}get targetRayMode(){return this.inputSource.targetRayMode}get targetRaySpace(){return this.inputSource.targetRaySpace}get gripSpace(){return this.inputSource.gripSpace}get side(){return this.__side??=this.inputSource.handedness}__side=void 0;get isRight(){return this.side==="right"}get isLeft(){return this.side==="left"}get isStylus(){return this._isMxInk}getHitTestSource(){return this._hitTestSource||this._requestHitTestSource(),this._hitTestSource}get hasHitTestSource(){return this._hitTestSource}cancelHitTestSource(){this._hitTestSource&&(this._hitTestSource.cancel(),this._hitTestSource=void 0)}_hitTestSource=void 0;_hasSelectEvent=!1;get hasSelectEvent(){return this._hasSelectEvent}_isMxInk=!1;_isMetaQuestTouchController=!1;getHitTest(){return this.xr.getHitTest(this)}_handJointPoses=new Map;getHandJointPose(e,t){if(t=t||this.xr.frame,!this.hand||!t?.getJointPose||!this.xr.referenceSpace)return null;let i=this._handJointPoses?.get(e);return i||(i=t.getJointPose(e,this.xr.referenceSpace),i&&this._handJointPoses.set(e,i),i)}_gripMatrix=new c.Matrix4;_gripPosition=new c.Vector3;_gripQuaternion=new c.Quaternion;_linearVelocity=new c.Vector3;_rayPositionRaw=new c.Vector3;_rayRotationRaw=new c.Quaternion;_rayMatrix=new c.Matrix4;_rayPosition=new c.Vector3;_rayQuaternion=new c.Quaternion;get gripPosition(){return F(this._gripPosition)}get gripQuaternion(){return ci(this._gripQuaternion)}get gripMatrix(){return this._gripMatrix}get gripLinearVelocity(){return F(this._linearVelocity).applyQuaternion(Wi)}get rayPosition(){return F(this._rayPosition)}get rayQuaternion(){return ci(this._rayQuaternion)}get gripWorldPosition(){return F(this._gripWorldPosition)}_gripWorldPosition=new c.Vector3;get gripWorldQuaternion(){return ci(this._gripWorldQuaternion)}_gripWorldQuaternion=new c.Quaternion;get rayWorldPosition(){return F(this._rayWorldPosition)}_rayWorldPosition=new c.Vector3;updateRayWorldPosition(){const e=this.xr.context.mainCamera?.parent;this._rayWorldPosition.copy(this._rayPositionRaw),e&&this._rayWorldPosition.applyMatrix4(e.matrixWorld)}get rayWorldQuaternion(){return ci(this._rayWorldQuaternion)}_rayWorldQuaternion=new c.Quaternion;get pinchPosition(){return F(this._pinchPosition)}_pinchPosition=new c.Vector3;updateRayWorldQuaternion(){const e=this.xr.context.mainCamera?.parent,t=e?Se(e):void 0;this._rayWorldQuaternion.copy(this._rayRotationRaw).multiply(Wi),t&&this._rayWorldQuaternion.premultiply(t)}get ray(){return this._ray.origin.copy(this.rayWorldPosition),this._ray.direction.copy(F(0,0,1).applyQuaternion(this.rayWorldQuaternion)),this._ray}_ray;_hand_wristDotUp=void 0;get handWristDotUp(){if(this._hand_wristDotUp!==void 0)return this._hand_wristDotUp;const e=this.handObject?.joints.wrist;if(e){const t=F(0,1,0).applyQuaternion(e.quaternion),i=F(0,1,0).dot(t);return this._hand_wristDotUp=i}}get isHandUpsideDown(){return this.handWristDotUp!==void 0?this.handWristDotUp<-.7:!1}get isTeleportGesture(){return this.isHandUpsideDown&&this.getGesture("pinch")?.isDown}get object(){return this._object}_object;_gripSpaceObject;_raySpaceObject;model=null;_debugAxesHelper=new c.AxesHelper(.15);_debugGripAxesHelper=new c.AxesHelper(.07);_debugRayAxesHelper=new c.AxesHelper(.07);async getModelUrl(){return this.getMotionController?.then(e=>e?.assetUrl||null)}constructor(e,t,i){this.xr=e,this.inputSource=t,this.index=i,this._object=new c.Object3D,this._object.name=`NeedleXRController_${i}`,_s&&(this._object.add(this._debugAxesHelper),this._gripSpaceObject=new c.Object3D,this._raySpaceObject=new c.Object3D,this._gripSpaceObject.name=`NeedleXRController_${i}_gripSpace`,this._raySpaceObject.name=`NeedleXRController_${i}_raySpace`,this._gripSpaceObject.add(this._debugGripAxesHelper),this._raySpaceObject.add(this._debugRayAxesHelper),this.xr.context.scene.add(this._gripSpaceObject),this.xr.context.scene.add(this._raySpaceObject)),this.xr.context.scene.add(this._object),this._ray=new c.Ray,this.pointerInit={origin:this,pointerType:this.hand?"hand":"controller",deviceIndex:this.index,pointerId:-1,mode:this.inputSource.targetRayMode,ray:this._ray,device:this._object,buttonName:"none"},this.initialize(),this.subscribeEvents()}_hitTestSourcePromise=null;_requestHitTestSource(){return this._hitTestSourcePromise?this._hitTestSourcePromise:this.xr.mode==="immersive-ar"&&this.inputSource.targetRayMode==="tracked-pointer"&&this.xr.session.requestHitTestSourceForTransientInput?this._hitTestSourcePromise=this.xr.session.requestHitTestSourceForTransientInput({profile:this.inputSource.profiles[0],offsetRay:new XRRay})?.then(e=>(this._hitTestSourcePromise=null,this.connected?this._hitTestSource=e:(e.cancel(),null)))??null:null}onPointerHits=e=>{};onUpdate(e){this.onUpdateFrame(e),this.updateInputEvents(),this.onUpdateMove()}onRenderDebug(){B.DrawSphere(this.rayWorldPosition,.003),B.DrawDirection(this.rayWorldPosition,F(0,0,10).applyQuaternion(this.rayWorldQuaternion));const t=(this.inputSource.gripSpace?this.gripWorldPosition:this.object.worldPosition).sub(this.object.worldForward.multiplyScalar(.1)),i=this.inputSource.profiles.join(`
|
|
411
|
+
If you need multisampling consider changing 'auto' to a fixed value (e.g. 4).`));else{const i=e.time.realtimeSinceStartup-this._multisampleAutoChangeTime;if(e.time.realtimeSinceStartup-this._enabledTime>2&&i>.5){const n=this._handler.multisampling;if(this._handler.multisampling>0&&e.time.smoothedFps<=50){this._multisampleAutoChangeTime=e.time.realtimeSinceStartup,this._multisampleAutoDecreaseTime=e.time.realtimeSinceStartup;let o=this._handler.multisampling*.5;o=Math.floor(o),o!=this._handler.multisampling&&(this._handler.multisampling=o),Zo&&console.debug(`[PostProcessing] Reduced multisampling from ${n} to ${this._handler.multisampling}`)}else if(i>1&&e.time.smoothedFps>=59&&this._handler.multisampling<e.renderer.capabilities.maxSamples&&e.time.realtimeSinceStartup-this._multisampleAutoDecreaseTime>10){this._multisampleAutoChangeTime=e.time.realtimeSinceStartup;let o=this._handler.multisampling<=0?1:this._handler.multisampling*2;o=Math.floor(o),o!==this._handler.multisampling&&(this._handler.multisampling=o),Zo&&console.debug(`[PostProcessing] Increased multisampling from ${n} to ${this._handler.multisampling}`)}}}else{const i=Math.max(0,Math.min(this.multisampling,e.renderer.capabilities.maxSamples));i!==this._handler.multisampling&&(this._handler.multisampling=i)}if(this._handler.adaptivePixelRatio=this.adaptiveResolution,this._handler.updateAdaptivePixelRatio(),e.mainCamera){const i=t.passes;for(const n of i)if(n.mainCamera&&n.mainCamera!==e.mainCamera){t.setMainCamera(e.mainCamera);break}}}_lastApplyTime;_rapidApplyCount=0;_tonemappingOnlyActive=!1;_previousToneMapping;_previousToneMappingExposure;apply(){Zo&&console.log(`[PostProcessing] Apply stack (${this._effects.length} effects)`),E()&&(this._lastApplyTime!==void 0&&Date.now()-this._lastApplyTime<100&&(this._rapidApplyCount++,this._rapidApplyCount===5&&console.warn("[PostProcessing] Detected rapid post processing modifications - this might be a bug")),this._lastApplyTime=Date.now()),this._isDirty=!1;const e=this._enabled?this._effects.filter(i=>i.active&&i.enabled):[];if(e.length<=0){this.restoreTonemapping(),this._handler?.unapply(!1);return}if(e.every(i=>i.isToneMapping===!0)){const i=e[e.length-1];Zo&&console.log("[PostProcessing] Only tonemapping effects in stack — applying directly to renderer"),this._tonemappingOnlyActive||(this._previousToneMapping=this._context.renderer.toneMapping,this._previousToneMappingExposure=this._context.renderer.toneMappingExposure,this._tonemappingOnlyActive=!0),this._context.renderer.toneMapping=i.threeToneMapping,this._context.renderer.toneMappingExposure=i.toneMappingExposure,this._handler?.unapply(!1);return}this.restoreTonemapping(),this.ensureHandler().then(i=>{if(i)return i.apply(e)}).then(()=>{this._handler&&(this.multisampling==="auto"?this._handler.multisampling=exports.DeviceUtilities.isMobileDevice()?2:4:this._handler.multisampling=Math.max(0,Math.min(this.multisampling,this._context.renderer.capabilities.maxSamples)),Zo&&console.debug(`[PostProcessing] Set multisampling to ${this._handler.multisampling} (Is Mobile: ${exports.DeviceUtilities.isMobileDevice()})`))}).catch(i=>{console.error("[PostProcessing] Failed to build/apply the postprocessing pipeline",i)}),this._enabledTime=this._context.time.realtimeSinceStartup}restoreTonemapping(){this._tonemappingOnlyActive&&(this._previousToneMapping!==void 0&&(this._context.renderer.toneMapping=this._previousToneMapping),this._previousToneMappingExposure!==void 0&&(this._context.renderer.toneMappingExposure=this._previousToneMappingExposure),this._tonemappingOnlyActive=!1,this._previousToneMapping=void 0,this._previousToneMappingExposure=void 0,Zo&&console.log("[PostProcessing] Restored renderer tonemapping"))}async ensureHandler(){if(!this._handler){const{PostProcessingHandler:e}=await Promise.resolve().then(()=>F3);this._handler||(this._handler=new e(this._context))}return this._handler}dispose(){this.restoreTonemapping(),this._handler?.dispose(),this._handler=null,this._composer=null,this._effects.length=0}}const mr=[],Su=[];exports.NeedleEngineModelLoader=void 0;(s=>{function e(i,n){const o={name:n?.name,priority:n?.priority??0,callback:i};return mr.push(o),mr.sort((r,a)=>r.priority===a.priority?0:r.priority>a.priority?-1:1),()=>{const r=mr.indexOf(o);r>=0&&mr.splice(r,1)}}s.onCreateCustomModelLoader=e;function t(i){return Su.push(i),()=>{const n=Su.indexOf(i);n>=0&&Su.splice(n,1)}}s.onDetermineModelMimetype=t})(exports.NeedleEngineModelLoader||(exports.NeedleEngineModelLoader={}));const rm="Gaussian Splat Loader",hO=x("debugsplats")||x("debugsplatsort")||x("debugspatsort"),dO=(()=>{const s=x("splatcull"),e=typeof s=="number"?s:typeof s=="string"?parseFloat(s):NaN;return Number.isFinite(e)&&e>0?Math.min(Math.PI,e*(Math.PI/180)):void 0})(),uO={high:{maxSh:3,minSortIntervalMs:150,fetchers:3,lodRenderScale:1,lodSplatScale:1,maxStdDev:Math.sqrt(8),maxPixelRadius:512,coneFoveate:.4,behindFoveate:.2,xrFramebufferScale:1,maxPagedSplats:0,minAlpha:.5/255,resolutionScale:1,sortCullHalfAngle:Math.PI,xrMaxFps:0},medium:{maxSh:2,minSortIntervalMs:200,fetchers:2,lodRenderScale:1,lodSplatScale:1,maxStdDev:Math.sqrt(8),maxPixelRadius:384,coneFoveate:.3,behindFoveate:.15,xrFramebufferScale:.9,maxPagedSplats:0,minAlpha:.5/255,resolutionScale:1,sortCullHalfAngle:120/180*Math.PI,xrMaxFps:0},low:{maxSh:1,minSortIntervalMs:250,fetchers:1,lodRenderScale:1,lodSplatScale:1,maxStdDev:Math.sqrt(7),maxPixelRadius:320,coneFoveate:.25,behindFoveate:.1,xrFramebufferScale:.8,maxPagedSplats:48*65536,minAlpha:.5/255,resolutionScale:1,sortCullHalfAngle:110/180*Math.PI,xrMaxFps:30}};function Ff(s,e=exports.DeviceUtilities.isMobileDevice()){return{...uO[s==="auto"?e?"low":"high":s]}}function Tg(s,e,t){const i=Ff(t),n=gr.get(s);n&&(n.quality=t,t!=="auto"&&(n.level=0,n.fpsBeforeStep=null,n.downBackoffUntil=0,n.goodStreak=0,n.stepFromLevel=null,n.jumpBackoffUntil=0,n.fpsBeforeProbe=null,n.upBackoffUntil=0,n.stableStreak=0),Zy(n));const o=e;if(o){typeof o.maxSh=="number"&&(o.maxSh=i.maxSh);const r=o.paged;r&&(r.setMaxSh(i.maxSh),r.pager&&(r.pager.numFetchers=i.fetchers))}return i}const ef=[{lodRenderScale:1,lodSplatScale:1,maxPixelRadius:1,maxStdDevCap:Number.POSITIVE_INFINITY,foveate:1,minAlphaFloor:0,resolutionScale:1},{lodRenderScale:1.5,lodSplatScale:.75,maxPixelRadius:1,maxStdDevCap:Number.POSITIVE_INFINITY,foveate:.8,minAlphaFloor:0,resolutionScale:1},{lodRenderScale:2.25,lodSplatScale:.5,maxPixelRadius:.75,maxStdDevCap:Math.sqrt(7),foveate:.6,minAlphaFloor:0,resolutionScale:1},{lodRenderScale:3.5,lodSplatScale:.35,maxPixelRadius:.5,maxStdDevCap:Math.sqrt(6),foveate:.45,minAlphaFloor:0,resolutionScale:1},{lodRenderScale:3.5,lodSplatScale:.35,maxPixelRadius:.5,maxStdDevCap:Math.sqrt(6),foveate:.45,minAlphaFloor:4/255,resolutionScale:1},{lodRenderScale:3.5,lodSplatScale:.35,maxPixelRadius:.5,maxStdDevCap:Math.sqrt(6),foveate:.45,minAlphaFloor:10/255,resolutionScale:1},{lodRenderScale:3.5,lodSplatScale:.35,maxPixelRadius:.5,maxStdDevCap:Math.sqrt(6),foveate:.45,minAlphaFloor:10/255,resolutionScale:.75},{lodRenderScale:3.5,lodSplatScale:.35,maxPixelRadius:.5,maxStdDevCap:Math.sqrt(6),foveate:.45,minAlphaFloor:10/255,resolutionScale:.6}],hr=ef.length-1;function Ky(s,e){const t=Math.max(0,Math.min(hr,Math.round(e))),i=ef[t];return{...s,lodRenderScale:s.lodRenderScale*i.lodRenderScale,lodSplatScale:s.lodSplatScale*i.lodSplatScale,maxPixelRadius:Math.round(s.maxPixelRadius*i.maxPixelRadius),maxStdDev:Math.min(s.maxStdDev,i.maxStdDevCap),coneFoveate:Math.max(.05,s.coneFoveate*i.foveate),behindFoveate:Math.max(.05,s.behindFoveate*i.foveate),minAlpha:Math.max(s.minAlpha,i.minAlphaFloor),resolutionScale:s.resolutionScale*i.resolutionScale}}const gr=new WeakMap;function fO(s){const e=gr.get(s);return e?{quality:e.quality,adaptationLevel:e.level,effective:Ky(Ff(e.quality),e.level)}:null}const pO=1,mO=2,gO=.8,yO=.95,_O=4,Tv=3,bO=1.1,oc=30,Av=2,vO=10,Dv=.8,wO=8,xO=.9,Iv=.5;function rS(s,e,t){const i=gr.get(s);if(!i||i.quality!=="auto")return;let n=i.level;e.streaming&&(i.lastStreamingTime=Math.max(i.lastStreamingTime,t));const o=t-i.lastStreamingTime>=Av||t-i.lastChangeTime>=vO;i.fpsBeforeStep!==null&&t-i.lastChangeTime>=Tv&&o&&(e.smoothedFps<i.fpsBeforeStep*Dv?E()&&console.debug(`[SplatQuality] conditions collapsed since the degradation (${i.fpsBeforeStep.toFixed(1)} → ${e.smoothedFps.toFixed(1)}) — discarding the measurement, keeping level ${n}`):e.smoothedFps<i.fpsBeforeStep*bO?(n=i.stepFromLevel??Math.max(0,n-1),i.downBackoffUntil=t+oc,i.stepFromLevel!==null&&i.level-i.stepFromLevel>1&&(i.jumpBackoffUntil=t+oc),E()&&console.debug(`[SplatQuality] degradation bought no fps (${i.fpsBeforeStep.toFixed(1)} → ${e.smoothedFps.toFixed(1)}) — reverting to level ${n}, backing off ${oc}s`)):E()&&console.debug(`[SplatQuality] degradation bought fps (${i.fpsBeforeStep.toFixed(1)} → ${e.smoothedFps.toFixed(1)}) — keeping level ${n}`),i.fpsBeforeStep=null,i.stepFromLevel=null),i.fpsBeforeProbe!==null&&t-i.lastChangeTime>=Tv&&o&&(e.smoothedFps<i.fpsBeforeProbe*Dv?(n=Math.min(hr,n+1),E()&&console.debug(`[SplatQuality] conditions collapsed during recovery probe (${i.fpsBeforeProbe.toFixed(1)} → ${e.smoothedFps.toFixed(1)}) — restoring level ${n}`)):e.smoothedFps<i.fpsBeforeProbe*xO?(n=Math.min(hr,n+1),i.upBackoffUntil=t+oc,E()&&console.debug(`[SplatQuality] recovery probe cost fps (${i.fpsBeforeProbe.toFixed(1)} → ${e.smoothedFps.toFixed(1)}) — restoring level ${n}, backing off ${oc}s`)):E()&&console.debug(`[SplatQuality] recovery probe kept (fps ${i.fpsBeforeProbe.toFixed(1)} → ${e.smoothedFps.toFixed(1)}), level ${n}`),i.fpsBeforeProbe=null);const r=e.smoothedFps<e.targetFps*gO,a=e.smoothedFps>=e.targetFps*yO,l=t-i.lastChangeTime>=mO;r?(i.goodStreak=0,l&&t>=i.downBackoffUntil&&n===i.level&&i.fpsBeforeStep===null&&i.fpsBeforeProbe===null&&n<hr?(!(ef[n+1].resolutionScale<ef[n].resolutionScale)||e.smoothedFps<e.targetFps*Iv)&&(i.fpsBeforeStep=e.smoothedFps,i.stepFromLevel=n,n++):l&&t<i.downBackoffUntil&&t>=i.jumpBackoffUntil&&e.smoothedFps<e.targetFps*Iv&&n===i.level&&i.fpsBeforeStep===null&&i.fpsBeforeProbe===null&&n<hr&&(i.fpsBeforeStep=e.smoothedFps,i.stepFromLevel=n,n=hr)):a?(i.goodStreak++,i.goodStreak>=_O&&l&&i.fpsBeforeProbe===null&&n>0&&(n--,i.goodStreak=0)):i.goodStreak=0;const h=n===i.level&&i.fpsBeforeStep===null&&i.fpsBeforeProbe===null;i.stableStreak=h?i.stableStreak+1:0,h&&!r&&n>0&&i.stableStreak>=wO&&l&&t>=i.upBackoffUntil&&t-i.lastStreamingTime>=Av&&(i.fpsBeforeProbe=e.smoothedFps,i.stableStreak=0,n--),n!==i.level&&(E()&&console.debug(`[SplatQuality] adaptation level ${i.level} → ${n} (fps ${e.smoothedFps.toFixed(1)}/${e.targetFps}${n>i.level?", verifying fps gain":i.fpsBeforeProbe!==null?", probing recovery":""})`),i.level=n,i.lastChangeTime=t,Zy(i))}const za=new WeakMap;function aS(s,e){if((za.get(s)??0)>0)return!0;const t=e.renderer.pager;return!!t&&((t.fetchers?.length??0)>0||(t.fetched?.length??0)>0)}const SO=1500;function CO(s,e){e.resumeQuietUntil!==0&&performance.now()>=e.resumeQuietUntil&&(e.renderer.pauseWork=!1,e.resumeQuietUntil=0,E()&&console.debug("[SplatQuality] calm resume over — splat work resumed"));const t=s.time.time,i=aS(s,e);if(i&&(e.lastStreamingTime=Math.max(e.lastStreamingTime,t)),t-e.lastEvalTime<pO||(e.lastEvalTime=t,hO&&PO(s,e),s.time.frameCount<60))return;const n=s.isInXR;let o=(n?s.xrSession?.frameRate:void 0)??60;n&&s.xrFrameRateLimit>0&&(o=Math.min(o,s.xrFrameRateLimit)),rS(s,{smoothedFps:s.time.smoothedFps,targetFps:o,streaming:i},t)}function PO(s,e){const t=e.renderer;if(!t.sortedCenter)return;const i=(a,l)=>{const h=l.getWorldPosition(kO),d=l.getWorldScale(MO),u=(d.x+d.y+d.z)/3,f=t.sortedCenter?h.distanceTo(t.sortedCenter):-1,m=t.lastLod?t.lastLod.pos.distanceTo(h):-1;console.debug(`[SplatSort] ${a} pos=(${h.x.toFixed(4)}, ${h.y.toFixed(4)}, ${h.z.toFixed(4)}) scale=${u.toFixed(4)} sortedCenterDist=${f.toFixed(5)} threshold=${(.001*u).toFixed(5)} lodPosDist=${m.toFixed(4)} activeSplats=${t.activeSplats}`)};if(s.mainCamera){i("mainCamera",s.mainCamera);let a="";for(let l=s.mainCamera.parent;l;l=l.parent)a+=`${l.name||l.type}(s=${l.scale.x.toFixed(2)}) > `;console.debug(`[SplatSort] mainCamera parents: ${a||"none"}`)}if(s.isInXR){const a=s.renderer.xr.getCamera();a&&(i("xrCamera",a),a.cameras?.[0]&&i("xrCamera.eye0",a.cameras[0]))}let n=0;s.scene.traverse(a=>{a.constructor?.name?.includes("SplatMesh")&&n++});const o=(t.pager?.pageLru?.size??0)*(t.pager?.pageSplats??0),r=aS(s,e);console.debug(`[SplatSort] fps=${s.time.smoothedFps.toFixed(1)} splatMeshes=${n} resident=${o}/${t.pager?.maxSplats??0} streaming=${r}(f=${t.pager?.fetchers?.length??0},q=${t.pager?.fetched?.length??0},l=${za.get(s)??0}) lod renderScale=${t.lodRenderScale} splatScale=${t.lodSplatScale} pixelScaleLimit=${t.lastLod?.pixelScaleLimit?.toExponential(3)} maxSplats=${t.lastLod?.maxSplats} adaptLevel=${e.level}`)}const kO=new c.Vector3,MO=new c.Vector3;function OO(s,e){s.minSortIntervalMs=e.minSortIntervalMs,s.numLodFetchers=e.fetchers,s.lodRenderScale=e.lodRenderScale;const t=exports.DeviceUtilities.isiOS()?2/3:1;s.lodSplatScale=e.lodSplatScale*t,s.sortCullHalfAngle=dO??e.sortCullHalfAngle,s.maxStdDev=e.maxStdDev,s.maxPixelRadius=e.maxPixelRadius,s.coneFoveate=e.coneFoveate,s.behindFoveate=e.behindFoveate,s.minAlpha=e.minAlpha,e.maxPagedSplats>0&&!s.pager&&(s.maxPagedSplats=e.maxPagedSplats),s.pager&&(s.pager.numFetchers=e.fetchers),lS=e.xrFramebufferScale}let lS;function Lv(){return lS}let cS=1;function EO(){return cS}function Zy(s){const e=Ky(Ff(s.quality),s.level);if(OO(s.renderer,e),e.resolutionScale!==s.appliedResolutionScale){const t=s.context.resolutionScaleFactor/s.appliedResolutionScale;s.context.resolutionScaleFactor=t*e.resolutionScale,s.appliedResolutionScale=e.resolutionScale,cS=e.resolutionScale,s.context.xr?.setDynamicResolutionScale(e.resolutionScale)}s.context.xr?.refreshRenderResolution(),e.xrMaxFps!==s.appliedXrMaxFps&&(s.context.xrFrameRateLimit===s.appliedXrMaxFps&&(s.context.xrFrameRateLimit=e.xrMaxFps),s.appliedXrMaxFps=e.xrMaxFps),s.context.scene.traverse(t=>t.updateVersion?.())}function RO(s,e){let t;if(s.scene.traverse(i=>{i instanceof e&&(t=i)}),t||(t=new e({renderer:s.renderer}),s.scene.add(t)),gr.has(s))gr.get(s).renderer=t;else{const i={context:s,renderer:t,quality:"auto",level:0,lastChangeTime:0,lastEvalTime:0,goodStreak:0,fpsBeforeStep:null,downBackoffUntil:0,lastStreamingTime:-1/0,stepFromLevel:null,jumpBackoffUntil:0,fpsBeforeProbe:null,upBackoffUntil:0,stableStreak:0,appliedResolutionScale:1,appliedXrMaxFps:0,resumeQuietUntil:0};gr.set(s,i),Zy(i),s.pre_render_callbacks.push(()=>CO(s,i)),typeof document<"u"&&document.addEventListener("visibilitychange",()=>{const n=gr.get(s);if(!n)return;const o=n.renderer;document.visibilityState==="hidden"?(o.pauseWork=!0,n.resumeQuietUntil=Number.POSITIVE_INFINITY):n.resumeQuietUntil=performance.now()+SO})}return t}function TO(s){return!/^(blob:|data:)/i.test(s)}function AO(){mr.some(s=>s.name===rm)||exports.NeedleEngineModelLoader.onCreateCustomModelLoader(s=>{switch(s.mimetype){case"model/ply":case"model/spz":case"model/splat":case"model/ksplat":case"model/sog":case"model/rad":{const e=s.mimetype,t=s.context,i={name:rm,loadAsync:async(n,o)=>{const r=await Promise.resolve().then(()=>require("./vendor-CDN1hirK.umd.cjs")).then(m=>m.spark_module);if(RO(t,r.SparkRenderer),e==="model/rad"&&TO(n))return new r.SplatMesh({url:n,paged:!0});za.set(t,(za.get(t)??0)+1);const a=()=>za.set(t,Math.max(0,(za.get(t)??1)-1)),l=new r.SplatLoader,h={"model/ply":r.SplatFileType.PLY,"model/spz":r.SplatFileType.SPZ,"model/splat":r.SplatFileType.SPLAT,"model/ksplat":r.SplatFileType.KSPLAT,"model/sog":r.SplatFileType.PCSOGSZIP,"model/rad":r.SplatFileType.RAD}[e];let d;try{d=await new Promise((m,g)=>{l.loadInternal({url:n,fileType:h,onLoad:m,onError:g,onProgress:v=>{if(o&&v.type==="progress"){const _=v;o(new ProgressEvent("progress",{loaded:_.loaded??0,total:_.total??0,lengthComputable:_.total!=null&&_.total>0}))}}})})}catch(m){throw a(),m}const u=d instanceof r.PackedSplats?{packedSplats:d,lod:!0}:{extSplats:d,lod:!0},f=new r.SplatMesh(u);return f.createLodSplats().catch(m=>console.warn("[Needle Engine] Building the splat LOD tree failed — rendering without LOD",m)).finally(a),(e==="model/ply"||e==="model/sog")&&f.quaternion.set(1,0,0,0),f},parse:n=>{const o=typeof n=="string"?new TextEncoder().encode(n):n,r=URL.createObjectURL(new Blob([o]));return i.loadAsync(r).finally(()=>URL.revokeObjectURL(r))}};return i}}return null},{name:rm})}const Ka=new c.Matrix4().makeRotationY(Math.PI),Wi=new c.Quaternion().setFromAxisAngle(new c.Vector3(0,1,0),Math.PI),DO=x("debugwebxr");class IO{priority=-1e5;gameObject;isXRRig(){return!0}get isActive(){return this.gameObject.visible}constructor(){if(this.gameObject=new c.Object3D,this.gameObject.name="Implicit XR Rig",DO){const e=s_(16733661);e.position.y+=.5,this.gameObject.add(e)}}}const _s=x("debugwebxr"),Md=x("debugcustomgesture"),LO="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",BO="generic-trigger",FO=new c.Quaternion().setFromEuler(new c.Euler(c.MathUtils.degToRad(0),c.MathUtils.degToRad(-90),c.MathUtils.degToRad(-90))),jO=new c.Vector3(.04,-.04,0);class Jy{xr;get context(){return this.xr.context}inputSource;index=0;emitEvents=!0;get connected(){return this._connected}_connected=!0;get isTracking(){return this._isTracking}_isTracking=!1;get gamepad(){return this.__gamepad??=this.inputSource.gamepad}__gamepad;get isHand(){return this.hand!=null}get hand(){return this.__hand??=this.inputSource.hand}__hand;get handObject(){return this.context.renderer.xr.getHand(this.index)}get profiles(){return this.inputSource.profiles}get layout(){return this._layout}get targetRayMode(){return this.inputSource.targetRayMode}get targetRaySpace(){return this.inputSource.targetRaySpace}get gripSpace(){return this.inputSource.gripSpace}get side(){return this.__side??=this.inputSource.handedness}__side=void 0;get isRight(){return this.side==="right"}get isLeft(){return this.side==="left"}get isStylus(){return this._isMxInk}getHitTestSource(){return this._hitTestSource||this._requestHitTestSource(),this._hitTestSource}get hasHitTestSource(){return this._hitTestSource}cancelHitTestSource(){this._hitTestSource&&(this._hitTestSource.cancel(),this._hitTestSource=void 0)}_hitTestSource=void 0;_hasSelectEvent=!1;get hasSelectEvent(){return this._hasSelectEvent}_isMxInk=!1;_isMetaQuestTouchController=!1;getHitTest(){return this.xr.getHitTest(this)}_handJointPoses=new Map;getHandJointPose(e,t){if(t=t||this.xr.frame,!this.hand||!t?.getJointPose||!this.xr.referenceSpace)return null;let i=this._handJointPoses?.get(e);return i||(i=t.getJointPose(e,this.xr.referenceSpace),i&&this._handJointPoses.set(e,i),i)}_gripMatrix=new c.Matrix4;_gripPosition=new c.Vector3;_gripQuaternion=new c.Quaternion;_linearVelocity=new c.Vector3;_rayPositionRaw=new c.Vector3;_rayRotationRaw=new c.Quaternion;_rayMatrix=new c.Matrix4;_rayPosition=new c.Vector3;_rayQuaternion=new c.Quaternion;get gripPosition(){return F(this._gripPosition)}get gripQuaternion(){return ci(this._gripQuaternion)}get gripMatrix(){return this._gripMatrix}get gripLinearVelocity(){return F(this._linearVelocity).applyQuaternion(Wi)}get rayPosition(){return F(this._rayPosition)}get rayQuaternion(){return ci(this._rayQuaternion)}get gripWorldPosition(){return F(this._gripWorldPosition)}_gripWorldPosition=new c.Vector3;get gripWorldQuaternion(){return ci(this._gripWorldQuaternion)}_gripWorldQuaternion=new c.Quaternion;get rayWorldPosition(){return F(this._rayWorldPosition)}_rayWorldPosition=new c.Vector3;updateRayWorldPosition(){const e=this.xr.context.mainCamera?.parent;this._rayWorldPosition.copy(this._rayPositionRaw),e&&this._rayWorldPosition.applyMatrix4(e.matrixWorld)}get rayWorldQuaternion(){return ci(this._rayWorldQuaternion)}_rayWorldQuaternion=new c.Quaternion;get pinchPosition(){return F(this._pinchPosition)}_pinchPosition=new c.Vector3;updateRayWorldQuaternion(){const e=this.xr.context.mainCamera?.parent,t=e?Se(e):void 0;this._rayWorldQuaternion.copy(this._rayRotationRaw).multiply(Wi),t&&this._rayWorldQuaternion.premultiply(t)}get ray(){return this._ray.origin.copy(this.rayWorldPosition),this._ray.direction.copy(F(0,0,1).applyQuaternion(this.rayWorldQuaternion)),this._ray}_ray;_hand_wristDotUp=void 0;get handWristDotUp(){if(this._hand_wristDotUp!==void 0)return this._hand_wristDotUp;const e=this.handObject?.joints.wrist;if(e){const t=F(0,1,0).applyQuaternion(e.quaternion),i=F(0,1,0).dot(t);return this._hand_wristDotUp=i}}get isHandUpsideDown(){return this.handWristDotUp!==void 0?this.handWristDotUp<-.7:!1}get isTeleportGesture(){return this.isHandUpsideDown&&this.getGesture("pinch")?.isDown}get object(){return this._object}_object;_gripSpaceObject;_raySpaceObject;model=null;_debugAxesHelper=new c.AxesHelper(.15);_debugGripAxesHelper=new c.AxesHelper(.07);_debugRayAxesHelper=new c.AxesHelper(.07);async getModelUrl(){return this.getMotionController?.then(e=>e?.assetUrl||null)}constructor(e,t,i){this.xr=e,this.inputSource=t,this.index=i,this._object=new c.Object3D,this._object.name=`NeedleXRController_${i}`,_s&&(this._object.add(this._debugAxesHelper),this._gripSpaceObject=new c.Object3D,this._raySpaceObject=new c.Object3D,this._gripSpaceObject.name=`NeedleXRController_${i}_gripSpace`,this._raySpaceObject.name=`NeedleXRController_${i}_raySpace`,this._gripSpaceObject.add(this._debugGripAxesHelper),this._raySpaceObject.add(this._debugRayAxesHelper),this.xr.context.scene.add(this._gripSpaceObject),this.xr.context.scene.add(this._raySpaceObject)),this.xr.context.scene.add(this._object),this._ray=new c.Ray,this.pointerInit={origin:this,pointerType:this.hand?"hand":"controller",deviceIndex:this.index,pointerId:-1,mode:this.inputSource.targetRayMode,ray:this._ray,device:this._object,buttonName:"none"},this.initialize(),this.subscribeEvents()}_hitTestSourcePromise=null;_requestHitTestSource(){return this._hitTestSourcePromise?this._hitTestSourcePromise:this.xr.mode==="immersive-ar"&&this.inputSource.targetRayMode==="tracked-pointer"&&this.xr.session.requestHitTestSourceForTransientInput?this._hitTestSourcePromise=this.xr.session.requestHitTestSourceForTransientInput({profile:this.inputSource.profiles[0],offsetRay:new XRRay})?.then(e=>(this._hitTestSourcePromise=null,this.connected?this._hitTestSource=e:(e.cancel(),null)))??null:null}onPointerHits=e=>{};onUpdate(e){this.onUpdateFrame(e),this.updateInputEvents(),this.onUpdateMove()}onRenderDebug(){B.DrawSphere(this.rayWorldPosition,.003),B.DrawDirection(this.rayWorldPosition,F(0,0,10).applyQuaternion(this.rayWorldQuaternion));const t=(this.inputSource.gripSpace?this.gripWorldPosition:this.object.worldPosition).sub(this.object.worldForward.multiplyScalar(.1)),i=this.inputSource.profiles.join(`
|
|
412
412
|
`);let n=`Controller[${this.index}] (${this.inputSource.targetRayMode}, ${this.side})
|
|
413
413
|
C:${this.connected?"x":"-"} T:${this.isTracking?"x":"-"} Hand:${this.inputSource.hand?"x":"-"} Pen: ${this._isMxInk?"x":"-"}`;if(this.inputSource.hand&&(n+=`
|
|
414
414
|
Pinch: ${this.getGesture("pinch")?.value.toFixed(3)}`),n+=`
|
|
@@ -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-DOHf03pR.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-CDN1hirK.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)+`
|
|
@@ -1084,7 +1084,7 @@ Consider registering a custom loader via the 'onCreateCustomModelLoader' callbac
|
|
|
1084
1084
|
Content-Type: "${t.headers.get("content-type")}"
|
|
1085
1085
|
"Text: "${o}"
|
|
1086
1086
|
Binary:`,i)}else Ae&&console.debug("Could not determine file type from binary data");return"unknown"}const Pm=x("debugstencil");function cA(s,e){return(s&1<<e.layer)!=0}const hA=Symbol("stencils");class bo{get name(){return"NEEDLE_render_objects"}static stencils={};static applyStencil(e){if(!e)return;const t=e.sourceId;if(Pm&&console.log(t,bo.stencils),!t)return;const i=bo.stencils[t];if(i)for(let n=i.length-1;n>=0;n--){const o=i[n];if(cA(o.layer,e)){Pm&&console.log(o),setTimeout(()=>{ki()&&$f(e.gameObject)&&(de("Stencil not supported on instanced objects"),console.warn("Stencil not supported on instanced objects",e))},500);for(let r=0;r<e.sharedMaterials.length;r++){let a=e.sharedMaterials[r];a&&(a=a.clone(),a[hA]=!0,a.stencilWrite=!0,a.stencilWriteMask=255,a.stencilFuncMask=255,a.stencilRef=o.value,a.stencilFunc=o.compareFunc,a.stencilZPass=o.passOp,a.stencilFail=o.failOp,a.stencilZFail=o.zFailOp,e.sharedMaterials[r]=a)}e.gameObject.renderOrder=o.event*1e3+o.index*50;break}}}parser;source;constructor(e,t){this.parser=e,this.source=t}afterRoot(e){const t=this.parser.json.extensions;if(t){const i=t[uA];if(i){Pm&&console.log(i);const n=i.stencil;if(n&&Array.isArray(n))for(const o of n){const r={...o};r.compareFunc=dA(r.compareFunc),r.passOp=km(r.passOp),r.failOp=km(r.failOp),r.zFailOp=km(r.zFailOp),bo.stencils[this.source]||(bo.stencils[this.source]=[]),bo.stencils[this.source].push(r)}}}return null}}function km(s){switch(s){case 0:return c.KeepStencilOp;case 1:return c.ZeroStencilOp;case 2:return c.ReplaceStencilOp;case 3:return c.IncrementStencilOp;case 4:return c.DecrementStencilOp;case 6:return c.IncrementWrapStencilOp;case 7:return c.DecrementWrapStencilOp;case 5:return c.InvertStencilOp}return 0}function dA(s){switch(s){case 1:return c.NeverStencilFunc;case 2:return c.LessStencilFunc;case 3:return c.EqualStencilFunc;case 4:return c.LessEqualStencilFunc;case 5:return c.GreaterStencilFunc;case 6:return c.NotEqualStencilFunc;case 7:return c.GreaterEqualStencilFunc;case 8:return c.AlwaysStencilFunc}return c.NeverStencilFunc}const uA="NEEDLE_render_objects";class fA{objectToBlock=new WeakMap;meshToOwners=new WeakMap;meshToOriginalCallbacks=new WeakMap;getBlock(e){return this.objectToBlock.get(e)}setBlock(e,t){this.objectToBlock.set(e,t)}deleteBlock(e){this.objectToBlock.delete(e)}isHooked(e,t){return this.meshToOwners.get(e)?.has(t)??!1}addHook(e,t){let i=this.meshToOwners.get(e);i||(i=new Set,this.meshToOwners.set(e,i)),i.add(t)}removeHook(e,t){const i=this.meshToOwners.get(e);i&&(i.delete(t),i.size===0&&this.meshToOwners.delete(e))}getOriginalCallbacks(e){return this.meshToOriginalCallbacks.get(e)}setOriginalCallbacks(e,t){this.meshToOriginalCallbacks.set(e,t)}}const So=new fA;class As{_overrides=[];_defines={};_object=null;get object(){return this._object}constructor(e=null){this._object=e}static get(e){let t=So.getBlock(e);return t||(t=new As(e),So.setBlock(e,t),yA(e,t)),t}static hasOverrides(e){const t=So.getBlock(e);return t?t.hasOverrides():!1}dispose(){this._object&&So.deleteBlock(this._object),this._overrides=[],this._object=null}setOverride(e,t,i){const n=this._overrides.find(o=>o.name===e);n?(n.value=t,n.textureTransform=i):this._overrides.push({name:e,value:t,textureTransform:i})}getOverride(e){return this._overrides.find(t=>t.name===e)}removeOverride(e){const t=this._overrides.findIndex(i=>i.name===e);t>=0&&this._overrides.splice(t,1)}removeOveride(e){this.removeOverride(e)}clearAllOverrides(){this._overrides=[]}get overrides(){return this._overrides}hasOverrides(){return this._overrides.length>0}setDefine(e,t){this._defines[e]=t}clearDefine(e){this._defines[e]=void 0}getDefines(){return this._defines}getCacheKey(){const e=[],t=Object.keys(this._defines).sort();for(const i of t){const n=this._defines[i];n!==void 0&&e.push(`d:${i}=${n}`)}for(const i of this._overrides){if(i.value===null)continue;let n="";if(i.value instanceof c.Texture){if(n=i.value.uuid||"texture",i.textureTransform){const o=i.textureTransform;o.offset&&(n+=`;to:${o.offset.x},${o.offset.y}`),o.repeat&&(n+=`;tr:${o.repeat.x},${o.repeat.y}`)}}else if(Array.isArray(i.value))n=i.value.join(",");else if(i.value&&typeof i.value=="object"&&"r"in i.value){const o=i.value;n=`${o.r},${o.g},${o.b},${o.a!==void 0?o.a:""}`}else if(i.value&&typeof i.value=="object"&&"x"in i.value){const o=i.value;n=`${o.x},${o.y}${o.z!==void 0?`,${o.z}`:""}${o.w!==void 0?`,${o.w}`:""}`}else n=String(i.value);e.push(`${i.name}=${n}`)}return e.join(";")}}const Ru=Symbol("originalValues"),Tu=Symbol("savedTextureTransforms");function A_(s){let e=So.getBlock(s);if(e)return{block:e,owner:s};if(s.parent&&s.parent.type==="Group"&&(e=So.getBlock(s.parent),e))return{block:e,owner:s.parent}}const tl=Symbol("beforeRenderingFlag"),sy=new WeakMap,oy=new WeakMap,pA=function(s,e,t,i){const n=A_(this)?.block;if(n&&n.hasOverrides()){const o=n.getOverride("transmission")?.value,r=n.getOverride("transparent")?.value;o!==void 0&&typeof o=="number"&&"transmission"in t&&o!==t.transmission&&(oy.set(this,t.transmission),t.transmission=o),r!==void 0&&typeof r=="boolean"&&r!==t.transparent&&(sy.set(this,t.transparent),t.transparent=r)}},mA=function(s,e,t,i){const n=sy.get(s);n!==void 0&&(sy.delete(s),t.transparent=n);const o=oy.get(s);o!==void 0&&(oy.delete(s),t.transmission=o)};let R0=!1;const gA=x("debugreflectionprobe"),T0=function(s,e,t,i,n,o){const r=this.material;if(!r)return;if(Array.isArray(r)){if(!r.includes(n))return}else if(r!==n)return;this[tl]===void 0&&(this[tl]=new WeakSet),this[tl].add(n);const a=A_(this);if(!a)return;const{block:l,owner:h}=a,d=l.overrides,u=n,f=l.getDefines(),m=Object.keys(f);if(m.length>0){u.defines||(u.defines={});for(const _ of m){const y=f[_];y!==void 0&&(u.defines[_]=y)}}if(d.length===0&&m.length===0)return;let g=m.length>0;u[Ru]||(u[Ru]=[]);const v=u[Ru];for(const _ of d){if(_.value===null)continue;if(u.isMeshBasicMaterial===!0&&(_.name==="envMap"||_.name==="envMapRotation"||_.name==="envMapIntensity")){_.name==="envMap"&&!R0&&(E()||gA)&&(R0=!0,console.warn(`MaterialPropertyBlock: Ignoring envMap override on MeshBasicMaterial (object: "${this.name}", material: "${n.name}"). Use a lit material such as MeshStandardMaterial if reflection probes are intended.`));continue}const y=u[_.name],b=v.find(w=>w.name===_.name);if(b?b.value=y:v.push({name:_.name,value:y}),!g&&!!y!=!!_.value&&(g=!0),u[_.name]=_.value,_.textureTransform&&_.value instanceof c.Texture){const w=_.value;u[Tu]||(u[Tu]=[]),u[Tu].push({name:_.name,offsetX:w.offset.x,offsetY:w.offset.y,repeatX:w.repeat.x,repeatY:w.repeat.y});const C=_.textureTransform;C.offset&&w.offset.copy(C.offset),C.repeat&&w.repeat.copy(C.repeat)}}g&&(u.needsUpdate=!0),u._forceRefresh=!0},A0=function(s,e,t,i,n,o){if(this[tl]===void 0||!this[tl].has(n))return;this[tl].delete(n);const r=A_(this);if(!r)return;const{block:a,owner:l}=r,h=a.overrides,d=n,u=d[Ru],f=a.getDefines(),m=Object.keys(f);let g=!1;if(m.length>0&&d.defines){for(const _ of m)delete d.defines[_];g=!0}if(h.length===0){g&&(d.needsUpdate=!0,d._forceRefresh=!0);return}if(!u)return;const v=d[Tu];if(v&&v.length>0){for(const _ of v){const y=h.find(b=>b.name===_.name);y?.value instanceof c.Texture&&(y.value.offset.set(_.offsetX,_.offsetY),y.value.repeat.set(_.repeatX,_.repeatY))}v.length=0}for(const _ of h){const y=u.find(b=>b.name===_.name);y&&(!g&&!!_.value!=!!y.value&&(g=!0),d[_.name]=y.value)}g&&(d.needsUpdate=!0),d._forceRefresh=!0};function yA(s,e){s.type==="Group"?s.children.forEach(t=>{(t.type==="Mesh"||t.type==="SkinnedMesh")&&D0(t,s,e)}):(s.type==="Mesh"||s.type==="SkinnedMesh")&&D0(s,s,e)}function D0(s,e,t){if(!So.isHooked(s,e)){if(So.addHook(s,e),s["needle:materialPropertyBlock"]=t,!s.onBeforeRender)s.onBeforeRender=T0;else{const i=s.onBeforeRender;s.onBeforeRender=function(n,o,r,a,l,h){i.call(this,n,o,r,a,l,h),T0.call(this,n,o,r,a,l,h)}}if(!s.onAfterRender)s.onAfterRender=A0;else{const i=s.onAfterRender;s.onAfterRender=function(n,o,r,a,l,h){A0.call(this,n,o,r,a,l,h),i.call(this,n,o,r,a,l,h)}}s.onBeforeRenderListPush=pA,s.onAfterRenderListPush=mA}}var _A=Object.defineProperty,bA=Object.getOwnPropertyDescriptor,lp=(s,e,t,i)=>{for(var n=i>1?void 0:i?bA(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&&_A(e,t,n),n};const va=x("debugreflectionprobe"),I0=x("noreflectionprobe");let tr=null;const vA=Symbol("reflectionProbeKey"),$h=class gn extends T{static _probes=new Map;static testBox=new c.Box3;static isUsingReflectionProbe(e){return!!e[vA]}static onEnabled=new Z;static onDisabled=new Z;static get(e,t,i,n){if(!e||e.isObject3D!==!0||I0)return null;const o=gn._probes.get(t);if(o){for(const r of o)if(r.__didAwake||r.__internalAwake(),r.activeAndEnabled){if(n){if(r.gameObject===n)return r}else if(r.isInBox(e))return va&&console.log("Found reflection probe",e.name,r.name),r}}return va&&console.debug("Did not find reflection probe",e.name,i,e),null}_texture;_textureUrlInFlight;set texture(e){if(this._texture!==e){if(typeof e=="string"){va&&console.debug(`[ReflectionProbe] Loading reflection probe texture from URL: ${e}`),this._textureUrlInFlight=e;const t=cs(this.sourceId,e);Bh(t,this.context.renderer).then(i=>{this._textureUrlInFlight===e&&i&&(this._textureUrlInFlight=void 0,va&&console.debug(`[ReflectionProbe] Successfully loaded reflection probe texture: ${e}`),this.texture=i)});return}this.__didAwake&&(this._textureUrlInFlight=void 0),this._texture=e,va&&console.debug("[ReflectionProbe] Set reflection probe texture "+(e?.name||"(removed)")),e&&(e instanceof c.CubeTexture||e.mapping===c.CubeUVReflectionMapping||e.mapping!==c.EquirectangularReflectionMapping&&(e.mapping=c.EquirectangularReflectionMapping),e.colorSpace=c.LinearSRGBColorSpace,e.needsUpdate=!0)}}get texture(){return this._texture}intensity=1;center=new c.Vector3;size=new c.Vector3(1,1,1);__lightmapIntensityScale=!0;isInBox(e){return tr??=new c.Box3,tr.setFromCenterAndSize(this.gameObject.worldPosition.add(this.center),this.size),pi([e],void 0,void 0,gn.testBox),gn.testBox.isEmpty()?tr.containsPoint(e.worldPosition):tr?.intersectsBox(gn.testBox)}constructor(){super(),gn._probes.has(this.context)||gn._probes.set(this.context,[]),gn._probes.get(this.context)?.push(this)}awake(){this._texture&&(this._texture.mapping!==c.CubeUVReflectionMapping&&(this._texture.mapping=c.EquirectangularReflectionMapping),this._texture.colorSpace=c.LinearSRGBColorSpace,this._texture.needsUpdate=!0)}update(){va&&(tr??=new c.Box3,tr.setFromCenterAndSize(this.gameObject.worldPosition.add(this.center),this.size),B.DrawWireBox3(tr,5592320))}onEnable(){gn.onEnabled?.invoke(this)}onDisable(){gn.onDisabled?.invoke(this)}start(){this._texture||console.warn(`[ReflectionProbe] Missing texture. Please assign a custom cubemap texture. To use reflection probes assign them to your renderer's "anchor" property.`)}onDestroy(){const e=gn._probes.get(this.context);if(e){const t=e.indexOf(this);t>=0&&e.splice(t,1)}}apply(e){if(I0||!this.enabled||!this.texture)return;const t=As.get(e);t.setOverride("envMap",this.texture),t.setOverride("envMapRotation",this.gameObject.rotation);let i=this.intensity;this.__lightmapIntensityScale&&t.getOverride("lightMap")&&(i/=Math.PI),t.setOverride("envMapIntensity",i)}unapply(e){const t=As.get(e);t&&t.getOverride("envMap")?.value===this.texture&&(t.removeOverride("envMap"),t.removeOverride("envMapRotation"),t.removeOverride("envMapIntensity"))}};lp([p([c.Texture,String])],$h.prototype,"texture",1);lp([p()],$h.prototype,"intensity",2);lp([p(c.Vector3)],$h.prototype,"center",2);lp([p(c.Vector3)],$h.prototype,"size",2);let Ps=$h;const Mm=x("debugexr");class wA{get name(){return"EXT_texture_exr"}parser;constructor(e){this.parser=e,Mm&&console.log(e)}loadTexture(e){const t=this.name,i=this.parser,o=i.json.textures[e];if(Mm&&console.log("EXT_texture_exr.loadTexture",e,o),!o.extensions||!o.extensions[t])return null;const r=o.extensions[t],a=new V.EXRLoader(i.options.manager);return Mm&&console.log("EXT_texture_exr.loadTexture",r),i.loadTextureImage(e,r.source,a)}}typeof window<"u"&&window.addEventListener("unhandledrejection",s=>{});const Ln=_t,Wd="$___Export_Components",xA="NEEDLE_components";class SA{[cr]}class CA{node;nodeIndex;nodeDef;constructor(e,t,i){this.node=e,this.nodeIndex=t,this.nodeDef=i}}class D_{get name(){return xA}exportContext;objectToNodeMap={};context;writer;registerExport(e){e.register(t=>{if("serializeUserData"in t){const i=t.serializeUserData.bind(t);this.writer=t,t.serializeUserData=(n,o)=>{try{this.serializeUserData(n,o)&&(t.extensionsUsed[this.name]=!0),i(n,o)}finally{this.afterSerializeUserData(n,o)}}}return this})}beforeParse(){this.exportContext={},this.objectToNodeMap={}}serializeUserData(e,t){const i=e.userData?.components;return!i||i.length<=0?!1:(delete e.userData.components,e[Wd]=i,!0)}afterSerializeUserData(e,t){if(e.type==="Scene"&&Ln&&console.log("DONE",JSON.stringify(t)),e[Wd]===void 0)return;const i=e[Wd];delete e[Wd],i!==null&&(e.userData.components=i)}writeNode(e,t){Ln&&console.log(e.name,e.uuid);const i=new CA(e,-1,t);this.exportContext[e.uuid]=i}afterParse(e){Ln&&console.log("AFTER",e);const t=this.writer?.nodeMap;if(t)for(const[n,o]of t)this.objectToNodeMap[n.uuid]=o;for(const n in this.exportContext){const o=this.exportContext[n],r=o.node,a=o.nodeDef,l=t?.get(r)??o.nodeIndex;l===void 0||l<0||this.writeComponentsIntoDef(r,a,l)}const i=this.writer?.json?.scenes;if(i){const n=Array.isArray(e)?e:[e];let o=0;for(const r of n)if(r?.isScene===!0){if(o>=i.length)break;this.writeComponentsIntoDef(r,i[o]),o++}}}writeComponentsIntoDef(e,t,i){const n=e.userData?.components;if(!n||n.length<=0)return;this.context.object=e,this.context.nodeId=i,this.context.objectToNode=this.objectToNodeMap;const o=[];for(const r of n){this.context.target=r;const a=Is().writeBuiltinComponentData(r,this.context);a!==null&&o.push(a)}if(o.length>0){const r=new SA;r[cr]=o,t.extensions=t.extensions||{},t.extensions[this.name]=r,Ln&&console.log("DID WRITE",e,i!==void 0?`nodeIndex ${i}`:"(scene)",o)}}parser;nodeToObjectMap={};gltf=null;beforeRoot(){return Ln&&console.log("BEGIN LOAD"),this.nodeToObjectMap={},null}async afterRoot(e){this.gltf=e;const t=e.parser,i=t?.extensions;if(!i)return;const n=i[this.name];Ln&&console.log("After root",e,this.parser,i);const o=[];if(n===!0){const r=t.json.nodes;if(r){for(let l=0;l<r.length;l++){const h=await t.getDependency("node",l);this.nodeToObjectMap[l]=h}for(let l=0;l<r.length;l++){const h=r[l],d=l,u=h.extensions;if(!u)continue;const f=u[this.name];if(!f)continue;Ln&&console.log("NODE",h);const m=this.nodeToObjectMap[d];if(!m){console.error("Could not find object for node index: "+d,h,t);continue}lh(m),o.push(this.createComponents(e,h,m,f))}}const a=t.json.scenes;if(a)for(let l=0;l<a.length;l++){const h=a[l],d=h?.extensions?.[this.name];if(!d)continue;const u=await t.getDependency("scene",l);if(!u){console.error("Could not find scene for index: "+l,h,t);continue}lh(u),o.push(this.createComponents(e,h,u,d))}}await Promise.all(o);for(const r of t.associations.keys()){const a=t.associations.get(r);if(a?.materials!=null){const l="/materials/"+a.materials;xM(r,l)}}}async createComponents(e,t,i,n){if(!n)return;const o=n[cr];if(o){const r=new Array;Ln&&console.log(i.name,o);for(const a in o){const l=o[a];if(Ln&&console.log("Serialized data",JSON.parse(JSON.stringify(l))),(l?.name==="MeshRenderer"||l?.name==="SkinnedMeshRenderer")&&!l.sharedMaterials){let h=!1;if("mesh"in t){const d=t.mesh;if(typeof d=="number"&&e.parser){const u=e.parser.json.meshes?.[d];u?.primitives&&(l.sharedMaterials=u.primitives.map(f=>"/materials/"+(f.material??0)),h=!0)}}!h&&(Ln||E())&&console.warn(`[NEEDLE_components] Component '${l.name}' on object '${i.name}' is not added to a mesh or failed to retrieve materials from glTF.`)}l&&this.parser&&r.push(Gy(this.parser,l).catch(h=>console.error(`Error while resolving references (see console for details)
|
|
1087
|
-
`,h,i,l))),i.userData=i.userData||{},i.userData[cr]=i.userData[cr]||[],i.userData[cr].push(l)}await Promise.all(r).catch(a=>{console.error("Error while loading components",a)})}}}const L0="NEEDLE_gameobject_data",PA={Default:0,"Ignore Raycast":2},Gd=new Map,Om=8,Hd=31;function kA(s){if(typeof s=="number"&&isFinite(s))return s;if(typeof s=="string"&&s.length>0){const e=PA[s];if(e!==void 0)return e;let t=Gd.get(s);return t===void 0&&(t=Math.min(Om+Gd.size,Hd),Om+Gd.size>Hd&&console.warn(`[NEEDLE_gameobject_data] more than ${Hd-Om+1} named layers — "${s}" shares index ${Hd}`),Gd.set(s,t)),t}return 0}class MA{get name(){return L0}parser;constructor(e){this.parser=e}afterRoot(e){const t=[];for(let i=0;i<this.parser.json.nodes?.length;i++){const n=this.parser.json.nodes[i];if(n&&n.extensions){const o=n.extensions[L0];if(o){const r=this.findAndApplyExtensionData(i,o);t.push(r)}}}return Promise.all(t).then(()=>null)}async findAndApplyExtensionData(e,t){const i=await this.parser.getDependency("node",e);i&&this.applyExtensionData(i,t)}applyExtensionData(e,t){t.layers===void 0&&(t.layers=0),e.userData.layer=t.layers,e.layers.disableAll(),e.layers.set(kA(t.layers)),e.userData.tag=t.tag??"none",e.hideFlags=0,e.userData.static=t.static??!1,e.visible=t.activeSelf??!0,e.guid=t.guid}}const B0="NEEDLE_lighting_settings",Aa=x("debugenvlight");class OA{get name(){return B0}parser;sourceId;context;constructor(e,t,i){this.parser=e,this.sourceId=t,this.context=i}afterRoot(e){const t=this.parser.json.extensions;if(t){const i=t[B0];if(i){Aa&&console.log('Loaded "'+this.name+'", src: "'+this.sourceId+'"',i);let n;if(e.scene.children.length===1){const o=e.scene.children[0];n=P.addComponent(o,ff,{},{callAwake:!1})}else{const o=new c.Object3D;o.name="LightSettings "+this.sourceId,e.scene.add(o),n=P.addComponent(o,ff,{},{callAwake:!1})}n.sourceId=this.sourceId,n.ambientIntensity=i.ambientIntensity,n.ambientLight=new c.Color().fromArray(i.ambientLight),Array.isArray(i.ambientTrilight)&&(n.ambientTrilight=i.ambientTrilight.map(o=>new c.Color().fromArray(o))),n.ambientMode=i.ambientMode,n.environmentReflectionSource=i.environmentReflectionSource}}return null}}se.registerCallback(ae.ContextCreated,s=>{const e=s.context,t=P.findObjectOfType(ff,e);t?.sourceId&&(t.enabled=!0)});class ff extends T{ambientMode=Ya.Skybox;ambientLight;ambientTrilight;ambientIntensity=1;environmentReflectionSource=Ju.Skybox;_hasReflection=!1;_ambientLightObj;_hemisphereLightObj;awake(){if(this.sourceId){const t=this.environmentReflectionSource===Ju.Skybox?$n.Skybox:$n.Reflection,i=this.context.lightmaps.tryGet(this.sourceId,t,0);this._hasReflection=i!=null,i&&this.context.sceneLighting.internalRegisterReflection(this.sourceId,i)}this.enabled=!1,this.context.sceneLighting.internalRegisterSceneLightSettings(this),Aa&&window.addEventListener("keydown",t=>{this.destroyed||t.key==="l"&&(this.enabled=!this.enabled)});const e=this.gameObject.userData?.components;if(e){const t=e.indexOf(this);e.splice(t,1),e.push(this)}}onDestroy(){this.context.sceneLighting.internalUnregisterSceneLightSettings(this)}calculateIntensityFactor(e){const t=Math.max(e.r,e.g,e.b);return 2.2*L.lerp(0,1.33,t)}onEnable(){if(Aa&&console.warn("💡🟡 >>> Enable lighting",this.sourceId,this.enabled,this),this.ambientMode==Ya.Flat){if(this.ambientLight&&!this._ambientLightObj){const e=this.calculateIntensityFactor(this.ambientLight);this._ambientLightObj=new c.AmbientLight(this.ambientLight,this.ambientIntensity*e),Aa&&console.log("Created ambient light",this.sourceId,this._ambientLightObj,this.ambientIntensity,e)}this._ambientLightObj&&this.gameObject.add(this._ambientLightObj)}else if(this.ambientMode===Ya.Trilight){if(this.ambientTrilight){const e=this.ambientTrilight[0],t=this.ambientTrilight[this.ambientTrilight.length-1],i=this.calculateIntensityFactor(t);this._hemisphereLightObj=new c.HemisphereLight(t,e,this.ambientIntensity*i),this.gameObject.add(this._hemisphereLightObj),Aa&&console.log("Created hemisphere ambient light",this.sourceId,this._hemisphereLightObj,this.ambientIntensity,i)}}else this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._hemisphereLightObj&&this._hemisphereLightObj.removeFromParent();this.sourceId&&(this.context.domElement.getAttribute("environment-image")||this.context.sceneLighting.internalEnableReflection(this.sourceId))}onDisable(){Aa&&console.warn("💡⚫ <<< Disable lighting:",this.sourceId,this),this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._hemisphereLightObj&&this._hemisphereLightObj.removeFromParent(),this.sourceId&&this.context.sceneLighting.internalDisableReflection(this.sourceId)}}exports.MaterialX=void 0;(s=>{async function e(t,i){if(!t)throw new Error("URL or XML string is required to load a MaterialX material");const n=await A.MaterialX.load(),o=t.trimStart().startsWith("<"),r=o?t:await fetch(t).then(h=>h.text()).catch(console.error);if(!r)return console.warn("Failed to load MaterialX file from url",t),null;let a;if(i?.url||!o){const h=(i?.url||t).split("/");h.pop(),a=h.join("/")}const l=new c.TextureLoader;return n.Experimental_API.createMaterialXMaterial(r,i?.materialNameOrIndex??0,{getTexture:async h=>(!h.startsWith("http")&&!h.startsWith("data:")&&!h.startsWith("blob:")&&!h.startsWith("file:")&&a&&(h=a+"/"+h),l.loadAsync(h).catch(d=>{console.warn(`Failed to load texture for MaterialX material ${h}`,d)}))},{cacheKey:t})}s.loadFromUrl=e})(exports.MaterialX||(exports.MaterialX={}));class EA extends c.Loader{loadAsync(e,t){return new Promise((i,n)=>{this.load(e,i,t,n)})}load(e,t,i,n){i?.({type:"progress",loaded:0,total:0}),exports.MaterialX.loadFromUrl(e,{}).then(o=>{o?t(this.onLoaded(o)):n?.(new Error("Failed to load MaterialX material from url: "+e))})}onLoaded(e){return jo.createPrimitive("ShaderBall",{material:e})}}class RA{constructor(e,t,i,n){this.context=e,this.url=i,this.parser=n}context;url;parser;get name(){return"materialx-loading-helper"}mtlxLoader;async beforeRoot(){if(this.parser.json.extensions?.NEEDLE_materials_mtlx){const t=await A.MaterialX.load();try{this.mtlxLoader=new t.MaterialXLoader(this.parser,{cacheKey:`${this.url}:materialx`,parameters:{precision:this.context.renderer?.capabilities.precision}},{getFrame:()=>this.context.time.frame,getTime:()=>this.context.time.time})}catch(i){console.error(i)}}}loadMaterial(e){return this.mtlxLoader?this.mtlxLoader.loadMaterial(e):null}}var kC=(s=>(s[s.INT=5124]="INT",s[s.FLOAT=5126]="FLOAT",s[s.FLOAT_VEC2=35664]="FLOAT_VEC2",s[s.FLOAT_VEC3=35665]="FLOAT_VEC3",s[s.FLOAT_VEC4=35666]="FLOAT_VEC4",s[s.INT_VEC2=35667]="INT_VEC2",s[s.INT_VEC3=35668]="INT_VEC3",s[s.INT_VEC4=35669]="INT_VEC4",s[s.BOOL=35670]="BOOL",s[s.BOOL_VEC2=35671]="BOOL_VEC2",s[s.BOOL_VEC3=35672]="BOOL_VEC3",s[s.BOOL_VEC4=35673]="BOOL_VEC4",s[s.FLOAT_MAT2=35674]="FLOAT_MAT2",s[s.FLOAT_MAT3=35675]="FLOAT_MAT3",s[s.FLOAT_MAT4=35676]="FLOAT_MAT4",s[s.SAMPLER_2D=35678]="SAMPLER_2D",s[s.SAMPLER_3D=35680]="SAMPLER_3D",s[s.SAMPLER_CUBE=35681]="SAMPLER_CUBE",s[s.UNKNOWN=0]="UNKNOWN",s))(kC||{});const Un=x("debugcustomshader"),wa="NEEDLE_techniques_webgl";class TA{objectToWorldMatrix=new c.Matrix4;worldToObjectMatrix=new c.Matrix4;objectToWorld=new Array;worldToObject=new Array;updateFrom(e){this.objectToWorldMatrix.copy(e.matrixWorld),Zu(this.objectToWorldMatrix,this.objectToWorld),this.worldToObjectMatrix.copy(e.matrixWorld).invert(),Zu(this.worldToObjectMatrix,this.worldToObject)}}class Me extends c.RawShaderMaterial{identifier;onBeforeRenderSceneCallback=this.onBeforeRenderScene.bind(this);clone(){const e=super.clone();return MC(e),e}constructor(e,...t){super(...t),this.identifier=e,Un&&console.log(this),this.type="NEEDLE_CUSTOM_SHADER",this.uniforms[this._objToWorldName]||(this.uniforms[this._objToWorldName]={value:[]}),this.uniforms[this._worldToObjectName]||(this.uniforms[this._worldToObjectName]={value:[]}),this.uniforms[this._viewProjectionName]||(this.uniforms[this._viewProjectionName]={value:[]}),this.uniforms[this._sphericalHarmonicsName],(this.depthTextureUniform||this.opaqueTextureUniform)&&X.Current.pre_render_callbacks.push(this.onBeforeRenderSceneCallback)}dispose(){super.dispose();const e=X.Current.pre_render_callbacks.indexOf(this.onBeforeRenderSceneCallback);e>=0&&X.Current.pre_render_callbacks.splice(e,1)}_sphericalHarmonicsName="unity_SpecCube0";_objToWorldName="hlslcc_mtx4x4unity_ObjectToWorld";_worldToObjectName="hlslcc_mtx4x4unity_WorldToObject";static viewProjection=new c.Matrix4;static _viewProjectionValues=[];_viewProjectionName="hlslcc_mtx4x4unity_MatrixVP";static viewMatrix=new c.Matrix4;static _viewMatrixValues=[];_viewMatrixName="hlslcc_mtx4x4unity_MatrixV";static _worldSpaceCameraPosName="_WorldSpaceCameraPos";static _worldSpaceCameraPos=new c.Vector3;static _mainLightColor=new c.Vector4;static _mainLightPosition=new c.Vector3;static _lightData=new c.Vector4;_rendererData=new TA;get depthTextureUniform(){if(this.uniforms)return this.uniforms._CameraDepthTexture}get opaqueTextureUniform(){if(this.uniforms)return this.uniforms._CameraOpaqueTexture}onBeforeRenderScene(){this.opaqueTextureUniform&&X.Current.setRequireColor(!0),this.depthTextureUniform&&X.Current.setRequireDepth(!0)}onBeforeRender(e,t,i,n,o,r){n.attributes.tangent||n.computeTangents(),this.onUpdateUniforms(i,o)}onUpdateUniforms(e,t){const i=X.Current;if(e&&(Me.viewProjection&&this.uniforms[this._viewProjectionName]&&(Me.viewProjection.copy(e.projectionMatrix).multiply(e.matrixWorldInverse),Zu(Me.viewProjection,Me._viewProjectionValues)),Me.viewMatrix&&this.uniforms[this._viewMatrixName]&&(Me.viewMatrix.copy(e.matrixWorldInverse),Zu(Me.viewMatrix,Me._viewMatrixValues)),this.uniforms[Me._worldSpaceCameraPosName]&&Me._worldSpaceCameraPos.setFromMatrixPosition(e.matrixWorld)),this.uniforms._TimeParameters&&(this.uniforms._TimeParameters.value=i.sceneLighting.timeVec4),this.uniforms._Time){const a=this.uniforms._Time.value;a.x=i.sceneLighting.timeVec4.x/20,a.y=i.sceneLighting.timeVec4.x,a.z=i.sceneLighting.timeVec4.x*2,a.w=i.sceneLighting.timeVec4.x*3}if(this.uniforms._SinTime){const a=this.uniforms._SinTime.value;a.x=Math.sin(i.sceneLighting.timeVec4.x/8),a.y=Math.sin(i.sceneLighting.timeVec4.x/4),a.z=Math.sin(i.sceneLighting.timeVec4.x/2),a.w=Math.sin(i.sceneLighting.timeVec4.x)}if(this.uniforms._CosTime){const a=this.uniforms._CosTime.value;a.x=Math.cos(i.sceneLighting.timeVec4.x/8),a.y=Math.cos(i.sceneLighting.timeVec4.x/4),a.z=Math.cos(i.sceneLighting.timeVec4.x/2),a.w=Math.cos(i.sceneLighting.timeVec4.x)}if(this.uniforms.unity_DeltaTime){const a=this.uniforms.unity_DeltaTime.value;a.x=i.time.deltaTime,a.y=1/i.time.deltaTime,a.z=i.time.smoothedDeltaTime,a.w=1/i.time.smoothedDeltaTime}const n=i.mainLight;if(n){const a=ie(n.gameObject,Me._mainLightPosition);this.uniforms._MainLightPosition={value:a.normalize()},Me._mainLightColor.set(n.color.r,n.color.g,n.color.b,0),this.uniforms._MainLightColor={value:Me._mainLightColor};const l=n.intensity;Me._lightData.z=l,this.uniforms.unity_LightData={value:Me._lightData}}if(e&&(Me.viewProjection&&this.uniforms[this._viewProjectionName]&&(this.uniforms[this._viewProjectionName].value=Me._viewProjectionValues),Me.viewMatrix&&this.uniforms[this._viewMatrixName]&&(this.uniforms[this._viewMatrixName].value=Me._viewMatrixValues),this.uniforms[Me._worldSpaceCameraPosName]&&(this.uniforms[Me._worldSpaceCameraPosName]={value:Me._worldSpaceCameraPos}),i.mainCameraComponent)){if(this.uniforms._ProjectionParams){const a=this.uniforms._ProjectionParams.value;a.x=1,a.y=i.mainCameraComponent.nearClipPlane,a.z=i.mainCameraComponent.farClipPlane,a.w=1/a.z,this.uniforms._ProjectionParams.value=a}if(this.uniforms._ZBufferParams){const a=this.uniforms._ZBufferParams.value,l=i.mainCameraComponent;a.x=1-l.farClipPlane/l.nearClipPlane,a.y=l.farClipPlane/l.nearClipPlane,a.z=a.x/l.farClipPlane,a.w=a.y/l.farClipPlane,this.uniforms._ZBufferParams.value=a}if(this.uniforms._ScreenParams){const a=this.uniforms._ScreenParams.value;a.x=i.domWidth,a.y=i.domHeight,a.z=1+1/a.x,a.w=1+1/a.y,this.uniforms._ScreenParams.value=a}if(this.uniforms._ScaledScreenParams){const a=this.uniforms._ScaledScreenParams.value;a.x=i.domWidth,a.y=i.domHeight,a.z=1+1/a.x,a.w=1+1/a.y,this.uniforms._ScaledScreenParams.value=a}}const o=this.depthTextureUniform;o&&(o.value=i.depthTexture);const r=this.opaqueTextureUniform;if(r&&(r.value=i.opaqueColorTexture),t){const a=this._rendererData;a.updateFrom(t),this.uniforms[this._worldToObjectName].value=a.worldToObject,this.uniforms[this._objToWorldName].value=a.objectToWorld}this.uniformsNeedUpdate=!0}}class AA{get name(){return wa}parser;identifier;constructor(e,t){this.parser=e,this.identifier=t}loadMaterial(e){const t=this.parser.json.materials[e];if(!t)return Un&&console.log(e,this.parser.json.materials),null;if(!t.extensions||!t.extensions[wa])return Un&&console.log(`Material ${e} does not use NEEDLE_techniques_webgl`),null;Un&&console.log(`Material ${e} uses NEEDLE_techniques_webgl`,t);const i=t.extensions[wa].technique;if(i<0)return console.debug(`Material ${e} does not have a valid technique index`),null;const n=this.parser.json.extensions[wa];if(!n)return Un?console.error("Missing shader data",this.parser.json.extensions):console.debug("Missing custom shader data in parser.json.extensions"),null;Un&&console.log(n);const o=n.techniques[i];return o?new Promise(async(r,a)=>{const l=await sO(n,o.program),h=l?.fragmentShader,d=l?.vertexShader;if(!h||!d)return a();Un&&console.log("loadMaterial",t,l);const u={},f=o.uniforms;(d.includes("_Time")||h.includes("_Time"))&&(u._Time={value:new c.Vector4(0,0,0,0)}),(d.includes("_SinTime")||h.includes("_SinTime"))&&(u._SinTime={value:new c.Vector4(0,0,0,0)}),(d.includes("_CosTime")||h.includes("_CosTime"))&&(u._CosTime={value:new c.Vector4(0,0,0,0)}),(d.includes("unity_DeltaTime")||h.includes("unity_DeltaTime"))&&(u.unity_DeltaTime={value:new c.Vector4(0,0,0,0)});for(const y in f){const b=y;switch(b){case"_TimeParameters":const w=new c.Vector4;u[b]={value:w};break;case"hlslcc_mtx4x4unity_MatrixV":case"hlslcc_mtx4x4unity_MatrixVP":u[b]={value:[]};break;case"_MainLightPosition":case"_MainLightColor":case"_WorldSpaceCameraPos":u[b]={value:[0,0,0,1]};break;case"unity_OrthoParams":break;case"unity_SpecCube0":u[b]={value:null};break;default:case"_ScreenParams":case"_ZBufferParams":case"_ProjectionParams":u[b]={value:[0,0,0,0]};break;case"_CameraOpaqueTexture":case"_CameraDepthTexture":u[b]={value:null};break}}let m=!1;if(t.extensions&&t.extensions[wa]){const y=t.extensions[wa];if(y.technique===i){Un&&console.log(t.name,"Material Properties",y);for(const b in y.values){const w=y.values[b];if(typeof w=="string"){if(w.startsWith("/textures/")){const C=w.substring(10),k=Number.parseInt(C);if(k>=0){const O=await this.parser.getDependency("texture",k);O instanceof c.Texture&&(O.colorSpace=c.LinearSRGBColorSpace,O.needsUpdate=!0),u[b]={value:O};continue}}if(b==="alphaMode"){w==="BLEND"&&(m=!0);continue}}if(Array.isArray(w)&&w.length===4){u[b]={value:new c.Vector4(w[0],w[1],w[2],w[3])};continue}u[b]={value:w}}}}const g=new Me(this.identifier,{name:t.name??"",uniforms:u,vertexShader:d,fragmentShader:h,lights:!1});switch(g.glslVersion=c.GLSL3,g.vertexShader=g.vertexShader.replace("#version 300 es",""),g.fragmentShader=g.fragmentShader.replace("#version 300 es",""),u._Cull?.value){case 0:g.side=c.DoubleSide;break;case 1:g.side=c.BackSide;break;case 2:g.side=c.FrontSide;break;default:g.side=c.FrontSide;break}switch(u._ZTest?.value){case 3:g.depthTest=!0,g.depthFunc=c.EqualDepth;break;case 6:g.depthTest=!0,g.depthFunc=c.NotEqualDepth;break;case 2:g.depthTest=!0,g.depthFunc=c.LessDepth;break;case 4:g.depthTest=!0,g.depthFunc=c.LessEqualDepth;break;case 5:g.depthTest=!0,g.depthFunc=c.GreaterDepth;break;case 7:g.depthTest=!0,g.depthFunc=c.GreaterEqualDepth;break;case 8:g.depthTest=!1,g.depthFunc=c.AlwaysDepth;break}g.transparent=m,m&&(g.depthWrite=!1),iO(u),g.onUpdateUniforms();for(const y in f){const b=y,w=f[y].type;u[b]?.value===void 0&&(w===kC.SAMPLER_2D?(u[b]={value:eO},console.warn("Missing/unassigned texture, fallback to white: "+b)):b==="unity_OrthoParams"||console.warn("TODO: EXPECTED UNIFORM / fallback NOT SET: "+b,f[y]))}Un&&console.log(g.uuid,u),MC(g),r(g)}):null}}function MC(s){if(s.uniforms){Un&&console.log("Uniforms:",s.uniforms);for(const t in s.uniforms)switch(e(t,t),t){case"_Color":e("color",t);break;case"_map":e("map",t);break}}function e(t,i){Object.getOwnPropertyDescriptor(s,t)||Object.defineProperty(s,t,{get:()=>s.uniforms[i].value,set:n=>{s.uniforms[i].value=n,s.needsUpdate=!0}})}}const DA=x("debugextensions");let pf;const IA=Promise.resolve().then(()=>require("./vendor-BJviq-Oq.umd.cjs")).then(s=>s.index$2).then(async s=>(pf=s.GLTFAnimationPointerExtension,pf)).catch(s=>{console.warn("Failed to import GLTFLoaderAnimationPointer. Please use @needle-tools/three-animationpointer for full KHR_animation support",s)}),Fr=new Array;function LA(s){Fr.includes(s)||Fr.push(s)}function BA(s){const e=Fr.indexOf(s);e>=0&&Fr.splice(e,1)}function I_(s){if(s instanceof V.GLTFLoader){const e=new D_;return s.register(t=>(e.parser=t,e)),e}return null}class FA{resolvePath(e){return e.includes("/extensions/builtin_components/")?e.replace("/extensions/builtin_components/","/userData/components/"):e.includes("extensions/builtin_components/")?e.replace("extensions/builtin_components/","/userData/components/"):e}}async function mf(s,e,t,i){const n=t.indexOf("?");n>=0&&(t=t.substring(0,n)),i||(i=t),(i.startsWith("blob:")||i.startsWith("data:"))&&console.debug("[GLTFLoader] Suspicious sourceId detected"),s.register(o=>new MA(o)),s.register(o=>new CM(o)),s.register(o=>new $M(o,e.lightmaps,i)),s.register(o=>new OA(o,i,e)),s.register(o=>new AA(o,i)),s.register(o=>new bo(o,i)),s.register(o=>new re.NEEDLE_progressive(o)),s.register(o=>new wA(o)),s.register(o=>new Bf(o)),s.register(o=>new RA(e,s,t,o)),kS()&&s.register(o=>new Za(o)),await IA.catch(o=>{}),s.register(o=>{if(pf){const r=new pf(o);return r.setAnimationPointerResolver.bind(r)(new FA),r}else return(DA||E())&&console.error("Missing KHR_animation_pointer extension..."),{name:"KHR_animation_pointer_NOT_AVAILABLE"}});for(const o of Fr)o.onImport&&o.onImport(s,t,e)}function L_(s,e){for(const t of Fr)t.onExport&&t.onExport(s,e)}function OC(s,e,t){for(const i of Fr)i.onLoaded&&i.onLoaded(s,e,t)}const gt=x("debuginstancing"),jA=gt==="lods",Em=x("debugprogressive")==="colors"||jA;function ry(s,e,t,i){return s.lodsManager.manager?.trackLoadingPromise(e,t,i),i}function EC(s){return s.determinant()<0}class jr{static instance=new jr;static getStartInstanceCount=e=>4;objs=[];setup(e,t,i,n,o,r=0){e.applySettings(t);const a=this.tryCreateOrAddInstance(t,i,o);if(a){n===null&&(n=[]),n.push(a);const l=a.object.material;Array.isArray(l)?l.forEach(h=>ry(i,"texture",h,re.NEEDLE_progressive.assignTextureLOD(h,0))):ry(i,"texture",l,re.NEEDLE_progressive.assignTextureLOD(l,0))}else if(r<=0&&t.type!=="Mesh"){const l=r+1;for(const h of t.children)n=this.setup(e,h,i,n,o,l)}return r===0&&o.useMatrixWorldAutoUpdate&&n&&n.length>=0&&this.autoUpdateInstanceMatrix(t),n}tryCreateOrAddInstance(e,t,i){if(e.type==="Mesh"){const n=i.foundMeshes;if(i.foundMeshes+=1,!i.rend.enableInstancing)return null;if(i.rend.enableInstancing!==!0){if(n>=i.rend.enableInstancing.length)return gt&&console.error("Something is wrong with instance setup",e,i.rend.enableInstancing,n),null;if(!i.rend.enableInstancing[n])return null}const o=e,r=o.geometry,a=o.material;if(Array.isArray(a))return null;o.updateWorldMatrix(!0,!1);const l=EC(o.matrixWorld);for(const m of this.objs){if(!m.canAdd(r,a,l))continue;return m.addInstance(o,r)}let h=jr.getStartInstanceCount(e);(!h||h<0)&&(h=4);let d=e.name;d?.length||(d=Dw());const u=new fo(d,r,a,h,t,l);return this.objs.push(u),u.addInstance(o,r)}return null}autoUpdateInstanceMatrix(e){const t=e.matrixWorld.multiplyMatrices.bind(e.matrixWorld),i=e.matrixWorld.clone(),n=(o,r)=>{const a=t(o,r);return(e[rh]||i.equals(a)===!1)&&(i.copy(a),e[rh]=!0),a};e.matrixWorld.multiplyMatrices=n}}class Rr{static all=[];get name(){return this.object.name}get isActive(){return this.__instanceIndex>=0}get vertexCount(){return this.geometry.attributes.position.count}get maxVertexCount(){return Math.max(this.meshInformation.vertexCount,this.vertexCount)}get reservedVertexCount(){return this.__reservedVertexRange}get indexCount(){return this.geometry.index?this.geometry.index.count:0}get maxIndexCount(){return Math.max(this.meshInformation.indexCount,this.indexCount)}get reservedIndexCount(){return this.__reservedIndexRange}object;_geometry;get geometry(){return this._geometry}renderer;__instanceIndex=-1;__reservedVertexRange=0;__reservedIndexRange=0;__geometryIndex=-1;meshInformation;currentMeshLOD;pendingMeshLOD;constructor(e,t,i=e.geometry){this.__instanceIndex=-1,this.object=e,this._geometry=i,this.renderer=t,this.currentMeshLOD=i.userData?.LODS?.level,e[TS]=t,this.meshInformation=dr(e.geometry),Rr.all.push(this)}updateMeshInformation(){const e=dr(this.geometry),t=this.meshInformation.vertexCount,i=this.meshInformation.indexCount;return Object.assign(this.meshInformation,e),t!==this.meshInformation.vertexCount||i!==this.meshInformation.indexCount}updateInstanceMatrix(e=!1,t=!0){this.__instanceIndex<0||(t&&this.object.updateWorldMatrix(!0,e),this.assertMirroringUnchanged(),this.renderer.updateInstance(this.object.matrixWorld,this.__instanceIndex))}_didWarnAboutMirroringChange=!1;assertMirroringUnchanged(){this._didWarnAboutMirroringChange||EC(this.object.matrixWorld)!==this.renderer.mirrored&&(this._didWarnAboutMirroringChange=!0,console.warn(`[Instancing] "${this.name}" changed its mirroring at runtime (world matrix determinant flipped sign). Instanced objects can not change mirroring - this object will render its backfaces. Disable instancing for it via Renderer.setInstanced(obj, false).`))}setMatrix(e){this.__instanceIndex<0||this.renderer.updateInstance(e,this.__instanceIndex)}setGeometry(e){if(this.__geometryIndex<0)return!1;if(this._geometry!==e){const n=this.__instanceIndex>=0;return n&&this.renderer.remove(this,!1),this._geometry=e,this.updateMeshInformation(),n?this.renderer.add(this):!0}this._geometry=e;const t=this;if(this.vertexCount>this.__reservedVertexRange)return i(`Instancing: Can not update geometry (${this.name}), reserved vertex range is too small: ${this.__reservedVertexRange.toLocaleString()} < ${this.vertexCount.toLocaleString()} vertices for ${this.name}`);if(this.indexCount>this.__reservedIndexRange)return i(`Instancing: Can not update geometry (${this.name}), reserved index range is too small: ${this.__reservedIndexRange.toLocaleString()} < ${this.indexCount.toLocaleString()} indices for ${this.name}`);return this.renderer.updateGeometry(e,this.__geometryIndex);function i(n){return t.updateMeshInformation()&&(t.renderer.remove(t,!0),t.renderer.add(t))?!0:((E()||gt)&&console.error(n),!1)}}add(){this.__instanceIndex>=0||(this.renderer.add(this),P.markAsInstancedRendered(this.object,!0))}remove(e){if(!(this.__instanceIndex<0)&&(this.renderer.remove(this,e),P.markAsInstancedRendered(this.object,!1),e)){const t=Rr.all.indexOf(this);t>=0&&Rr.all.splice(t,1)}}}class fo{get batchedMesh(){return this._batchedMesh}get mirrored(){return this._mirrored}get visible(){return this._batchedMesh.visible}set visible(e){this._batchedMesh.visible=e}get castShadow(){return this._batchedMesh.castShadow}set castShadow(e){this._batchedMesh.castShadow=e}set receiveShadow(e){this._batchedMesh.receiveShadow=e}allowResize=!0;name="";geometry;material;get count(){return this._currentInstanceCount}updateBounds(e=!0,t=!0){if(this._needUpdateBounds=!1,e&&this._batchedMesh.computeBoundingBox(),t&&this._batchedMesh.computeBoundingSphere(),gt&&this._batchedMesh.boundingSphere){const i=fo.debugBoundsSphere.copy(this._batchedMesh.boundingSphere).applyMatrix4(this._batchedMesh.matrixWorld);B.DrawWireSphere(i.center,i.radius,65280)}}_context;_batchedMesh;_mirrored;_handles=[];_geometryIds=new WeakMap;_maxInstanceCount;_currentInstanceCount=0;_currentVertexCount=0;_currentIndexCount=0;_maxVertexCount;_maxIndexCount;static instanceMatrix=new c.Matrix4;static lodProjectionScreenMatrix=new c.Matrix4;static debugBoundsSphere=new c.Sphere;static debugLODColor=new c.Color;static lodSelectionResult={level:-1,primitiveIndex:0,screenCoverage:0,screenspaceVolume:new c.Vector3,centrality:1};canAdd(e,t,i){return this._maxVertexCount>1e7||this._mirrored!==i||t!==this.material||!this.validateGeometry(e)?!1:!!(!this.mustGrow(e)||this.allowResize)}_needUpdateBounds=!1;_debugMaterial=null;getBatchedMeshName(){return this.name?`${this.name} (BatchedMesh)`:"BatchedMesh"}constructor(e,t,i,n,o,r=!1){this.name=e,this.geometry=t,this.material=i,this._context=o,this._mirrored=r,this._maxInstanceCount=Math.max(2,n),gt&&(this._debugMaterial=F0(Em));const a=this.tryEstimateVertexCountSize(this._maxInstanceCount,[t],n);this._maxVertexCount=a.vertexCount,this._maxIndexCount=a.indexCount,this._batchedMesh=new c.BatchedMesh(this._maxInstanceCount,this._maxVertexCount,this._maxIndexCount,this._debugMaterial??this.material),this._batchedMesh.name=this.getBatchedMeshName(),this.applyBatchTransform(this._batchedMesh),this._batchedMesh[Cc]=!0,this._batchedMesh.visible=!0,this._context.scene.add(this._batchedMesh),i instanceof c.RawShaderMaterial&&(i.defines.USE_INSTANCING=!0,i.needsUpdate=!0),o.pre_render_callbacks.push(this.onBeforeRender),o.post_render_callbacks.push(this.onAfterRender),gt&&console.log(`Instanced renderer (${this.name}) created with ${this._maxInstanceCount} instances, ${this._maxVertexCount} max vertices and ${this._maxIndexCount} max indices for "${e}"`)}dispose(){gt&&console.warn("Dispose instanced renderer",this.name),this._context.scene.remove(this._batchedMesh),this._batchedMesh.dispose(),this._batchedMesh=null,this._handles=[]}addInstance(e,t){const i=new Rr(e,this,t);e.castShadow===!0&&this._batchedMesh.castShadow===!1&&(this._batchedMesh.castShadow=!0),e.receiveShadow===!0&&this._batchedMesh.receiveShadow===!1&&(this._batchedMesh.receiveShadow=!0);try{this.add(i)}catch(n){if(console.error(`Failed adding mesh to instancing (object name: "${e.name}", instances: ${this._currentInstanceCount.toLocaleString()}/${this._maxInstanceCount.toLocaleString()}, vertices: ${this._currentVertexCount.toLocaleString()}/${this._maxVertexCount.toLocaleString()}, indices: ${this._currentIndexCount.toLocaleString()}/${this._maxIndexCount.toLocaleString()})
|
|
1087
|
+
`,h,i,l))),i.userData=i.userData||{},i.userData[cr]=i.userData[cr]||[],i.userData[cr].push(l)}await Promise.all(r).catch(a=>{console.error("Error while loading components",a)})}}}const L0="NEEDLE_gameobject_data",PA={Default:0,"Ignore Raycast":2},Gd=new Map,Om=8,Hd=31;function kA(s){if(typeof s=="number"&&isFinite(s))return s;if(typeof s=="string"&&s.length>0){const e=PA[s];if(e!==void 0)return e;let t=Gd.get(s);return t===void 0&&(t=Math.min(Om+Gd.size,Hd),Om+Gd.size>Hd&&console.warn(`[NEEDLE_gameobject_data] more than ${Hd-Om+1} named layers — "${s}" shares index ${Hd}`),Gd.set(s,t)),t}return 0}class MA{get name(){return L0}parser;constructor(e){this.parser=e}afterRoot(e){const t=[];for(let i=0;i<this.parser.json.nodes?.length;i++){const n=this.parser.json.nodes[i];if(n&&n.extensions){const o=n.extensions[L0];if(o){const r=this.findAndApplyExtensionData(i,o);t.push(r)}}}return Promise.all(t).then(()=>null)}async findAndApplyExtensionData(e,t){const i=await this.parser.getDependency("node",e);i&&this.applyExtensionData(i,t)}applyExtensionData(e,t){t.layers===void 0&&(t.layers=0),e.userData.layer=t.layers,e.layers.disableAll(),e.layers.set(kA(t.layers)),e.userData.tag=t.tag??"none",e.hideFlags=0,e.userData.static=t.static??!1,e.visible=t.activeSelf??!0,e.guid=t.guid}}const B0="NEEDLE_lighting_settings",Aa=x("debugenvlight");class OA{get name(){return B0}parser;sourceId;context;constructor(e,t,i){this.parser=e,this.sourceId=t,this.context=i}afterRoot(e){const t=this.parser.json.extensions;if(t){const i=t[B0];if(i){Aa&&console.log('Loaded "'+this.name+'", src: "'+this.sourceId+'"',i);let n;if(e.scene.children.length===1){const o=e.scene.children[0];n=P.addComponent(o,ff,{},{callAwake:!1})}else{const o=new c.Object3D;o.name="LightSettings "+this.sourceId,e.scene.add(o),n=P.addComponent(o,ff,{},{callAwake:!1})}n.sourceId=this.sourceId,n.ambientIntensity=i.ambientIntensity,n.ambientLight=new c.Color().fromArray(i.ambientLight),Array.isArray(i.ambientTrilight)&&(n.ambientTrilight=i.ambientTrilight.map(o=>new c.Color().fromArray(o))),n.ambientMode=i.ambientMode,n.environmentReflectionSource=i.environmentReflectionSource}}return null}}se.registerCallback(ae.ContextCreated,s=>{const e=s.context,t=P.findObjectOfType(ff,e);t?.sourceId&&(t.enabled=!0)});class ff extends T{ambientMode=Ya.Skybox;ambientLight;ambientTrilight;ambientIntensity=1;environmentReflectionSource=Ju.Skybox;_hasReflection=!1;_ambientLightObj;_hemisphereLightObj;awake(){if(this.sourceId){const t=this.environmentReflectionSource===Ju.Skybox?$n.Skybox:$n.Reflection,i=this.context.lightmaps.tryGet(this.sourceId,t,0);this._hasReflection=i!=null,i&&this.context.sceneLighting.internalRegisterReflection(this.sourceId,i)}this.enabled=!1,this.context.sceneLighting.internalRegisterSceneLightSettings(this),Aa&&window.addEventListener("keydown",t=>{this.destroyed||t.key==="l"&&(this.enabled=!this.enabled)});const e=this.gameObject.userData?.components;if(e){const t=e.indexOf(this);e.splice(t,1),e.push(this)}}onDestroy(){this.context.sceneLighting.internalUnregisterSceneLightSettings(this)}calculateIntensityFactor(e){const t=Math.max(e.r,e.g,e.b);return 2.2*L.lerp(0,1.33,t)}onEnable(){if(Aa&&console.warn("💡🟡 >>> Enable lighting",this.sourceId,this.enabled,this),this.ambientMode==Ya.Flat){if(this.ambientLight&&!this._ambientLightObj){const e=this.calculateIntensityFactor(this.ambientLight);this._ambientLightObj=new c.AmbientLight(this.ambientLight,this.ambientIntensity*e),Aa&&console.log("Created ambient light",this.sourceId,this._ambientLightObj,this.ambientIntensity,e)}this._ambientLightObj&&this.gameObject.add(this._ambientLightObj)}else if(this.ambientMode===Ya.Trilight){if(this.ambientTrilight){const e=this.ambientTrilight[0],t=this.ambientTrilight[this.ambientTrilight.length-1],i=this.calculateIntensityFactor(t);this._hemisphereLightObj=new c.HemisphereLight(t,e,this.ambientIntensity*i),this.gameObject.add(this._hemisphereLightObj),Aa&&console.log("Created hemisphere ambient light",this.sourceId,this._hemisphereLightObj,this.ambientIntensity,i)}}else this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._hemisphereLightObj&&this._hemisphereLightObj.removeFromParent();this.sourceId&&(this.context.domElement.getAttribute("environment-image")||this.context.sceneLighting.internalEnableReflection(this.sourceId))}onDisable(){Aa&&console.warn("💡⚫ <<< Disable lighting:",this.sourceId,this),this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._hemisphereLightObj&&this._hemisphereLightObj.removeFromParent(),this.sourceId&&this.context.sceneLighting.internalDisableReflection(this.sourceId)}}exports.MaterialX=void 0;(s=>{async function e(t,i){if(!t)throw new Error("URL or XML string is required to load a MaterialX material");const n=await A.MaterialX.load(),o=t.trimStart().startsWith("<"),r=o?t:await fetch(t).then(h=>h.text()).catch(console.error);if(!r)return console.warn("Failed to load MaterialX file from url",t),null;let a;if(i?.url||!o){const h=(i?.url||t).split("/");h.pop(),a=h.join("/")}const l=new c.TextureLoader;return n.Experimental_API.createMaterialXMaterial(r,i?.materialNameOrIndex??0,{getTexture:async h=>(!h.startsWith("http")&&!h.startsWith("data:")&&!h.startsWith("blob:")&&!h.startsWith("file:")&&a&&(h=a+"/"+h),l.loadAsync(h).catch(d=>{console.warn(`Failed to load texture for MaterialX material ${h}`,d)}))},{cacheKey:t})}s.loadFromUrl=e})(exports.MaterialX||(exports.MaterialX={}));class EA extends c.Loader{loadAsync(e,t){return new Promise((i,n)=>{this.load(e,i,t,n)})}load(e,t,i,n){i?.({type:"progress",loaded:0,total:0}),exports.MaterialX.loadFromUrl(e,{}).then(o=>{o?t(this.onLoaded(o)):n?.(new Error("Failed to load MaterialX material from url: "+e))})}onLoaded(e){return jo.createPrimitive("ShaderBall",{material:e})}}class RA{constructor(e,t,i,n){this.context=e,this.url=i,this.parser=n}context;url;parser;get name(){return"materialx-loading-helper"}mtlxLoader;async beforeRoot(){if(this.parser.json.extensions?.NEEDLE_materials_mtlx){const t=await A.MaterialX.load();try{this.mtlxLoader=new t.MaterialXLoader(this.parser,{cacheKey:`${this.url}:materialx`,parameters:{precision:this.context.renderer?.capabilities.precision}},{getFrame:()=>this.context.time.frame,getTime:()=>this.context.time.time})}catch(i){console.error(i)}}}loadMaterial(e){return this.mtlxLoader?this.mtlxLoader.loadMaterial(e):null}}var kC=(s=>(s[s.INT=5124]="INT",s[s.FLOAT=5126]="FLOAT",s[s.FLOAT_VEC2=35664]="FLOAT_VEC2",s[s.FLOAT_VEC3=35665]="FLOAT_VEC3",s[s.FLOAT_VEC4=35666]="FLOAT_VEC4",s[s.INT_VEC2=35667]="INT_VEC2",s[s.INT_VEC3=35668]="INT_VEC3",s[s.INT_VEC4=35669]="INT_VEC4",s[s.BOOL=35670]="BOOL",s[s.BOOL_VEC2=35671]="BOOL_VEC2",s[s.BOOL_VEC3=35672]="BOOL_VEC3",s[s.BOOL_VEC4=35673]="BOOL_VEC4",s[s.FLOAT_MAT2=35674]="FLOAT_MAT2",s[s.FLOAT_MAT3=35675]="FLOAT_MAT3",s[s.FLOAT_MAT4=35676]="FLOAT_MAT4",s[s.SAMPLER_2D=35678]="SAMPLER_2D",s[s.SAMPLER_3D=35680]="SAMPLER_3D",s[s.SAMPLER_CUBE=35681]="SAMPLER_CUBE",s[s.UNKNOWN=0]="UNKNOWN",s))(kC||{});const Un=x("debugcustomshader"),wa="NEEDLE_techniques_webgl";class TA{objectToWorldMatrix=new c.Matrix4;worldToObjectMatrix=new c.Matrix4;objectToWorld=new Array;worldToObject=new Array;updateFrom(e){this.objectToWorldMatrix.copy(e.matrixWorld),Zu(this.objectToWorldMatrix,this.objectToWorld),this.worldToObjectMatrix.copy(e.matrixWorld).invert(),Zu(this.worldToObjectMatrix,this.worldToObject)}}class Me extends c.RawShaderMaterial{identifier;onBeforeRenderSceneCallback=this.onBeforeRenderScene.bind(this);clone(){const e=super.clone();return MC(e),e}constructor(e,...t){super(...t),this.identifier=e,Un&&console.log(this),this.type="NEEDLE_CUSTOM_SHADER",this.uniforms[this._objToWorldName]||(this.uniforms[this._objToWorldName]={value:[]}),this.uniforms[this._worldToObjectName]||(this.uniforms[this._worldToObjectName]={value:[]}),this.uniforms[this._viewProjectionName]||(this.uniforms[this._viewProjectionName]={value:[]}),this.uniforms[this._sphericalHarmonicsName],(this.depthTextureUniform||this.opaqueTextureUniform)&&X.Current.pre_render_callbacks.push(this.onBeforeRenderSceneCallback)}dispose(){super.dispose();const e=X.Current.pre_render_callbacks.indexOf(this.onBeforeRenderSceneCallback);e>=0&&X.Current.pre_render_callbacks.splice(e,1)}_sphericalHarmonicsName="unity_SpecCube0";_objToWorldName="hlslcc_mtx4x4unity_ObjectToWorld";_worldToObjectName="hlslcc_mtx4x4unity_WorldToObject";static viewProjection=new c.Matrix4;static _viewProjectionValues=[];_viewProjectionName="hlslcc_mtx4x4unity_MatrixVP";static viewMatrix=new c.Matrix4;static _viewMatrixValues=[];_viewMatrixName="hlslcc_mtx4x4unity_MatrixV";static _worldSpaceCameraPosName="_WorldSpaceCameraPos";static _worldSpaceCameraPos=new c.Vector3;static _mainLightColor=new c.Vector4;static _mainLightPosition=new c.Vector3;static _lightData=new c.Vector4;_rendererData=new TA;get depthTextureUniform(){if(this.uniforms)return this.uniforms._CameraDepthTexture}get opaqueTextureUniform(){if(this.uniforms)return this.uniforms._CameraOpaqueTexture}onBeforeRenderScene(){this.opaqueTextureUniform&&X.Current.setRequireColor(!0),this.depthTextureUniform&&X.Current.setRequireDepth(!0)}onBeforeRender(e,t,i,n,o,r){n.attributes.tangent||n.computeTangents(),this.onUpdateUniforms(i,o)}onUpdateUniforms(e,t){const i=X.Current;if(e&&(Me.viewProjection&&this.uniforms[this._viewProjectionName]&&(Me.viewProjection.copy(e.projectionMatrix).multiply(e.matrixWorldInverse),Zu(Me.viewProjection,Me._viewProjectionValues)),Me.viewMatrix&&this.uniforms[this._viewMatrixName]&&(Me.viewMatrix.copy(e.matrixWorldInverse),Zu(Me.viewMatrix,Me._viewMatrixValues)),this.uniforms[Me._worldSpaceCameraPosName]&&Me._worldSpaceCameraPos.setFromMatrixPosition(e.matrixWorld)),this.uniforms._TimeParameters&&(this.uniforms._TimeParameters.value=i.sceneLighting.timeVec4),this.uniforms._Time){const a=this.uniforms._Time.value;a.x=i.sceneLighting.timeVec4.x/20,a.y=i.sceneLighting.timeVec4.x,a.z=i.sceneLighting.timeVec4.x*2,a.w=i.sceneLighting.timeVec4.x*3}if(this.uniforms._SinTime){const a=this.uniforms._SinTime.value;a.x=Math.sin(i.sceneLighting.timeVec4.x/8),a.y=Math.sin(i.sceneLighting.timeVec4.x/4),a.z=Math.sin(i.sceneLighting.timeVec4.x/2),a.w=Math.sin(i.sceneLighting.timeVec4.x)}if(this.uniforms._CosTime){const a=this.uniforms._CosTime.value;a.x=Math.cos(i.sceneLighting.timeVec4.x/8),a.y=Math.cos(i.sceneLighting.timeVec4.x/4),a.z=Math.cos(i.sceneLighting.timeVec4.x/2),a.w=Math.cos(i.sceneLighting.timeVec4.x)}if(this.uniforms.unity_DeltaTime){const a=this.uniforms.unity_DeltaTime.value;a.x=i.time.deltaTime,a.y=1/i.time.deltaTime,a.z=i.time.smoothedDeltaTime,a.w=1/i.time.smoothedDeltaTime}const n=i.mainLight;if(n){const a=ie(n.gameObject,Me._mainLightPosition);this.uniforms._MainLightPosition={value:a.normalize()},Me._mainLightColor.set(n.color.r,n.color.g,n.color.b,0),this.uniforms._MainLightColor={value:Me._mainLightColor};const l=n.intensity;Me._lightData.z=l,this.uniforms.unity_LightData={value:Me._lightData}}if(e&&(Me.viewProjection&&this.uniforms[this._viewProjectionName]&&(this.uniforms[this._viewProjectionName].value=Me._viewProjectionValues),Me.viewMatrix&&this.uniforms[this._viewMatrixName]&&(this.uniforms[this._viewMatrixName].value=Me._viewMatrixValues),this.uniforms[Me._worldSpaceCameraPosName]&&(this.uniforms[Me._worldSpaceCameraPosName]={value:Me._worldSpaceCameraPos}),i.mainCameraComponent)){if(this.uniforms._ProjectionParams){const a=this.uniforms._ProjectionParams.value;a.x=1,a.y=i.mainCameraComponent.nearClipPlane,a.z=i.mainCameraComponent.farClipPlane,a.w=1/a.z,this.uniforms._ProjectionParams.value=a}if(this.uniforms._ZBufferParams){const a=this.uniforms._ZBufferParams.value,l=i.mainCameraComponent;a.x=1-l.farClipPlane/l.nearClipPlane,a.y=l.farClipPlane/l.nearClipPlane,a.z=a.x/l.farClipPlane,a.w=a.y/l.farClipPlane,this.uniforms._ZBufferParams.value=a}if(this.uniforms._ScreenParams){const a=this.uniforms._ScreenParams.value;a.x=i.domWidth,a.y=i.domHeight,a.z=1+1/a.x,a.w=1+1/a.y,this.uniforms._ScreenParams.value=a}if(this.uniforms._ScaledScreenParams){const a=this.uniforms._ScaledScreenParams.value;a.x=i.domWidth,a.y=i.domHeight,a.z=1+1/a.x,a.w=1+1/a.y,this.uniforms._ScaledScreenParams.value=a}}const o=this.depthTextureUniform;o&&(o.value=i.depthTexture);const r=this.opaqueTextureUniform;if(r&&(r.value=i.opaqueColorTexture),t){const a=this._rendererData;a.updateFrom(t),this.uniforms[this._worldToObjectName].value=a.worldToObject,this.uniforms[this._objToWorldName].value=a.objectToWorld}this.uniformsNeedUpdate=!0}}class AA{get name(){return wa}parser;identifier;constructor(e,t){this.parser=e,this.identifier=t}loadMaterial(e){const t=this.parser.json.materials[e];if(!t)return Un&&console.log(e,this.parser.json.materials),null;if(!t.extensions||!t.extensions[wa])return Un&&console.log(`Material ${e} does not use NEEDLE_techniques_webgl`),null;Un&&console.log(`Material ${e} uses NEEDLE_techniques_webgl`,t);const i=t.extensions[wa].technique;if(i<0)return console.debug(`Material ${e} does not have a valid technique index`),null;const n=this.parser.json.extensions[wa];if(!n)return Un?console.error("Missing shader data",this.parser.json.extensions):console.debug("Missing custom shader data in parser.json.extensions"),null;Un&&console.log(n);const o=n.techniques[i];return o?new Promise(async(r,a)=>{const l=await sO(n,o.program),h=l?.fragmentShader,d=l?.vertexShader;if(!h||!d)return a();Un&&console.log("loadMaterial",t,l);const u={},f=o.uniforms;(d.includes("_Time")||h.includes("_Time"))&&(u._Time={value:new c.Vector4(0,0,0,0)}),(d.includes("_SinTime")||h.includes("_SinTime"))&&(u._SinTime={value:new c.Vector4(0,0,0,0)}),(d.includes("_CosTime")||h.includes("_CosTime"))&&(u._CosTime={value:new c.Vector4(0,0,0,0)}),(d.includes("unity_DeltaTime")||h.includes("unity_DeltaTime"))&&(u.unity_DeltaTime={value:new c.Vector4(0,0,0,0)});for(const y in f){const b=y;switch(b){case"_TimeParameters":const w=new c.Vector4;u[b]={value:w};break;case"hlslcc_mtx4x4unity_MatrixV":case"hlslcc_mtx4x4unity_MatrixVP":u[b]={value:[]};break;case"_MainLightPosition":case"_MainLightColor":case"_WorldSpaceCameraPos":u[b]={value:[0,0,0,1]};break;case"unity_OrthoParams":break;case"unity_SpecCube0":u[b]={value:null};break;default:case"_ScreenParams":case"_ZBufferParams":case"_ProjectionParams":u[b]={value:[0,0,0,0]};break;case"_CameraOpaqueTexture":case"_CameraDepthTexture":u[b]={value:null};break}}let m=!1;if(t.extensions&&t.extensions[wa]){const y=t.extensions[wa];if(y.technique===i){Un&&console.log(t.name,"Material Properties",y);for(const b in y.values){const w=y.values[b];if(typeof w=="string"){if(w.startsWith("/textures/")){const C=w.substring(10),k=Number.parseInt(C);if(k>=0){const O=await this.parser.getDependency("texture",k);O instanceof c.Texture&&(O.colorSpace=c.LinearSRGBColorSpace,O.needsUpdate=!0),u[b]={value:O};continue}}if(b==="alphaMode"){w==="BLEND"&&(m=!0);continue}}if(Array.isArray(w)&&w.length===4){u[b]={value:new c.Vector4(w[0],w[1],w[2],w[3])};continue}u[b]={value:w}}}}const g=new Me(this.identifier,{name:t.name??"",uniforms:u,vertexShader:d,fragmentShader:h,lights:!1});switch(g.glslVersion=c.GLSL3,g.vertexShader=g.vertexShader.replace("#version 300 es",""),g.fragmentShader=g.fragmentShader.replace("#version 300 es",""),u._Cull?.value){case 0:g.side=c.DoubleSide;break;case 1:g.side=c.BackSide;break;case 2:g.side=c.FrontSide;break;default:g.side=c.FrontSide;break}switch(u._ZTest?.value){case 3:g.depthTest=!0,g.depthFunc=c.EqualDepth;break;case 6:g.depthTest=!0,g.depthFunc=c.NotEqualDepth;break;case 2:g.depthTest=!0,g.depthFunc=c.LessDepth;break;case 4:g.depthTest=!0,g.depthFunc=c.LessEqualDepth;break;case 5:g.depthTest=!0,g.depthFunc=c.GreaterDepth;break;case 7:g.depthTest=!0,g.depthFunc=c.GreaterEqualDepth;break;case 8:g.depthTest=!1,g.depthFunc=c.AlwaysDepth;break}g.transparent=m,m&&(g.depthWrite=!1),iO(u),g.onUpdateUniforms();for(const y in f){const b=y,w=f[y].type;u[b]?.value===void 0&&(w===kC.SAMPLER_2D?(u[b]={value:eO},console.warn("Missing/unassigned texture, fallback to white: "+b)):b==="unity_OrthoParams"||console.warn("TODO: EXPECTED UNIFORM / fallback NOT SET: "+b,f[y]))}Un&&console.log(g.uuid,u),MC(g),r(g)}):null}}function MC(s){if(s.uniforms){Un&&console.log("Uniforms:",s.uniforms);for(const t in s.uniforms)switch(e(t,t),t){case"_Color":e("color",t);break;case"_map":e("map",t);break}}function e(t,i){Object.getOwnPropertyDescriptor(s,t)||Object.defineProperty(s,t,{get:()=>s.uniforms[i].value,set:n=>{s.uniforms[i].value=n,s.needsUpdate=!0}})}}const DA=x("debugextensions");let pf;const IA=Promise.resolve().then(()=>require("./vendor-CDN1hirK.umd.cjs")).then(s=>s.index$2).then(async s=>(pf=s.GLTFAnimationPointerExtension,pf)).catch(s=>{console.warn("Failed to import GLTFLoaderAnimationPointer. Please use @needle-tools/three-animationpointer for full KHR_animation support",s)}),Fr=new Array;function LA(s){Fr.includes(s)||Fr.push(s)}function BA(s){const e=Fr.indexOf(s);e>=0&&Fr.splice(e,1)}function I_(s){if(s instanceof V.GLTFLoader){const e=new D_;return s.register(t=>(e.parser=t,e)),e}return null}class FA{resolvePath(e){return e.includes("/extensions/builtin_components/")?e.replace("/extensions/builtin_components/","/userData/components/"):e.includes("extensions/builtin_components/")?e.replace("extensions/builtin_components/","/userData/components/"):e}}async function mf(s,e,t,i){const n=t.indexOf("?");n>=0&&(t=t.substring(0,n)),i||(i=t),(i.startsWith("blob:")||i.startsWith("data:"))&&console.debug("[GLTFLoader] Suspicious sourceId detected"),s.register(o=>new MA(o)),s.register(o=>new CM(o)),s.register(o=>new $M(o,e.lightmaps,i)),s.register(o=>new OA(o,i,e)),s.register(o=>new AA(o,i)),s.register(o=>new bo(o,i)),s.register(o=>new re.NEEDLE_progressive(o)),s.register(o=>new wA(o)),s.register(o=>new Bf(o)),s.register(o=>new RA(e,s,t,o)),kS()&&s.register(o=>new Za(o)),await IA.catch(o=>{}),s.register(o=>{if(pf){const r=new pf(o);return r.setAnimationPointerResolver.bind(r)(new FA),r}else return(DA||E())&&console.error("Missing KHR_animation_pointer extension..."),{name:"KHR_animation_pointer_NOT_AVAILABLE"}});for(const o of Fr)o.onImport&&o.onImport(s,t,e)}function L_(s,e){for(const t of Fr)t.onExport&&t.onExport(s,e)}function OC(s,e,t){for(const i of Fr)i.onLoaded&&i.onLoaded(s,e,t)}const gt=x("debuginstancing"),jA=gt==="lods",Em=x("debugprogressive")==="colors"||jA;function ry(s,e,t,i){return s.lodsManager.manager?.trackLoadingPromise(e,t,i),i}function EC(s){return s.determinant()<0}class jr{static instance=new jr;static getStartInstanceCount=e=>4;objs=[];setup(e,t,i,n,o,r=0){e.applySettings(t);const a=this.tryCreateOrAddInstance(t,i,o);if(a){n===null&&(n=[]),n.push(a);const l=a.object.material;Array.isArray(l)?l.forEach(h=>ry(i,"texture",h,re.NEEDLE_progressive.assignTextureLOD(h,0))):ry(i,"texture",l,re.NEEDLE_progressive.assignTextureLOD(l,0))}else if(r<=0&&t.type!=="Mesh"){const l=r+1;for(const h of t.children)n=this.setup(e,h,i,n,o,l)}return r===0&&o.useMatrixWorldAutoUpdate&&n&&n.length>=0&&this.autoUpdateInstanceMatrix(t),n}tryCreateOrAddInstance(e,t,i){if(e.type==="Mesh"){const n=i.foundMeshes;if(i.foundMeshes+=1,!i.rend.enableInstancing)return null;if(i.rend.enableInstancing!==!0){if(n>=i.rend.enableInstancing.length)return gt&&console.error("Something is wrong with instance setup",e,i.rend.enableInstancing,n),null;if(!i.rend.enableInstancing[n])return null}const o=e,r=o.geometry,a=o.material;if(Array.isArray(a))return null;o.updateWorldMatrix(!0,!1);const l=EC(o.matrixWorld);for(const m of this.objs){if(!m.canAdd(r,a,l))continue;return m.addInstance(o,r)}let h=jr.getStartInstanceCount(e);(!h||h<0)&&(h=4);let d=e.name;d?.length||(d=Dw());const u=new fo(d,r,a,h,t,l);return this.objs.push(u),u.addInstance(o,r)}return null}autoUpdateInstanceMatrix(e){const t=e.matrixWorld.multiplyMatrices.bind(e.matrixWorld),i=e.matrixWorld.clone(),n=(o,r)=>{const a=t(o,r);return(e[rh]||i.equals(a)===!1)&&(i.copy(a),e[rh]=!0),a};e.matrixWorld.multiplyMatrices=n}}class Rr{static all=[];get name(){return this.object.name}get isActive(){return this.__instanceIndex>=0}get vertexCount(){return this.geometry.attributes.position.count}get maxVertexCount(){return Math.max(this.meshInformation.vertexCount,this.vertexCount)}get reservedVertexCount(){return this.__reservedVertexRange}get indexCount(){return this.geometry.index?this.geometry.index.count:0}get maxIndexCount(){return Math.max(this.meshInformation.indexCount,this.indexCount)}get reservedIndexCount(){return this.__reservedIndexRange}object;_geometry;get geometry(){return this._geometry}renderer;__instanceIndex=-1;__reservedVertexRange=0;__reservedIndexRange=0;__geometryIndex=-1;meshInformation;currentMeshLOD;pendingMeshLOD;constructor(e,t,i=e.geometry){this.__instanceIndex=-1,this.object=e,this._geometry=i,this.renderer=t,this.currentMeshLOD=i.userData?.LODS?.level,e[TS]=t,this.meshInformation=dr(e.geometry),Rr.all.push(this)}updateMeshInformation(){const e=dr(this.geometry),t=this.meshInformation.vertexCount,i=this.meshInformation.indexCount;return Object.assign(this.meshInformation,e),t!==this.meshInformation.vertexCount||i!==this.meshInformation.indexCount}updateInstanceMatrix(e=!1,t=!0){this.__instanceIndex<0||(t&&this.object.updateWorldMatrix(!0,e),this.assertMirroringUnchanged(),this.renderer.updateInstance(this.object.matrixWorld,this.__instanceIndex))}_didWarnAboutMirroringChange=!1;assertMirroringUnchanged(){this._didWarnAboutMirroringChange||EC(this.object.matrixWorld)!==this.renderer.mirrored&&(this._didWarnAboutMirroringChange=!0,console.warn(`[Instancing] "${this.name}" changed its mirroring at runtime (world matrix determinant flipped sign). Instanced objects can not change mirroring - this object will render its backfaces. Disable instancing for it via Renderer.setInstanced(obj, false).`))}setMatrix(e){this.__instanceIndex<0||this.renderer.updateInstance(e,this.__instanceIndex)}setGeometry(e){if(this.__geometryIndex<0)return!1;if(this._geometry!==e){const n=this.__instanceIndex>=0;return n&&this.renderer.remove(this,!1),this._geometry=e,this.updateMeshInformation(),n?this.renderer.add(this):!0}this._geometry=e;const t=this;if(this.vertexCount>this.__reservedVertexRange)return i(`Instancing: Can not update geometry (${this.name}), reserved vertex range is too small: ${this.__reservedVertexRange.toLocaleString()} < ${this.vertexCount.toLocaleString()} vertices for ${this.name}`);if(this.indexCount>this.__reservedIndexRange)return i(`Instancing: Can not update geometry (${this.name}), reserved index range is too small: ${this.__reservedIndexRange.toLocaleString()} < ${this.indexCount.toLocaleString()} indices for ${this.name}`);return this.renderer.updateGeometry(e,this.__geometryIndex);function i(n){return t.updateMeshInformation()&&(t.renderer.remove(t,!0),t.renderer.add(t))?!0:((E()||gt)&&console.error(n),!1)}}add(){this.__instanceIndex>=0||(this.renderer.add(this),P.markAsInstancedRendered(this.object,!0))}remove(e){if(!(this.__instanceIndex<0)&&(this.renderer.remove(this,e),P.markAsInstancedRendered(this.object,!1),e)){const t=Rr.all.indexOf(this);t>=0&&Rr.all.splice(t,1)}}}class fo{get batchedMesh(){return this._batchedMesh}get mirrored(){return this._mirrored}get visible(){return this._batchedMesh.visible}set visible(e){this._batchedMesh.visible=e}get castShadow(){return this._batchedMesh.castShadow}set castShadow(e){this._batchedMesh.castShadow=e}set receiveShadow(e){this._batchedMesh.receiveShadow=e}allowResize=!0;name="";geometry;material;get count(){return this._currentInstanceCount}updateBounds(e=!0,t=!0){if(this._needUpdateBounds=!1,e&&this._batchedMesh.computeBoundingBox(),t&&this._batchedMesh.computeBoundingSphere(),gt&&this._batchedMesh.boundingSphere){const i=fo.debugBoundsSphere.copy(this._batchedMesh.boundingSphere).applyMatrix4(this._batchedMesh.matrixWorld);B.DrawWireSphere(i.center,i.radius,65280)}}_context;_batchedMesh;_mirrored;_handles=[];_geometryIds=new WeakMap;_maxInstanceCount;_currentInstanceCount=0;_currentVertexCount=0;_currentIndexCount=0;_maxVertexCount;_maxIndexCount;static instanceMatrix=new c.Matrix4;static lodProjectionScreenMatrix=new c.Matrix4;static debugBoundsSphere=new c.Sphere;static debugLODColor=new c.Color;static lodSelectionResult={level:-1,primitiveIndex:0,screenCoverage:0,screenspaceVolume:new c.Vector3,centrality:1};canAdd(e,t,i){return this._maxVertexCount>1e7||this._mirrored!==i||t!==this.material||!this.validateGeometry(e)?!1:!!(!this.mustGrow(e)||this.allowResize)}_needUpdateBounds=!1;_debugMaterial=null;getBatchedMeshName(){return this.name?`${this.name} (BatchedMesh)`:"BatchedMesh"}constructor(e,t,i,n,o,r=!1){this.name=e,this.geometry=t,this.material=i,this._context=o,this._mirrored=r,this._maxInstanceCount=Math.max(2,n),gt&&(this._debugMaterial=F0(Em));const a=this.tryEstimateVertexCountSize(this._maxInstanceCount,[t],n);this._maxVertexCount=a.vertexCount,this._maxIndexCount=a.indexCount,this._batchedMesh=new c.BatchedMesh(this._maxInstanceCount,this._maxVertexCount,this._maxIndexCount,this._debugMaterial??this.material),this._batchedMesh.name=this.getBatchedMeshName(),this.applyBatchTransform(this._batchedMesh),this._batchedMesh[Cc]=!0,this._batchedMesh.visible=!0,this._context.scene.add(this._batchedMesh),i instanceof c.RawShaderMaterial&&(i.defines.USE_INSTANCING=!0,i.needsUpdate=!0),o.pre_render_callbacks.push(this.onBeforeRender),o.post_render_callbacks.push(this.onAfterRender),gt&&console.log(`Instanced renderer (${this.name}) created with ${this._maxInstanceCount} instances, ${this._maxVertexCount} max vertices and ${this._maxIndexCount} max indices for "${e}"`)}dispose(){gt&&console.warn("Dispose instanced renderer",this.name),this._context.scene.remove(this._batchedMesh),this._batchedMesh.dispose(),this._batchedMesh=null,this._handles=[]}addInstance(e,t){const i=new Rr(e,this,t);e.castShadow===!0&&this._batchedMesh.castShadow===!1&&(this._batchedMesh.castShadow=!0),e.receiveShadow===!0&&this._batchedMesh.receiveShadow===!1&&(this._batchedMesh.receiveShadow=!0);try{this.add(i)}catch(n){if(console.error(`Failed adding mesh to instancing (object name: "${e.name}", instances: ${this._currentInstanceCount.toLocaleString()}/${this._maxInstanceCount.toLocaleString()}, vertices: ${this._currentVertexCount.toLocaleString()}/${this._maxVertexCount.toLocaleString()}, indices: ${this._currentIndexCount.toLocaleString()}/${this._maxIndexCount.toLocaleString()})
|
|
1088
1088
|
`,n),E()){wl("Failed instancing mesh. See the browser console for details.");debugger}return null}return i}add(e){const t=e.geometry;if(!t||!t.attributes)return console.error("Cannot add object to instancing without geometry",e.name),!1;if(this._currentInstanceCount+1>this._maxInstanceCount||this.mustGrow(t))if(this.allowResize)this.grow(t);else return console.error("Cannot add instance, max count reached",this.name,this.count,this._maxInstanceCount),!1;return e.object.updateWorldMatrix(!0,!0),this.addGeometry(e),this._handles[e.__instanceIndex]=e,this._currentInstanceCount+=1,this.markNeedsUpdate(),this._currentInstanceCount>0&&(this._batchedMesh.visible=!0),!0}remove(e,t){e&&(e.__instanceIndex<0||this._handles[e.__instanceIndex]!=e||this._currentInstanceCount<=0||(this.removeGeometry(e,t),this._handles[e.__instanceIndex]=null,e.__instanceIndex=-1,this._currentInstanceCount>0&&(this._currentInstanceCount-=1),this._currentInstanceCount<=0&&(this._batchedMesh.visible=!1),this.markNeedsUpdate()))}updateInstance(e,t){this.setInstanceMatrix(t,e),this.markNeedsUpdate()}applyBatchTransform(e){this._mirrored&&e.scale.z!==-1&&(e.scale.z=-1,e.updateMatrixWorld())}setInstanceMatrix(e,t){if(!this._mirrored){this._batchedMesh.setMatrixAt(e,t);return}const i=fo.instanceMatrix.copy(t),n=i.elements;n[2]=-n[2],n[6]=-n[6],n[10]=-n[10],n[14]=-n[14],this._batchedMesh.setMatrixAt(e,i)}updateGeometry(e,t){return this.validateGeometry(e)?(this.mustGrow()&&this.grow(e),gt&&console.debug("[Instancing] UPDATE GEOMETRY at "+t,this._batchedMesh._geometryCount,e.name,dr(e),e.attributes.position.count,e.index?e.index.count:0),this._batchedMesh.setGeometryAt(t,e),this._geometryIds.set(e,t),this.markNeedsUpdate(),!0):!1}onBeforeRender=()=>{this.updateProgressiveMeshLODs(),this._batchedMesh.layers.enableAll(),this._needUpdateBounds&&this._batchedMesh[Cc]===!0&&(gt==="verbose"&&console.log("Update instancing bounds",this.name,this._batchedMesh.matrixWorldNeedsUpdate),this.updateBounds())};updateProgressiveMeshLODs(){const e=this._context.mainCamera;if(!e)return;fo.lodProjectionScreenMatrix.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse);const t=this._context.lodsManager?.targetTriangleDensity??2e5,i=this._handles.length;for(let n=0;n<i;n++){const o=this._handles[n];if(!o||o.__instanceIndex<0)continue;const r=this.calculateProgressiveMeshLOD(o,t);r<0||o.currentMeshLOD===r||o.pendingMeshLOD===r||this.assignProgressiveMeshLOD(o,r)}}assignProgressiveMeshLOD(e,t){const i=e.geometry;e.pendingMeshLOD=t;const n=re.NEEDLE_progressive.assignMeshLOD(e.object,t,{apply:o=>this.shouldApplyProgressiveMeshLOD(e,t)&&(i===o||e.setGeometry(o))?(e.object.geometry=o,e.currentMeshLOD=t,this.updateDebugLODColor(e),!0):!1});ry(this._context,"mesh",e.object,n).catch(o=>{(gt||E())&&console.warn(`Failed loading instanced mesh LOD ${t} for ${e.name}`,o)}).finally(()=>{e.pendingMeshLOD===t&&(e.pendingMeshLOD=void 0)})}shouldApplyProgressiveMeshLOD(e,t){if(e.__instanceIndex<0)return!1;if(e.pendingMeshLOD===t)return!0;const i=e.currentMeshLOD??e.geometry.userData?.LODS?.level??1/0;if(t>=i)return!1;const n=e.pendingMeshLOD;return typeof n=="number"&&t>=n}calculateProgressiveMeshLOD(e,t){e.object.matrixWorldNeedsUpdate&&e.object.updateWorldMatrix(!0,!1);const i=this._context.mainCamera;return i?re.calculateMeshLODLevel({geometry:e.geometry,matrixWorld:e.object.matrixWorld,camera:i,projectionScreenMatrix:fo.lodProjectionScreenMatrix,desiredDensity:t,canvasHeight:this._context.renderer.domElement.clientHeight||this._context.renderer.domElement.height,currentLevel:e.currentMeshLOD??-1,target:fo.lodSelectionResult}).level:-1}onAfterRender=()=>{this._batchedMesh.layers.disableAll()};validateGeometry(e){const t=this.geometry;for(const i in e.attributes)if(i!=="batchId"&&!t.hasAttribute(i))return E()&&console.warn(`BatchedMesh: Added geometry has extra "${i}" attribute. All geometries must have consistent attributes.`),!1;for(const i in t.attributes)if(i!=="batchId"&&!e.hasAttribute(i))return E()&&console.warn(`BatchedMesh: Added geometry missing "${i}". All geometries must have consistent attributes.`),!1;return!0}markNeedsUpdate(){gt==="verbose"&&console.warn("Marking instanced mesh dirty",this.name),this._needUpdateBounds=!0}mustGrow(e){if(this.count>=this._maxInstanceCount)return!0;if(!e||!e.attributes||this._geometryIds.has(e))return!1;const i=dr(e),n=i.vertexCount,o=i.indexCount;return this._currentVertexCount+n>this._maxVertexCount||this._currentIndexCount+o>this._maxIndexCount}_growId=0;grow(e){const t=++this._growId,o=this.count>=this._maxInstanceCount?Math.ceil(this._maxInstanceCount*2):this._maxInstanceCount,r=this.tryEstimateVertexCountSize(o,[e]),a=1.25,l=Math.max(this._maxVertexCount,Math.ceil(r.vertexCount*a)),h=Math.max(this._maxIndexCount,Math.ceil(r.indexCount*a));if(gt){const f=dr(e);console.warn(`[Instancing] Growing Buffer
|
|
1089
1089
|
Mesh: "${this.name}${e.name?.length?"/"+e.name:""}" (${f.vertexCount.toLocaleString()} vertices, ${f.indexCount.toLocaleString()} indices)
|
|
1090
1090
|
Max count ${this._maxInstanceCount.toLocaleString()} → ${o.toLocaleString()}
|
|
@@ -1137,7 +1137,7 @@ Texture:`,i),this.setLightmapDebugMaterial()):qd&&console.log("Use debuglightmap
|
|
|
1137
1137
|
gl_FragColor = lightMapTexel;
|
|
1138
1138
|
gl_FragColor.a = 1.;
|
|
1139
1139
|
}
|
|
1140
|
-
`,defines:{USE_LIGHTMAP:""}})}}var UA=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&&UA(e,t,n),n};const Da=x("debugrenderer"),U0=x("debugskinnedmesh"),z0=x("noinstancing"),zA=x("wireframe");var RC=(s=>(s[s.Off=0]="Off",s[s.BlendProbes=1]="BlendProbes",s[s.BlendProbesAndSkybox=2]="BlendProbesAndSkybox",s[s.Simple=3]="Simple",s))(RC||{});class TC{path=null;asset=null;default}class NA{_renderer;_targets=[];_indexMapMaxIndex;_indexMap;_changed=!1;get changed(){return this._changed}set changed(e){e===!0&&Da&&console.warn("SharedMaterials have changed: "+this._renderer.name),this._changed=e}is(e){return this._renderer===e}constructor(e,t){this._renderer=e;const i=this.setMaterial.bind(this),n=this.getMaterial.bind(this),o=e.gameObject;if(this._targets=[],o)switch(o.type){case"Group":this._targets=[...o.children];break;case"SkinnedMesh":case"Mesh":this._targets.push(o);break}let r=!1,a,l=0;for(let h=0;h<this._targets.length;h++){const d=this._targets[h];if(!d)continue;const u=d.material;if(u){u.shadowSide=u.side;for(let f=0;f<t.length;f++){const m=t[f];if(!m){r=!0;continue}if(u.name===m.name){a===void 0&&(a=new Map),a.set(f,h),l=Math.max(l,f);break}}}}if(r){this._indexMapMaxIndex=l,this._indexMap=a;const h=`Renderer ${e.name} was initialized with missing materials - this may lead to unexpected behaviour when trying to access sharedMaterials by index.`;console.warn(h),ki()&&de("Found renderer with missing materials: please check the console for details.")}return new Proxy(this,{get(h,d){if(typeof d=="string"){const u=parseInt(d);if(!isNaN(u))return n(u)}return h[d]},set(h,d,u){return typeof d=="string"&&i(u,Number.parseInt(d)),Reflect.set(h,d,u)?(u instanceof c.Material&&(h.changed=!0),!0):!1}})}get length(){return this._indexMapMaxIndex!==void 0?this._indexMapMaxIndex+1:this._targets.length}*[Symbol.iterator](){for(let e=0;e<this.length;e++)yield this.getMaterial(e)}resolveIndex(e){const t=this._indexMap;return t&&t.has(e)?t.get(e):e}setMaterial(e,t){if(t=this.resolveIndex(t),t<0||t>=this._targets.length)return;const i=this._targets[t];!i||i.material===void 0||(i.material=e,this.changed=!0)}getMaterial(e){if(e=this.resolveIndex(e),e<0)return null;const t=this._targets;if(e>=t.length)return null;const i=t[e];return i?i.material:null}}const us=class Oc extends T{static setInstanced(e,t){const i=Th(e,Oc);return i.enableInstancing=t,i.setInstancingEnabled(t),i}static isInstanced(e){const t=Bs(e,Oc);return t?t.isInstancingActive:Ki.isUsingInstancing(e)}static setVisible(e,t){Qn(e,t)}receiveShadows=!1;shadowCastingMode=0;lightmapIndex=-1;lightmapScaleOffset=new c.Vector4(1,1,0,0);enableInstancing=void 0;renderOrder=void 0;allowOcclusionWhenDynamic=!0;probeAnchor;reflectionProbeUsage=0;_lightmaps;get sharedMesh(){if(this.gameObject.type==="Mesh")return this.gameObject;if(this.gameObject.type==="SkinnesMesh")return this.gameObject;if(this.gameObject.type==="Group")return this.gameObject.children[0]}_sharedMeshes=[];get sharedMeshes(){if(this.destroyed||!this.gameObject)return this._sharedMeshes;if(this._sharedMeshes.length=0,this.isMultiMaterialObject(this.gameObject))for(const e of this.gameObject.children)this.isOwnSubmesh(e)&&this._sharedMeshes.push(e);else this.isMeshOrSkinnedMesh(this.gameObject)&&this._sharedMeshes.push(this.gameObject);return this._sharedMeshes}get sharedMaterial(){return this.sharedMaterials?.[0]}set sharedMaterial(e){this.sharedMaterials[0]!==e&&(this.sharedMaterials[0]=e,this.applyLightmapping())}get material(){return this.sharedMaterials?.[0]}set material(e){this.sharedMaterial=e}_sharedMaterials;_originalMaterials;_probeAnchorLastFrame;set sharedMaterials(e){if(!this._originalMaterials)this._originalMaterials=e;else if(e){let t=!1;for(let i=0;i<this._sharedMaterials.length;i++){const n=i<e.length?e[i]:null;n&&n instanceof c.Material?this.sharedMaterials[i]=n:t||(t=!0,console.warn("Can not assign null as material: "+this.name,n))}}}get sharedMaterials(){if(this._originalMaterials===void 0)if(this.__didAwake)this._originalMaterials=[];else return null;return(!this._sharedMaterials||!this._sharedMaterials.is(this))&&(this._originalMaterials||(this._originalMaterials=[]),this._sharedMaterials=new NA(this,this._originalMaterials)),this._sharedMaterials}static get shouldSuppressInstancing(){return z0}_lightmapTextureOverride=void 0;get lightmap(){return this._lightmaps?.length?this._lightmaps[0].lightmap:null}set lightmap(e){if(this._lightmapTextureOverride=e,e===void 0&&(e=this.context.lightmaps.tryGetLightmap(this.sourceId,this.lightmapIndex)),this._lightmaps?.length)for(const t of this._lightmaps)t.lightmap=e}get hasLightmap(){const e=this.lightmap;return e!=null}allowProgressiveLoading=!0;_firstFrame=-1;registering(){this.enabled||this.setVisibility(!1)}awake(){if(this._firstFrame=this.context.time.frame,Da&&console.log("Renderer ",this.name,this),this.clearInstancingState(),this.probeAnchor&&Da&&this.probeAnchor.add(new c.AxesHelper(.2)),this._reflectionProbe=null,this.isMultiMaterialObject(this.gameObject)){for(const e of this.gameObject.children)this.context.addBeforeRenderListener(e,this.onBeforeRenderThree),e.layers.mask=this.gameObject.layers.mask;if(this.renderOrder!==void 0){let e=0;for(let t=0;t<this.gameObject.children.length;t++){const i=this.gameObject.children[t];if(!(!this.isMeshOrSkinnedMesh(i)||P.getComponent(i,Oc))){if(this.renderOrder.length<=e){console.warn("Incorrect renderOrder element count",this,this.renderOrder.length+" but expected "+this.gameObject.children.length,"Index: "+e,"ChildElement:",i);continue}i.renderOrder=this.renderOrder[e],e+=1}}}}else this.isMeshOrSkinnedMesh(this.gameObject)?(this.context.addBeforeRenderListener(this.gameObject,this.onBeforeRenderThree),this.renderOrder!==void 0&&this.renderOrder.length>0&&(this.gameObject.renderOrder=this.renderOrder[0])):this.context.addBeforeRenderListener(this.gameObject,this.onBeforeRenderThree);if(this._lightmaps=void 0,this.applyLightmapping(),zA)for(let e=0;e<this.sharedMaterials.length;e++){const t=this.sharedMaterials[e];t&&(t.wireframe=!0)}}applyLightmapping(){if(this.lightmapIndex>=0&&!this._lightmaps){const e=this._lightmapTextureOverride!==void 0?this._lightmapTextureOverride:this.context.lightmaps.tryGetLightmap(this.sourceId,this.lightmapIndex);if(e){this._lightmaps||(this._lightmaps=[]);const t=new B_(this);t.init(this.lightmapIndex,this.lightmapScaleOffset,e),this._lightmaps.push(t)}else Da&&console.warn(`[Renderer] No lightmaps found ${this.name} (${this.sourceId}, ${this.lightmapIndex})`)}}_isInstancingEnabled=!1;_handles=void 0;get isInstancingActive(){return this._handles!=null&&this._handles.length>0&&this._isInstancingEnabled}get instances(){if(!this._handles||this._handles.length<=0)return null;if(this._handlesTempArray.length=0,this._handles)for(const e of this._handles)this._handlesTempArray.push(e);return this._handlesTempArray}_handlesTempArray=[];setInstancingEnabled(e){if(this._isInstancingEnabled===e){if(!e||this._handles&&this._handles.length>0)return!0}else this._isInstancingEnabled=e;if(e){if(this.enableInstancing===void 0&&(this.enableInstancing=!0),this._handles===void 0||this._handles===null){if(this._handles=jr.instance.setup(this,this.gameObject,this.context,null,{rend:this,foundMeshes:0,useMatrixWorldAutoUpdate:this.useInstanceMatrixWorldAutoUpdate()}),this._handles)return P.markAsInstancedRendered(this.gameObject,!0),!0}else if(this._handles!==null){for(const t of this._handles)t.updateInstanceMatrix(!0),t.add();return P.markAsInstancedRendered(this.gameObject,!0),!0}}else{if(this._handles)for(const t of this._handles)t.remove(this.destroyed);return!0}return!1}clearInstancingState(){this._isInstancingEnabled=!1,this._handles=void 0}useInstanceMatrixWorldAutoUpdate(){return!0}start(){if(this.enableInstancing&&!z0&&(this.setInstancingEnabled(!0),Ki.markDirty(this.gameObject)),this.gameObject.frustumCulled=this.allowOcclusionWhenDynamic,this.isMultiMaterialObject(this.gameObject))for(let e=0;e<this.gameObject.children.length;e++){const t=this.gameObject.children[e];t.frustumCulled=this.allowOcclusionWhenDynamic}}onEnable(){this.sharedMeshes,this.setVisibility(!0),this._isInstancingEnabled||this.enableInstancing==!0||Array.isArray(this.enableInstancing)&&this.enableInstancing.some(t=>t)?this.__internalDidAwakeAndStart&&this.setInstancingEnabled(!0):this.enabled&&this.applyStencil(),this.updateReflectionProbe(),Ps.onEnabled.addEventListener(this.onReflectionProbeEnabled),Ps.onDisabled.addEventListener(this.onReflectionProbeDisabled)}onDisable(){this.setVisibility(!1),Ps.onEnabled.removeEventListener(this.onReflectionProbeEnabled),Ps.onDisabled.removeEventListener(this.onReflectionProbeDisabled),this._handles&&this._handles.length>0&&this.setInstancingEnabled(!1)}onDestroy(){if(this._handles=null,this.isMultiMaterialObject(this.gameObject))for(const e of this.gameObject.children)this.context.removeBeforeRenderListener(e,this.onBeforeRenderThree);else this.context.removeBeforeRenderListener(this.gameObject,this.onBeforeRenderThree)}onReflectionProbeEnabled=()=>{this.updateReflectionProbe()};onReflectionProbeDisabled=e=>{this._reflectionProbe===e&&(this._reflectionProbe.unapply(this.gameObject),this._reflectionProbe=null)};onBeforeRender(){if(this.gameObject){if((this._probeAnchorLastFrame!==this.probeAnchor||this._reflectionProbe?.activeAndEnabled===!1)&&(this._reflectionProbe?.unapply(this.gameObject),this.updateReflectionProbe()),Da==this.name&&this.gameObject instanceof c.Mesh){this.gameObject.geometry.computeBoundingSphere();const e=F(this.gameObject.geometry.boundingSphere.center).applyMatrix4(this.gameObject.matrixWorld);B.DrawWireSphere(e,this.gameObject.geometry.boundingSphere.radius,56831)}if(this.isMultiMaterialObject(this.gameObject)&&this.gameObject.children?.length>0)for(const e of this.gameObject.children)this.applySettings(e);else this.applySettings(this.gameObject);if(this.sharedMaterials?.changed&&(this.sharedMaterials.changed=!1,this.applyLightmapping()),this._handles?.length&&this.gameObject[rh]===!0){this.gameObject[rh]=!1;for(let t=this._handles.length-1;t>=0;t--)this._handles[t].updateInstanceMatrix();this.gameObject.matrixWorldNeedsUpdate=!1}if(this._handles&&this._handles.length<=0&&P.markAsInstancedRendered(this.gameObject,!1),this._isInstancingEnabled&&this._handles)for(let e=0;e<this._handles.length;e++){const t=this._handles[e];Qn(t.object,!1)}if(this.reflectionProbeUsage!==0&&this._reflectionProbe?this._reflectionProbe.apply(this.gameObject):this.reflectionProbeUsage===0&&this._reflectionProbe&&this._reflectionProbe.unapply(this.gameObject),this._sharedMaterials)for(const e of this._sharedMaterials)e&&"envMap"in e&&"envMapIntensity"in e&&!Ps.isUsingReflectionProbe(e)&&(e.envMap=this.context.scene.environment,e.envMapRotation=this.context.scene.environmentRotation);else Da&&console.warn("[Renderer] sharedMaterials not initialized yet: "+this.name)}}onBeforeRenderThree=(e,t,i,n,o,r)=>{if(o.envMapIntensity!==void 0){const a=this.hasLightmap?Math.PI:1,l=this.context.scene.environmentIntensity;o.envMapIntensity=Math.max(0,l*this.context.sceneLighting.environmentIntensity/a)}if(this._lightmaps)for(const a of this._lightmaps)a.updateLightmapUniforms(o),a.applyLightmap()};onAfterRender(){if(this._isInstancingEnabled&&this._handles)for(let e=0;e<this._handles.length;e++){const t=this._handles[e];Qn(t.object,!0)}this._reflectionProbe?.activeAndEnabled===!1&&this._reflectionProbe.unapply(this.gameObject),this.static&&this.gameObject.matrixAutoUpdate&&this.context.time.frame-this._firstFrame>=10&&(this.gameObject.matrixAutoUpdate=!1)}applyStencil(){bo.applyStencil(this)}applySettings(e){e.receiveShadow=this.receiveShadows,this.shadowCastingMode==1?e.castShadow=!0:e.castShadow=!1}_reflectionProbe=null;updateReflectionProbe(){this._reflectionProbe=null,this.reflectionProbeUsage!==0&&(this.startCoroutine(this._updateReflectionProbe(),Ce.LateUpdate),this._probeAnchorLastFrame=this.probeAnchor)}*_updateReflectionProbe(){const e=this.probeAnchor||this.gameObject,t=!!this.probeAnchor;this._reflectionProbe=Ps.get(e,this.context,t,this.probeAnchor)}setVisibility(e){if(!this.isMultiMaterialObject(this.gameObject))Qn(this.gameObject,e);else for(const t of this.gameObject.children)this.isOwnSubmesh(t)&&Qn(t,e)}isMultiMaterialObject(e){return e.type==="Group"}isMeshOrSkinnedMesh(e){return e.type==="Mesh"||e.type==="SkinnedMesh"}isOwnSubmesh(e){return this.isMeshOrSkinnedMesh(e)&&!Bs(e,Oc)}};$s([p()],us.prototype,"receiveShadows");$s([p()],us.prototype,"shadowCastingMode");$s([p()],us.prototype,"lightmapIndex");$s([p(c.Vector4)],us.prototype,"lightmapScaleOffset");$s([p()],us.prototype,"enableInstancing");$s([p()],us.prototype,"renderOrder");$s([p()],us.prototype,"allowOcclusionWhenDynamic");$s([p(c.Object3D)],us.prototype,"probeAnchor");$s([p()],us.prototype,"reflectionProbeUsage");let ti=us;class Vh extends ti{}class F_ extends Vh{_needUpdateBoundingSphere=!1;awake(){super.awake(),U0&&console.log('SkinnedMeshRenderer for "'+this.name+'"',this),this.allowOcclusionWhenDynamic=!1;for(const e of this.sharedMeshes)e.parent?.updateWorldMatrix(!1,!0),this.markBoundsDirty()}onAfterRender(){if(super.onAfterRender(),this._needUpdateBoundingSphere){for(const e of this.sharedMeshes)if(e instanceof c.SkinnedMesh){this._needUpdateBoundingSphere=!1;try{const t=e.geometry,i=re.getRaycastMesh(e);i&&(e.geometry=i),e.computeBoundingSphere(),e.geometry=t}catch(t){console.error(`Error updating bounding sphere for ${e.name}`,t)}}}if(U0){for(const e of this.sharedMeshes)if(e instanceof c.SkinnedMesh&&e.boundingSphere){const t=F(e.boundingSphere.center).applyMatrix4(e.matrixWorld);B.DrawWireSphere(t,e.boundingSphere.radius,"red")}}}markBoundsDirty(){this._needUpdateBoundingSphere=!0}}var gf=(s=>(s[s.Off=0]="Off",s[s.On=1]="On",s[s.TwoSided=2]="TwoSided",s[s.ShadowsOnly=3]="ShadowsOnly",s))(gf||{}),$A=Object.defineProperty,Tl=(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&&$A(e,t,n),n};const Xt=x("debugdroplistener");class VA extends CustomEvent{constructor(e){super("object-added",{detail:e})}}const WA="blob";class Vs extends T{dropArea;fitIntoVolume=!1;fitVolumeSize=new c.Vector3(1,1,1);placeAtHitPosition=!0;useNetworking=!1;onDropped=new Z;loadFromURL(e,t){return this.addFromUrl(e,{screenposition:new c.Vector2,point:t?.point,size:t?.size},!1)}forgetObjects(){this.removePreviouslyAddedObjects(!1)}awake(){for(const e of this.gameObject.children)this.dropArea&&e.contains(this.dropArea)||this._addedObjects.push(e)}onEnable(){this.context.renderer.domElement.addEventListener("dragover",this.onDrag),this.context.renderer.domElement.addEventListener("drop",this.onDrop),window.addEventListener("paste",this.handlePaste),this.context.connection.beginListen("droplistener",this.onNetworkEvent),E()&&this.dropArea&&(this.dropArea.getComponentInChildren(ti)||console.warn("[DropListener] The assigned DropArea does not seem to have a renderer/mesh. Drag and Drop events will not be detected."))}onDisable(){this.context.renderer.domElement.removeEventListener("dragover",this.onDrag),this.context.renderer.domElement.removeEventListener("drop",this.onDrop),window.removeEventListener("paste",this.handlePaste),this.context.connection.stopListen("droplistener",this.onNetworkEvent)}onNetworkEvent=e=>{if(!this.useNetworking){Xt&&console.debug("[DropListener] Ignoring networked event because networking is disabled",e);return}if(e.guid?.startsWith(this.guid)){const t=e.url;if(console.debug("[DropListener] Received networked event",e),t)if(Array.isArray(t))for(const i of t)this.addFromUrl(i,{screenposition:new c.Vector2,point:e.point,size:e.size},!0);else this.addFromUrl(t,{screenposition:new c.Vector2,point:e.point,size:e.size},!0)}};handlePaste=e=>{if(this.context.connection.allowEditing===!1||e.defaultPrevented)return;navigator.clipboard.readText().then(i=>{if(i&&(i.startsWith("http")||i.startsWith("https")||i.startsWith("blob"))){const o={screenposition:new c.Vector2(this.context.input.mousePosition.x,this.context.input.mousePosition.y)};this.testIfIsInDropArea(o)&&this.addFromUrl(i,o,!1)}}).catch(console.warn)};onDrag=e=>{Xt&&console.debug("DropListener Drag",e,this.context.connection.allowEditing),this.context.connection.allowEditing!==!1&&e.preventDefault()};onDrop=async e=>{if(Xt&&console.debug("DropListener Drop",e,this.context.connection.allowEditing),this.context.connection.allowEditing===!1||!e?.dataTransfer||e["droplistener:handled"])return;e.preventDefault();const t={screenposition:new c.Vector2(e.offsetX,e.offsetY)};if(this.dropArea&&this.testIfIsInDropArea(t)===!1)return;e["droplistener:handled"]=!0;const i=e.dataTransfer.items;if(!i)return;const n=[];for(const o in i){const r=i[o];if(r.kind==="file"){const a=r.getAsFile();if(!a)continue;n.push(a)}else r.kind==="string"&&r.type=="text/plain"&&r.getAsString(a=>{this.addFromUrl(a,t,!1)})}n.length>0&&await this.addFromFiles(n,t)};async addFromUrl(e,t,i){Xt&&console.log("dropped url",e);try{if(e.startsWith("https://github.com/")){const r=e.split("/"),a=r[3],l=r[4],h=r[6],d=r.slice(7).join("/");e=`https://raw.githubusercontent.com/${a}/${l}/${h}/${d}`}else e.startsWith("https://polyhaven.com/a")&&(e=GA(e));if(!e)return null;const n=e.toLowerCase();if(n.endsWith(".hdr")||n.endsWith(".hdri")||n.endsWith(".exr")||n.endsWith(".png")||n.endsWith(".jpg")||n.endsWith(".jpeg"))return console.warn(`Fileformat is not supported: ${n}`),null;this.removePreviouslyAddedObjects();const o=await yf.loadFileFromURL(new URL(e),{guid:this.guid,context:this.context,parent:this.gameObject,point:t.point,size:t.size});if(o&&this._addedObjects.length<=0)return t.url=e,this.onObjectLoaded(o,t,i)}catch{console.warn("String is not a valid URL",e)}return null}_abort=null;async addFromFiles(e,t){if(Xt&&console.log("Add files",e),!!Array.isArray(e)&&e.length){this.deleteDropEvent(),this.removePreviouslyAddedObjects(),Yc(WA,null),this._abort?.abort("New files dropped"),this._abort=new AbortController;for(const i of e){if(!i)continue;if(i.type.startsWith("image/")){Xt&&console.warn("Ignoring dropped image file",i.name,i.type);continue}else if(i.name.endsWith(".bin")){Xt&&console.warn("Ignoring dropped binary file",i.name,i.type);continue}console.debug("Load file "+i.name+" + "+i.type);const n=await yf.loadFile(i,this.context,{guid:this.guid});if(n){this.dispatchEvent(new CustomEvent("file-dropped",{detail:i})),t.file=i;const o=this.onObjectLoaded(n,t,!1);o&&this.context.connection.isConnected&&this.useNetworking&&(console.debug("Uploading dropped file to blob storage"),exports.BlobStorage.upload(i,{abort:this._abort?.signal}).then(r=>{r?.download_url&&this._addedObjects.includes(o)&&this.sendDropEvent(r.download_url,o,n.contentMD5)}).catch(console.warn));break}}}}_addedObjects=new Array;_addedModels=new Array;removePreviouslyAddedObjects(e=!0){if(e)for(const t of this._addedObjects)t.parent===this.gameObject&&t.destroy();this._addedObjects.length=0,this._addedModels.length=0}onObjectLoaded(e,t,i){const{model:n,contentMD5:o}=e;if(Xt&&console.log(`Dropped ${this.gameObject.name}`,n),!n?.scene)return console.warn("No object specified to add to scene",n),null;this.removePreviouslyAddedObjects();const r=n.scene;r.position.copy(this.gameObject.worldPosition);const a=Ve(this.gameObject);let l=new c.Vector3(0,0,0);a.x=Math.abs(a.x),a.y=Math.abs(a.y),a.z=Math.abs(a.z);let h=r.scale.clone();const d=new c.Box3().setFromCenterAndSize(new c.Vector3(0,this.fitVolumeSize.y*a.y*.5,0).add(this.gameObject.worldPosition),this.fitVolumeSize.clone().multiply(a));if(Xt&&B.DrawWireBox3(d,255,5),this.fitIntoVolume&&(Jw(r,d,{position:!this.placeAtHitPosition}),h=r.scale.clone().divide(a),l=r.worldPosition.clone().sub(this.gameObject.worldPosition).divide(a),Xt&&B.DrawSphere(l,.1,16711680,5)),this.gameObject.attach(r),r.position.copy(l),r.quaternion.identity(),r.scale.copy(h),Xt&&B.DrawArrow(this.gameObject.worldPosition,r.getWorldPosition(new c.Vector3),65280,5),this._addedObjects.push(r),this._addedModels.push(n),this.placeAtHitPosition&&t&&t.screenposition){r.visible=!1;const f=this.context.physics.raycast({screenPoint:this.context.input.convertScreenspaceToRaycastSpace(t.screenposition.clone())});if(r.visible=!0,f&&f.length>0)for(const m of f){const g=m.point.clone();Xt&&console.log("Place object at hit",m),ex(r,g);break}}exports.AnimationUtils.autoplayAnimations(n);const u=new VA({sender:this,gltf:n,model:n,object:r,contentMD5:o,dropped:t.file||(t.url?new URL(t.url):void 0)});return this.dispatchEvent(u),this.onDropped?.invoke(u.detail),r&&this.context.events.emit("scene-content-changed",{source:this,object:r}),!i&&t.url?.startsWith("http")&&this.context.connection.isConnected&&r&&this.sendDropEvent(t.url,r,o),r}async sendDropEvent(e,t,i){if(!this.useNetworking){Xt&&console.debug("[DropListener] Ignoring networked event because networking is disabled",e);return}if(this.context.connection.isConnected){console.debug('Sending drop event "'+t.name+'"',e);const n=pi([t]),o={name:t.name,guid:this.guid,url:e,point:t.worldPosition.clone(),size:n.getSize(new c.Vector3),contentMD5:i};this.context.connection.send("droplistener",o)}}deleteDropEvent(){this.context.connection.sendDeleteRemoteState(this.guid)}testIfIsInDropArea(e){const t=this.context.input.convertScreenspaceToRaycastSpace(e.screenposition.clone()),i=this.context.physics.raycast({screenPoint:t,recursive:!0,testObject:o=>!this._addedObjects.some(r=>r.contains(o))});if(!i.length)return E()&&console.log(`Dropped outside of drop area for DropListener "${this.name}".`),!1;const n=i[0];return!!(this.dropArea&&this.dropArea.contains(n.object))}}Tl([p(c.Object3D)],Vs.prototype,"dropArea");Tl([p()],Vs.prototype,"fitIntoVolume");Tl([p(c.Vector3)],Vs.prototype,"fitVolumeSize");Tl([p()],Vs.prototype,"placeAtHitPosition");Tl([p()],Vs.prototype,"useNetworking");Tl([p(Z)],Vs.prototype,"onDropped");function GA(s){if(!s.startsWith("https://polyhaven.com/"))return s;const e="https://dl.polyhaven.org/file/ph-assets/Models/gltf/4k/",n=new URL(s).pathname.split("/").pop(),o=`${e}${n}/${n}_4k.gltf`;return console.log("Resolved polyhaven asset url",s,"→",o),o}var yf;(s=>{async function e(i,n,o){const r=o.guid,a=new ot(r),l=new Blob([i],{type:i.type||T_(i.name)||void 0}),h=URL.createObjectURL(l),d=await Is().loadSync(n,h,i.name,a).catch(u=>(console.error(`Failed to load file "${i.name}" (${i.type}):`,u),null));return URL.revokeObjectURL(h),d?new Promise((u,f)=>{const m=new FileReader;m.readAsArrayBuffer(i),m.onloadend=async g=>{const v=m.result,_=exports.BlobStorage.hashMD5(v);return u({model:d,contentMD5:_})}}):(console.warn(`Failed to load "${i.name}" (${i.type})`),null)}s.loadFile=e;async function t(i,n){const o=new ot(n.guid),r=i.toString();Xt&&B.DrawWireSphere(n.point,.1,16711680,3);const a=exports.PreviewHelper.addPreview({guid:n.guid,parent:n.parent,position:n?.point,size:n?.size});try{const l=await Is().loadSync(n.context,r,r,o,d=>{a.onProgress(d.loaded/d.total)}).catch(d=>(console.warn(d),null));if(!l)return console.warn("Unsupported file type: "+i.toString()),null;let h="";try{const d=await fetch(r).then(u=>u.arrayBuffer());h=exports.BlobStorage.hashMD5(d)}catch(d){console.warn("Failed to compute content hash for "+r,d)}return{model:l,contentMD5:h}}finally{Xt?setTimeout(()=>exports.PreviewHelper.removePreview(n.guid),3e3):exports.PreviewHelper.removePreview(n.guid)}}s.loadFileFromURL=t})(yf||(yf={}));var HA=Object.defineProperty,j_=(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&&HA(e,t,n),n};const cp=class AC extends T{parent=null;object=null;limitCount=60;_currentCount=0;_startPosition=null;_startQuaternion=null;start(){if(this._currentCount=0,this._startPosition=null,this._startQuaternion=null,this.ensureParentGuid(),this.object||(this.object=this.gameObject),this.object){if(this.object===this.gameObject){const t=new ot(this.guid);this.object=P.instantiate(this.object,{idProvider:t,keepWorldPosition:!1}),P.getComponent(this.object,AC)?.destroy();let n=this.object.getComponentInChildren(vr);n||(n=this.object.addComponent(vr,{dragMode:R_.SnapToSurfaces}),n.guid=t.generateUUID());let o=P.getComponent(n.gameObject,Sn);o||(o=n.gameObject.addComponent(Sn),o.guid=t.generateUUID())}this.object.visible=!1;const e=this.gameObject.getComponent(vr);e&&(e.enabled=!1),this._startPosition=this.object.position?.clone()??new c.Vector3(0,0,0),this._startQuaternion=this.object.quaternion?.clone()??new c.Quaternion(0,0,0,1)}this.gameObject.getComponentInParent(Ji)||this.gameObject.addComponent(Ji)}onEnable(){this.startCoroutine(this.cloneLimitIntervalFn())}_forwardPointerEvents=new Map;onPointerEnter(e){e.used||this.object&&this.context.connection.allowEditing&&e.button===0&&this.context.input.setCursor("pointer")}onPointerExit(e){e.used||this.object&&this.context.connection.allowEditing&&e.button===0&&this.context.input.unsetCursor("pointer")}onPointerDown(e){if(e.used||!this.object||!this.context.connection.allowEditing||e.button!==0)return;const t=this.handleDuplication();if(t){const i=P.getComponent(t,vr);i?(i.onPointerDown(e),this._forwardPointerEvents.set(e.event.space,i)):E()&&console.warn(`Duplicated object (${t.name}) does not have DragControls`)}else this._currentCount>=this.limitCount?console.warn(`[Duplicatable] Limit of ${this.limitCount} objects created within a few seconds reached. Please wait a moment before creating more objects.`):console.warn("[Duplicatable] Could not duplicate object.")}onPointerUp(e){if(e.used)return;const t=this._forwardPointerEvents.get(e.event.space);t&&(t.onPointerUp(e),this._forwardPointerEvents.delete(e.event.space))}ensureParentGuid(){this.parent&&(this.parent.guid||this.parent.userData?.guid||(this.parent.guid=new ot(this.guid+"/parent").generateUUID()))}*cloneLimitIntervalFn(){for(;this.activeAndEnabled&&!this.destroyed;)this._currentCount>0?this._currentCount-=1:this._currentCount<0&&(this._currentCount=0),yield Hy(1)}handleDuplication(){if(!this.object||this.limitCount>0&&this._currentCount>=this.limitCount||this.object===this.gameObject)return null;if(P.isDestroyed(this.object))return this.object=null,null;this.object.matrixAutoUpdate===!1&&(this.object.updateMatrix(),E()&&(console.warn(`Object "${this.object.name}" has matrixAutoUpdate disabled. This can cause duplicated objects to have incorrect position/rotation/scale. Consider enabling matrixAutoUpdate or calling updateMatrix() before duplication.`),de("Duplicatable: Object has matrixAutoUpdate disabled"))),this.object.visible=!0,this._startPosition&&this.object.position.copy(this._startPosition),this._startQuaternion&&this.object.quaternion.copy(this._startQuaternion);const e=new hs;this.parent||(this.parent=this.gameObject.parent),this.ensureParentGuid(),this.parent&&(e.parent=this.parent.guid??this.parent.userData?.guid,e.keepWorldPosition=!0),e.position=this.worldPosition,e.rotation=this.worldQuaternion,e.context=this.context,this._currentCount+=1;const t=P.instantiateSynced(this.object,e);return console.assert(t!==this.object,"Duplicated object is original"),this.object.visible=!1,this._startPosition&&this.object.position.clone().copy(this._startPosition),this._startQuaternion&&this.object.quaternion.clone().copy(this._startQuaternion),t}};j_([p(c.Object3D)],cp.prototype,"parent");j_([p(c.Object3D)],cp.prototype,"object");j_([p()],cp.prototype,"limitCount");let U_=cp;var xs=(s=>(s[s.PointerEnter=0]="PointerEnter",s[s.PointerExit=1]="PointerExit",s[s.PointerDown=2]="PointerDown",s[s.PointerUp=3]="PointerUp",s[s.PointerClick=4]="PointerClick",s))(xs||{}),qA=Object.defineProperty,z_=(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&&qA(e,t,n),n};class N_{eventID;callback=new Z}z_([p()],N_.prototype,"eventID");z_([p(Z)],N_.prototype,"callback");class hp extends T{triggers=[];invoke(e){if(this.triggers)for(const t of this.triggers)t.eventID===e&&t.callback?.invoke()}hasTrigger(e){return this.triggers?.some(t=>t.eventID===e)??!1}shouldChangeCursor(){return this.hasTrigger(xs.PointerClick)||this.hasTrigger(xs.PointerDown)||this.hasTrigger(xs.PointerUp)}onPointerClick(e){this.invoke(xs.PointerClick)}onPointerEnter(e){this.shouldChangeCursor()&&this.context.input.setCursor("pointer"),this.invoke(xs.PointerEnter)}onPointerExit(e){this.shouldChangeCursor()&&this.context.input.unsetCursor("pointer"),this.invoke(xs.PointerExit)}onPointerDown(e){this.invoke(xs.PointerDown)}onPointerUp(e){this.invoke(xs.PointerUp)}}z_([p(N_)],hp.prototype,"triggers");class DC{constructor(e){this.writer=e,this.name="EXT_mesh_gpu_instancing"}writeNode(e,t){if(e.constructor.name!=="InstancedMesh")return;const i=this.writer,n=i.extensionsUsed,o={};t.extensions=t.extensions||{},t.extensions[this.name]=o;let r=new c.Matrix4;const a=new Array,l=new Array,h=new Array;for(let m=0;m<e.count;m++){e.getMatrixAt(m,r);let g=new c.Vector3,v=new c.Quaternion,_=new c.Vector3;r.decompose(g,v,_),a.push(g.x,g.y,g.z),l.push(v.x,v.y,v.z,v.w),h.push(_.x,_.y,_.z)}const d=new Float32Array(a),u=new Float32Array(l),f=new Float32Array(h);o.attributes={TRANSLATION:i.processAccessor(new c.BufferAttribute(d,3)),ROTATION:i.processAccessor(new c.BufferAttribute(u,4)),SCALE:i.processAccessor(new c.BufferAttribute(f,3))},n[this.name]=!0}}class IC{writer;constructor(e){this.writer=e}writeNode(e){}}class XA extends IC{beforeWriteNode(e,t){B.isGizmo(e)&&(t.keep=!1)}}class LC extends IC{beforeWriteTexture(e,t){e.isRenderTargetTexture&&(t.newTexture=Yy(new oe(1,1,1,0)))}}function BC(s){const e=as.DontExport;return!(s.hideFlags&e)}function FC(s){return jC(s)}function jC(s,e=[]){let t=0;for(let i=0;i<s.children.length;t++){const n=s.children[i];if(!BC(n)){s.children.splice(i,1),n.parent=null;const o=t;e.push(()=>QA(n,s,o));continue}jC(n,e),i++}return e}function QA(s,e,t){s.parent=e,e.children.splice(Math.min(t,e.children.length),0,s)}var YA=Object.defineProperty,UC=(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&&YA(e,t,n),n};const Xd=x("debuggltfexport");class $_ extends At{sceneRoot}const V_=class Ia extends T{binary=!0;objects=[];ext;async exportNow(e,t){Xd&&console.log("Exporting objects as glTF",this.objects),e||(e="scene"),(!this.objects||this.objects.length<=0)&&(this.objects=[this.context.scene]);const i={binary:this.binary,pivot:Ia.calculateCenter(this.objects),...t},n=await this.export(this.objects,i).catch(o=>(console.error(o),!1));return n===!1?!1:(this.binary?e.endsWith(".glb")||(e+=".glb"):e.endsWith(".gltf")||(e+=".gltf"),this.binary?Ia.saveArrayBuffer(n,e):Ia.saveJson(n,e),!0)}async export(e,t){if(!e||e.length<=0){console.warn("No objects set to export");return}const i=new V.GLTFExporter;i.register(d=>new DC(d)),i.register(d=>new LC(d)),L_(i,this.context),Ia.filterTopmostParent(e);const n={trs:!1,onlyVisible:!0,truncateDrawRange:!1,binary:!0,maxTextureSize:1/0,embedImages:!0,includeCustomExtensions:!0,animations:t?.animations||Ia.collectAnimations(e),...t},o=new Array,r=new c.Object3D;t?.pivot&&r.position.sub(t.pivot),Xd&&console.log("EXPORT",e),e.forEach(d=>{d&&BC(d)&&(r.children.push(d),d.matrixAutoUpdate=!1,d.matrix.copy(d.matrixWorld),P.getComponentsInChildren(d,ti).forEach(u=>{P.isActiveInHierarchy(u.gameObject)&&u.setInstancingEnabled(!1)}),o.push(...FC(d)))});const a=new Eh(r);return t?.needleComponents&&(this.ext=new D_),this.ext&&(this.ext.registerExport(i),this.ext.context=a),new Promise((d,u)=>{Xd&&console.log("Starting glTF export.");try{i?.parse(r,f=>{l(),d(f)},f=>{l(),u(f)},n)}catch(f){console.error(f),l(),u(f)}finally{Xd&&console.log("Finished glTF export.")}});function l(){o.forEach(d=>d()),o.length=0,h()}function h(){e.forEach(d=>{d&&(d.matrixAutoUpdate=!0,P.getComponentsInChildren(d,ti).forEach(u=>{P.isActiveInHierarchy(u.gameObject)&&u.setInstancingEnabled(!1)}))})}}static saveArrayBuffer(e,t){this.save(new Blob([e],{type:"application/octet-stream"}),t)}static saveJson(e,t){this.save("data: text/json;charset=utf-8,"+encodeURIComponent(JSON.stringify(e)),t)}static save(e,t){const i=document.createElement("a");i.style.display="none",document.body.appendChild(i),typeof e=="string"?i.href=e:i.href=URL.createObjectURL(e),i.download=t,i.click(),i.remove()}static collectAnimations(e,t){t=t||[];for(const i of e)i&&i.traverseVisible(n=>{n.animations&&n.animations.length>0&&t.push(...n.animations)});return t}static calculateCenter(e,t){const i=t||new c.Vector3;return i.set(0,0,0),e.forEach(n=>{i.add(ie(n))}),i.divideScalar(e.length),i}static filterTopmostParent(e){if(!(e.length<=0))for(let t=0;t<e.length;t++){let i=e[t];if(!i){e.splice(t,1),t--;continue}for(;i.parent;){if(e.includes(i.parent)){e.splice(t,1),t--;break}i=i.parent}}}};UC([p()],V_.prototype,"binary");UC([p(c.Object3D)],V_.prototype,"objects");let W_=V_;function KA(){typeof globalThis!==void 0&&!("OffscreenCanvas"in globalThis)&&(globalThis.OffscreenCanvas=class{canvas;constructor(e,t){return this.canvas=document.createElement("canvas"),this.canvas.width=e,this.canvas.height=t,this.canvas.convertToBlob=(i,n)=>new Promise(o=>{this.canvas.toBlob(o,i,n)}),this.canvas}})}const ZA=x("debugprogress");function zC(s){s=s||new Date;const e=s.getMonth()+1,t=s.getDate(),i=s.getHours(),n=s.getMinutes(),o=s.getSeconds(),r=(e<10?"0":"")+e,a=(t<10?"0":"")+t,l=(i<10?"0":"")+i,h=(n<10?"0":"")+n,d=(o<10?"0":"")+o;return s.getFullYear()+r+a+"-"+l+h+d}class he{static start(e,t){typeof t=="string"&&(t={parentScope:t});const i=new JA(e,t);Ec.set(e,i)}static report(e,t){const i=Ec.get(e);if(!i){console.warn("Reporting progress for non-existing scope",e);return}typeof t=="string"&&(t={message:t,autoStep:!0}),i.report(t)}static end(e){const t=Ec.get(e);t&&(t.end(),Ec.delete(e))}}const Ec=new Map;class JA{scopeLabel;parentScope;childScopes=[];parentDepth=0;lastStep=0;lastAutoStepWeight=1;lastTotalSteps=0;onProgress;showLogs=!1;selfProgress=0;totalProgress=0;selfReports=0;totalReports=0;constructor(e,t){this.parentScope=t?.parentScope?Ec.get(t.parentScope):void 0,this.parentScope&&(this.parentScope.childScopes.push(this),this.parentDepth=this.parentScope.parentDepth+1),this.scopeLabel=" ".repeat(this.parentDepth*2)+e,this.showLogs=t?.logTimings??!!ZA,this.showLogs&&console.time(this.scopeLabel),this.onProgress=t?.onProgress}report(e,t=!1){if(e){if(e.totalSteps!==void 0&&(this.lastTotalSteps=e.totalSteps),e.currentStep!==void 0&&(this.lastStep=e.currentStep),e.autoStep!==void 0){if(e.currentStep===void 0){this.lastStep===void 0&&(this.lastStep=0);const n=typeof e.autoStep=="number"?e.autoStep:1;this.lastStep+=this.lastAutoStepWeight,this.lastAutoStepWeight=n,e.currentStep=this.lastStep}e.totalSteps=this.lastTotalSteps}e.progress!==void 0?this.selfProgress=e.progress:e.currentStep!==void 0&&e.totalSteps!==void 0&&(this.selfProgress=e.currentStep/e.totalSteps)}if(this.childScopes.length>0){let n=0,o=0;for(const a of this.childScopes)n+=a.selfProgress,o+=1;o>0&&(n/=o);const r=this.lastAutoStepWeight/(this.lastTotalSteps??1);this.totalProgress=this.selfProgress+n*r}else this.totalProgress=this.selfProgress;this.selfProgress=Math.min(1,this.selfProgress),this.totalProgress=Math.min(1,this.totalProgress);let i=(this.totalProgress*100).toFixed(3)+"%";this.childScopes.length>0&&(i+=" ("+(this.selfProgress*100).toFixed(3)+"% self)"),e?.message&&(i=e.message+" – "+i),this.lastStep!==void 0&&this.lastTotalSteps!==void 0&&(i="Step "+(this.lastStep+(this.lastAutoStepWeight!=1?"–"+(this.lastStep+this.lastAutoStepWeight):"")+"/"+this.lastTotalSteps)+" "+i),t?this.totalReports++:(this.selfReports++,this.totalReports++),this.showLogs&&console.timeLog(this.scopeLabel,i),this.onProgress&&this.onProgress(this.totalProgress),this.parentScope&&this.parentScope.report(void 0,!0)}end(){this.report({progress:1,autoStep:!0},!0),this.showLogs&&(console.timeLog(this.scopeLabel,"Total reports: "+this.totalReports,"Self reports: "+this.selfReports),console.timeEnd(this.scopeLabel));let e=!1;for(const t of this.childScopes)if(!(t.selfProgress>=1)){e=!0;break}e&&console.warn("Progress end with child scopes that are still running",this),this.onProgress=void 0}}const Le="</StageRoot/Materials";function eD(s,e,t){const i=new Map,n=v=>{const _=v.type___needle,y=i.get(_)||new Map;if(i.set(_,y),!y.has(v)){const b=`${_}${y.size?`_${y.size}`:""}`;y.set(v,b)}return y.get(v)},o=s.colorNode?Qd(s.colorNode):[],r=s.colorNode?`color3f inputs:diffuseColor.connect = ${Le}/${e}/${n(o.values().next().value)}.outputs:out>`:"",a=s.roughnessNode?Qd(s.roughnessNode):[],l=s.roughnessNode?`float inputs:roughness.connect = ${Le}/${e}/${n(a.values().next().value)}.outputs:out>`:"",h=s.normalNode?Qd(s.normalNode):[],d=s.normalNode?`float3 inputs:normal.connect = ${Le}/${e}/${n(h.values().next().value)}.outputs:out>`:"",u=s.metalnessNode?Qd(s.metalnessNode):[],f=s.metalnessNode?`float inputs:metallic.connect = ${Le}/${e}/${n(u.values().next().value)}.outputs:out>`:"",m=new Set([...o,...a,...h,...u]),g=nD(m,e,t,n);return console.debug(g),`
|
|
1140
|
+
`,defines:{USE_LIGHTMAP:""}})}}var UA=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&&UA(e,t,n),n};const Da=x("debugrenderer"),U0=x("debugskinnedmesh"),z0=x("noinstancing"),zA=x("wireframe");var RC=(s=>(s[s.Off=0]="Off",s[s.BlendProbes=1]="BlendProbes",s[s.BlendProbesAndSkybox=2]="BlendProbesAndSkybox",s[s.Simple=3]="Simple",s))(RC||{});class TC{path=null;asset=null;default}class NA{_renderer;_targets=[];_indexMapMaxIndex;_indexMap;_changed=!1;get changed(){return this._changed}set changed(e){e===!0&&Da&&console.warn("SharedMaterials have changed: "+this._renderer.name),this._changed=e}is(e){return this._renderer===e}constructor(e,t){this._renderer=e;const i=this.setMaterial.bind(this),n=this.getMaterial.bind(this),o=e.gameObject;if(this._targets=[],o)switch(o.type){case"Group":this._targets=[...o.children];break;case"SkinnedMesh":case"Mesh":this._targets.push(o);break}let r=!1,a,l=0;for(let h=0;h<this._targets.length;h++){const d=this._targets[h];if(!d)continue;const u=d.material;if(u){u.shadowSide=u.side;for(let f=0;f<t.length;f++){const m=t[f];if(!m){r=!0;continue}if(u.name===m.name){a===void 0&&(a=new Map),a.set(f,h),l=Math.max(l,f);break}}}}if(r){this._indexMapMaxIndex=l,this._indexMap=a;const h=`Renderer ${e.name} was initialized with missing materials - this may lead to unexpected behaviour when trying to access sharedMaterials by index.`;console.warn(h),ki()&&de("Found renderer with missing materials: please check the console for details.")}return new Proxy(this,{get(h,d){if(typeof d=="string"){const u=parseInt(d);if(!isNaN(u))return n(u)}return h[d]},set(h,d,u){return typeof d=="string"&&i(u,Number.parseInt(d)),Reflect.set(h,d,u)?(u instanceof c.Material&&(h.changed=!0),!0):!1}})}get length(){return this._indexMapMaxIndex!==void 0?this._indexMapMaxIndex+1:this._targets.length}*[Symbol.iterator](){for(let e=0;e<this.length;e++)yield this.getMaterial(e)}resolveIndex(e){const t=this._indexMap;return t&&t.has(e)?t.get(e):e}setMaterial(e,t){if(t=this.resolveIndex(t),t<0||t>=this._targets.length)return;const i=this._targets[t];!i||i.material===void 0||(i.material=e,this.changed=!0)}getMaterial(e){if(e=this.resolveIndex(e),e<0)return null;const t=this._targets;if(e>=t.length)return null;const i=t[e];return i?i.material:null}}const us=class Oc extends T{static setInstanced(e,t){const i=Th(e,Oc);return i.enableInstancing=t,i.setInstancingEnabled(t),i}static isInstanced(e){const t=Bs(e,Oc);return t?t.isInstancingActive:Ki.isUsingInstancing(e)}static setVisible(e,t){Qn(e,t)}receiveShadows=!1;shadowCastingMode=0;lightmapIndex=-1;lightmapScaleOffset=new c.Vector4(1,1,0,0);enableInstancing=void 0;renderOrder=void 0;allowOcclusionWhenDynamic=!0;probeAnchor;reflectionProbeUsage=0;_lightmaps;get sharedMesh(){return this.sharedMeshes[0]}_sharedMeshes=[];get sharedMeshes(){if(this.destroyed||!this.gameObject)return this._sharedMeshes;if(this._sharedMeshes.length=0,this.isMultiMaterialObject(this.gameObject))for(const e of this.gameObject.children)this.isOwnSubmesh(e)&&this._sharedMeshes.push(e);else this.isMeshOrSkinnedMesh(this.gameObject)&&this._sharedMeshes.push(this.gameObject);return this._sharedMeshes}get sharedMaterial(){return this.sharedMaterials?.[0]}set sharedMaterial(e){this.sharedMaterials[0]!==e&&(this.sharedMaterials[0]=e,this.applyLightmapping())}get material(){return this.sharedMaterials?.[0]}set material(e){this.sharedMaterial=e}_sharedMaterials;_originalMaterials;_probeAnchorLastFrame;set sharedMaterials(e){if(!this._originalMaterials)this._originalMaterials=e;else if(e){let t=!1;for(let i=0;i<this._sharedMaterials.length;i++){const n=i<e.length?e[i]:null;n&&n instanceof c.Material?this.sharedMaterials[i]=n:t||(t=!0,console.warn("Can not assign null as material: "+this.name,n))}}}get sharedMaterials(){if(this._originalMaterials===void 0)if(this.__didAwake)this._originalMaterials=[];else return null;return(!this._sharedMaterials||!this._sharedMaterials.is(this))&&(this._originalMaterials||(this._originalMaterials=[]),this._sharedMaterials=new NA(this,this._originalMaterials)),this._sharedMaterials}static get shouldSuppressInstancing(){return z0}_lightmapTextureOverride=void 0;get lightmap(){return this._lightmaps?.length?this._lightmaps[0].lightmap:null}set lightmap(e){if(this._lightmapTextureOverride=e,e===void 0&&(e=this.context.lightmaps.tryGetLightmap(this.sourceId,this.lightmapIndex)),this._lightmaps?.length)for(const t of this._lightmaps)t.lightmap=e}get hasLightmap(){const e=this.lightmap;return e!=null}allowProgressiveLoading=!0;_firstFrame=-1;registering(){this.enabled||this.setVisibility(!1)}awake(){if(this._firstFrame=this.context.time.frame,Da&&console.log("Renderer ",this.name,this),this.clearInstancingState(),this.probeAnchor&&Da&&this.probeAnchor.add(new c.AxesHelper(.2)),this._reflectionProbe=null,this.isMultiMaterialObject(this.gameObject)){for(const e of this.gameObject.children)this.context.addBeforeRenderListener(e,this.onBeforeRenderThree),e.layers.mask=this.gameObject.layers.mask;if(this.renderOrder!==void 0){let e=0;for(let t=0;t<this.gameObject.children.length;t++){const i=this.gameObject.children[t];if(!(!this.isMeshOrSkinnedMesh(i)||P.getComponent(i,Oc))){if(this.renderOrder.length<=e){console.warn("Incorrect renderOrder element count",this,this.renderOrder.length+" but expected "+this.gameObject.children.length,"Index: "+e,"ChildElement:",i);continue}i.renderOrder=this.renderOrder[e],e+=1}}}}else this.isMeshOrSkinnedMesh(this.gameObject)?(this.context.addBeforeRenderListener(this.gameObject,this.onBeforeRenderThree),this.renderOrder!==void 0&&this.renderOrder.length>0&&(this.gameObject.renderOrder=this.renderOrder[0])):this.context.addBeforeRenderListener(this.gameObject,this.onBeforeRenderThree);if(this._lightmaps=void 0,this.applyLightmapping(),zA)for(let e=0;e<this.sharedMaterials.length;e++){const t=this.sharedMaterials[e];t&&(t.wireframe=!0)}}applyLightmapping(){if(this.lightmapIndex>=0&&!this._lightmaps){const e=this._lightmapTextureOverride!==void 0?this._lightmapTextureOverride:this.context.lightmaps.tryGetLightmap(this.sourceId,this.lightmapIndex);if(e){this._lightmaps||(this._lightmaps=[]);const t=new B_(this);t.init(this.lightmapIndex,this.lightmapScaleOffset,e),this._lightmaps.push(t)}else Da&&console.warn(`[Renderer] No lightmaps found ${this.name} (${this.sourceId}, ${this.lightmapIndex})`)}}_isInstancingEnabled=!1;_handles=void 0;get isInstancingActive(){return this._handles!=null&&this._handles.length>0&&this._isInstancingEnabled}get instances(){if(!this._handles||this._handles.length<=0)return null;if(this._handlesTempArray.length=0,this._handles)for(const e of this._handles)this._handlesTempArray.push(e);return this._handlesTempArray}_handlesTempArray=[];setInstancingEnabled(e){if(this._isInstancingEnabled===e){if(!e||this._handles&&this._handles.length>0)return!0}else this._isInstancingEnabled=e;if(e){if(this.enableInstancing===void 0&&(this.enableInstancing=!0),this._handles===void 0||this._handles===null){if(this._handles=jr.instance.setup(this,this.gameObject,this.context,null,{rend:this,foundMeshes:0,useMatrixWorldAutoUpdate:this.useInstanceMatrixWorldAutoUpdate()}),this._handles)return P.markAsInstancedRendered(this.gameObject,!0),!0}else if(this._handles!==null){for(const t of this._handles)t.updateInstanceMatrix(!0),t.add();return P.markAsInstancedRendered(this.gameObject,!0),!0}}else{if(this._handles)for(const t of this._handles)t.remove(this.destroyed);return!0}return!1}clearInstancingState(){this._isInstancingEnabled=!1,this._handles=void 0}useInstanceMatrixWorldAutoUpdate(){return!0}start(){if(this.enableInstancing&&!z0&&(this.setInstancingEnabled(!0),Ki.markDirty(this.gameObject)),this.gameObject.frustumCulled=this.allowOcclusionWhenDynamic,this.isMultiMaterialObject(this.gameObject))for(let e=0;e<this.gameObject.children.length;e++){const t=this.gameObject.children[e];t.frustumCulled=this.allowOcclusionWhenDynamic}}onEnable(){this.sharedMeshes,this.setVisibility(!0),this._isInstancingEnabled||this.enableInstancing==!0||Array.isArray(this.enableInstancing)&&this.enableInstancing.some(t=>t)?this.__internalDidAwakeAndStart&&this.setInstancingEnabled(!0):this.enabled&&this.applyStencil(),this.updateReflectionProbe(),Ps.onEnabled.addEventListener(this.onReflectionProbeEnabled),Ps.onDisabled.addEventListener(this.onReflectionProbeDisabled)}onDisable(){this.setVisibility(!1),Ps.onEnabled.removeEventListener(this.onReflectionProbeEnabled),Ps.onDisabled.removeEventListener(this.onReflectionProbeDisabled),this._handles&&this._handles.length>0&&this.setInstancingEnabled(!1)}onDestroy(){if(this._handles=null,this.isMultiMaterialObject(this.gameObject))for(const e of this.gameObject.children)this.context.removeBeforeRenderListener(e,this.onBeforeRenderThree);else this.context.removeBeforeRenderListener(this.gameObject,this.onBeforeRenderThree)}onReflectionProbeEnabled=()=>{this.updateReflectionProbe()};onReflectionProbeDisabled=e=>{this._reflectionProbe===e&&(this._reflectionProbe.unapply(this.gameObject),this._reflectionProbe=null)};onBeforeRender(){if(this.gameObject){if((this._probeAnchorLastFrame!==this.probeAnchor||this._reflectionProbe?.activeAndEnabled===!1)&&(this._reflectionProbe?.unapply(this.gameObject),this.updateReflectionProbe()),Da==this.name&&this.gameObject instanceof c.Mesh){this.gameObject.geometry.computeBoundingSphere();const e=F(this.gameObject.geometry.boundingSphere.center).applyMatrix4(this.gameObject.matrixWorld);B.DrawWireSphere(e,this.gameObject.geometry.boundingSphere.radius,56831)}if(this.isMultiMaterialObject(this.gameObject)&&this.gameObject.children?.length>0)for(const e of this.gameObject.children)this.applySettings(e);else this.applySettings(this.gameObject);if(this.sharedMaterials?.changed&&(this.sharedMaterials.changed=!1,this.applyLightmapping()),this._handles?.length&&this.gameObject[rh]===!0){this.gameObject[rh]=!1;for(let t=this._handles.length-1;t>=0;t--)this._handles[t].updateInstanceMatrix();this.gameObject.matrixWorldNeedsUpdate=!1}if(this._handles&&this._handles.length<=0&&P.markAsInstancedRendered(this.gameObject,!1),this._isInstancingEnabled&&this._handles)for(let e=0;e<this._handles.length;e++){const t=this._handles[e];Qn(t.object,!1)}if(this.reflectionProbeUsage!==0&&this._reflectionProbe?this._reflectionProbe.apply(this.gameObject):this.reflectionProbeUsage===0&&this._reflectionProbe&&this._reflectionProbe.unapply(this.gameObject),this._sharedMaterials)for(const e of this._sharedMaterials)e&&"envMap"in e&&"envMapIntensity"in e&&!Ps.isUsingReflectionProbe(e)&&(e.envMap=this.context.scene.environment,e.envMapRotation=this.context.scene.environmentRotation);else Da&&console.warn("[Renderer] sharedMaterials not initialized yet: "+this.name)}}onBeforeRenderThree=(e,t,i,n,o,r)=>{if(o.envMapIntensity!==void 0){const a=this.hasLightmap?Math.PI:1,l=this.context.scene.environmentIntensity;o.envMapIntensity=Math.max(0,l*this.context.sceneLighting.environmentIntensity/a)}if(this._lightmaps)for(const a of this._lightmaps)a.updateLightmapUniforms(o),a.applyLightmap()};onAfterRender(){if(this._isInstancingEnabled&&this._handles)for(let e=0;e<this._handles.length;e++){const t=this._handles[e];Qn(t.object,!0)}this._reflectionProbe?.activeAndEnabled===!1&&this._reflectionProbe.unapply(this.gameObject),this.static&&this.gameObject.matrixAutoUpdate&&this.context.time.frame-this._firstFrame>=10&&(this.gameObject.matrixAutoUpdate=!1)}applyStencil(){bo.applyStencil(this)}applySettings(e){e.receiveShadow=this.receiveShadows,this.shadowCastingMode==1?e.castShadow=!0:e.castShadow=!1}_reflectionProbe=null;updateReflectionProbe(){this._reflectionProbe=null,this.reflectionProbeUsage!==0&&(this.startCoroutine(this._updateReflectionProbe(),Ce.LateUpdate),this._probeAnchorLastFrame=this.probeAnchor)}*_updateReflectionProbe(){const e=this.probeAnchor||this.gameObject,t=!!this.probeAnchor;this._reflectionProbe=Ps.get(e,this.context,t,this.probeAnchor)}setVisibility(e){if(!this.isMultiMaterialObject(this.gameObject))Qn(this.gameObject,e);else for(const t of this.gameObject.children)this.isOwnSubmesh(t)&&Qn(t,e)}isMultiMaterialObject(e){return e.type==="Group"}isMeshOrSkinnedMesh(e){return e.type==="Mesh"||e.type==="SkinnedMesh"}isOwnSubmesh(e){return this.isMeshOrSkinnedMesh(e)&&!Bs(e,Oc)}};$s([p()],us.prototype,"receiveShadows");$s([p()],us.prototype,"shadowCastingMode");$s([p()],us.prototype,"lightmapIndex");$s([p(c.Vector4)],us.prototype,"lightmapScaleOffset");$s([p()],us.prototype,"enableInstancing");$s([p()],us.prototype,"renderOrder");$s([p()],us.prototype,"allowOcclusionWhenDynamic");$s([p(c.Object3D)],us.prototype,"probeAnchor");$s([p()],us.prototype,"reflectionProbeUsage");let ti=us;class Vh extends ti{}class F_ extends Vh{_needUpdateBoundingSphere=!1;awake(){super.awake(),U0&&console.log('SkinnedMeshRenderer for "'+this.name+'"',this),this.allowOcclusionWhenDynamic=!1;for(const e of this.sharedMeshes)e.parent?.updateWorldMatrix(!1,!0),this.markBoundsDirty()}onAfterRender(){if(super.onAfterRender(),this._needUpdateBoundingSphere){for(const e of this.sharedMeshes)if(e instanceof c.SkinnedMesh){this._needUpdateBoundingSphere=!1;try{const t=e.geometry,i=re.getRaycastMesh(e);i&&(e.geometry=i),e.computeBoundingSphere(),e.geometry=t}catch(t){console.error(`Error updating bounding sphere for ${e.name}`,t)}}}if(U0){for(const e of this.sharedMeshes)if(e instanceof c.SkinnedMesh&&e.boundingSphere){const t=F(e.boundingSphere.center).applyMatrix4(e.matrixWorld);B.DrawWireSphere(t,e.boundingSphere.radius,"red")}}}markBoundsDirty(){this._needUpdateBoundingSphere=!0}}var gf=(s=>(s[s.Off=0]="Off",s[s.On=1]="On",s[s.TwoSided=2]="TwoSided",s[s.ShadowsOnly=3]="ShadowsOnly",s))(gf||{}),$A=Object.defineProperty,Tl=(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&&$A(e,t,n),n};const Xt=x("debugdroplistener");class VA extends CustomEvent{constructor(e){super("object-added",{detail:e})}}const WA="blob";class Vs extends T{dropArea;fitIntoVolume=!1;fitVolumeSize=new c.Vector3(1,1,1);placeAtHitPosition=!0;useNetworking=!1;onDropped=new Z;loadFromURL(e,t){return this.addFromUrl(e,{screenposition:new c.Vector2,point:t?.point,size:t?.size},!1)}forgetObjects(){this.removePreviouslyAddedObjects(!1)}awake(){for(const e of this.gameObject.children)this.dropArea&&e.contains(this.dropArea)||this._addedObjects.push(e)}onEnable(){this.context.renderer.domElement.addEventListener("dragover",this.onDrag),this.context.renderer.domElement.addEventListener("drop",this.onDrop),window.addEventListener("paste",this.handlePaste),this.context.connection.beginListen("droplistener",this.onNetworkEvent),E()&&this.dropArea&&(this.dropArea.getComponentInChildren(ti)||console.warn("[DropListener] The assigned DropArea does not seem to have a renderer/mesh. Drag and Drop events will not be detected."))}onDisable(){this.context.renderer.domElement.removeEventListener("dragover",this.onDrag),this.context.renderer.domElement.removeEventListener("drop",this.onDrop),window.removeEventListener("paste",this.handlePaste),this.context.connection.stopListen("droplistener",this.onNetworkEvent)}onNetworkEvent=e=>{if(!this.useNetworking){Xt&&console.debug("[DropListener] Ignoring networked event because networking is disabled",e);return}if(e.guid?.startsWith(this.guid)){const t=e.url;if(console.debug("[DropListener] Received networked event",e),t)if(Array.isArray(t))for(const i of t)this.addFromUrl(i,{screenposition:new c.Vector2,point:e.point,size:e.size},!0);else this.addFromUrl(t,{screenposition:new c.Vector2,point:e.point,size:e.size},!0)}};handlePaste=e=>{if(this.context.connection.allowEditing===!1||e.defaultPrevented)return;navigator.clipboard.readText().then(i=>{if(i&&(i.startsWith("http")||i.startsWith("https")||i.startsWith("blob"))){const o={screenposition:new c.Vector2(this.context.input.mousePosition.x,this.context.input.mousePosition.y)};this.testIfIsInDropArea(o)&&this.addFromUrl(i,o,!1)}}).catch(console.warn)};onDrag=e=>{Xt&&console.debug("DropListener Drag",e,this.context.connection.allowEditing),this.context.connection.allowEditing!==!1&&e.preventDefault()};onDrop=async e=>{if(Xt&&console.debug("DropListener Drop",e,this.context.connection.allowEditing),this.context.connection.allowEditing===!1||!e?.dataTransfer||e["droplistener:handled"])return;e.preventDefault();const t={screenposition:new c.Vector2(e.offsetX,e.offsetY)};if(this.dropArea&&this.testIfIsInDropArea(t)===!1)return;e["droplistener:handled"]=!0;const i=e.dataTransfer.items;if(!i)return;const n=[];for(const o in i){const r=i[o];if(r.kind==="file"){const a=r.getAsFile();if(!a)continue;n.push(a)}else r.kind==="string"&&r.type=="text/plain"&&r.getAsString(a=>{this.addFromUrl(a,t,!1)})}n.length>0&&await this.addFromFiles(n,t)};async addFromUrl(e,t,i){Xt&&console.log("dropped url",e);try{if(e.startsWith("https://github.com/")){const r=e.split("/"),a=r[3],l=r[4],h=r[6],d=r.slice(7).join("/");e=`https://raw.githubusercontent.com/${a}/${l}/${h}/${d}`}else e.startsWith("https://polyhaven.com/a")&&(e=GA(e));if(!e)return null;const n=e.toLowerCase();if(n.endsWith(".hdr")||n.endsWith(".hdri")||n.endsWith(".exr")||n.endsWith(".png")||n.endsWith(".jpg")||n.endsWith(".jpeg"))return console.warn(`Fileformat is not supported: ${n}`),null;this.removePreviouslyAddedObjects();const o=await yf.loadFileFromURL(new URL(e),{guid:this.guid,context:this.context,parent:this.gameObject,point:t.point,size:t.size});if(o&&this._addedObjects.length<=0)return t.url=e,this.onObjectLoaded(o,t,i)}catch{console.warn("String is not a valid URL",e)}return null}_abort=null;async addFromFiles(e,t){if(Xt&&console.log("Add files",e),!!Array.isArray(e)&&e.length){this.deleteDropEvent(),this.removePreviouslyAddedObjects(),Yc(WA,null),this._abort?.abort("New files dropped"),this._abort=new AbortController;for(const i of e){if(!i)continue;if(i.type.startsWith("image/")){Xt&&console.warn("Ignoring dropped image file",i.name,i.type);continue}else if(i.name.endsWith(".bin")){Xt&&console.warn("Ignoring dropped binary file",i.name,i.type);continue}console.debug("Load file "+i.name+" + "+i.type);const n=await yf.loadFile(i,this.context,{guid:this.guid});if(n){this.dispatchEvent(new CustomEvent("file-dropped",{detail:i})),t.file=i;const o=this.onObjectLoaded(n,t,!1);o&&this.context.connection.isConnected&&this.useNetworking&&(console.debug("Uploading dropped file to blob storage"),exports.BlobStorage.upload(i,{abort:this._abort?.signal}).then(r=>{r?.download_url&&this._addedObjects.includes(o)&&this.sendDropEvent(r.download_url,o,n.contentMD5)}).catch(console.warn));break}}}}_addedObjects=new Array;_addedModels=new Array;removePreviouslyAddedObjects(e=!0){if(e)for(const t of this._addedObjects)t.parent===this.gameObject&&t.destroy();this._addedObjects.length=0,this._addedModels.length=0}onObjectLoaded(e,t,i){const{model:n,contentMD5:o}=e;if(Xt&&console.log(`Dropped ${this.gameObject.name}`,n),!n?.scene)return console.warn("No object specified to add to scene",n),null;this.removePreviouslyAddedObjects();const r=n.scene;r.position.copy(this.gameObject.worldPosition);const a=Ve(this.gameObject);let l=new c.Vector3(0,0,0);a.x=Math.abs(a.x),a.y=Math.abs(a.y),a.z=Math.abs(a.z);let h=r.scale.clone();const d=new c.Box3().setFromCenterAndSize(new c.Vector3(0,this.fitVolumeSize.y*a.y*.5,0).add(this.gameObject.worldPosition),this.fitVolumeSize.clone().multiply(a));if(Xt&&B.DrawWireBox3(d,255,5),this.fitIntoVolume&&(Jw(r,d,{position:!this.placeAtHitPosition}),h=r.scale.clone().divide(a),l=r.worldPosition.clone().sub(this.gameObject.worldPosition).divide(a),Xt&&B.DrawSphere(l,.1,16711680,5)),this.gameObject.attach(r),r.position.copy(l),r.quaternion.identity(),r.scale.copy(h),Xt&&B.DrawArrow(this.gameObject.worldPosition,r.getWorldPosition(new c.Vector3),65280,5),this._addedObjects.push(r),this._addedModels.push(n),this.placeAtHitPosition&&t&&t.screenposition){r.visible=!1;const f=this.context.physics.raycast({screenPoint:this.context.input.convertScreenspaceToRaycastSpace(t.screenposition.clone())});if(r.visible=!0,f&&f.length>0)for(const m of f){const g=m.point.clone();Xt&&console.log("Place object at hit",m),ex(r,g);break}}exports.AnimationUtils.autoplayAnimations(n);const u=new VA({sender:this,gltf:n,model:n,object:r,contentMD5:o,dropped:t.file||(t.url?new URL(t.url):void 0)});return this.dispatchEvent(u),this.onDropped?.invoke(u.detail),r&&this.context.events.emit("scene-content-changed",{source:this,object:r}),!i&&t.url?.startsWith("http")&&this.context.connection.isConnected&&r&&this.sendDropEvent(t.url,r,o),r}async sendDropEvent(e,t,i){if(!this.useNetworking){Xt&&console.debug("[DropListener] Ignoring networked event because networking is disabled",e);return}if(this.context.connection.isConnected){console.debug('Sending drop event "'+t.name+'"',e);const n=pi([t]),o={name:t.name,guid:this.guid,url:e,point:t.worldPosition.clone(),size:n.getSize(new c.Vector3),contentMD5:i};this.context.connection.send("droplistener",o)}}deleteDropEvent(){this.context.connection.sendDeleteRemoteState(this.guid)}testIfIsInDropArea(e){const t=this.context.input.convertScreenspaceToRaycastSpace(e.screenposition.clone()),i=this.context.physics.raycast({screenPoint:t,recursive:!0,testObject:o=>!this._addedObjects.some(r=>r.contains(o))});if(!i.length)return E()&&console.log(`Dropped outside of drop area for DropListener "${this.name}".`),!1;const n=i[0];return!!(this.dropArea&&this.dropArea.contains(n.object))}}Tl([p(c.Object3D)],Vs.prototype,"dropArea");Tl([p()],Vs.prototype,"fitIntoVolume");Tl([p(c.Vector3)],Vs.prototype,"fitVolumeSize");Tl([p()],Vs.prototype,"placeAtHitPosition");Tl([p()],Vs.prototype,"useNetworking");Tl([p(Z)],Vs.prototype,"onDropped");function GA(s){if(!s.startsWith("https://polyhaven.com/"))return s;const e="https://dl.polyhaven.org/file/ph-assets/Models/gltf/4k/",n=new URL(s).pathname.split("/").pop(),o=`${e}${n}/${n}_4k.gltf`;return console.log("Resolved polyhaven asset url",s,"→",o),o}var yf;(s=>{async function e(i,n,o){const r=o.guid,a=new ot(r),l=new Blob([i],{type:i.type||T_(i.name)||void 0}),h=URL.createObjectURL(l),d=await Is().loadSync(n,h,i.name,a).catch(u=>(console.error(`Failed to load file "${i.name}" (${i.type}):`,u),null));return URL.revokeObjectURL(h),d?new Promise((u,f)=>{const m=new FileReader;m.readAsArrayBuffer(i),m.onloadend=async g=>{const v=m.result,_=exports.BlobStorage.hashMD5(v);return u({model:d,contentMD5:_})}}):(console.warn(`Failed to load "${i.name}" (${i.type})`),null)}s.loadFile=e;async function t(i,n){const o=new ot(n.guid),r=i.toString();Xt&&B.DrawWireSphere(n.point,.1,16711680,3);const a=exports.PreviewHelper.addPreview({guid:n.guid,parent:n.parent,position:n?.point,size:n?.size});try{const l=await Is().loadSync(n.context,r,r,o,d=>{a.onProgress(d.loaded/d.total)}).catch(d=>(console.warn(d),null));if(!l)return console.warn("Unsupported file type: "+i.toString()),null;let h="";try{const d=await fetch(r).then(u=>u.arrayBuffer());h=exports.BlobStorage.hashMD5(d)}catch(d){console.warn("Failed to compute content hash for "+r,d)}return{model:l,contentMD5:h}}finally{Xt?setTimeout(()=>exports.PreviewHelper.removePreview(n.guid),3e3):exports.PreviewHelper.removePreview(n.guid)}}s.loadFileFromURL=t})(yf||(yf={}));var HA=Object.defineProperty,j_=(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&&HA(e,t,n),n};const cp=class AC extends T{parent=null;object=null;limitCount=60;_currentCount=0;_startPosition=null;_startQuaternion=null;start(){if(this._currentCount=0,this._startPosition=null,this._startQuaternion=null,this.ensureParentGuid(),this.object||(this.object=this.gameObject),this.object){if(this.object===this.gameObject){const t=new ot(this.guid);this.object=P.instantiate(this.object,{idProvider:t,keepWorldPosition:!1}),P.getComponent(this.object,AC)?.destroy();let n=this.object.getComponentInChildren(vr);n||(n=this.object.addComponent(vr,{dragMode:R_.SnapToSurfaces}),n.guid=t.generateUUID());let o=P.getComponent(n.gameObject,Sn);o||(o=n.gameObject.addComponent(Sn),o.guid=t.generateUUID())}this.object.visible=!1;const e=this.gameObject.getComponent(vr);e&&(e.enabled=!1),this._startPosition=this.object.position?.clone()??new c.Vector3(0,0,0),this._startQuaternion=this.object.quaternion?.clone()??new c.Quaternion(0,0,0,1)}this.gameObject.getComponentInParent(Ji)||this.gameObject.addComponent(Ji)}onEnable(){this.startCoroutine(this.cloneLimitIntervalFn())}_forwardPointerEvents=new Map;onPointerEnter(e){e.used||this.object&&this.context.connection.allowEditing&&e.button===0&&this.context.input.setCursor("pointer")}onPointerExit(e){e.used||this.object&&this.context.connection.allowEditing&&e.button===0&&this.context.input.unsetCursor("pointer")}onPointerDown(e){if(e.used||!this.object||!this.context.connection.allowEditing||e.button!==0)return;const t=this.handleDuplication();if(t){const i=P.getComponent(t,vr);i?(i.onPointerDown(e),this._forwardPointerEvents.set(e.event.space,i)):E()&&console.warn(`Duplicated object (${t.name}) does not have DragControls`)}else this._currentCount>=this.limitCount?console.warn(`[Duplicatable] Limit of ${this.limitCount} objects created within a few seconds reached. Please wait a moment before creating more objects.`):console.warn("[Duplicatable] Could not duplicate object.")}onPointerUp(e){if(e.used)return;const t=this._forwardPointerEvents.get(e.event.space);t&&(t.onPointerUp(e),this._forwardPointerEvents.delete(e.event.space))}ensureParentGuid(){this.parent&&(this.parent.guid||this.parent.userData?.guid||(this.parent.guid=new ot(this.guid+"/parent").generateUUID()))}*cloneLimitIntervalFn(){for(;this.activeAndEnabled&&!this.destroyed;)this._currentCount>0?this._currentCount-=1:this._currentCount<0&&(this._currentCount=0),yield Hy(1)}handleDuplication(){if(!this.object||this.limitCount>0&&this._currentCount>=this.limitCount||this.object===this.gameObject)return null;if(P.isDestroyed(this.object))return this.object=null,null;this.object.matrixAutoUpdate===!1&&(this.object.updateMatrix(),E()&&(console.warn(`Object "${this.object.name}" has matrixAutoUpdate disabled. This can cause duplicated objects to have incorrect position/rotation/scale. Consider enabling matrixAutoUpdate or calling updateMatrix() before duplication.`),de("Duplicatable: Object has matrixAutoUpdate disabled"))),this.object.visible=!0,this._startPosition&&this.object.position.copy(this._startPosition),this._startQuaternion&&this.object.quaternion.copy(this._startQuaternion);const e=new hs;this.parent||(this.parent=this.gameObject.parent),this.ensureParentGuid(),this.parent&&(e.parent=this.parent.guid??this.parent.userData?.guid,e.keepWorldPosition=!0),e.position=this.worldPosition,e.rotation=this.worldQuaternion,e.context=this.context,this._currentCount+=1;const t=P.instantiateSynced(this.object,e);return console.assert(t!==this.object,"Duplicated object is original"),this.object.visible=!1,this._startPosition&&this.object.position.clone().copy(this._startPosition),this._startQuaternion&&this.object.quaternion.clone().copy(this._startQuaternion),t}};j_([p(c.Object3D)],cp.prototype,"parent");j_([p(c.Object3D)],cp.prototype,"object");j_([p()],cp.prototype,"limitCount");let U_=cp;var xs=(s=>(s[s.PointerEnter=0]="PointerEnter",s[s.PointerExit=1]="PointerExit",s[s.PointerDown=2]="PointerDown",s[s.PointerUp=3]="PointerUp",s[s.PointerClick=4]="PointerClick",s))(xs||{}),qA=Object.defineProperty,z_=(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&&qA(e,t,n),n};class N_{eventID;callback=new Z}z_([p()],N_.prototype,"eventID");z_([p(Z)],N_.prototype,"callback");class hp extends T{triggers=[];invoke(e){if(this.triggers)for(const t of this.triggers)t.eventID===e&&t.callback?.invoke()}hasTrigger(e){return this.triggers?.some(t=>t.eventID===e)??!1}shouldChangeCursor(){return this.hasTrigger(xs.PointerClick)||this.hasTrigger(xs.PointerDown)||this.hasTrigger(xs.PointerUp)}onPointerClick(e){this.invoke(xs.PointerClick)}onPointerEnter(e){this.shouldChangeCursor()&&this.context.input.setCursor("pointer"),this.invoke(xs.PointerEnter)}onPointerExit(e){this.shouldChangeCursor()&&this.context.input.unsetCursor("pointer"),this.invoke(xs.PointerExit)}onPointerDown(e){this.invoke(xs.PointerDown)}onPointerUp(e){this.invoke(xs.PointerUp)}}z_([p(N_)],hp.prototype,"triggers");class DC{constructor(e){this.writer=e,this.name="EXT_mesh_gpu_instancing"}writeNode(e,t){if(e.constructor.name!=="InstancedMesh")return;const i=this.writer,n=i.extensionsUsed,o={};t.extensions=t.extensions||{},t.extensions[this.name]=o;let r=new c.Matrix4;const a=new Array,l=new Array,h=new Array;for(let m=0;m<e.count;m++){e.getMatrixAt(m,r);let g=new c.Vector3,v=new c.Quaternion,_=new c.Vector3;r.decompose(g,v,_),a.push(g.x,g.y,g.z),l.push(v.x,v.y,v.z,v.w),h.push(_.x,_.y,_.z)}const d=new Float32Array(a),u=new Float32Array(l),f=new Float32Array(h);o.attributes={TRANSLATION:i.processAccessor(new c.BufferAttribute(d,3)),ROTATION:i.processAccessor(new c.BufferAttribute(u,4)),SCALE:i.processAccessor(new c.BufferAttribute(f,3))},n[this.name]=!0}}class IC{writer;constructor(e){this.writer=e}writeNode(e){}}class XA extends IC{beforeWriteNode(e,t){B.isGizmo(e)&&(t.keep=!1)}}class LC extends IC{beforeWriteTexture(e,t){e.isRenderTargetTexture&&(t.newTexture=Yy(new oe(1,1,1,0)))}}function BC(s){const e=as.DontExport;return!(s.hideFlags&e)}function FC(s){return jC(s)}function jC(s,e=[]){let t=0;for(let i=0;i<s.children.length;t++){const n=s.children[i];if(!BC(n)){s.children.splice(i,1),n.parent=null;const o=t;e.push(()=>QA(n,s,o));continue}jC(n,e),i++}return e}function QA(s,e,t){s.parent=e,e.children.splice(Math.min(t,e.children.length),0,s)}var YA=Object.defineProperty,UC=(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&&YA(e,t,n),n};const Xd=x("debuggltfexport");class $_ extends At{sceneRoot}const V_=class Ia extends T{binary=!0;objects=[];ext;async exportNow(e,t){Xd&&console.log("Exporting objects as glTF",this.objects),e||(e="scene"),(!this.objects||this.objects.length<=0)&&(this.objects=[this.context.scene]);const i={binary:this.binary,pivot:Ia.calculateCenter(this.objects),...t},n=await this.export(this.objects,i).catch(o=>(console.error(o),!1));return n===!1?!1:(this.binary?e.endsWith(".glb")||(e+=".glb"):e.endsWith(".gltf")||(e+=".gltf"),this.binary?Ia.saveArrayBuffer(n,e):Ia.saveJson(n,e),!0)}async export(e,t){if(!e||e.length<=0){console.warn("No objects set to export");return}const i=new V.GLTFExporter;i.register(d=>new DC(d)),i.register(d=>new LC(d)),L_(i,this.context),Ia.filterTopmostParent(e);const n={trs:!1,onlyVisible:!0,truncateDrawRange:!1,binary:!0,maxTextureSize:1/0,embedImages:!0,includeCustomExtensions:!0,animations:t?.animations||Ia.collectAnimations(e),...t},o=new Array,r=new c.Object3D;t?.pivot&&r.position.sub(t.pivot),Xd&&console.log("EXPORT",e),e.forEach(d=>{d&&BC(d)&&(r.children.push(d),d.matrixAutoUpdate=!1,d.matrix.copy(d.matrixWorld),P.getComponentsInChildren(d,ti).forEach(u=>{P.isActiveInHierarchy(u.gameObject)&&u.setInstancingEnabled(!1)}),o.push(...FC(d)))});const a=new Eh(r);return t?.needleComponents&&(this.ext=new D_),this.ext&&(this.ext.registerExport(i),this.ext.context=a),new Promise((d,u)=>{Xd&&console.log("Starting glTF export.");try{i?.parse(r,f=>{l(),d(f)},f=>{l(),u(f)},n)}catch(f){console.error(f),l(),u(f)}finally{Xd&&console.log("Finished glTF export.")}});function l(){o.forEach(d=>d()),o.length=0,h()}function h(){e.forEach(d=>{d&&(d.matrixAutoUpdate=!0,P.getComponentsInChildren(d,ti).forEach(u=>{P.isActiveInHierarchy(u.gameObject)&&u.setInstancingEnabled(!1)}))})}}static saveArrayBuffer(e,t){this.save(new Blob([e],{type:"application/octet-stream"}),t)}static saveJson(e,t){this.save("data: text/json;charset=utf-8,"+encodeURIComponent(JSON.stringify(e)),t)}static save(e,t){const i=document.createElement("a");i.style.display="none",document.body.appendChild(i),typeof e=="string"?i.href=e:i.href=URL.createObjectURL(e),i.download=t,i.click(),i.remove()}static collectAnimations(e,t){t=t||[];for(const i of e)i&&i.traverseVisible(n=>{n.animations&&n.animations.length>0&&t.push(...n.animations)});return t}static calculateCenter(e,t){const i=t||new c.Vector3;return i.set(0,0,0),e.forEach(n=>{i.add(ie(n))}),i.divideScalar(e.length),i}static filterTopmostParent(e){if(!(e.length<=0))for(let t=0;t<e.length;t++){let i=e[t];if(!i){e.splice(t,1),t--;continue}for(;i.parent;){if(e.includes(i.parent)){e.splice(t,1),t--;break}i=i.parent}}}};UC([p()],V_.prototype,"binary");UC([p(c.Object3D)],V_.prototype,"objects");let W_=V_;function KA(){typeof globalThis!==void 0&&!("OffscreenCanvas"in globalThis)&&(globalThis.OffscreenCanvas=class{canvas;constructor(e,t){return this.canvas=document.createElement("canvas"),this.canvas.width=e,this.canvas.height=t,this.canvas.convertToBlob=(i,n)=>new Promise(o=>{this.canvas.toBlob(o,i,n)}),this.canvas}})}const ZA=x("debugprogress");function zC(s){s=s||new Date;const e=s.getMonth()+1,t=s.getDate(),i=s.getHours(),n=s.getMinutes(),o=s.getSeconds(),r=(e<10?"0":"")+e,a=(t<10?"0":"")+t,l=(i<10?"0":"")+i,h=(n<10?"0":"")+n,d=(o<10?"0":"")+o;return s.getFullYear()+r+a+"-"+l+h+d}class he{static start(e,t){typeof t=="string"&&(t={parentScope:t});const i=new JA(e,t);Ec.set(e,i)}static report(e,t){const i=Ec.get(e);if(!i){console.warn("Reporting progress for non-existing scope",e);return}typeof t=="string"&&(t={message:t,autoStep:!0}),i.report(t)}static end(e){const t=Ec.get(e);t&&(t.end(),Ec.delete(e))}}const Ec=new Map;class JA{scopeLabel;parentScope;childScopes=[];parentDepth=0;lastStep=0;lastAutoStepWeight=1;lastTotalSteps=0;onProgress;showLogs=!1;selfProgress=0;totalProgress=0;selfReports=0;totalReports=0;constructor(e,t){this.parentScope=t?.parentScope?Ec.get(t.parentScope):void 0,this.parentScope&&(this.parentScope.childScopes.push(this),this.parentDepth=this.parentScope.parentDepth+1),this.scopeLabel=" ".repeat(this.parentDepth*2)+e,this.showLogs=t?.logTimings??!!ZA,this.showLogs&&console.time(this.scopeLabel),this.onProgress=t?.onProgress}report(e,t=!1){if(e){if(e.totalSteps!==void 0&&(this.lastTotalSteps=e.totalSteps),e.currentStep!==void 0&&(this.lastStep=e.currentStep),e.autoStep!==void 0){if(e.currentStep===void 0){this.lastStep===void 0&&(this.lastStep=0);const n=typeof e.autoStep=="number"?e.autoStep:1;this.lastStep+=this.lastAutoStepWeight,this.lastAutoStepWeight=n,e.currentStep=this.lastStep}e.totalSteps=this.lastTotalSteps}e.progress!==void 0?this.selfProgress=e.progress:e.currentStep!==void 0&&e.totalSteps!==void 0&&(this.selfProgress=e.currentStep/e.totalSteps)}if(this.childScopes.length>0){let n=0,o=0;for(const a of this.childScopes)n+=a.selfProgress,o+=1;o>0&&(n/=o);const r=this.lastAutoStepWeight/(this.lastTotalSteps??1);this.totalProgress=this.selfProgress+n*r}else this.totalProgress=this.selfProgress;this.selfProgress=Math.min(1,this.selfProgress),this.totalProgress=Math.min(1,this.totalProgress);let i=(this.totalProgress*100).toFixed(3)+"%";this.childScopes.length>0&&(i+=" ("+(this.selfProgress*100).toFixed(3)+"% self)"),e?.message&&(i=e.message+" – "+i),this.lastStep!==void 0&&this.lastTotalSteps!==void 0&&(i="Step "+(this.lastStep+(this.lastAutoStepWeight!=1?"–"+(this.lastStep+this.lastAutoStepWeight):"")+"/"+this.lastTotalSteps)+" "+i),t?this.totalReports++:(this.selfReports++,this.totalReports++),this.showLogs&&console.timeLog(this.scopeLabel,i),this.onProgress&&this.onProgress(this.totalProgress),this.parentScope&&this.parentScope.report(void 0,!0)}end(){this.report({progress:1,autoStep:!0},!0),this.showLogs&&(console.timeLog(this.scopeLabel,"Total reports: "+this.totalReports,"Self reports: "+this.selfReports),console.timeEnd(this.scopeLabel));let e=!1;for(const t of this.childScopes)if(!(t.selfProgress>=1)){e=!0;break}e&&console.warn("Progress end with child scopes that are still running",this),this.onProgress=void 0}}const Le="</StageRoot/Materials";function eD(s,e,t){const i=new Map,n=v=>{const _=v.type___needle,y=i.get(_)||new Map;if(i.set(_,y),!y.has(v)){const b=`${_}${y.size?`_${y.size}`:""}`;y.set(v,b)}return y.get(v)},o=s.colorNode?Qd(s.colorNode):[],r=s.colorNode?`color3f inputs:diffuseColor.connect = ${Le}/${e}/${n(o.values().next().value)}.outputs:out>`:"",a=s.roughnessNode?Qd(s.roughnessNode):[],l=s.roughnessNode?`float inputs:roughness.connect = ${Le}/${e}/${n(a.values().next().value)}.outputs:out>`:"",h=s.normalNode?Qd(s.normalNode):[],d=s.normalNode?`float3 inputs:normal.connect = ${Le}/${e}/${n(h.values().next().value)}.outputs:out>`:"",u=s.metalnessNode?Qd(s.metalnessNode):[],f=s.metalnessNode?`float inputs:metallic.connect = ${Le}/${e}/${n(u.values().next().value)}.outputs:out>`:"",m=new Set([...o,...a,...h,...u]),g=nD(m,e,t,n);return console.debug(g),`
|
|
1141
1141
|
|
|
1142
1142
|
def Material "${e}" ${s.name?`(
|
|
1143
1143
|
displayName = "${s.name}"
|
|
@@ -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=`
|
|
@@ -1525,7 +1525,7 @@ To allow joining a room without a query parameter you can set "requireRoomParame
|
|
|
1525
1525
|
Please choose one of the following options to fix this:
|
|
1526
1526
|
A) Set a room name in the SyncedRoom component
|
|
1527
1527
|
B) Set a room name in the URL parameter "?`+this.urlParameterName+`=my_room"
|
|
1528
|
-
C) Set "joinRandomRoom" to true`),!1):(hu&&console.log("Join "+this.roomName),this._userWantsToBeInARoom=!0,this.context.connection.joinRoom(this.roomName),!0))}_lastPingTime=0;_lastRoomTime=-1;_userWantsToBeInARoom=!1;update(){this.context.connection.isConnected&&(this.context.time.time-this._lastPingTime>3&&(this._lastPingTime=this.context.time.time,this.context.connection.sendPing()),this.context.connection.isInRoom&&(this._lastRoomTime=this.context.time.time)),this._lastRoomTime>0&&this.context.time.time-this._lastRoomTime>.3&&(this._lastRoomTime=-1,this.autoRejoin?this._userWantsToBeInARoom&&(console.log("Disconnected from networking backend - attempt reconnecting now"),this.tryJoinRoom()):E()&&console.warn("You are not connected to a room anymore (possibly because the tab was inactive for too long and the server kicked you?)"))}getViewOnlyUrl(){if(this.context.connection.isConnected&&this.context.connection.currentRoomViewId){const e=window.location.search,t=new URLSearchParams(e);return t.has(this.urlParameterName)&&t.delete(this.urlParameterName),t.set(Km,this.context.connection.currentRoomViewId),window.location.origin+window.location.pathname+"?"+t.toString()}return null}setRandomRoomUrlParameter(){const e=xh(),t=this.generateRoomName();x(this.urlParameterName)?e.set(this.urlParameterName,t):e.append(this.urlParameterName,t),Sy(t,e)}generateRoomName(){let e="";for(let t=0;t<6;t++)e+=Math.floor(Math.random()*10).toFixed(0);return e}_roomButton;_roomButtonIconJoin;_roomButtonIconLeave;createRoomButton(){if(this._roomButton)return this._roomButton;const e=document.createElement("button");return this._roomButton=e,e.classList.add("create-room-button"),e.setAttribute("priority","90"),e.onclick=()=>{if(this.context.connection.isInRoom)this.urlParameterName&&Yc(this.urlParameterName,null),this.context.connection.leaveRoom(),this._userWantsToBeInARoom=!1;else{if(this.urlParameterName){const t=x(this.urlParameterName);(!t||t===!0)&&(this._lastJoinedRoom?Yc(this.urlParameterName,this._lastJoinedRoom):this.setRandomRoomUrlParameter())}this.tryJoinRoom()}},this._roomButtonIconJoin=bt("group"),this._roomButtonIconLeave=bt("group_off"),this.updateRoomButtonState(),this.context.connection.beginListen(te.JoinedRoom,this.updateRoomButtonState),this.context.connection.beginListen(te.LeftRoom,this.updateRoomButtonState),e}updateRoomButtonState=()=>{this._roomButton&&(this.context.connection.isInRoom?(this._roomButton.title="Leave the networked room",this._roomButton.textContent="Leave Room",this._roomButtonIconJoin?.remove(),this._roomButton.prepend(this._roomButtonIconLeave)):(this._roomButton.title="Create or join a networked room",this._roomButton.textContent="Join Room",this._roomButtonIconLeave?.remove(),this._roomButton.prepend(this._roomButtonIconJoin)))};destroyRoomButton(){this.context.connection.stopListen(te.JoinedRoom,this.updateRoomButtonState),this.context.connection.stopListen(te.LeftRoom,this.updateRoomButtonState)}_viewOnlyButton;onEnableViewOnlyButton(){this.context.connection.isConnected?this.onCreateViewOnlyButton():(this.context.connection.stopListen(te.JoinedRoom,this.onCreateViewOnlyButton),this.context.connection.beginListen(te.JoinedRoom,this.onCreateViewOnlyButton))}onDisableViewOnlyButton(){this.context.connection.stopListen(te.JoinedRoom,this.onCreateViewOnlyButton),this._viewOnlyButton?.remove()}onCreateViewOnlyButton=()=>{if(!this._viewOnlyButton){const e=document.createElement("button");this._viewOnlyButton=e,e.classList.add("view-only-button"),e.setAttribute("priority","90"),e.onclick=()=>{const t=this.getViewOnlyUrl();t?.length?navigator.canShare({url:t})?navigator.share({url:t})?.catch(i=>{console.warn(i)}):(navigator.clipboard.writeText(t),Re("View only URL copied to clipboard")):de("Could not create view only URL")},e.title="Copy the view only URL: A page accessed by the view only URL can not be modified by visiting users.",e.textContent="Share View URL",e.prepend(bt("visibility"))}this.context.menu.appendChild(this._viewOnlyButton)}}Xo([p()],Rn.prototype,"roomName",2);Xo([p()],Rn.prototype,"urlParameterName",2);Xo([p()],Rn.prototype,"joinRandomRoom",2);Xo([p()],Rn.prototype,"requireRoomParameter",2);Xo([p()],Rn.prototype,"autoRejoin",2);Xo([p()],Rn.prototype,"createJoinButton",2);Xo([p()],Rn.prototype,"createViewOnlyButton",2);Xo([p()],Rn.prototype,"roomPrefix",1);var S2=Object.defineProperty,C2=Object.getOwnPropertyDescriptor,Hl=(s,e,t,i)=>{for(var n=i>1?void 0:i?C2(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&&S2(e,t,n),n};const P2="noVoip",k2=x("debugvoip");class Qs extends T{autoConnect=!0;runInBackground=!0;createMenuButton=!0;debug=!1;_volume=1;get volume(){return this._volume}set volume(e){if(Number.isNaN(e))return;const t=Math.max(0,Math.min(1,e));this._volume=t;for(const i of this._incomingStreams.values())i.volume=t}getAudioElement(e){return this._incomingStreams.get(e)}get incomingStreams(){return this._incomingStreams}speakingThreshold=.1;onSpeakingChanged=new Z;_speakingStates=new Map;_analysers=new Map;_sharedAudioContext;_lastSpeakingPollMs=0;_net;_menubutton;awake(){k2&&(this.debug=!0),this.debug&&(console.log("VOIP debugging: press 'v' to toggle incoming mute, 'c' to toggle connect/disconnect"),window.addEventListener("keydown",async e=>{switch(e.key.toLowerCase()){case"v":console.log("VOIP: toggle incoming mute → ",!this.isMuted),this.setMuted(!this.isMuted);break;case"c":this.isSending?this.disconnect():this.connect();break}}))}onEnable(){this._net||(this._net=rd.create(this)),this.debug&&(this._net.debug=!0),this._net.addEventListener(is.StreamReceived,this.onReceiveStream),this._net.addEventListener(is.StreamEnded,this.onStreamEnded),this._net.enable(),this.autoConnect&&this.context.connection.isConnected&&this.connect(),this.context.connection.beginListen(te.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(te.LeftRoom,this.onLeftRoom),this.onEnabledChanged(),this.updateButton(),window.addEventListener("visibilitychange",this.onVisibilityChanged)}onDisable(){this._net&&(this._net.stopSendingStream(this._outputStream),this._net.removeEventListener(is.StreamReceived,this.onReceiveStream),this._net.removeEventListener(is.StreamEnded,this.onStreamEnded),this._net?.disable()),this.context.connection.stopListen(te.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(te.LeftRoom,this.onLeftRoom),this.onEnabledChanged(),this.updateButton(),window.removeEventListener("visibilitychange",this.onVisibilityChanged);for(const e of[...this._analysers.keys()])this.cleanupAnalyser(e);this.closeSharedAudioContext()}onDestroy(){this._menubutton?.remove(),this._menubutton=void 0;for(const e of[...this._analysers.keys()])this.cleanupAnalyser(e);this.closeSharedAudioContext();for(const e of this._incomingStreams.values())Hi(e.srcObject);this._incomingStreams.clear(),this._speakingStates.clear()}_allowSending=!0;_outputStream=null;_connectInFlight;get isSending(){return this._outputStream!=null&&this._outputStream.active}connect(e){return this._connectInFlight?this._connectInFlight:(this._connectInFlight=this._connectImpl(e).finally(()=>{this._connectInFlight=void 0}),this._connectInFlight)}async _connectImpl(e){if(!this._net)return console.error("Cannot connect to voice chat - NetworkedStreams not initialized. Make sure the component is enabled before calling this method."),!1;if(this.context.connection.isConnected){if(!await exports.DeviceUtilities.microphonePermissionsGranted())return console.error("Cannot connect to voice chat - microphone permissions not granted"),this.updateButton(),!1}else return console.error("Cannot connect to voice chat - not connected to server"),this.updateButton(),!1;return this._allowSending=!0,this._net?.stopSendingStream(this._outputStream),Hi(this._outputStream),this._outputStream=await this.getAudioStream(e),this._outputStream?(this.debug&&console.log("VOIP: Got audio stream"),this._net?.startSendingStream(this._outputStream),this.updateButton(),!0):(this.updateButton(),await exports.DeviceUtilities.microphonePermissionsGranted()?console.error("VOIP: Could not get audio stream - please make sure to connect an audio device and grant microphone permissions"):wl("Microphone permissions not granted: Please grant microphone permissions to use voice chat"),(this.debug||E())&&console.log("VOIP: Failed to get audio stream"),!1)}disconnect(e){e?.remember&&(this._allowSending=!1),this._net?.stopSendingStream(this._outputStream),Hi(this._outputStream),this._outputStream=null,this.updateButton()}setMuted(e){for(const t of this._incomingStreams.values())t.muted=e}get isMuted(){if(this._incomingStreams.size===0)return!1;for(const e of this._incomingStreams.values())if(!e.muted)return!1;return!0}async updateButton(){if(this.createMenuButton){if(this._menubutton||(this._menubutton=document.createElement("button"),this._menubutton.addEventListener("click",()=>{this.isSending?this.disconnect({remember:!0}):this.connect(),exports.DeviceUtilities.microphonePermissionsGranted().then(e=>{e||de("<strong>Microphone permissions not granted</strong>. Please allow your browser to use the microphone to be able to talk. Click on the button on the left side of your browser's address bar to allow microphone permissions.")})})),this._menubutton){this.context.menu.appendChild(this._menubutton),this.activeAndEnabled?this._menubutton.style.display="":this._menubutton.style.display="none",this._menubutton.title=this.isSending?"Click to disable your microphone":"Click to enable your microphone";let e=(this.isSending,""),t=this.isSending?"mic":"mic_off";await exports.DeviceUtilities.microphonePermissionsGranted()||(e="No Permission",t="mic_off",this._menubutton.title="Microphone permissions not granted. Please allow your browser to use the microphone to be able to talk. This can usually be done in the addressbar of the webpage."),this._menubutton.innerText=e,this._menubutton.prepend(bt(t)),this.context.connection.isConnected==!1?this._menubutton.setAttribute("disabled",""):this._menubutton.removeAttribute("disabled")}}else this.activeAndEnabled||this._menubutton?.remove()}getFrequency(e){return this.unsupported_getfrequency||(this.unsupported_getfrequency=!0,E()&&de("VOIP: getFrequency is currently not supported"),console.warn("VOIP: getFrequency is currently not supported")),null}async getAudioStream(e){if(!navigator.mediaDevices.getUserMedia)return console.error("No getDisplayMedia support"),null;const t=async n=>await navigator.mediaDevices.getUserMedia({audio:n??!0,video:!1}).catch(o=>(console.warn("VOIP failed getting audio stream",o),null)),i=await t(e);if(!i)return null;if(exports.DeviceUtilities.isiOS()&&e?.deviceId===void 0){const o=(await navigator.mediaDevices.enumerateDevices()).find(r=>(r.kind==="audioinput"||r.kind==="audiooutput")&&!r.label.includes("iPhone"));if(o){const r=Object.assign({},e);r.deviceId=o.deviceId;const a=await t(r);if(a)return Hi(i),a}}return i}onJoinedRoom=async()=>{this.debug&&console.log("VOIP: Joined room"),await Ds(300),this.autoConnect&&!this.isSending&&this._allowSending&&this.connect()};onLeftRoom=()=>{this.debug&&console.log("VOIP: Left room"),this.disconnect();for(const e of this._incomingStreams.values())Hi(e.srcObject);this._incomingStreams.clear();for(const e of this._analysers.keys())this.cleanupAnalyser(e)};_incomingStreams=new Map;update(){if(!this.onSpeakingChanged||this.onSpeakingChanged.listenerCount<=0)return;const e=performance.now();if(!(e-this._lastSpeakingPollMs<100)){this._lastSpeakingPollMs=e;for(const[t,i]of this._analysers){i.analyser.getByteFrequencyData(i.data);let n=0;for(let l=0;l<i.data.length;l++)n+=i.data[l];const o=n/i.data.length/255,r=this._speakingStates.get(t)??!1,a=o>this.speakingThreshold;a!==r&&(this._speakingStates.set(t,a),this.onSpeakingChanged.invoke({userId:t,isSpeaking:a,volume:o}))}}}setupAnalyser(e,t,i){if(!this._analysers.has(e))try{this._sharedAudioContext||(this._sharedAudioContext=new AudioContext);const n=this._sharedAudioContext,o=n.createMediaStreamSource(i),r=n.createAnalyser();r.fftSize=256,o.connect(r);const a=new Uint8Array(r.frequencyBinCount);this._analysers.set(e,{source:o,analyser:r,data:a})}catch(n){this.debug&&console.warn("VOIP: Failed to create analyser for",e,n)}}cleanupAnalyser(e){const t=this._analysers.get(e);t&&(t.source.disconnect(),t.analyser.disconnect(),this._analysers.delete(e)),this._speakingStates.delete(e)}closeSharedAudioContext(){this._sharedAudioContext&&(this._sharedAudioContext.close(),this._sharedAudioContext=void 0)}onReceiveStream=e=>{const t=e.target.userId,i=e.stream;let n=this._incomingStreams.get(t);n||(n=new Audio,this._incomingStreams.set(t,n)),n.srcObject=i,n.volume=this._volume,n.setAttribute("autoplay","true"),this.setupAnalyser(t,n,i),wn.registerWaitForInteraction(()=>{n?.play().catch(o=>{console.error("VOIP: Failed to play audio",o)})})};onStreamEnded=e=>{const t=this._incomingStreams.get(e.userId);Hi(t?.srcObject),this._incomingStreams.delete(e.userId),this.cleanupAnalyser(e.userId)};onEnabledChanged=()=>{for(const e of this._incomingStreams){const t=e[1];t.muted=!this.enabled}};onVisibilityChanged=()=>{if(this.runInBackground)return;const e=document.visibilityState!=="visible";this.setMuted(e);const t=this._outputStream?.getAudioTracks();if(t)for(const i of t)i.enabled=!e}}Hl([p()],Qs.prototype,"autoConnect",2);Hl([p()],Qs.prototype,"runInBackground",2);Hl([p()],Qs.prototype,"createMenuButton",2);Hl([p()],Qs.prototype,"volume",1);Hl([p()],Qs.prototype,"speakingThreshold",2);Hl([p(Z)],Qs.prototype,"onSpeakingChanged",2);function M2(){const s=x("testwindowcount")||0;s&&s>0&&O2(s)}function O2(s){if(x("testwindow"))return null;const e=new URL(window.location.href);cg(e.searchParams,P2,1),cg(e.searchParams,"testwindow",1);const t=e.toString(),i=[];window.onbeforeunload=()=>{for(const l of i)l.close()};const n=.05,o=128;let r=0,a=0;for(let l=0;l<s;l++){r*o+o*.01>=window.innerWidth&&(a+=1,r=0);const h=r*(o*(1+n))+window.screenLeft,d=a*(o*(1+n))+window.screenTop+90+60*a;r+=1;const u=window.open(t,"test window "+l,`popup=yes width=${o} height=${o} top=${d} left=${h}`);if(!u){console.warn("Failed to open window");continue}i.push(u),u.onload=()=>{u.onbeforeunload=()=>{for(let f=0;f<i.length;f++){const m=i[f];m!==u&&m.close()}i.length=0}}}return i}class Rb extends T{awake(){M2()}}class Tb extends T{transformsPerFrame=10;interval=0;useFlatbuffers=!0;awake(){if(this.useFlatbuffers)this.context.connection.beginListenBinary(uh,e=>{});else{this.models=[];for(let e=0;e<this.transformsPerFrame;e++)this.models.push(new E2(this.context.connection.connectionId+"_simulatedTransform_"+e,this))}}builder=null;models=null;update(){if(this.context.connection.isConnected){if(this.useFlatbuffers){if(!this.context.connection.connectionId||this.context.time.frameCount%this.interval!==0)return;this.builder===null&&(this.builder=new ee.Builder(1024));const e=this.builder;for(let t=0;t<this.transformsPerFrame;t++){e.clear();const i=cC(this.context.connection.connectionId,this);this.context.connection.sendBinary(i)}}else if(this.models)for(let e=0;e<this.models.length;e++){const t=this.models[e];t.dontSave=!0,t.update(this,null),this.context.connection.send("TestSimulateUserData-"+e,t)}}}}class E2{guid;fast=!1;position;rotation;velocity=void 0;dontSave;isValid(){return this.fast!==void 0||this.position!==void 0||this.rotation!==void 0||this.velocity!==void 0}constructor(e,t){this.guid=e,this.position={x:0,y:0,z:0},this.rotation={x:0,y:0,z:0,w:0},this.update(t,null)}static temp=new c.Vector3;update(e,t){const i=e.worldPosition;this.position.x=i.x,this.position.y=i.y,this.position.z=i.z;const n=e.worldQuaternion;if(this.rotation.x=n.x,this.rotation.y=n.y,this.rotation.z=n.z,this.rotation.w=n.w,this.fast=!1,t){const o=t.getVelocity();this.velocity===void 0&&(this.velocity={x:0,y:0,z:0}),this.velocity.x=o.x,this.velocity.y=o.y,this.velocity.z=o.z}}}var R2=Object.defineProperty,Lp=(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&&R2(e,t,n),n};class ca extends T{isGizmo=!1;translationSnap=1;rotationSnapAngle=15;scaleSnap=.25;get control(){return this._control}_control;orbit;onEnable(){if(!(this.isGizmo&&!Oh)&&this.context.mainCamera&&(this._control||(this._control=new V.TransformControls(this.context.mainCamera,this.context.renderer.domElement),this._control.enabled=!0,this._control.getRaycaster().layers.set(2),this._control.size=1,("_root"in this._control?this._control._root:this._control).traverse(t=>{const i=t;if(i.layers.set(2),i){const n=i.material;n&&(n.opacity=.3)}}),this.orbit=P.getComponentInParent(this.context.mainCamera,ue)??void 0),this._control)){const e=this._control.getHelper();this.context.scene.add(e),this._control.attach(this.gameObject),this._control?.addEventListener("dragging-changed",this.onControlChangedEvent),window.addEventListener("keydown",this.windowKeyDownListener),window.addEventListener("keyup",this.windowKeyUpListener)}}onDisable(){this._control?.getHelper()?.removeFromParent(),this._control?.removeEventListener("dragging-changed",this.onControlChangedEvent),window.removeEventListener("keydown",this.windowKeyDownListener),window.removeEventListener("keyup",this.windowKeyUpListener)}enableSnapping(){this._control&&(this._control.setTranslationSnap(this.translationSnap),this._control.setRotationSnap(c.MathUtils.degToRad(this.rotationSnapAngle)),this._control.setScaleSnap(this.scaleSnap))}disableSnapping(){this._control&&(this._control.setTranslationSnap(null),this._control.setRotationSnap(null),this._control.setScaleSnap(null))}onControlChangedEvent=e=>{const t=this.orbit;if(t&&(t.enabled=!e.value),e.value){const i=this.gameObject.getComponentInParent(Sn);i&&(i.fastMode=!0,i.requestOwnership())}else{const i=this.gameObject.getComponentInParent(Sn);i&&(i.fastMode=!1)}};windowKeyDownListener=e=>{if(this.enabled&&this._control)switch(e.keyCode){case 81:this._control.setSpace(this._control.space==="local"?"world":"local");break;case 16:this.enableSnapping();break;case 87:this._control.setMode("translate");break;case 69:this._control.setMode("rotate");break;case 82:this._control.setMode("scale");break;case 187:case 107:this._control.setSize(this._control.size+.1);break;case 189:case 109:this._control.setSize(Math.max(this._control.size-.1,.1));break;case 88:this._control.showX=!this._control.showX;break;case 89:this._control.showY=!this._control.showY;break;case 90:this._control.showZ=!this._control.showZ;break;case 32:this._control.enabled=!this._control.enabled;break}};windowKeyUpListener=e=>{this.enabled&&e.keyCode===16&&this.disableSnapping()}}Lp([p()],ca.prototype,"isGizmo");Lp([p()],ca.prototype,"translationSnap");Lp([p()],ca.prototype,"rotationSnapAngle");Lp([p()],ca.prototype,"scaleSnap");var T2=Object.defineProperty,A2=Object.getOwnPropertyDescriptor,Bp=(s,e,t,i)=>{for(var n=i>1?void 0:i?A2(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&&T2(e,t,n),n};class Ab{texture=null;rect}Bp([p(c.Texture)],Ab.prototype,"texture",2);let ql=class extends Yh{set image(e){this.sprite||(this.sprite=new Ab),this.sprite.texture=e,this.onAfterCreated()}get image(){return this.sprite?this.sprite.texture:null}get sprite(){return this._sprite}set sprite(e){this._sprite!==e&&(this._sprite=e,this.onAfterCreated())}_sprite;pixelsPerUnitMultiplier=1;isBuiltinSprite(){const e=this.sprite;switch(e?.texture?.name){case"InputFieldBackground":case"UISprite":case"Background":case"Knob":return!0}const t=e?.texture?.image;return!!(!e?.texture?.name?.length&&Lc(t)&&t.width===32&&t.height===32)}onBeforeCreate(e){super.onBeforeCreate(e),this.isBuiltinSprite()&&(e.borderRadius=5/this.pixelsPerUnitMultiplier,this.sprite?.texture?.name==="Knob"&&(e.borderRadius=999))}onAfterCreated(){this.__didAwake&&(super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture(this.sprite?.texture))}};Bp([p(Ab)],ql.prototype,"sprite",1);Bp([p()],ql.prototype,"pixelsPerUnitMultiplier",2);class Fp extends Yh{get mainTexture(){return this._mainTexture}set mainTexture(e){this._mainTexture!==e&&(this._mainTexture=e,this.onAfterCreated())}_mainTexture;onAfterCreated(){this.__didAwake&&(super.onAfterCreated(),this.setTexture(this.mainTexture))}}Bp([p(c.Texture)],Fp.prototype,"mainTexture",1);var D2=Object.defineProperty,I2=Object.getOwnPropertyDescriptor,ji=(s,e,t,i)=>{for(var n=i>1?void 0:i?I2(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&&D2(e,t,n),n};const sr=x("debugbutton");class Qo{colorMultiplier;disabledColor;fadeDuration;highlightedColor;normalColor;pressedColor;selectedColor}ji([p()],Qo.prototype,"colorMultiplier",2);ji([p(oe)],Qo.prototype,"disabledColor",2);ji([p()],Qo.prototype,"fadeDuration",2);ji([p(oe)],Qo.prototype,"highlightedColor",2);ji([p(oe)],Qo.prototype,"normalColor",2);ji([p(oe)],Qo.prototype,"pressedColor",2);ji([p(oe)],Qo.prototype,"selectedColor",2);class L2{disabledTrigger;highlightedTrigger;normalTrigger;pressedTrigger;selectedTrigger}class Ys extends T{click(){this.onClick?.invoke()}onClick=new Z;_isHovered=0;onPointerEnter(e){const t=e.event.pointerType==="mouse"&&e.button===0;t&&(this._isHovered+=1),sr&&console.warn("Button Enter",t,this._isHovered,this.animationTriggers?.highlightedTrigger,this.animator),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.highlightedTrigger):this.transition===1&&this.colors&&this._image?.setState("hovered"),t&&this.context.input.setCursor("pointer"))}onPointerExit(){this._isHovered-=1,this._isHovered<0&&(this._isHovered=0),sr&&console.log("Button Exit",this._isHovered,this.animationTriggers?.highlightedTrigger,this.animator),this.interactable&&(this._isHovered>0||(this._isHovered=0,this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&this._image?.setState("normal"),this.context.input.unsetCursor("pointer")))}onPointerDown(e){sr&&console.log("Button Down",this.animationTriggers?.highlightedTrigger,this.animator),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.pressedTrigger):this.transition===1&&this.colors&&this._image?.setState("pressed"))}onPointerUp(e){sr&&console.warn("Button Up",this.animationTriggers?.highlightedTrigger,this.animator,this._isHovered),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this._isHovered?this.animationTriggers.highlightedTrigger:this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&this._image?.setState(this._isHovered?"hovered":"normal"))}onPointerClick(e){if(this.interactable&&!(e.button!==0&&e.event.pointerType===Lf.Mouse)&&(sr&&(console.warn("Button Click",this.onClick),Re("CLICKED button "+this.name+" at "+this.context.time.frameCount)),this.onClick&&this.onClick.listenerCount>0&&(this.onClick.invoke(),e.use(),this.context.accessibility.focus(this),sr))){const t=this.gameObject.worldPosition;t.add(this.gameObject.worldUp.multiplyScalar(1+Math.random()*.5)),B.DrawLabel(t,"CLICK:"+Date.now(),.1,1+Math.random()*.5)}}colors;transition;animationTriggers;animator;set interactable(e){this._interactable=e,this._image&&(this._image.setInteractable(e),e?this._image.setState("normal"):this._image.setState("disabled"))}get interactable(){return this._interactable}_interactable=!0;set_interactable(e){this.interactable=e}awake(){super.awake(),sr&&console.log(this),this._isInit=!1,this.init()}start(){this._image?.setInteractable(this.interactable),this.gameObject.getComponentInParent(fh)||this.gameObject.addComponent(Yf)}onEnable(){super.onEnable(),this.context.accessibility.updateElement(this,{role:"button",label:this.gameObject.name+" button",hidden:!1})}onDisable(){super.onDisable(),this.context.accessibility.updateElement(this,{hidden:!0})}onDestroy(){this.context.accessibility.removeElement(this),this._isHovered&&this.context.input.unsetCursor("pointer")}_requestedAnimatorTrigger;*setAnimatorTriggerAtEndOfFrame(e){this._requestedAnimatorTrigger=e,yield,yield,this._requestedAnimatorTrigger==e&&this.animator?.setTrigger(e)}_isInit=!1;_image;init(){this._isInit||(this._isInit=!0,this._image=P.getComponent(this.gameObject,ql),this._image&&(this.stateSetup(this._image),this.interactable?this._image.setState("normal"):this._image.setState("disabled")))}stateSetup(e){e.setInteractable(this.interactable);const t=this.getFinalColor(e.color,this.colors?.normalColor),i={state:"normal",attributes:{backgroundColor:t,backgroundOpacity:t.alpha}};e.setupState(i);const n=this.getFinalColor(e.color,this.colors?.highlightedColor),o={state:"hovered",attributes:{backgroundColor:n,backgroundOpacity:n.alpha}};e.setupState(o);const r=this.getFinalColor(e.color,this.colors?.pressedColor),a={state:"pressed",attributes:{backgroundColor:r,backgroundOpacity:r.alpha}};e.setupState(a);const l=this.getFinalColor(e.color,this.colors?.selectedColor),h={state:"selected",attributes:{backgroundColor:l,backgroundOpacity:l.alpha}};e.setupState(h);const d=this.getFinalColor(e.color,this.colors?.disabledColor),u={state:"disabled",attributes:{backgroundColor:d,backgroundOpacity:d.alpha}};e.setupState(u)}getFinalColor(e,t){return t?e.clone().multiply(t).convertLinearToSRGB():e.clone().convertLinearToSRGB()}}ji([p(Z)],Ys.prototype,"onClick",2);ji([p(Qo)],Ys.prototype,"colors",2);ji([p()],Ys.prototype,"transition",2);ji([p(L2)],Ys.prototype,"animationTriggers",2);ji([p(vt)],Ys.prototype,"animator",2);ji([p()],Ys.prototype,"interactable",1);var B2=Object.defineProperty,jp=(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&&B2(e,t,n),n};const ao=x("debuginputfield"),dd=class H extends T{get text(){return this.textComponent?.text??""}set text(e){this.textComponent&&(this.textComponent.text=e,this.placeholder&&(e.length>0?this.placeholder.gameObject.visible=!1:this.placeholder.gameObject.visible=!0))}get isFocused(){return H.active===this}textComponent;placeholder;onValueChanged;onEndEdit;static active=null;static activeTime=-1;static htmlField=null;static htmlFieldFocused=!1;inputEventFn;_iosEventFn;start(){ao&&console.log(this.name,this)}onEnable(){H.htmlField||(H.htmlField=document.createElement("input"),H.htmlField.style.width="0px",H.htmlField.style.height="0px",H.htmlField.style.padding="0px",H.htmlField.style.border="none",H.htmlField.style.overflow="hidden",H.htmlField.style.caretColor="transparent",H.htmlField.style.outline="none",H.htmlField.classList.add("ar"),H.htmlField.onfocus=()=>H.htmlFieldFocused=!0,H.htmlField.onblur=()=>H.htmlFieldFocused=!1,document.body.append(H.htmlField)),this.inputEventFn||(this.inputEventFn=this.onInput.bind(this)),H.htmlField.addEventListener("keyup",this.inputEventFn),this.placeholder&&this.textComponent?.text.length&&P.setActive(this.placeholder.gameObject,!1),exports.DeviceUtilities.isiOS()&&(this._iosEventFn=this.processInputOniOS.bind(this),window.addEventListener("click",this._iosEventFn))}onDisable(){H.htmlField?.removeEventListener("keyup",this.inputEventFn),this.onDeselected(),this._iosEventFn&&window.removeEventListener("click",this._iosEventFn)}clear(){H.active===this&&H.htmlField?(H.htmlField.value="",this.setTextFromInputField()):(this.textComponent&&(this.textComponent.text=""),this.placeholder&&P.setActive(this.placeholder.gameObject,!0))}select(){this.onSelected()}deselect(){this.onDeselected()}onPointerEnter(e){e.event.pointerType==="mouse"&&e.button===0&&this.context.input.setCursor("text")}onPointerExit(e){this.context.input.unsetCursor("text")}onPointerClick(e){ao&&console.log("CLICK",e,H.active),H.activeTime=this.context.time.time,H.active!==this&&this.startCoroutine(this.activeLoop(),Ce.LateUpdate),this.selectInputField()}*activeLoop(){for(this.onSelected();H.active===this&&!(this.context.input.getPointerClicked(0)&&this.context.time.time-H.activeTime>.2);)this.setTextFromInputField(),yield;this.onDeselected()}onSelected(){if(H.active!==this&&(ao&&console.log("Select",this.name,this,H.htmlField,this.context.isInXR,this.context.arOverlayElement,this.textComponent?.text,H.htmlField?.value),H.active?.onDeselected(),H.active=this,this.placeholder&&P.setActive(this.placeholder.gameObject,!1),H.htmlField)){if(H.htmlField.value=this.textComponent?.text||"",ao&&console.log("set input field value",H.htmlField.value),this.context.isInXR){const e=this.context.arOverlayElement;e&&e.append(H.htmlField)}this.selectInputField()}}onDeselected(){H.active===this&&(H.active=null,ao&&console.log("Deselect",this.name,this),H.htmlField&&(H.htmlField.blur(),document.body.append(H.htmlField)),this.placeholder&&(!this.textComponent||this.textComponent.text.length<=0)&&P.setActive(this.placeholder.gameObject,!0),H.htmlField&&this.onEndEdit?.invoke(H.htmlField.value))}update(){H.active===this&&this.textComponent?.markDirty()}onInput(e){if(H.active===this){if(ao&&console.log(e.code,e,H.htmlField?.value,this.textComponent?.text),e.code==="Escape"||e.code==="Enter"){this.onDeselected();return}H.htmlField&&(this.textComponent&&(this.setTextFromInputField(),this.placeholder&&P.setActive(this.placeholder.gameObject,this.textComponent.text.length<=0)),this.selectInputField())}}setTextFromInputField(){if(this.textComponent&&H.htmlField){const e=this.textComponent.text,t=H.htmlField.value,i=this.textComponent.text!==H.htmlField.value;this.textComponent.text=H.htmlField.value,i&&(ao&&console.log("[InputField] value changed:",t,e),this.onValueChanged?.invoke(t,e))}}selectInputField(){H.htmlField&&(ao&&console.log("Focus Inputfield",H.htmlFieldFocused,H.htmlField),H.htmlField.setSelectionRange(H.htmlField.value.length,H.htmlField.value.length),exports.DeviceUtilities.isiOS()?(H.htmlField.style.display="block",H.htmlField.focus({preventScroll:!0})):setTimeout(()=>H.htmlField?.focus(),1))}processInputOniOS(){const e=this.context.physics.raycast();if(!e.length)return;const i=e[0].object,n=g_(i);(n?.gameObject===this.gameObject||n?.gameObject.parent===this.gameObject)&&this.selectInputField()}};jp([p(Nt)],dd.prototype,"textComponent");jp([p(Nt)],dd.prototype,"placeholder");jp([p(Z)],dd.prototype,"onValueChanged");jp([p(Z)],dd.prototype,"onEndEdit");let Db=dd;var F2=Object.defineProperty,H1=(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&&F2(e,t,n),n};class ud extends T{id=null;keepAspect=!1;_object=null;onEnable(){if(this._object){this.gameObject.add(this._object);return}if(!this.id||!this.context.mainCamera)return;const e=document.getElementById(this.id);if(!e){console.warn('Could not find element with id "'+this.id+'"');return}e.style.display="block",e.style.visibility="hidden";const t=new V.InteractiveGroup;t.listenToPointerEvents(this.context.renderer,this.context.mainCamera),this.gameObject.add(t);const i=new V.HTMLMesh(e);t.add(i),i.visible=!1;const n=i.material;n.transparent=!0,setTimeout(()=>{i.visible=!0;const o=Of(this.gameObject).clone();Ph(this.gameObject,0,0,0),this.gameObject.updateMatrixWorld();const r=new c.Box3;r.setFromObject(t),this.setWorldRotation(o.x,o.y,o.z);const a=r.max.x-r.min.x,l=r.max.y-r.min.y;if(this.keepAspect){const d=a/l;a>l?i.scale.set(1/a,1/l/d,1):i.scale.set(1/a*d,1/l,1)}else i.scale.set(1/a,1/l,1);const h=this.gameObject.scale;i.scale.multiply(h)},1)}onDisable(){this._object?.removeFromParent()}}H1([p()],ud.prototype,"id");H1([p()],ud.prototype,"keepAspect");var j2=Object.defineProperty,Up=(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&&j2(e,t,n),n};const fd=class q1 extends T{target;invertForward=!1;keepUpDirection=!0;copyTargetRotation=!1;static flipYQuat=new c.Quaternion().setFromAxisAngle(new c.Vector3(0,1,0),Math.PI);onBeforeRender(){let e=this.target;if(e||(e=this.context.mainCamera,E()&&!this.__did_warn&&(this.__did_warn=!0,console.debug(`[LookAt] No target set on ${this.name}, using main camera as target.`))),!e)return;let t=this.copyTargetRotation;(this.context.isInVR||this.context.isInPassThrough)&&(t=!1),Ch(this.gameObject,e,this.keepUpDirection,t),this.invertForward&&this.gameObject.quaternion.multiply(q1.flipYQuat)}createBehaviours(e,t,i){if(t.uuid===this.gameObject.uuid){let n=t;if(this.keepUpDirection){const r=nt.createEmptyParent(t);n=r;const a=this.invertForward?-1:1;r.setMatrix(r.getMatrix().multiply(new c.Matrix4().makeRotationZ(Math.PI/2*a))),t.setMatrix(t.getMatrix().multiply(new c.Matrix4().makeRotationZ(-Math.PI/2*a)))}const o=new Dt("lookat "+this.name,jt.sceneStartTrigger(),pe.lookAtCameraAction(n,void 0,this.invertForward?qi.back:qi.forward,this.keepUpDirection?qi.up:qi.zero));e.addBehavior(o)}}};Up([p(c.Object3D)],fd.prototype,"target");Up([p()],fd.prototype,"invertForward");Up([p()],fd.prototype,"keepUpDirection");Up([p()],fd.prototype,"copyTargetRotation");let Ib=fd;var U2=Object.defineProperty,Lb=(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&&U2(e,t,n),n};class Xl extends T{url;mode=0;clickable=!0;async open(){if(!this.url){console.warn("OpenURL: URL is not set, can't open.",this);return}this._validateUrl();let e=this.url;switch(!e.startsWith("mailto:")&&e.includes("@")&&(e="mailto:"+e),this.mode){case 0:exports.DeviceUtilities.isSafari(),globalThis.open(e,"_blank");break;case 1:exports.DeviceUtilities.isSafari()&&exports.DeviceUtilities.isiOS()?globalThis.open(e,"_top"):globalThis.open(e,"_self");break;case 2:exports.DeviceUtilities.isSafari()?globalThis.open(e,"_top"):globalThis.open(e,"_new");break}}start(){this.gameObject.getComponentInParent(Ji)||this.gameObject.addComponent(Ji)}onPointerEnter(e){!e.used&&this.clickable&&this.context.input.setCursor("pointer")}onPointerExit(){this.clickable&&this.context.input.unsetCursor("pointer")}onPointerClick(e){this.clickable&&!e.used&&this.url?.length&&this.open()}_validateUrl(){this.url&&this.url.startsWith("www.")&&(E()&&console.warn("URL is not valid, adding https:// to the start of the URL",this.url),this.url="https://"+this.url)}}Lb([p()],Xl.prototype,"url");Lb([p()],Xl.prototype,"mode");Lb([p()],Xl.prototype,"clickable");If(s=>{const e=s.domElement.getAttribute("clickthrough");if(t(e)){const i=s.scene.addComponent(zp);ju(s.domElement,"clickthrough",()=>{const n=s.domElement.getAttribute("clickthrough");i.enabled=t(n)})}function t(i){return i!==null&&i!=="0"&&i!=="false"}});class zp extends T{_previousPointerEvents="all";onEnable(){this.context.input.addEventListener("pointerdown",this.onPointerEvent),this.context.input.addEventListener("pointermove",this.onPointerEvent,{queue:100}),window.addEventListener("touchstart",this.onTouchStart,{passive:!0}),window.addEventListener("touchend",this.onTouchEnd,{passive:!0}),this._previousPointerEvents=this.context.domElement.style.pointerEvents}onDisable(){this.context.input.removeEventListener("pointerdown",this.onPointerEvent),this.context.input.removeEventListener("pointermove",this.onPointerEvent),window.removeEventListener("touchstart",this.onTouchStart),window.removeEventListener("touchend",this.onTouchEnd),this.context.domElement.style.pointerEvents=this._previousPointerEvents}onPointerEnter(){}onPointerEvent=e=>{if(e.pointerId>0)return;e.intersections?.length<=0?this.context.domElement.style.pointerEvents="none":this.context.domElement.style.pointerEvents="all"};_touchDidHitAnything=!1;onTouchStart=e=>{const t=e.touches[0];if(!t)return;const i=t.clientX/window.innerWidth*2-1,n=-(t.clientY/window.innerHeight)*2+1;this.context.physics.raycast({screenPoint:new c.Vector2(i,n)}).length>0&&(this._touchDidHitAnything=!0)};onTouchEnd=e=>{const t=this._touchDidHitAnything;this._touchDidHitAnything=!1,setTimeout(()=>{t&&(this.context.domElement.style.pointerEvents="all")},100)}}var z2=Object.defineProperty,Np=(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&&z2(e,t,n),n};const N2=x("debugcursor");class ha extends T{static NAME="CursorFollow";damping=0;useFullPage=!0;keepDistance=!0;snapToSurface=!1;_distance=-1;updateDistance(e=!1){!e&&this.keepDistance&&this._distance!==-1||(this._distance=this.gameObject.worldPosition.distanceTo(this.context.mainCamera.worldPosition))}awake(){this._distance=-1}onEnable(){this._distance=-1,window.addEventListener("pointermove",this._onPointerMove)}onDisable(){window.removeEventListener("pointermove",this._onPointerMove)}_ndc_x=0;_ndc_y=0;_onPointerMove=e=>{if(!this.useFullPage)return;const t=e.clientX,i=e.clientY,n=this.context.domX,o=this.context.domY,r=this.context.domWidth,a=this.context.domHeight;this._ndc_x=(t-n)/r*2-1,this._ndc_y=-(i-o)/a*2+1};lateUpdate(){this.updateDistance();const e=this.useFullPage?this._ndc_x:this.context.input.mousePositionRC.x,t=this.useFullPage?this._ndc_y:this.context.input.mousePositionRC.y,i=this.context.mainCamera,n=i.worldPosition,o=F(e,t,1).unproject(i);o.sub(n).normalize();const r=F(o).multiplyScalar(this._distance).add(n);let a=r;if(this.damping>0){const l=this.gameObject.worldPosition;l.lerp(r,this.context.time.deltaTime/this.damping),this.gameObject.worldPosition=l,a=l}else this.gameObject.worldPosition=r;if(this.snapToSurface){Zm.origin=n,Zm.direction=o;const l=this.context.physics.raycastFromRay(Zm,{testObject:h=>h!==this.gameObject&&!this.gameObject.contains(h)});if(l?.length){const h=l[0];h&&(this.damping>0?this.gameObject.worldPosition=a.lerp(h.point,this.context.time.deltaTime/this.damping):this.gameObject.worldPosition=h.point,N2&&B.DrawLine(h.point,h.normal.add(h.point),65280))}}}}Np([p()],ha.prototype,"damping");Np([p()],ha.prototype,"useFullPage");Np([p()],ha.prototype,"keepDistance");Np([p()],ha.prototype,"snapToSurface");const Zm=new c.Ray;var $2=Object.defineProperty,V2=Object.getOwnPropertyDescriptor,Ql=(s,e,t,i)=>{for(var n=i>1?void 0:i?V2(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&&$2(e,t,n),n};exports.HoverAnimation=class extends T{type="linear";duration=.1;scaleFactor=1.1;hovered=null;idle=null;animation=null;start(){this.idle||(this.idle=exports.AnimationUtils.emptyClip()),(!this.hovered||!(this.hovered instanceof c.AnimationClip))&&(this.hovered=exports.AnimationUtils.createScaleClip({type:"linear",duration:this.duration||.1,scale:this.gameObject.scale,scaleFactor:this.scaleFactor||1.1})),this.animation??=this.gameObject.addComponent(Ut),this.animation.playAutomatically=!1,this.playIdle()}onEnable(){this.animation&&(this.animation.enabled=!0),this.playIdle()}onDisable(){this.animation&&(this.animation.enabled=!1),this.playIdle()}onPointerEnter(){this.playHover()}onPointerExit(){this.playIdle()}playIdle(){this.idle&&this.animation?.play(this.idle,{exclusive:!0,fadeDuration:.1,loop:!0})}playHover(){this.hovered&&this.animation?.play(this.hovered,{exclusive:!0,fadeDuration:.1,loop:!1,clampWhenFinished:!0})}};Ql([p()],exports.HoverAnimation.prototype,"type",2);Ql([p()],exports.HoverAnimation.prototype,"duration",2);Ql([p()],exports.HoverAnimation.prototype,"scaleFactor",2);Ql([p(c.AnimationClip)],exports.HoverAnimation.prototype,"hovered",2);Ql([p(c.AnimationClip)],exports.HoverAnimation.prototype,"idle",2);exports.HoverAnimation=Ql([Ly],exports.HoverAnimation);var W2=Object.defineProperty,da=(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&&W2(e,t,n),n};typeof window<"u"&&Promise.resolve().then(()=>require("./vendor-BJviq-Oq.umd.cjs")).then(s=>s.scrollTimeline);const bs=x("debugscroll");class gs extends T{target=null;damping=0;invert=!1;htmlSelector=null;mode="window";useTopWindowScroll=!0;changed=new Z;get currentValue(){return this._current_value}_current_value=0;_target_value=0;_appliedValue=-1;_needsUpdate=!1;_firstUpdate=!1;_scrollWindow=null;_wheelTarget=null;_crossOriginWarned=!1;_viewTimelineWarned=!1;awake(){this._firstUpdate=!0}onEnable(){this.rebindScrollListener(),this._appliedValue=-1,this._needsUpdate=!0}onDisable(){this._wheelTarget?.removeEventListener("wheel",this.updateCurrentScrollValue),this._wheelTarget=null}onValidate(e){e==="useTopWindowScroll"&&this._wheelTarget&&(this.rebindScrollListener(),this._needsUpdate=!0)}resolveScrollWindow(){if(!this.useTopWindowScroll)return window;const e=window.top;if(!e||e===window.self)return window;try{return e.document,e}catch{return this._crossOriginWarned||(this._crossOriginWarned=!0,(bs||E())&&console.warn("[ScrollFollow] useTopWindowScroll is enabled but the top-level window is cross-origin and cannot be read. Falling back to the local window. Supporting cross-origin embeds requires a postMessage scroll bridge from the host page.")),window}}rebindScrollListener(){const e=this.resolveScrollWindow();this._scrollWindow=e,e!==this._wheelTarget&&(this._wheelTarget?.removeEventListener("wheel",this.updateCurrentScrollValue),this._wheelTarget=e,e.addEventListener("wheel",this.updateCurrentScrollValue,{passive:!0}),this._lastSelectorValue=null,this._lastSelectorElement=null,bs&&console.debug(`[ScrollFollow] Scroll listener bound to ${e===window?"local window":"top-level window"}`,{scrollWindow:this._scrollWindow,isTopWindow:e===window}))}lateUpdate(){if(this.updateCurrentScrollValue(),this._target_value>=0&&(this.damping>0&&!this._firstUpdate?(this._current_value=L.lerp(this._current_value,this._target_value,this.context.time.deltaTime/this.damping),Math.abs(this._current_value-this._target_value)<.001&&(this._current_value=this._target_value)):this._current_value=this._target_value),this._needsUpdate||this._current_value!==this._appliedValue){this._appliedValue=this._current_value,this._needsUpdate=!1;let e=!1;if(this.changed.listenerCount>0){const t={type:"change",value:this._current_value,component:this,preventDefault:()=>{t.defaultPrevented=!0},defaultPrevented:!1};this.changed.invoke(t),e=t.defaultPrevented}if(!e){const t=this.invert?1-this._current_value:this._current_value;Array.isArray(this.target)?this.target.forEach(i=>i&&this.applyScroll(i,t)):this.target&&this.applyScroll(this.target,t),bs&&this.context.time.frame%30===0&&console.debug(`[ScrollFollow] ${this._current_value.toFixed(5)} — ${(this._target_value*100).toFixed(0)}%, targets [${Array.isArray(this.target)?this.target.length:1}]`)}this._firstUpdate=!1}}_lastSelectorValue=null;_lastSelectorElement=null;updateCurrentScrollValue=()=>{const e=this._scrollWindow??window,t=e.document,i=t.scrollingElement??t.documentElement;switch(this.mode){case"window":if(this.htmlSelector?.length){if(this.htmlSelector!==this._lastSelectorValue&&(this._lastSelectorElement=t.querySelector(this.htmlSelector),this._lastSelectorValue=this.htmlSelector),this._lastSelectorElement){const n=this._lastSelectorElement.getBoundingClientRect();this._target_value=-n.top/(n.height-e.innerHeight);break}}else{const n=i.scrollHeight-i.clientHeight;n<=0||(this._target_value=i.scrollTop/n)}break}(isNaN(this._target_value)||!isFinite(this._target_value))&&(this._target_value=-1),bs&&console.debug(`[ScrollFollow] Scroll value updated: ${this._target_value.toFixed(5)} (ScrollTop: ${i.scrollTop}, ScrollHeight: ${i.scrollHeight}, ClientHeight: ${i.clientHeight})`)};applyScroll(e,t){if(e)if(e instanceof ml)this.handleTimelineTarget(e,t),e.isPlaying&&e.pause(),e.evaluate();else if(e instanceof vt)e.setFloat("scroll",t);else if(e instanceof Ut)e.time=t*e.duration;else if(e instanceof Ei){if(!e.duration)return;e.time=t*e.duration}else if(e instanceof ln)e.position01=t;else if(e instanceof Lt)e.intensity=t;else if(e instanceof c.Object3D){const i=e;i["needle:scrollbounds"]===void 0&&(i["needle:scrollbounds"]=pi(e)||null);const n=i["needle:scrollbounds"];n&&(e.position.y=-n.min.y-t*(n.max.y-n.min.y))}else"scroll"in e&&(typeof e.scroll=="number"?e.scroll=t:typeof e.scroll=="function"&&e.scroll(t))}handleTimelineTarget(e,t){const i=this._scrollWindow??window,n=i.document,o=e.duration;let r=Jm.get(e);if(!r){r=[],Jm.set(e,r);let d=0;for(const f of e.foreachMarker("ScrollMarker")){const m=d++;if(f.element===void 0||f.needsUpdate===!0||f.element&&!f.element?.parentNode){f.needsUpdate=!1;try{if(f.element=X1(m,n),bs&&console.debug(`ScrollMarker #${m} (${f.time.toFixed(2)}) found`,f.element),!f.element){(bs||E())&&console.warn(`No HTML element found for ScrollMarker: ${f.name} (index ${m})`);continue}}catch(g){f.element=null,console.error("ScrollMarker selector is not valid: "+f.name+`
|
|
1528
|
+
C) Set "joinRandomRoom" to true`),!1):(hu&&console.log("Join "+this.roomName),this._userWantsToBeInARoom=!0,this.context.connection.joinRoom(this.roomName),!0))}_lastPingTime=0;_lastRoomTime=-1;_userWantsToBeInARoom=!1;update(){this.context.connection.isConnected&&(this.context.time.time-this._lastPingTime>3&&(this._lastPingTime=this.context.time.time,this.context.connection.sendPing()),this.context.connection.isInRoom&&(this._lastRoomTime=this.context.time.time)),this._lastRoomTime>0&&this.context.time.time-this._lastRoomTime>.3&&(this._lastRoomTime=-1,this.autoRejoin?this._userWantsToBeInARoom&&(console.log("Disconnected from networking backend - attempt reconnecting now"),this.tryJoinRoom()):E()&&console.warn("You are not connected to a room anymore (possibly because the tab was inactive for too long and the server kicked you?)"))}getViewOnlyUrl(){if(this.context.connection.isConnected&&this.context.connection.currentRoomViewId){const e=window.location.search,t=new URLSearchParams(e);return t.has(this.urlParameterName)&&t.delete(this.urlParameterName),t.set(Km,this.context.connection.currentRoomViewId),window.location.origin+window.location.pathname+"?"+t.toString()}return null}setRandomRoomUrlParameter(){const e=xh(),t=this.generateRoomName();x(this.urlParameterName)?e.set(this.urlParameterName,t):e.append(this.urlParameterName,t),Sy(t,e)}generateRoomName(){let e="";for(let t=0;t<6;t++)e+=Math.floor(Math.random()*10).toFixed(0);return e}_roomButton;_roomButtonIconJoin;_roomButtonIconLeave;createRoomButton(){if(this._roomButton)return this._roomButton;const e=document.createElement("button");return this._roomButton=e,e.classList.add("create-room-button"),e.setAttribute("priority","90"),e.onclick=()=>{if(this.context.connection.isInRoom)this.urlParameterName&&Yc(this.urlParameterName,null),this.context.connection.leaveRoom(),this._userWantsToBeInARoom=!1;else{if(this.urlParameterName){const t=x(this.urlParameterName);(!t||t===!0)&&(this._lastJoinedRoom?Yc(this.urlParameterName,this._lastJoinedRoom):this.setRandomRoomUrlParameter())}this.tryJoinRoom()}},this._roomButtonIconJoin=bt("group"),this._roomButtonIconLeave=bt("group_off"),this.updateRoomButtonState(),this.context.connection.beginListen(te.JoinedRoom,this.updateRoomButtonState),this.context.connection.beginListen(te.LeftRoom,this.updateRoomButtonState),e}updateRoomButtonState=()=>{this._roomButton&&(this.context.connection.isInRoom?(this._roomButton.title="Leave the networked room",this._roomButton.textContent="Leave Room",this._roomButtonIconJoin?.remove(),this._roomButton.prepend(this._roomButtonIconLeave)):(this._roomButton.title="Create or join a networked room",this._roomButton.textContent="Join Room",this._roomButtonIconLeave?.remove(),this._roomButton.prepend(this._roomButtonIconJoin)))};destroyRoomButton(){this.context.connection.stopListen(te.JoinedRoom,this.updateRoomButtonState),this.context.connection.stopListen(te.LeftRoom,this.updateRoomButtonState)}_viewOnlyButton;onEnableViewOnlyButton(){this.context.connection.isConnected?this.onCreateViewOnlyButton():(this.context.connection.stopListen(te.JoinedRoom,this.onCreateViewOnlyButton),this.context.connection.beginListen(te.JoinedRoom,this.onCreateViewOnlyButton))}onDisableViewOnlyButton(){this.context.connection.stopListen(te.JoinedRoom,this.onCreateViewOnlyButton),this._viewOnlyButton?.remove()}onCreateViewOnlyButton=()=>{if(!this._viewOnlyButton){const e=document.createElement("button");this._viewOnlyButton=e,e.classList.add("view-only-button"),e.setAttribute("priority","90"),e.onclick=()=>{const t=this.getViewOnlyUrl();t?.length?navigator.canShare({url:t})?navigator.share({url:t})?.catch(i=>{console.warn(i)}):(navigator.clipboard.writeText(t),Re("View only URL copied to clipboard")):de("Could not create view only URL")},e.title="Copy the view only URL: A page accessed by the view only URL can not be modified by visiting users.",e.textContent="Share View URL",e.prepend(bt("visibility"))}this.context.menu.appendChild(this._viewOnlyButton)}}Xo([p()],Rn.prototype,"roomName",2);Xo([p()],Rn.prototype,"urlParameterName",2);Xo([p()],Rn.prototype,"joinRandomRoom",2);Xo([p()],Rn.prototype,"requireRoomParameter",2);Xo([p()],Rn.prototype,"autoRejoin",2);Xo([p()],Rn.prototype,"createJoinButton",2);Xo([p()],Rn.prototype,"createViewOnlyButton",2);Xo([p()],Rn.prototype,"roomPrefix",1);var S2=Object.defineProperty,C2=Object.getOwnPropertyDescriptor,Hl=(s,e,t,i)=>{for(var n=i>1?void 0:i?C2(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&&S2(e,t,n),n};const P2="noVoip",k2=x("debugvoip");class Qs extends T{autoConnect=!0;runInBackground=!0;createMenuButton=!0;debug=!1;_volume=1;get volume(){return this._volume}set volume(e){if(Number.isNaN(e))return;const t=Math.max(0,Math.min(1,e));this._volume=t;for(const i of this._incomingStreams.values())i.volume=t}getAudioElement(e){return this._incomingStreams.get(e)}get incomingStreams(){return this._incomingStreams}speakingThreshold=.1;onSpeakingChanged=new Z;_speakingStates=new Map;_analysers=new Map;_sharedAudioContext;_lastSpeakingPollMs=0;_net;_menubutton;awake(){k2&&(this.debug=!0),this.debug&&(console.log("VOIP debugging: press 'v' to toggle incoming mute, 'c' to toggle connect/disconnect"),window.addEventListener("keydown",async e=>{switch(e.key.toLowerCase()){case"v":console.log("VOIP: toggle incoming mute → ",!this.isMuted),this.setMuted(!this.isMuted);break;case"c":this.isSending?this.disconnect():this.connect();break}}))}onEnable(){this._net||(this._net=rd.create(this)),this.debug&&(this._net.debug=!0),this._net.addEventListener(is.StreamReceived,this.onReceiveStream),this._net.addEventListener(is.StreamEnded,this.onStreamEnded),this._net.enable(),this.autoConnect&&this.context.connection.isConnected&&this.connect(),this.context.connection.beginListen(te.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(te.LeftRoom,this.onLeftRoom),this.onEnabledChanged(),this.updateButton(),window.addEventListener("visibilitychange",this.onVisibilityChanged)}onDisable(){this._net&&(this._net.stopSendingStream(this._outputStream),this._net.removeEventListener(is.StreamReceived,this.onReceiveStream),this._net.removeEventListener(is.StreamEnded,this.onStreamEnded),this._net?.disable()),this.context.connection.stopListen(te.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(te.LeftRoom,this.onLeftRoom),this.onEnabledChanged(),this.updateButton(),window.removeEventListener("visibilitychange",this.onVisibilityChanged);for(const e of[...this._analysers.keys()])this.cleanupAnalyser(e);this.closeSharedAudioContext()}onDestroy(){this._menubutton?.remove(),this._menubutton=void 0;for(const e of[...this._analysers.keys()])this.cleanupAnalyser(e);this.closeSharedAudioContext();for(const e of this._incomingStreams.values())Hi(e.srcObject);this._incomingStreams.clear(),this._speakingStates.clear()}_allowSending=!0;_outputStream=null;_connectInFlight;get isSending(){return this._outputStream!=null&&this._outputStream.active}connect(e){return this._connectInFlight?this._connectInFlight:(this._connectInFlight=this._connectImpl(e).finally(()=>{this._connectInFlight=void 0}),this._connectInFlight)}async _connectImpl(e){if(!this._net)return console.error("Cannot connect to voice chat - NetworkedStreams not initialized. Make sure the component is enabled before calling this method."),!1;if(this.context.connection.isConnected){if(!await exports.DeviceUtilities.microphonePermissionsGranted())return console.error("Cannot connect to voice chat - microphone permissions not granted"),this.updateButton(),!1}else return console.error("Cannot connect to voice chat - not connected to server"),this.updateButton(),!1;return this._allowSending=!0,this._net?.stopSendingStream(this._outputStream),Hi(this._outputStream),this._outputStream=await this.getAudioStream(e),this._outputStream?(this.debug&&console.log("VOIP: Got audio stream"),this._net?.startSendingStream(this._outputStream),this.updateButton(),!0):(this.updateButton(),await exports.DeviceUtilities.microphonePermissionsGranted()?console.error("VOIP: Could not get audio stream - please make sure to connect an audio device and grant microphone permissions"):wl("Microphone permissions not granted: Please grant microphone permissions to use voice chat"),(this.debug||E())&&console.log("VOIP: Failed to get audio stream"),!1)}disconnect(e){e?.remember&&(this._allowSending=!1),this._net?.stopSendingStream(this._outputStream),Hi(this._outputStream),this._outputStream=null,this.updateButton()}setMuted(e){for(const t of this._incomingStreams.values())t.muted=e}get isMuted(){if(this._incomingStreams.size===0)return!1;for(const e of this._incomingStreams.values())if(!e.muted)return!1;return!0}async updateButton(){if(this.createMenuButton){if(this._menubutton||(this._menubutton=document.createElement("button"),this._menubutton.addEventListener("click",()=>{this.isSending?this.disconnect({remember:!0}):this.connect(),exports.DeviceUtilities.microphonePermissionsGranted().then(e=>{e||de("<strong>Microphone permissions not granted</strong>. Please allow your browser to use the microphone to be able to talk. Click on the button on the left side of your browser's address bar to allow microphone permissions.")})})),this._menubutton){this.context.menu.appendChild(this._menubutton),this.activeAndEnabled?this._menubutton.style.display="":this._menubutton.style.display="none",this._menubutton.title=this.isSending?"Click to disable your microphone":"Click to enable your microphone";let e=(this.isSending,""),t=this.isSending?"mic":"mic_off";await exports.DeviceUtilities.microphonePermissionsGranted()||(e="No Permission",t="mic_off",this._menubutton.title="Microphone permissions not granted. Please allow your browser to use the microphone to be able to talk. This can usually be done in the addressbar of the webpage."),this._menubutton.innerText=e,this._menubutton.prepend(bt(t)),this.context.connection.isConnected==!1?this._menubutton.setAttribute("disabled",""):this._menubutton.removeAttribute("disabled")}}else this.activeAndEnabled||this._menubutton?.remove()}getFrequency(e){return this.unsupported_getfrequency||(this.unsupported_getfrequency=!0,E()&&de("VOIP: getFrequency is currently not supported"),console.warn("VOIP: getFrequency is currently not supported")),null}async getAudioStream(e){if(!navigator.mediaDevices.getUserMedia)return console.error("No getDisplayMedia support"),null;const t=async n=>await navigator.mediaDevices.getUserMedia({audio:n??!0,video:!1}).catch(o=>(console.warn("VOIP failed getting audio stream",o),null)),i=await t(e);if(!i)return null;if(exports.DeviceUtilities.isiOS()&&e?.deviceId===void 0){const o=(await navigator.mediaDevices.enumerateDevices()).find(r=>(r.kind==="audioinput"||r.kind==="audiooutput")&&!r.label.includes("iPhone"));if(o){const r=Object.assign({},e);r.deviceId=o.deviceId;const a=await t(r);if(a)return Hi(i),a}}return i}onJoinedRoom=async()=>{this.debug&&console.log("VOIP: Joined room"),await Ds(300),this.autoConnect&&!this.isSending&&this._allowSending&&this.connect()};onLeftRoom=()=>{this.debug&&console.log("VOIP: Left room"),this.disconnect();for(const e of this._incomingStreams.values())Hi(e.srcObject);this._incomingStreams.clear();for(const e of this._analysers.keys())this.cleanupAnalyser(e)};_incomingStreams=new Map;update(){if(!this.onSpeakingChanged||this.onSpeakingChanged.listenerCount<=0)return;const e=performance.now();if(!(e-this._lastSpeakingPollMs<100)){this._lastSpeakingPollMs=e;for(const[t,i]of this._analysers){i.analyser.getByteFrequencyData(i.data);let n=0;for(let l=0;l<i.data.length;l++)n+=i.data[l];const o=n/i.data.length/255,r=this._speakingStates.get(t)??!1,a=o>this.speakingThreshold;a!==r&&(this._speakingStates.set(t,a),this.onSpeakingChanged.invoke({userId:t,isSpeaking:a,volume:o}))}}}setupAnalyser(e,t,i){if(!this._analysers.has(e))try{this._sharedAudioContext||(this._sharedAudioContext=new AudioContext);const n=this._sharedAudioContext,o=n.createMediaStreamSource(i),r=n.createAnalyser();r.fftSize=256,o.connect(r);const a=new Uint8Array(r.frequencyBinCount);this._analysers.set(e,{source:o,analyser:r,data:a})}catch(n){this.debug&&console.warn("VOIP: Failed to create analyser for",e,n)}}cleanupAnalyser(e){const t=this._analysers.get(e);t&&(t.source.disconnect(),t.analyser.disconnect(),this._analysers.delete(e)),this._speakingStates.delete(e)}closeSharedAudioContext(){this._sharedAudioContext&&(this._sharedAudioContext.close(),this._sharedAudioContext=void 0)}onReceiveStream=e=>{const t=e.target.userId,i=e.stream;let n=this._incomingStreams.get(t);n||(n=new Audio,this._incomingStreams.set(t,n)),n.srcObject=i,n.volume=this._volume,n.setAttribute("autoplay","true"),this.setupAnalyser(t,n,i),wn.registerWaitForInteraction(()=>{n?.play().catch(o=>{console.error("VOIP: Failed to play audio",o)})})};onStreamEnded=e=>{const t=this._incomingStreams.get(e.userId);Hi(t?.srcObject),this._incomingStreams.delete(e.userId),this.cleanupAnalyser(e.userId)};onEnabledChanged=()=>{for(const e of this._incomingStreams){const t=e[1];t.muted=!this.enabled}};onVisibilityChanged=()=>{if(this.runInBackground)return;const e=document.visibilityState!=="visible";this.setMuted(e);const t=this._outputStream?.getAudioTracks();if(t)for(const i of t)i.enabled=!e}}Hl([p()],Qs.prototype,"autoConnect",2);Hl([p()],Qs.prototype,"runInBackground",2);Hl([p()],Qs.prototype,"createMenuButton",2);Hl([p()],Qs.prototype,"volume",1);Hl([p()],Qs.prototype,"speakingThreshold",2);Hl([p(Z)],Qs.prototype,"onSpeakingChanged",2);function M2(){const s=x("testwindowcount")||0;s&&s>0&&O2(s)}function O2(s){if(x("testwindow"))return null;const e=new URL(window.location.href);cg(e.searchParams,P2,1),cg(e.searchParams,"testwindow",1);const t=e.toString(),i=[];window.onbeforeunload=()=>{for(const l of i)l.close()};const n=.05,o=128;let r=0,a=0;for(let l=0;l<s;l++){r*o+o*.01>=window.innerWidth&&(a+=1,r=0);const h=r*(o*(1+n))+window.screenLeft,d=a*(o*(1+n))+window.screenTop+90+60*a;r+=1;const u=window.open(t,"test window "+l,`popup=yes width=${o} height=${o} top=${d} left=${h}`);if(!u){console.warn("Failed to open window");continue}i.push(u),u.onload=()=>{u.onbeforeunload=()=>{for(let f=0;f<i.length;f++){const m=i[f];m!==u&&m.close()}i.length=0}}}return i}class Rb extends T{awake(){M2()}}class Tb extends T{transformsPerFrame=10;interval=0;useFlatbuffers=!0;awake(){if(this.useFlatbuffers)this.context.connection.beginListenBinary(uh,e=>{});else{this.models=[];for(let e=0;e<this.transformsPerFrame;e++)this.models.push(new E2(this.context.connection.connectionId+"_simulatedTransform_"+e,this))}}builder=null;models=null;update(){if(this.context.connection.isConnected){if(this.useFlatbuffers){if(!this.context.connection.connectionId||this.context.time.frameCount%this.interval!==0)return;this.builder===null&&(this.builder=new ee.Builder(1024));const e=this.builder;for(let t=0;t<this.transformsPerFrame;t++){e.clear();const i=cC(this.context.connection.connectionId,this);this.context.connection.sendBinary(i)}}else if(this.models)for(let e=0;e<this.models.length;e++){const t=this.models[e];t.dontSave=!0,t.update(this,null),this.context.connection.send("TestSimulateUserData-"+e,t)}}}}class E2{guid;fast=!1;position;rotation;velocity=void 0;dontSave;isValid(){return this.fast!==void 0||this.position!==void 0||this.rotation!==void 0||this.velocity!==void 0}constructor(e,t){this.guid=e,this.position={x:0,y:0,z:0},this.rotation={x:0,y:0,z:0,w:0},this.update(t,null)}static temp=new c.Vector3;update(e,t){const i=e.worldPosition;this.position.x=i.x,this.position.y=i.y,this.position.z=i.z;const n=e.worldQuaternion;if(this.rotation.x=n.x,this.rotation.y=n.y,this.rotation.z=n.z,this.rotation.w=n.w,this.fast=!1,t){const o=t.getVelocity();this.velocity===void 0&&(this.velocity={x:0,y:0,z:0}),this.velocity.x=o.x,this.velocity.y=o.y,this.velocity.z=o.z}}}var R2=Object.defineProperty,Lp=(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&&R2(e,t,n),n};class ca extends T{isGizmo=!1;translationSnap=1;rotationSnapAngle=15;scaleSnap=.25;get control(){return this._control}_control;orbit;onEnable(){if(!(this.isGizmo&&!Oh)&&this.context.mainCamera&&(this._control||(this._control=new V.TransformControls(this.context.mainCamera,this.context.renderer.domElement),this._control.enabled=!0,this._control.getRaycaster().layers.set(2),this._control.size=1,("_root"in this._control?this._control._root:this._control).traverse(t=>{const i=t;if(i.layers.set(2),i){const n=i.material;n&&(n.opacity=.3)}}),this.orbit=P.getComponentInParent(this.context.mainCamera,ue)??void 0),this._control)){const e=this._control.getHelper();this.context.scene.add(e),this._control.attach(this.gameObject),this._control?.addEventListener("dragging-changed",this.onControlChangedEvent),window.addEventListener("keydown",this.windowKeyDownListener),window.addEventListener("keyup",this.windowKeyUpListener)}}onDisable(){this._control?.getHelper()?.removeFromParent(),this._control?.removeEventListener("dragging-changed",this.onControlChangedEvent),window.removeEventListener("keydown",this.windowKeyDownListener),window.removeEventListener("keyup",this.windowKeyUpListener)}enableSnapping(){this._control&&(this._control.setTranslationSnap(this.translationSnap),this._control.setRotationSnap(c.MathUtils.degToRad(this.rotationSnapAngle)),this._control.setScaleSnap(this.scaleSnap))}disableSnapping(){this._control&&(this._control.setTranslationSnap(null),this._control.setRotationSnap(null),this._control.setScaleSnap(null))}onControlChangedEvent=e=>{const t=this.orbit;if(t&&(t.enabled=!e.value),e.value){const i=this.gameObject.getComponentInParent(Sn);i&&(i.fastMode=!0,i.requestOwnership())}else{const i=this.gameObject.getComponentInParent(Sn);i&&(i.fastMode=!1)}};windowKeyDownListener=e=>{if(this.enabled&&this._control)switch(e.keyCode){case 81:this._control.setSpace(this._control.space==="local"?"world":"local");break;case 16:this.enableSnapping();break;case 87:this._control.setMode("translate");break;case 69:this._control.setMode("rotate");break;case 82:this._control.setMode("scale");break;case 187:case 107:this._control.setSize(this._control.size+.1);break;case 189:case 109:this._control.setSize(Math.max(this._control.size-.1,.1));break;case 88:this._control.showX=!this._control.showX;break;case 89:this._control.showY=!this._control.showY;break;case 90:this._control.showZ=!this._control.showZ;break;case 32:this._control.enabled=!this._control.enabled;break}};windowKeyUpListener=e=>{this.enabled&&e.keyCode===16&&this.disableSnapping()}}Lp([p()],ca.prototype,"isGizmo");Lp([p()],ca.prototype,"translationSnap");Lp([p()],ca.prototype,"rotationSnapAngle");Lp([p()],ca.prototype,"scaleSnap");var T2=Object.defineProperty,A2=Object.getOwnPropertyDescriptor,Bp=(s,e,t,i)=>{for(var n=i>1?void 0:i?A2(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&&T2(e,t,n),n};class Ab{texture=null;rect}Bp([p(c.Texture)],Ab.prototype,"texture",2);let ql=class extends Yh{set image(e){this.sprite||(this.sprite=new Ab),this.sprite.texture=e,this.onAfterCreated()}get image(){return this.sprite?this.sprite.texture:null}get sprite(){return this._sprite}set sprite(e){this._sprite!==e&&(this._sprite=e,this.onAfterCreated())}_sprite;pixelsPerUnitMultiplier=1;isBuiltinSprite(){const e=this.sprite;switch(e?.texture?.name){case"InputFieldBackground":case"UISprite":case"Background":case"Knob":return!0}const t=e?.texture?.image;return!!(!e?.texture?.name?.length&&Lc(t)&&t.width===32&&t.height===32)}onBeforeCreate(e){super.onBeforeCreate(e),this.isBuiltinSprite()&&(e.borderRadius=5/this.pixelsPerUnitMultiplier,this.sprite?.texture?.name==="Knob"&&(e.borderRadius=999))}onAfterCreated(){this.__didAwake&&(super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture(this.sprite?.texture))}};Bp([p(Ab)],ql.prototype,"sprite",1);Bp([p()],ql.prototype,"pixelsPerUnitMultiplier",2);class Fp extends Yh{get mainTexture(){return this._mainTexture}set mainTexture(e){this._mainTexture!==e&&(this._mainTexture=e,this.onAfterCreated())}_mainTexture;onAfterCreated(){this.__didAwake&&(super.onAfterCreated(),this.setTexture(this.mainTexture))}}Bp([p(c.Texture)],Fp.prototype,"mainTexture",1);var D2=Object.defineProperty,I2=Object.getOwnPropertyDescriptor,ji=(s,e,t,i)=>{for(var n=i>1?void 0:i?I2(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&&D2(e,t,n),n};const sr=x("debugbutton");class Qo{colorMultiplier;disabledColor;fadeDuration;highlightedColor;normalColor;pressedColor;selectedColor}ji([p()],Qo.prototype,"colorMultiplier",2);ji([p(oe)],Qo.prototype,"disabledColor",2);ji([p()],Qo.prototype,"fadeDuration",2);ji([p(oe)],Qo.prototype,"highlightedColor",2);ji([p(oe)],Qo.prototype,"normalColor",2);ji([p(oe)],Qo.prototype,"pressedColor",2);ji([p(oe)],Qo.prototype,"selectedColor",2);class L2{disabledTrigger;highlightedTrigger;normalTrigger;pressedTrigger;selectedTrigger}class Ys extends T{click(){this.onClick?.invoke()}onClick=new Z;_isHovered=0;onPointerEnter(e){const t=e.event.pointerType==="mouse"&&e.button===0;t&&(this._isHovered+=1),sr&&console.warn("Button Enter",t,this._isHovered,this.animationTriggers?.highlightedTrigger,this.animator),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.highlightedTrigger):this.transition===1&&this.colors&&this._image?.setState("hovered"),t&&this.context.input.setCursor("pointer"))}onPointerExit(){this._isHovered-=1,this._isHovered<0&&(this._isHovered=0),sr&&console.log("Button Exit",this._isHovered,this.animationTriggers?.highlightedTrigger,this.animator),this.interactable&&(this._isHovered>0||(this._isHovered=0,this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&this._image?.setState("normal"),this.context.input.unsetCursor("pointer")))}onPointerDown(e){sr&&console.log("Button Down",this.animationTriggers?.highlightedTrigger,this.animator),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.pressedTrigger):this.transition===1&&this.colors&&this._image?.setState("pressed"))}onPointerUp(e){sr&&console.warn("Button Up",this.animationTriggers?.highlightedTrigger,this.animator,this._isHovered),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this._isHovered?this.animationTriggers.highlightedTrigger:this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&this._image?.setState(this._isHovered?"hovered":"normal"))}onPointerClick(e){if(this.interactable&&!(e.button!==0&&e.event.pointerType===Lf.Mouse)&&(sr&&(console.warn("Button Click",this.onClick),Re("CLICKED button "+this.name+" at "+this.context.time.frameCount)),this.onClick&&this.onClick.listenerCount>0&&(this.onClick.invoke(),e.use(),this.context.accessibility.focus(this),sr))){const t=this.gameObject.worldPosition;t.add(this.gameObject.worldUp.multiplyScalar(1+Math.random()*.5)),B.DrawLabel(t,"CLICK:"+Date.now(),.1,1+Math.random()*.5)}}colors;transition;animationTriggers;animator;set interactable(e){this._interactable=e,this._image&&(this._image.setInteractable(e),e?this._image.setState("normal"):this._image.setState("disabled"))}get interactable(){return this._interactable}_interactable=!0;set_interactable(e){this.interactable=e}awake(){super.awake(),sr&&console.log(this),this._isInit=!1,this.init()}start(){this._image?.setInteractable(this.interactable),this.gameObject.getComponentInParent(fh)||this.gameObject.addComponent(Yf)}onEnable(){super.onEnable(),this.context.accessibility.updateElement(this,{role:"button",label:this.gameObject.name+" button",hidden:!1})}onDisable(){super.onDisable(),this.context.accessibility.updateElement(this,{hidden:!0})}onDestroy(){this.context.accessibility.removeElement(this),this._isHovered&&this.context.input.unsetCursor("pointer")}_requestedAnimatorTrigger;*setAnimatorTriggerAtEndOfFrame(e){this._requestedAnimatorTrigger=e,yield,yield,this._requestedAnimatorTrigger==e&&this.animator?.setTrigger(e)}_isInit=!1;_image;init(){this._isInit||(this._isInit=!0,this._image=P.getComponent(this.gameObject,ql),this._image&&(this.stateSetup(this._image),this.interactable?this._image.setState("normal"):this._image.setState("disabled")))}stateSetup(e){e.setInteractable(this.interactable);const t=this.getFinalColor(e.color,this.colors?.normalColor),i={state:"normal",attributes:{backgroundColor:t,backgroundOpacity:t.alpha}};e.setupState(i);const n=this.getFinalColor(e.color,this.colors?.highlightedColor),o={state:"hovered",attributes:{backgroundColor:n,backgroundOpacity:n.alpha}};e.setupState(o);const r=this.getFinalColor(e.color,this.colors?.pressedColor),a={state:"pressed",attributes:{backgroundColor:r,backgroundOpacity:r.alpha}};e.setupState(a);const l=this.getFinalColor(e.color,this.colors?.selectedColor),h={state:"selected",attributes:{backgroundColor:l,backgroundOpacity:l.alpha}};e.setupState(h);const d=this.getFinalColor(e.color,this.colors?.disabledColor),u={state:"disabled",attributes:{backgroundColor:d,backgroundOpacity:d.alpha}};e.setupState(u)}getFinalColor(e,t){return t?e.clone().multiply(t).convertLinearToSRGB():e.clone().convertLinearToSRGB()}}ji([p(Z)],Ys.prototype,"onClick",2);ji([p(Qo)],Ys.prototype,"colors",2);ji([p()],Ys.prototype,"transition",2);ji([p(L2)],Ys.prototype,"animationTriggers",2);ji([p(vt)],Ys.prototype,"animator",2);ji([p()],Ys.prototype,"interactable",1);var B2=Object.defineProperty,jp=(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&&B2(e,t,n),n};const ao=x("debuginputfield"),dd=class H extends T{get text(){return this.textComponent?.text??""}set text(e){this.textComponent&&(this.textComponent.text=e,this.placeholder&&(e.length>0?this.placeholder.gameObject.visible=!1:this.placeholder.gameObject.visible=!0))}get isFocused(){return H.active===this}textComponent;placeholder;onValueChanged;onEndEdit;static active=null;static activeTime=-1;static htmlField=null;static htmlFieldFocused=!1;inputEventFn;_iosEventFn;start(){ao&&console.log(this.name,this)}onEnable(){H.htmlField||(H.htmlField=document.createElement("input"),H.htmlField.style.width="0px",H.htmlField.style.height="0px",H.htmlField.style.padding="0px",H.htmlField.style.border="none",H.htmlField.style.overflow="hidden",H.htmlField.style.caretColor="transparent",H.htmlField.style.outline="none",H.htmlField.classList.add("ar"),H.htmlField.onfocus=()=>H.htmlFieldFocused=!0,H.htmlField.onblur=()=>H.htmlFieldFocused=!1,document.body.append(H.htmlField)),this.inputEventFn||(this.inputEventFn=this.onInput.bind(this)),H.htmlField.addEventListener("keyup",this.inputEventFn),this.placeholder&&this.textComponent?.text.length&&P.setActive(this.placeholder.gameObject,!1),exports.DeviceUtilities.isiOS()&&(this._iosEventFn=this.processInputOniOS.bind(this),window.addEventListener("click",this._iosEventFn))}onDisable(){H.htmlField?.removeEventListener("keyup",this.inputEventFn),this.onDeselected(),this._iosEventFn&&window.removeEventListener("click",this._iosEventFn)}clear(){H.active===this&&H.htmlField?(H.htmlField.value="",this.setTextFromInputField()):(this.textComponent&&(this.textComponent.text=""),this.placeholder&&P.setActive(this.placeholder.gameObject,!0))}select(){this.onSelected()}deselect(){this.onDeselected()}onPointerEnter(e){e.event.pointerType==="mouse"&&e.button===0&&this.context.input.setCursor("text")}onPointerExit(e){this.context.input.unsetCursor("text")}onPointerClick(e){ao&&console.log("CLICK",e,H.active),H.activeTime=this.context.time.time,H.active!==this&&this.startCoroutine(this.activeLoop(),Ce.LateUpdate),this.selectInputField()}*activeLoop(){for(this.onSelected();H.active===this&&!(this.context.input.getPointerClicked(0)&&this.context.time.time-H.activeTime>.2);)this.setTextFromInputField(),yield;this.onDeselected()}onSelected(){if(H.active!==this&&(ao&&console.log("Select",this.name,this,H.htmlField,this.context.isInXR,this.context.arOverlayElement,this.textComponent?.text,H.htmlField?.value),H.active?.onDeselected(),H.active=this,this.placeholder&&P.setActive(this.placeholder.gameObject,!1),H.htmlField)){if(H.htmlField.value=this.textComponent?.text||"",ao&&console.log("set input field value",H.htmlField.value),this.context.isInXR){const e=this.context.arOverlayElement;e&&e.append(H.htmlField)}this.selectInputField()}}onDeselected(){H.active===this&&(H.active=null,ao&&console.log("Deselect",this.name,this),H.htmlField&&(H.htmlField.blur(),document.body.append(H.htmlField)),this.placeholder&&(!this.textComponent||this.textComponent.text.length<=0)&&P.setActive(this.placeholder.gameObject,!0),H.htmlField&&this.onEndEdit?.invoke(H.htmlField.value))}update(){H.active===this&&this.textComponent?.markDirty()}onInput(e){if(H.active===this){if(ao&&console.log(e.code,e,H.htmlField?.value,this.textComponent?.text),e.code==="Escape"||e.code==="Enter"){this.onDeselected();return}H.htmlField&&(this.textComponent&&(this.setTextFromInputField(),this.placeholder&&P.setActive(this.placeholder.gameObject,this.textComponent.text.length<=0)),this.selectInputField())}}setTextFromInputField(){if(this.textComponent&&H.htmlField){const e=this.textComponent.text,t=H.htmlField.value,i=this.textComponent.text!==H.htmlField.value;this.textComponent.text=H.htmlField.value,i&&(ao&&console.log("[InputField] value changed:",t,e),this.onValueChanged?.invoke(t,e))}}selectInputField(){H.htmlField&&(ao&&console.log("Focus Inputfield",H.htmlFieldFocused,H.htmlField),H.htmlField.setSelectionRange(H.htmlField.value.length,H.htmlField.value.length),exports.DeviceUtilities.isiOS()?(H.htmlField.style.display="block",H.htmlField.focus({preventScroll:!0})):setTimeout(()=>H.htmlField?.focus(),1))}processInputOniOS(){const e=this.context.physics.raycast();if(!e.length)return;const i=e[0].object,n=g_(i);(n?.gameObject===this.gameObject||n?.gameObject.parent===this.gameObject)&&this.selectInputField()}};jp([p(Nt)],dd.prototype,"textComponent");jp([p(Nt)],dd.prototype,"placeholder");jp([p(Z)],dd.prototype,"onValueChanged");jp([p(Z)],dd.prototype,"onEndEdit");let Db=dd;var F2=Object.defineProperty,H1=(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&&F2(e,t,n),n};class ud extends T{id=null;keepAspect=!1;_object=null;onEnable(){if(this._object){this.gameObject.add(this._object);return}if(!this.id||!this.context.mainCamera)return;const e=document.getElementById(this.id);if(!e){console.warn('Could not find element with id "'+this.id+'"');return}e.style.display="block",e.style.visibility="hidden";const t=new V.InteractiveGroup;t.listenToPointerEvents(this.context.renderer,this.context.mainCamera),this.gameObject.add(t);const i=new V.HTMLMesh(e);t.add(i),i.visible=!1;const n=i.material;n.transparent=!0,setTimeout(()=>{i.visible=!0;const o=Of(this.gameObject).clone();Ph(this.gameObject,0,0,0),this.gameObject.updateMatrixWorld();const r=new c.Box3;r.setFromObject(t),this.setWorldRotation(o.x,o.y,o.z);const a=r.max.x-r.min.x,l=r.max.y-r.min.y;if(this.keepAspect){const d=a/l;a>l?i.scale.set(1/a,1/l/d,1):i.scale.set(1/a*d,1/l,1)}else i.scale.set(1/a,1/l,1);const h=this.gameObject.scale;i.scale.multiply(h)},1)}onDisable(){this._object?.removeFromParent()}}H1([p()],ud.prototype,"id");H1([p()],ud.prototype,"keepAspect");var j2=Object.defineProperty,Up=(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&&j2(e,t,n),n};const fd=class q1 extends T{target;invertForward=!1;keepUpDirection=!0;copyTargetRotation=!1;static flipYQuat=new c.Quaternion().setFromAxisAngle(new c.Vector3(0,1,0),Math.PI);onBeforeRender(){let e=this.target;if(e||(e=this.context.mainCamera,E()&&!this.__did_warn&&(this.__did_warn=!0,console.debug(`[LookAt] No target set on ${this.name}, using main camera as target.`))),!e)return;let t=this.copyTargetRotation;(this.context.isInVR||this.context.isInPassThrough)&&(t=!1),Ch(this.gameObject,e,this.keepUpDirection,t),this.invertForward&&this.gameObject.quaternion.multiply(q1.flipYQuat)}createBehaviours(e,t,i){if(t.uuid===this.gameObject.uuid){let n=t;if(this.keepUpDirection){const r=nt.createEmptyParent(t);n=r;const a=this.invertForward?-1:1;r.setMatrix(r.getMatrix().multiply(new c.Matrix4().makeRotationZ(Math.PI/2*a))),t.setMatrix(t.getMatrix().multiply(new c.Matrix4().makeRotationZ(-Math.PI/2*a)))}const o=new Dt("lookat "+this.name,jt.sceneStartTrigger(),pe.lookAtCameraAction(n,void 0,this.invertForward?qi.back:qi.forward,this.keepUpDirection?qi.up:qi.zero));e.addBehavior(o)}}};Up([p(c.Object3D)],fd.prototype,"target");Up([p()],fd.prototype,"invertForward");Up([p()],fd.prototype,"keepUpDirection");Up([p()],fd.prototype,"copyTargetRotation");let Ib=fd;var U2=Object.defineProperty,Lb=(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&&U2(e,t,n),n};class Xl extends T{url;mode=0;clickable=!0;async open(){if(!this.url){console.warn("OpenURL: URL is not set, can't open.",this);return}this._validateUrl();let e=this.url;switch(!e.startsWith("mailto:")&&e.includes("@")&&(e="mailto:"+e),this.mode){case 0:exports.DeviceUtilities.isSafari(),globalThis.open(e,"_blank");break;case 1:exports.DeviceUtilities.isSafari()&&exports.DeviceUtilities.isiOS()?globalThis.open(e,"_top"):globalThis.open(e,"_self");break;case 2:exports.DeviceUtilities.isSafari()?globalThis.open(e,"_top"):globalThis.open(e,"_new");break}}start(){this.gameObject.getComponentInParent(Ji)||this.gameObject.addComponent(Ji)}onPointerEnter(e){!e.used&&this.clickable&&this.context.input.setCursor("pointer")}onPointerExit(){this.clickable&&this.context.input.unsetCursor("pointer")}onPointerClick(e){this.clickable&&!e.used&&this.url?.length&&this.open()}_validateUrl(){this.url&&this.url.startsWith("www.")&&(E()&&console.warn("URL is not valid, adding https:// to the start of the URL",this.url),this.url="https://"+this.url)}}Lb([p()],Xl.prototype,"url");Lb([p()],Xl.prototype,"mode");Lb([p()],Xl.prototype,"clickable");If(s=>{const e=s.domElement.getAttribute("clickthrough");if(t(e)){const i=s.scene.addComponent(zp);ju(s.domElement,"clickthrough",()=>{const n=s.domElement.getAttribute("clickthrough");i.enabled=t(n)})}function t(i){return i!==null&&i!=="0"&&i!=="false"}});class zp extends T{_previousPointerEvents="all";onEnable(){this.context.input.addEventListener("pointerdown",this.onPointerEvent),this.context.input.addEventListener("pointermove",this.onPointerEvent,{queue:100}),window.addEventListener("touchstart",this.onTouchStart,{passive:!0}),window.addEventListener("touchend",this.onTouchEnd,{passive:!0}),this._previousPointerEvents=this.context.domElement.style.pointerEvents}onDisable(){this.context.input.removeEventListener("pointerdown",this.onPointerEvent),this.context.input.removeEventListener("pointermove",this.onPointerEvent),window.removeEventListener("touchstart",this.onTouchStart),window.removeEventListener("touchend",this.onTouchEnd),this.context.domElement.style.pointerEvents=this._previousPointerEvents}onPointerEnter(){}onPointerEvent=e=>{if(e.pointerId>0)return;e.intersections?.length<=0?this.context.domElement.style.pointerEvents="none":this.context.domElement.style.pointerEvents="all"};_touchDidHitAnything=!1;onTouchStart=e=>{const t=e.touches[0];if(!t)return;const i=t.clientX/window.innerWidth*2-1,n=-(t.clientY/window.innerHeight)*2+1;this.context.physics.raycast({screenPoint:new c.Vector2(i,n)}).length>0&&(this._touchDidHitAnything=!0)};onTouchEnd=e=>{const t=this._touchDidHitAnything;this._touchDidHitAnything=!1,setTimeout(()=>{t&&(this.context.domElement.style.pointerEvents="all")},100)}}var z2=Object.defineProperty,Np=(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&&z2(e,t,n),n};const N2=x("debugcursor");class ha extends T{static NAME="CursorFollow";damping=0;useFullPage=!0;keepDistance=!0;snapToSurface=!1;_distance=-1;updateDistance(e=!1){!e&&this.keepDistance&&this._distance!==-1||(this._distance=this.gameObject.worldPosition.distanceTo(this.context.mainCamera.worldPosition))}awake(){this._distance=-1}onEnable(){this._distance=-1,window.addEventListener("pointermove",this._onPointerMove)}onDisable(){window.removeEventListener("pointermove",this._onPointerMove)}_ndc_x=0;_ndc_y=0;_onPointerMove=e=>{if(!this.useFullPage)return;const t=e.clientX,i=e.clientY,n=this.context.domX,o=this.context.domY,r=this.context.domWidth,a=this.context.domHeight;this._ndc_x=(t-n)/r*2-1,this._ndc_y=-(i-o)/a*2+1};lateUpdate(){this.updateDistance();const e=this.useFullPage?this._ndc_x:this.context.input.mousePositionRC.x,t=this.useFullPage?this._ndc_y:this.context.input.mousePositionRC.y,i=this.context.mainCamera,n=i.worldPosition,o=F(e,t,1).unproject(i);o.sub(n).normalize();const r=F(o).multiplyScalar(this._distance).add(n);let a=r;if(this.damping>0){const l=this.gameObject.worldPosition;l.lerp(r,this.context.time.deltaTime/this.damping),this.gameObject.worldPosition=l,a=l}else this.gameObject.worldPosition=r;if(this.snapToSurface){Zm.origin=n,Zm.direction=o;const l=this.context.physics.raycastFromRay(Zm,{testObject:h=>h!==this.gameObject&&!this.gameObject.contains(h)});if(l?.length){const h=l[0];h&&(this.damping>0?this.gameObject.worldPosition=a.lerp(h.point,this.context.time.deltaTime/this.damping):this.gameObject.worldPosition=h.point,N2&&B.DrawLine(h.point,h.normal.add(h.point),65280))}}}}Np([p()],ha.prototype,"damping");Np([p()],ha.prototype,"useFullPage");Np([p()],ha.prototype,"keepDistance");Np([p()],ha.prototype,"snapToSurface");const Zm=new c.Ray;var $2=Object.defineProperty,V2=Object.getOwnPropertyDescriptor,Ql=(s,e,t,i)=>{for(var n=i>1?void 0:i?V2(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&&$2(e,t,n),n};exports.HoverAnimation=class extends T{type="linear";duration=.1;scaleFactor=1.1;hovered=null;idle=null;animation=null;start(){this.idle||(this.idle=exports.AnimationUtils.emptyClip()),(!this.hovered||!(this.hovered instanceof c.AnimationClip))&&(this.hovered=exports.AnimationUtils.createScaleClip({type:"linear",duration:this.duration||.1,scale:this.gameObject.scale,scaleFactor:this.scaleFactor||1.1})),this.animation??=this.gameObject.addComponent(Ut),this.animation.playAutomatically=!1,this.playIdle()}onEnable(){this.animation&&(this.animation.enabled=!0),this.playIdle()}onDisable(){this.animation&&(this.animation.enabled=!1),this.playIdle()}onPointerEnter(){this.playHover()}onPointerExit(){this.playIdle()}playIdle(){this.idle&&this.animation?.play(this.idle,{exclusive:!0,fadeDuration:.1,loop:!0})}playHover(){this.hovered&&this.animation?.play(this.hovered,{exclusive:!0,fadeDuration:.1,loop:!1,clampWhenFinished:!0})}};Ql([p()],exports.HoverAnimation.prototype,"type",2);Ql([p()],exports.HoverAnimation.prototype,"duration",2);Ql([p()],exports.HoverAnimation.prototype,"scaleFactor",2);Ql([p(c.AnimationClip)],exports.HoverAnimation.prototype,"hovered",2);Ql([p(c.AnimationClip)],exports.HoverAnimation.prototype,"idle",2);exports.HoverAnimation=Ql([Ly],exports.HoverAnimation);var W2=Object.defineProperty,da=(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&&W2(e,t,n),n};typeof window<"u"&&Promise.resolve().then(()=>require("./vendor-CDN1hirK.umd.cjs")).then(s=>s.scrollTimeline);const bs=x("debugscroll");class gs extends T{target=null;damping=0;invert=!1;htmlSelector=null;mode="window";useTopWindowScroll=!0;changed=new Z;get currentValue(){return this._current_value}_current_value=0;_target_value=0;_appliedValue=-1;_needsUpdate=!1;_firstUpdate=!1;_scrollWindow=null;_wheelTarget=null;_crossOriginWarned=!1;_viewTimelineWarned=!1;awake(){this._firstUpdate=!0}onEnable(){this.rebindScrollListener(),this._appliedValue=-1,this._needsUpdate=!0}onDisable(){this._wheelTarget?.removeEventListener("wheel",this.updateCurrentScrollValue),this._wheelTarget=null}onValidate(e){e==="useTopWindowScroll"&&this._wheelTarget&&(this.rebindScrollListener(),this._needsUpdate=!0)}resolveScrollWindow(){if(!this.useTopWindowScroll)return window;const e=window.top;if(!e||e===window.self)return window;try{return e.document,e}catch{return this._crossOriginWarned||(this._crossOriginWarned=!0,(bs||E())&&console.warn("[ScrollFollow] useTopWindowScroll is enabled but the top-level window is cross-origin and cannot be read. Falling back to the local window. Supporting cross-origin embeds requires a postMessage scroll bridge from the host page.")),window}}rebindScrollListener(){const e=this.resolveScrollWindow();this._scrollWindow=e,e!==this._wheelTarget&&(this._wheelTarget?.removeEventListener("wheel",this.updateCurrentScrollValue),this._wheelTarget=e,e.addEventListener("wheel",this.updateCurrentScrollValue,{passive:!0}),this._lastSelectorValue=null,this._lastSelectorElement=null,bs&&console.debug(`[ScrollFollow] Scroll listener bound to ${e===window?"local window":"top-level window"}`,{scrollWindow:this._scrollWindow,isTopWindow:e===window}))}lateUpdate(){if(this.updateCurrentScrollValue(),this._target_value>=0&&(this.damping>0&&!this._firstUpdate?(this._current_value=L.lerp(this._current_value,this._target_value,this.context.time.deltaTime/this.damping),Math.abs(this._current_value-this._target_value)<.001&&(this._current_value=this._target_value)):this._current_value=this._target_value),this._needsUpdate||this._current_value!==this._appliedValue){this._appliedValue=this._current_value,this._needsUpdate=!1;let e=!1;if(this.changed.listenerCount>0){const t={type:"change",value:this._current_value,component:this,preventDefault:()=>{t.defaultPrevented=!0},defaultPrevented:!1};this.changed.invoke(t),e=t.defaultPrevented}if(!e){const t=this.invert?1-this._current_value:this._current_value;Array.isArray(this.target)?this.target.forEach(i=>i&&this.applyScroll(i,t)):this.target&&this.applyScroll(this.target,t),bs&&this.context.time.frame%30===0&&console.debug(`[ScrollFollow] ${this._current_value.toFixed(5)} — ${(this._target_value*100).toFixed(0)}%, targets [${Array.isArray(this.target)?this.target.length:1}]`)}this._firstUpdate=!1}}_lastSelectorValue=null;_lastSelectorElement=null;updateCurrentScrollValue=()=>{const e=this._scrollWindow??window,t=e.document,i=t.scrollingElement??t.documentElement;switch(this.mode){case"window":if(this.htmlSelector?.length){if(this.htmlSelector!==this._lastSelectorValue&&(this._lastSelectorElement=t.querySelector(this.htmlSelector),this._lastSelectorValue=this.htmlSelector),this._lastSelectorElement){const n=this._lastSelectorElement.getBoundingClientRect();this._target_value=-n.top/(n.height-e.innerHeight);break}}else{const n=i.scrollHeight-i.clientHeight;n<=0||(this._target_value=i.scrollTop/n)}break}(isNaN(this._target_value)||!isFinite(this._target_value))&&(this._target_value=-1),bs&&console.debug(`[ScrollFollow] Scroll value updated: ${this._target_value.toFixed(5)} (ScrollTop: ${i.scrollTop}, ScrollHeight: ${i.scrollHeight}, ClientHeight: ${i.clientHeight})`)};applyScroll(e,t){if(e)if(e instanceof ml)this.handleTimelineTarget(e,t),e.isPlaying&&e.pause(),e.evaluate();else if(e instanceof vt)e.setFloat("scroll",t);else if(e instanceof Ut)e.time=t*e.duration;else if(e instanceof Ei){if(!e.duration)return;e.time=t*e.duration}else if(e instanceof ln)e.position01=t;else if(e instanceof Lt)e.intensity=t;else if(e instanceof c.Object3D){const i=e;i["needle:scrollbounds"]===void 0&&(i["needle:scrollbounds"]=pi(e)||null);const n=i["needle:scrollbounds"];n&&(e.position.y=-n.min.y-t*(n.max.y-n.min.y))}else"scroll"in e&&(typeof e.scroll=="number"?e.scroll=t:typeof e.scroll=="function"&&e.scroll(t))}handleTimelineTarget(e,t){const i=this._scrollWindow??window,n=i.document,o=e.duration;let r=Jm.get(e);if(!r){r=[],Jm.set(e,r);let d=0;for(const f of e.foreachMarker("ScrollMarker")){const m=d++;if(f.element===void 0||f.needsUpdate===!0||f.element&&!f.element?.parentNode){f.needsUpdate=!1;try{if(f.element=X1(m,n),bs&&console.debug(`ScrollMarker #${m} (${f.time.toFixed(2)}) found`,f.element),!f.element){(bs||E())&&console.warn(`No HTML element found for ScrollMarker: ${f.name} (index ${m})`);continue}}catch(g){f.element=null,console.error("ScrollMarker selector is not valid: "+f.name+`
|
|
1529
1529
|
`,g)}}f.element&&r.push(f)}r.length<=0&&n.querySelectorAll("[data-timeline-marker]").forEach(m=>{const g=m.getAttribute("data-timeline-marker"),v=parseFloat(g||"NaN");isNaN(v)?(E()||bs)&&console.warn('[ScrollFollow] data-timeline-marker attribute is not a valid number. Supported are numbers only (e.g. <div data-timeline-marker="0.5">)'):r.push({time:v,element:m})});const u=i.ViewTimeline;if(!u)!this._viewTimelineWarned&&(bs||E())&&(this._viewTimelineWarned=!0,console.warn("[ScrollFollow] ViewTimeline is not available on the target window — falling back to linear scroll. If this persists with useTopWindowScroll, the scroll-timeline polyfill must be present on the host page.")),Jm.delete(e),r.length=0;else for(const f of r)f.element&&(f.timeline=new u({subject:f.element,axis:"block"}))}Fn.length=0;let a=0;const l=1/60;let h=0;for(let d=0;d<r.length;d++){const u=r[d];if(!u.element)continue;const f=r[d+1],m=f?f.time-l:o;h+=1;const g=u.timeline;if(g){const v=G2(g),_=1-Math.abs(v-.5)*2,y=`marker${d}`;if(v>0&&v<=1){const b=u.time+(m-u.time)*v;Fn.push({name:y,time:b,weight:_}),a+=_}else d===0&&v<=0?(Fn.push({name:y,time:0,weight:1}),a+=1):d===r.length-1&&v>=1&&(Fn.push({name:y,time:o,weight:1}),a+=1)}}if(Fn.length<=0&&h<=0)e.time=t*o;else if(Fn.length>0){let d=Fn[0].time;if(Fn.length>1)for(const f of Fn){const m=f.weight/Math.max(1e-5,a),g=Math.abs(f.time-d);d+=g*m}this.damping<=0||this._firstUpdate?e.time=d:e.time=L.lerp(e.time,d,this.context.time.deltaTime/this.damping),Math.abs(e.time-d)>.001&&(this._needsUpdate=!0),bs&&this.context.time.frame%30===0&&console.log(`[ScrollFollow ] Timeline ${e.name}: ${d.toFixed(3)}`,Fn.map(f=>`[${f.name} ${(f.weight*100).toFixed(0)}%]`).join(", "))}}}da([p([T,c.Object3D])],gs.prototype,"target");da([p()],gs.prototype,"damping");da([p()],gs.prototype,"invert");da([p()],gs.prototype,"htmlSelector");da([p()],gs.prototype,"mode");da([je(),p()],gs.prototype,"useTopWindowScroll");da([p(Z)],gs.prototype,"changed");const Jm=new WeakMap,Fn=[],eg=new Array;let tg=!0;function X1(s,e){return tg?(tg=!1,eg.length=0,e.querySelectorAll("[data-timeline-marker]").forEach((i,n)=>{eg[n]=i}),tg=!1,X1(s,e)):eg[s]||null}function G2(s){if(!s.source)return 0;const e=s.currentTime,t=s.duration;let i=1;return(t.unit==="seconds"||t.unit==="percent")&&(i=t.value),e.unit==="seconds"?e.value/i:e.value/100}var Q1=Object.defineProperty,H2=Object.getOwnPropertyDescriptor,q2=(s,e,t)=>e in s?Q1(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,$p=(s,e,t,i)=>{for(var n=i>1?void 0:i?H2(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&&Q1(e,t,n),n},Bb=(s,e,t)=>q2(s,typeof e!="symbol"?e+"":e,t);const lo=x("debugviewbox"),X2=new oe(.5,.5,.5,.5);exports.ViewBox=class extends T{referenceFieldOfView=-1;get mode(){return this._mode}set mode(e){e!==this._mode&&(this._mode=e,e==="once"&&(this._applyCount=0),(lo||this.debug)&&console.debug("[ViewBox] Set mode:",e))}_mode="continuous";debug=!1;onEnable(){(lo||this.debug||E())&&console.debug("[ViewBox] Using camera fov:",this.referenceFieldOfView),exports.ViewBox.instances.push(this),this._applyCount=0,this.removeUpdateCallback(),this.context.pre_render_callbacks.push(this.internalUpdate)}onDisable(){(lo||this.debug)&&console.debug("[ViewBox] Disabled");const e=exports.ViewBox.instances.indexOf(this);e!==-1&&exports.ViewBox.instances.splice(e,1),this._projectedBoxElement?.remove(),this.removeUpdateCallback()}removeUpdateCallback(){const e=this.context.pre_render_callbacks.indexOf(this.internalUpdate);e!==-1&&this.context.pre_render_callbacks.splice(e,1)}_applyCount=0;internalUpdate=()=>{if(this.context.isInXR||this.destroyed||!this.activeAndEnabled)return;if(!(exports.ViewBox.instances[exports.ViewBox.instances.length-1]===this)){(lo||this.debug)&&B.DrawWireBox(this.gameObject.worldPosition,this.gameObject.worldScale,X2);return}(lo||this.debug)&&B.DrawWireBox(this.gameObject.worldPosition,this.gameObject.worldScale,14540032,0,!0,this.gameObject.worldQuaternion);const t=this.context.mainCamera;if(!t||!(t instanceof c.PerspectiveCamera))return;if((this.referenceFieldOfView===void 0||this.referenceFieldOfView===-1)&&(this.referenceFieldOfView=t.fov,console.debug("[ViewBox] No referenceFieldOfView set, using camera fov:",this.referenceFieldOfView)),this.referenceFieldOfView===void 0||this.referenceFieldOfView<=0){(lo||this.debug)&&console.warn("[ViewBox] No valid referenceFieldOfView set, cannot adjust box size:",this.referenceFieldOfView);return}if(this._applyCount>=1&&this.mode==="once")return;this._applyCount++;const i=this.context.domWidth,n=this.context.domHeight;let o=i,r=n,a=1,l=1;const h=this.context.focusRectSize;h&&(o=h.width,r=h.height,a=i/o,l=n/r),exports.ViewBox._tempProjectionMatrix.copy(t.projectionMatrix),exports.ViewBox._tempProjectionMatrixInverse.copy(t.projectionMatrixInverse);const d=t.view,u=t.zoom,f=t.aspect,m=t.fov;t.view=null,t.zoom=1,t.fov=this.referenceFieldOfView,t.updateProjectionMatrix();const g=this.gameObject.worldPosition,v=this.gameObject.worldScale,_=t.worldPosition,y=_.distanceTo(g),b=Math.max(v.x,v.y,v.z),w=F(_).sub(g);if(y<b){(this.debug||lo)&&console.warn("[ViewBox] Moving camera out of bounds",y,"<",b);const G=F(w);G.y*=1e-8,G.normalize();const Y=b-y,K=_.add(G.multiplyScalar(Y));t.worldPosition=K.lerp(_,1-this.context.time.deltaTime)}const C=F(g);t.worldToLocal(C),t.lookAt(g),t.updateMatrixWorld();const k=this.referenceFieldOfView*Math.PI/180,O=2*Math.tan(k/2)*y,D=O*t.aspect,I=this.projectBoxIntoCamera(t,1),j=I.maxX-I.minX,$=I.maxY-I.minY,R=this.fit(j*t.aspect,$,D/a,O/l)/(O*.5),U=F(g);U.project(t),this.context.focusRectSettings.offsetX=U.x,this.context.focusRectSettings.offsetY=U.y,this.context.focusRectSettings.zoom=R,this.context.focusRect||this.context.setCameraFocusRect(this.context.domElement),t.view=d,t.zoom=u,t.aspect=f,t.fov=m,t.projectionMatrix.copy(exports.ViewBox._tempProjectionMatrix),t.projectionMatrixInverse.copy(exports.ViewBox._tempProjectionMatrixInverse)};fit(e,t,i,n){const o=i/e,r=n/t;return Math.min(o,r)}projectBoxIntoCamera(e,t){const i=.5*t,n=[F(-i,-i,-i),F(i,-i,-i),F(-i,i,-i),F(i,i,-i),F(-i,-i,i),F(i,-i,i),F(-i,i,i),F(i,i,i)];let o=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY,a=Number.POSITIVE_INFINITY,l=Number.NEGATIVE_INFINITY;for(let h=0;h<n.length;h++){const d=n[h];d.applyMatrix4(this.gameObject.matrixWorld),d.project(e),d.x<o&&(o=d.x),d.x>r&&(r=d.x),d.y<a&&(a=d.y),d.y>l&&(l=d.y)}return lo&&(this._projectedBoxElement||(this._projectedBoxElement=document.createElement("div")),this._projectedBoxElement.parentElement!==this.context.domElement&&this.context.domElement.appendChild(this._projectedBoxElement),this._projectedBoxElement.style.position="fixed",this._projectedBoxElement.style.outline="2px dashed rgba(255,0,0,.5)",this._projectedBoxElement.style.left=(o*.5+.5)*this.context.domWidth+"px",this._projectedBoxElement.style.top=(-l*.5+.5)*this.context.domHeight+"px",this._projectedBoxElement.style.width=(r-o)*.5*this.context.domWidth+"px",this._projectedBoxElement.style.height=(l-a)*.5*this.context.domHeight+"px",this._projectedBoxElement.style.pointerEvents="none",this._projectedBoxElement.style.zIndex="1000"),{minX:o,maxX:r,minY:a,maxY:l}}_projectedBoxElement=null};Bb(exports.ViewBox,"instances",[]);Bb(exports.ViewBox,"_tempProjectionMatrix",new c.Matrix4);Bb(exports.ViewBox,"_tempProjectionMatrixInverse",new c.Matrix4);$p([p()],exports.ViewBox.prototype,"referenceFieldOfView",2);$p([p()],exports.ViewBox.prototype,"mode",1);$p([p()],exports.ViewBox.prototype,"debug",2);exports.ViewBox=$p([Ly],exports.ViewBox);var Q2=Object.defineProperty,Yl=(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&&Q2(e,t,n),n};class Ks extends T{get activeAndEnabled(){return!0}side="none";controller=!0;hands=!1;controlVisibility=!0;useGripSpace=!1;resetTransformAfterXRSession=!0;_startPosition=new c.Vector3;_startRotation=new c.Quaternion;_startScale=new c.Vector3;onEnterXR(e){this._startPosition.copy(this.gameObject.position),this._startRotation.copy(this.gameObject.quaternion),this._startScale.copy(this.gameObject.scale)}onUpdateXR(e){if(!this.enabled)return;const t=e.xr.getController(this.side);if(t){if(t.hand&&!this.hands){this.controlVisibility&&(this.gameObject.visible=!1);return}else if(!this.controller){this.controlVisibility&&(this.gameObject.visible=!1);return}this.controlVisibility&&(this.gameObject.visible=!0),this.useGripSpace||t.targetRayMode==="transient-pointer"?(this.gameObject.worldPosition=t.gripWorldPosition,this.gameObject.worldQuaternion=t.gripWorldQuaternion,this.gameObject.worldScale=F(t.xr.rigScale,t.xr.rigScale,t.xr.rigScale).multiply(this._startScale)):(this.gameObject.worldPosition=t.rayWorldPosition,this.gameObject.worldQuaternion=t.rayWorldQuaternion,this.gameObject.worldScale=F(t.xr.rigScale,t.xr.rigScale,t.xr.rigScale).multiply(this._startScale))}}onLeaveXR(e){this.resetTransformAfterXRSession&&(this.gameObject.position.copy(this._startPosition),this.gameObject.quaternion.copy(this._startRotation),this.gameObject.scale.copy(this._startScale))}}Yl([p()],Ks.prototype,"side");Yl([p()],Ks.prototype,"controller");Yl([p()],Ks.prototype,"hands");Yl([p()],Ks.prototype,"controlVisibility");Yl([p()],Ks.prototype,"useGripSpace");Yl([p()],Ks.prototype,"resetTransformAfterXRSession");function Y2(){if(typeof window>"u"||!exports.DeviceUtilities.isNeedleAppClip())return null;const s=window.NeedleGoNativeScreenshot;return typeof s=="function"?s:null}function Y1(s,e){const t=s.xr.getFrame();if(!t)return console.warn("No XRFrame available"),!1;const i=t.session.enabledFeatures;if(i&&!i.some(o=>o==="camera-access"))return console.error(`No camera feed available - please request the 'camera-access' feature before starting WebXR or add the ARCameraBackground component to your scene.
|
|
1530
1530
|
|
|
1531
1531
|
Example to request camera-access in global scope:
|
|
@@ -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-DOHf03pR.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.$jVksoCHS=ns;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.KLnyx=Yi;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._$sHuA=kh;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;
|