@needle-tools/engine 4.17.0-next.9367cd4 → 4.17.0-next.ca0e777
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/gltf-progressive-BryRjllq.min.js +10 -0
- package/dist/gltf-progressive-Cl167Vjx.js +1537 -0
- package/dist/gltf-progressive-DJBMx-zB.umd.cjs +10 -0
- package/dist/gltf-progressive.worker-BqODMeeW.js +23 -0
- package/dist/{needle-engine.bundle-B3ex0E4m.js → needle-engine.bundle-Cin-kyZ_.js} +8 -8
- package/dist/{needle-engine.bundle-BVgcWaGl.umd.cjs → needle-engine.bundle-DDZfnvgI.umd.cjs} +7 -7
- package/dist/{needle-engine.bundle-DJoYYWN-.min.js → needle-engine.bundle-Dl_Keq4m.min.js} +6 -6
- package/dist/needle-engine.d.ts +4 -1
- package/dist/needle-engine.js +3 -3
- package/dist/needle-engine.min.js +1 -1
- package/dist/needle-engine.umd.cjs +1 -1
- package/dist/three-examples.js +4302 -3315
- package/dist/three-examples.min.js +15 -13
- package/dist/three-examples.umd.cjs +14 -12
- package/dist/three.js +15994 -24892
- package/dist/three.min.js +214 -214
- package/dist/three.umd.cjs +208 -208
- package/dist/{vendor-9wyvw7Yk.js → vendor-BFFwhLCC.js} +900 -861
- package/dist/{vendor-BLeytgEr.umd.cjs → vendor-Csj7XHEr.umd.cjs} +19 -19
- package/dist/{vendor-DDo_PRrS.min.js → vendor-DUVka3vn.min.js} +19 -19
- package/lib/engine/engine_networking.d.ts +1 -0
- package/lib/engine/engine_networking.js +2 -0
- package/lib/engine/engine_networking.js.map +1 -1
- package/lib/engine-components/Networking.d.ts +2 -1
- package/lib/engine-components/Networking.js +2 -1
- package/lib/engine-components/Networking.js.map +1 -1
- package/lib/engine-components/SyncedRoom.d.ts +1 -0
- package/lib/engine-components/SyncedRoom.js +1 -0
- package/lib/engine-components/SyncedRoom.js.map +1 -1
- package/package.json +4 -1
- package/plugins/vite/ai.js +3 -5
- package/src/engine/engine_networking.ts +4 -0
- package/src/engine-components/Networking.ts +3 -1
- package/src/engine-components/SyncedRoom.ts +2 -0
- package/dist/gltf-progressive-BBIL1q1j.umd.cjs +0 -4022
- package/dist/gltf-progressive-BbHl9z0v.js +0 -28272
- package/dist/gltf-progressive-Clq_N7Zx.min.js +0 -4022
- package/dist/gltf-progressive.worker-CCrD-Ycm.js +0 -3
package/dist/{needle-engine.bundle-BVgcWaGl.umd.cjs → needle-engine.bundle-DDZfnvgI.umd.cjs}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";const c=require("./three.umd.cjs"),re=require("./gltf-progressive-
|
|
1
|
+
"use strict";const c=require("./three.umd.cjs"),re=require("./gltf-progressive-DJBMx-zB.umd.cjs"),X=require("./three-examples.umd.cjs"),ce=require("./vendor-Csj7XHEr.umd.cjs"),ie=require("./three-mesh-ui-Chib781Y.umd.cjs"),Zx=require("./postprocessing-B2wb6pzI.umd.cjs");var ga=typeof document<"u"?document.currentScript:null;const Qy=typeof window!==void 0?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 le{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&&(Qy&&console.warn("Registering context"),this.Registered.push(e),this.dispatchCallback("ContextRegistered",e))}static unregister(e){const t=this.Registered.indexOf(e);t!==-1&&(Qy&&console.warn("Unregistering context"),this.Registered.splice(t,1))}static _callbacks={};static registerCallback(e,t){this._callbacks[e]||(this._callbacks[e]=[]),this._callbacks[e].push(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 Pf=new Map;function yi(s=globalThis.location?.hostname){if(Pf.has(s))return Pf.get(s);const e=/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})|localhost/.test(s);return Pf.set(s,e),e===!0}function dv(){return window.location.hostname.includes("glitch.me")}const uv=()=>s=>s;function Jx(s){return uv()(s)}function eS(){return!!x("debug")}class _i{_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 Go=!1;const Tp=new Array;typeof window<"u"&&setTimeout(()=>{if(Go){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 Tp){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=Go===!0?"":` (containing "${Go}")`;console.group("Available URL parameters:"+n);for(const o of Object.keys(s).sort())typeof Go=="string"&&!o.toLowerCase().includes(Go.toLowerCase())||(console.groupCollapsed(o),console.log("Reload with this flag enabled:"),console.log(s[o]),console.groupEnd());console.groupEnd()}},100);function Bc(){return new URLSearchParams(globalThis.location?.search)}function x(s){Go&&!Tp.includes(s)&&Tp.push(s);const e=Bc();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}Go=x("help");function tS(s,e){const t=Bc();t.has(s)?t.set(s,e):t.append(s,e),document.location.search=t.toString()}function yc(s,e,t=!0){const i=Bc();i.has(s)?e===null?i.delete(s):i.set(s,e):e!==null&&i.append(s,e),t?fv(s,i):Am(s,i)}function Ap(s,e,t){s.has(e)?s.set(e,t.toString()):s.append(e,t.toString())}function fv(s,e,t){window.history.pushState(t,s,"?"+e.toString())}function Am(s,e,t){window.history.replaceState(t,s,"?"+e.toString())}function iS(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 nS(s,e){return Math.floor(Math.random()*(e-s+1))+s}const Yy=["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"],Ky=["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 pv(){const s=Yy[Math.floor(Math.random()*Yy.length)],e=Ky[Math.floor(Math.random()*Ky.length)];return s+"_"+e}function mv(s){return s=s.replace(/[^a-z0-9áéíóúñü \.,_-]/gim,""),s.trim()}function Oa(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=Oa(s,o,t,i);if(r)return r}if(e.children)for(const n in e.children){const o=e.children[n],r=Oa(s,o,t,i);if(r)return r}}}function Fc(s,e){if(s!=null&&typeof s=="object"){let t;Array.isArray(s)?t=[]:(t=Object.create(s),Object.assign(t,s));for(const i of Object.keys(s)){const n=s[i];e&&!e(s,i,n)?t[i]=n:n?.clone!==void 0&&typeof n.clone=="function"?t[i]=n.clone():t[i]=Fc(n,e)}return t}return s}function _s(s){return new Promise((e,t)=>{setTimeout(e,s)})}function Uc(s,e){if(s<=0)return Promise.resolve();if(e||(e=le.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 Dh=x("debugresolveurl"),gv="rel:";function sS(s,e){return ws(s,e)}function ws(s,e){if(e===void 0)return Dh&&console.warn("getPath: uri is undefined, returning uri",e),e;if(e.startsWith("./"))return e;if(e.startsWith("http"))return Dh&&console.warn("getPath: uri is absolute, returning uri",e),e;if(s===void 0)return Dh&&console.warn("getPath: source is undefined, returning uri",e),e;e.startsWith(gv)&&(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 Dh&&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
|
-
`,Lo?.prepend(i),s===!0&&_v()<=0&&Bv(),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.":"")),vl=!1,Zt=null},e.src="https://cdn.jsdelivr.net/npm/vconsole@3.15.1/dist/vconsole.min.js",document.body.appendChild(e)}function lC(){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"),Zt?.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 Fp="padding: 10px; font-family: monospace;",c_="margin-bottom: 10px;",Io="margin-bottom: 10px; margin-top: 15px;",cC="width: 100%; border-collapse: collapse; border: 1px solid rgba(0,0,0,0.1); table-layout: fixed;",Fv="border: 1px solid rgba(0,0,0,0.1); padding: 5px;",hC=Fv,dC=Fv+" word-break: break-all;";function En(s,e=!1){e&&s.sort((i,n)=>(n.value?1:0)-(i.value?1:0));let t=`<table style='${cC}'>`;t+="<tbody>";for(const i of s){const n=typeof i.value=="boolean"?i.value?"✅":"❌":i.value;t+=`<tr><td style='${hC}'>${i.label}</td><td style='${dC}'>${n}</td></tr>`}return t+="</tbody></table>",t}function Uv(){try{if(document.createElement("canvas").getContext("webgl2"))return"✅"}catch{}return"❌"}function uC(){if(!globalThis.VConsole)return;const s=new VConsole.VConsolePlugin("device-utilities","📱 Device Info");return s.on("renderTab",function(e){let t=`<div style='${Fp}'>`;const i=xC();t+=`<h3 style='${c_}'>Device: ${i}</h3>`,t+=En([{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+=En(n,!1)),t+="</div>",t+=`<div style='${Fp} margin-top: 20px;'>`,t+=`<h3 style='${c_}'>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:Uv()}];t+=En(l,!1),t+="</div>",e(t)}),s}function fC(){if(!globalThis.VConsole)return;const s=new VConsole.VConsolePlugin("graphics-info","🎨 Graphics Info");return s.on("renderTab",async function(e){let t=`<div style='${Fp}'>`;const i=pC();i.length>0&&(t+=`<h3 style='${Io}'>General GPU Info</h3>`,t+=En(i,!1));const n=gC();n.length>0&&(t+=`<h3 style='${Io}'>WebGL</h3>`,t+=En(n,!1));const o=yC();o.length>0&&(t+=`<h3 style='${Io}'>WebGL 2 Features</h3>`,t+=En(o,!1));const r=_C();r.length>0&&(t+=`<h3 style='${Io}'>WebGL Limits</h3>`,t+=En(r,!1));const a=bC();a.length>0&&(t+=`<h3 style='${Io}'>Texture Formats</h3>`,t+=En(a,!1));const l=await vC();if(l.length>0&&(t+=`<h3 style='${Io}'>WebGPU</h3>`,t+=En(l,!1)),exports.DeviceUtilities.isSafari()){const h=wC();h.length>0&&(t+=`<h3 style='${Io}'>Safari GPU Info</h3>`,t+=En(h,!1))}t+="</div>",e(t)}),s}function pC(){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=zv();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=mC(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 mC(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 gC(){const s=[],e=zv();return e&&(s.push({label:"📊 WebGL Version",value:e.version}),s.push({label:"🎮 WebGL 2 Available",value:Uv()})),s}function yC(){const s=[];try{const t=document.createElement("canvas").getContext("webgl2");if(!t)return s;s.push({label:"Float Color Buffer",value:t.getExtension("EXT_color_buffer_float")?"✅":"❌"}),s.push({label:"Anisotropic Filtering",value:t.getExtension("EXT_texture_filter_anisotropic")?"✅":"❌"}),s.push({label:"Float Texture Linear",value:t.getExtension("OES_texture_float_linear")?"✅":"❌"}),s.push({label:"S3TC Compression",value:t.getExtension("WEBGL_compressed_texture_s3tc")?"✅":"❌"}),s.push({label:"ETC Compression",value:t.getExtension("WEBGL_compressed_texture_etc")?"✅":"❌"}),s.push({label:"PVRTC Compression",value:t.getExtension("WEBGL_compressed_texture_pvrtc")?"✅":"❌"}),s.push({label:"ASTC Compression",value:t.getExtension("WEBGL_compressed_texture_astc")?"✅":"❌"})}catch{}return s}function _C(){const s=[];try{const e=document.createElement("canvas"),t=e.getContext("webgl2")||e.getContext("webgl");if(!t)return s;const i=t instanceof WebGL2RenderingContext;s.push({label:"📏 Max Texture Size",value:t.getParameter(t.MAX_TEXTURE_SIZE).toString()}),s.push({label:"🎨 Max Renderbuffer Size",value:t.getParameter(t.MAX_RENDERBUFFER_SIZE).toString()}),s.push({label:"🔗 Max Vertex Attribs",value:t.getParameter(t.MAX_VERTEX_ATTRIBS).toString()}),s.push({label:"🎯 Max Texture Units",value:t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS).toString()}),i&&(s.push({label:"⚡ Max Samples",value:t.getParameter(t.MAX_SAMPLES).toString()}),s.push({label:"🔄 Max Uniform Buffer Bindings",value:t.getParameter(t.MAX_UNIFORM_BUFFER_BINDINGS).toString()}),s.push({label:"📐 Max 3D Texture Size",value:t.getParameter(t.MAX_3D_TEXTURE_SIZE).toString()}))}catch{}return s}function bC(){const s=[];try{document.createElement("canvas").getContext("webgl")&&(s.push({label:"WebGL 1 RGBA",value:"✅"}),s.push({label:"WebGL 1 RGB",value:"✅"}));const n=document.createElement("canvas").getContext("webgl2");n&&(s.push({label:"WebGL 2 RGBA32F",value:n.getExtension("EXT_color_buffer_float")?"✅":"❌"}),s.push({label:"WebGL 2 RGB32F",value:n.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 vC(){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 zv(){try{const s=document.createElement("canvas"),e=s.getContext("webgl2")||s.getContext("webgl");if(!e)return null;const t=e.getExtension("WEBGL_debug_renderer_info"),i=t?e.getParameter(t.UNMASKED_RENDERER_WEBGL):e.getParameter(e.RENDERER),n=t?e.getParameter(t.UNMASKED_VENDOR_WEBGL):e.getParameter(e.VENDOR),o=e.getParameter(e.VERSION);let r;if(i&&i.includes("ANGLE")){const a=i.match(/ANGLE \(([^)]+)\)/);a&&(r=a[1])}return{renderer:i,vendor:n,version:o,angle:r}}catch{return null}}function wC(){const s=[];try{const t=document.createElement("canvas").getContext("webgl");if(t){const i=t.getExtension("WEBGL_debug_renderer_info");if(i){const n=t.getParameter(i.UNMASKED_RENDERER_WEBGL);n&&n.includes("Apple")&&s.push({label:"🍎 Apple GPU",value:n})}}}catch{}try{const t=document.createElement("canvas").getContext("webgl");t&&(t.getSupportedExtensions()||[]).includes("WEBGL_compressed_texture_pvrtc")&&s.push({label:"🗜️ PVRTC Support",value:"✅"})}catch{}return s}function xC(){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 SC(){const s=document.querySelector("#__vconsole .vc-switch");return s||null}function CC(){const s=document.querySelector("#__vconsole");return s||null}const Ih=x("debugtypes");class PC{_types=new Map;_reverseTypes=new Map;_lazyLoaders=new Map;constructor(){Ih&&console.warn("TypeStore: Created",this)}add(e,t){Ih&&console.warn("ADD TYPE",e);const i=this._types.get(e);i?Ih&&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){Ih&&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}}const OC=Symbol("BuiltInType"),P=new PC,Hm=function(s){P.get(s.name)||P.add(s.name,s)};class MC{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)}}class Hn{static testIfRootCanAnimate(e,t){const i=e.getRoot();return i&&(i.userData.static||i.matrixAutoUpdate===!1||i.matrixWorldAutoUpdate===!1)?((t===!0||t===void 0&&A())&&console.warn(`AnimationUtils: The root object (${i.name||i.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:i.userData.static,name:i.userData.name,tag:i.userData.tag,matrixAutoUpdate:i.matrixAutoUpdate,matrixWorldAutoUpdate:i.matrixWorldAutoUpdate}),!1):!0}static tryGetActionsFromMixer(e){const t=e._actions;return t||null}static tryGetAnimationClipsFromObjectHierarchy(e,t){if(t||(t=new Array),e)e.animations&&t.push(...e.animations);else return t;if(e.children)for(const i of e.children)this.tryGetAnimationClipsFromObjectHierarchy(i,t);return t}static autoplayAnimations(e){if(!e||!e.animations)return console.debug("No animations found in file"),null;const t="scene"in e?e.scene:e,i=new Array;for(let o=0;o<e.animations.length;o++){const r=e.animations[o];if(!r.tracks||r.tracks.length<=0){console.warn("Animation has no tracks");continue}for(const a in r.tracks){const l=r.tracks[a],h=c.PropertyBinding.parseTrackName(l.name);let d=c.PropertyBinding.findNode(t,h.nodeName);if(!d){const p=l.__objectName??l.name.substring(0,l.name.indexOf("."));if(d=t.getObjectByProperty("uuid",p),!d)continue}let u=n(d)||n(t);if(!u){const p=P.get("Animation");if(u=t.addComponent(p),!u){console.error("Failed creating Animation component: No 'Animation' component found in TypeStore");break}}i.push(u),u.addClip&&u.addClip(r)}}return i;function n(o){if(!o)return null;const r=o.userData?.components;if(r&&r.length>0)for(let a=0;a<r.length;a++){const l=r[a];if(l.isAnimationComponent===!0)return l}return n(o.parent)}}static emptyClip(){return new c.AnimationClip("empty",0,[])}static createScaleClip(e){const t=e?.duration??.3;let i={x:1,y:1,z:1};e?.scale!==void 0&&(typeof e.scale=="number"?i={x:e.scale,y:e.scale,z:e.scale}:i=e.scale);const n=e?.type??"linear",o=e?.scaleFactor??1.2,r=new Array,a=new Array;switch(n){case"linear":r.push(0,t),a.push(i.x,i.y,i.z,i.x*o,i.y*o,i.z*o);break;case"spring":r.push(0,t*.3,t*.5,t*.7,t*.9,t),a.push(i.x,i.y,i.z,i.x*o,i.y*o,i.z*o,i.x*.9,i.y*.9,i.z*.9,i.x*1.05,i.y*1.05,i.z*1.05,i.x*.98,i.y*.98,i.z*.98,i.x,i.y,i.z);break}const l=new c.KeyframeTrack(".scale",r,a);return new c.AnimationClip("scale",r[r.length-1],[l])}}const Be=function(s){return f(s)},f=function(s){if(s===void 0&&(s=null),!Array.isArray(s))s=h_(s);else for(let e=0;e<s.length;e++){const t=s[e];s[e]=h_(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 h_(s){switch(s?.prototype?.constructor?.name){case"Number":case"String":case"Boolean":return null}return s}const d_=x("debugcomponentevents");class mu{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),d_&&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(d_&&console.log("Dispatching event "+e,i),!!i)for(const n of i)n(t)}}const Nv=x("debugdefines");go('if(!globalThis["NEEDLE_ENGINE_VERSION"]) globalThis["NEEDLE_ENGINE_VERSION"] = "0.0.0";');go('if(!globalThis["NEEDLE_ENGINE_GENERATOR"]) globalThis["NEEDLE_ENGINE_GENERATOR"] = "unknown";');go('if(!globalThis["NEEDLE_PROJECT_BUILD_TIME"]) globalThis["NEEDLE_PROJECT_BUILD_TIME"] = "unknown";');go('if(!globalThis["NEEDLE_PUBLIC_KEY"]) globalThis["NEEDLE_PUBLIC_KEY"] = "unknown";');go('globalThis["__NEEDLE_ENGINE_VERSION__"] = "4.17.0-alpha.7";');go('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";');go('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Thu Mar 26 2026 12:58:23 GMT+0000 (Coordinated Universal Time)";');go('globalThis["__NEEDLE_PUBLIC_KEY__"] = "'+NEEDLE_PUBLIC_KEY+'";');const ii="4.17.0-alpha.7",ka="undefined",_c="Thu Mar 26 2026 12:58:23 GMT+0000 (Coordinated Universal Time)";Nv&&console.log(`Engine version: ${ii} (generator: ${ka})
|
|
143
|
+
`,Lo?.prepend(i),s===!0&&_v()<=0&&Bv(),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.":"")),vl=!1,Zt=null},e.src="https://cdn.jsdelivr.net/npm/vconsole@3.15.1/dist/vconsole.min.js",document.body.appendChild(e)}function lC(){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"),Zt?.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 Fp="padding: 10px; font-family: monospace;",c_="margin-bottom: 10px;",Io="margin-bottom: 10px; margin-top: 15px;",cC="width: 100%; border-collapse: collapse; border: 1px solid rgba(0,0,0,0.1); table-layout: fixed;",Fv="border: 1px solid rgba(0,0,0,0.1); padding: 5px;",hC=Fv,dC=Fv+" word-break: break-all;";function En(s,e=!1){e&&s.sort((i,n)=>(n.value?1:0)-(i.value?1:0));let t=`<table style='${cC}'>`;t+="<tbody>";for(const i of s){const n=typeof i.value=="boolean"?i.value?"✅":"❌":i.value;t+=`<tr><td style='${hC}'>${i.label}</td><td style='${dC}'>${n}</td></tr>`}return t+="</tbody></table>",t}function Uv(){try{if(document.createElement("canvas").getContext("webgl2"))return"✅"}catch{}return"❌"}function uC(){if(!globalThis.VConsole)return;const s=new VConsole.VConsolePlugin("device-utilities","📱 Device Info");return s.on("renderTab",function(e){let t=`<div style='${Fp}'>`;const i=xC();t+=`<h3 style='${c_}'>Device: ${i}</h3>`,t+=En([{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+=En(n,!1)),t+="</div>",t+=`<div style='${Fp} margin-top: 20px;'>`,t+=`<h3 style='${c_}'>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:Uv()}];t+=En(l,!1),t+="</div>",e(t)}),s}function fC(){if(!globalThis.VConsole)return;const s=new VConsole.VConsolePlugin("graphics-info","🎨 Graphics Info");return s.on("renderTab",async function(e){let t=`<div style='${Fp}'>`;const i=pC();i.length>0&&(t+=`<h3 style='${Io}'>General GPU Info</h3>`,t+=En(i,!1));const n=gC();n.length>0&&(t+=`<h3 style='${Io}'>WebGL</h3>`,t+=En(n,!1));const o=yC();o.length>0&&(t+=`<h3 style='${Io}'>WebGL 2 Features</h3>`,t+=En(o,!1));const r=_C();r.length>0&&(t+=`<h3 style='${Io}'>WebGL Limits</h3>`,t+=En(r,!1));const a=bC();a.length>0&&(t+=`<h3 style='${Io}'>Texture Formats</h3>`,t+=En(a,!1));const l=await vC();if(l.length>0&&(t+=`<h3 style='${Io}'>WebGPU</h3>`,t+=En(l,!1)),exports.DeviceUtilities.isSafari()){const h=wC();h.length>0&&(t+=`<h3 style='${Io}'>Safari GPU Info</h3>`,t+=En(h,!1))}t+="</div>",e(t)}),s}function pC(){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=zv();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=mC(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 mC(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 gC(){const s=[],e=zv();return e&&(s.push({label:"📊 WebGL Version",value:e.version}),s.push({label:"🎮 WebGL 2 Available",value:Uv()})),s}function yC(){const s=[];try{const t=document.createElement("canvas").getContext("webgl2");if(!t)return s;s.push({label:"Float Color Buffer",value:t.getExtension("EXT_color_buffer_float")?"✅":"❌"}),s.push({label:"Anisotropic Filtering",value:t.getExtension("EXT_texture_filter_anisotropic")?"✅":"❌"}),s.push({label:"Float Texture Linear",value:t.getExtension("OES_texture_float_linear")?"✅":"❌"}),s.push({label:"S3TC Compression",value:t.getExtension("WEBGL_compressed_texture_s3tc")?"✅":"❌"}),s.push({label:"ETC Compression",value:t.getExtension("WEBGL_compressed_texture_etc")?"✅":"❌"}),s.push({label:"PVRTC Compression",value:t.getExtension("WEBGL_compressed_texture_pvrtc")?"✅":"❌"}),s.push({label:"ASTC Compression",value:t.getExtension("WEBGL_compressed_texture_astc")?"✅":"❌"})}catch{}return s}function _C(){const s=[];try{const e=document.createElement("canvas"),t=e.getContext("webgl2")||e.getContext("webgl");if(!t)return s;const i=t instanceof WebGL2RenderingContext;s.push({label:"📏 Max Texture Size",value:t.getParameter(t.MAX_TEXTURE_SIZE).toString()}),s.push({label:"🎨 Max Renderbuffer Size",value:t.getParameter(t.MAX_RENDERBUFFER_SIZE).toString()}),s.push({label:"🔗 Max Vertex Attribs",value:t.getParameter(t.MAX_VERTEX_ATTRIBS).toString()}),s.push({label:"🎯 Max Texture Units",value:t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS).toString()}),i&&(s.push({label:"⚡ Max Samples",value:t.getParameter(t.MAX_SAMPLES).toString()}),s.push({label:"🔄 Max Uniform Buffer Bindings",value:t.getParameter(t.MAX_UNIFORM_BUFFER_BINDINGS).toString()}),s.push({label:"📐 Max 3D Texture Size",value:t.getParameter(t.MAX_3D_TEXTURE_SIZE).toString()}))}catch{}return s}function bC(){const s=[];try{document.createElement("canvas").getContext("webgl")&&(s.push({label:"WebGL 1 RGBA",value:"✅"}),s.push({label:"WebGL 1 RGB",value:"✅"}));const n=document.createElement("canvas").getContext("webgl2");n&&(s.push({label:"WebGL 2 RGBA32F",value:n.getExtension("EXT_color_buffer_float")?"✅":"❌"}),s.push({label:"WebGL 2 RGB32F",value:n.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 vC(){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 zv(){try{const s=document.createElement("canvas"),e=s.getContext("webgl2")||s.getContext("webgl");if(!e)return null;const t=e.getExtension("WEBGL_debug_renderer_info"),i=t?e.getParameter(t.UNMASKED_RENDERER_WEBGL):e.getParameter(e.RENDERER),n=t?e.getParameter(t.UNMASKED_VENDOR_WEBGL):e.getParameter(e.VENDOR),o=e.getParameter(e.VERSION);let r;if(i&&i.includes("ANGLE")){const a=i.match(/ANGLE \(([^)]+)\)/);a&&(r=a[1])}return{renderer:i,vendor:n,version:o,angle:r}}catch{return null}}function wC(){const s=[];try{const t=document.createElement("canvas").getContext("webgl");if(t){const i=t.getExtension("WEBGL_debug_renderer_info");if(i){const n=t.getParameter(i.UNMASKED_RENDERER_WEBGL);n&&n.includes("Apple")&&s.push({label:"🍎 Apple GPU",value:n})}}}catch{}try{const t=document.createElement("canvas").getContext("webgl");t&&(t.getSupportedExtensions()||[]).includes("WEBGL_compressed_texture_pvrtc")&&s.push({label:"🗜️ PVRTC Support",value:"✅"})}catch{}return s}function xC(){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 SC(){const s=document.querySelector("#__vconsole .vc-switch");return s||null}function CC(){const s=document.querySelector("#__vconsole");return s||null}const Ih=x("debugtypes");class PC{_types=new Map;_reverseTypes=new Map;_lazyLoaders=new Map;constructor(){Ih&&console.warn("TypeStore: Created",this)}add(e,t){Ih&&console.warn("ADD TYPE",e);const i=this._types.get(e);i?Ih&&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){Ih&&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}}const OC=Symbol("BuiltInType"),P=new PC,Hm=function(s){P.get(s.name)||P.add(s.name,s)};class MC{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)}}class Hn{static testIfRootCanAnimate(e,t){const i=e.getRoot();return i&&(i.userData.static||i.matrixAutoUpdate===!1||i.matrixWorldAutoUpdate===!1)?((t===!0||t===void 0&&A())&&console.warn(`AnimationUtils: The root object (${i.name||i.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:i.userData.static,name:i.userData.name,tag:i.userData.tag,matrixAutoUpdate:i.matrixAutoUpdate,matrixWorldAutoUpdate:i.matrixWorldAutoUpdate}),!1):!0}static tryGetActionsFromMixer(e){const t=e._actions;return t||null}static tryGetAnimationClipsFromObjectHierarchy(e,t){if(t||(t=new Array),e)e.animations&&t.push(...e.animations);else return t;if(e.children)for(const i of e.children)this.tryGetAnimationClipsFromObjectHierarchy(i,t);return t}static autoplayAnimations(e){if(!e||!e.animations)return console.debug("No animations found in file"),null;const t="scene"in e?e.scene:e,i=new Array;for(let o=0;o<e.animations.length;o++){const r=e.animations[o];if(!r.tracks||r.tracks.length<=0){console.warn("Animation has no tracks");continue}for(const a in r.tracks){const l=r.tracks[a],h=c.PropertyBinding.parseTrackName(l.name);let d=c.PropertyBinding.findNode(t,h.nodeName);if(!d){const p=l.__objectName??l.name.substring(0,l.name.indexOf("."));if(d=t.getObjectByProperty("uuid",p),!d)continue}let u=n(d)||n(t);if(!u){const p=P.get("Animation");if(u=t.addComponent(p),!u){console.error("Failed creating Animation component: No 'Animation' component found in TypeStore");break}}i.push(u),u.addClip&&u.addClip(r)}}return i;function n(o){if(!o)return null;const r=o.userData?.components;if(r&&r.length>0)for(let a=0;a<r.length;a++){const l=r[a];if(l.isAnimationComponent===!0)return l}return n(o.parent)}}static emptyClip(){return new c.AnimationClip("empty",0,[])}static createScaleClip(e){const t=e?.duration??.3;let i={x:1,y:1,z:1};e?.scale!==void 0&&(typeof e.scale=="number"?i={x:e.scale,y:e.scale,z:e.scale}:i=e.scale);const n=e?.type??"linear",o=e?.scaleFactor??1.2,r=new Array,a=new Array;switch(n){case"linear":r.push(0,t),a.push(i.x,i.y,i.z,i.x*o,i.y*o,i.z*o);break;case"spring":r.push(0,t*.3,t*.5,t*.7,t*.9,t),a.push(i.x,i.y,i.z,i.x*o,i.y*o,i.z*o,i.x*.9,i.y*.9,i.z*.9,i.x*1.05,i.y*1.05,i.z*1.05,i.x*.98,i.y*.98,i.z*.98,i.x,i.y,i.z);break}const l=new c.KeyframeTrack(".scale",r,a);return new c.AnimationClip("scale",r[r.length-1],[l])}}const Be=function(s){return f(s)},f=function(s){if(s===void 0&&(s=null),!Array.isArray(s))s=h_(s);else for(let e=0;e<s.length;e++){const t=s[e];s[e]=h_(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 h_(s){switch(s?.prototype?.constructor?.name){case"Number":case"String":case"Boolean":return null}return s}const d_=x("debugcomponentevents");class mu{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),d_&&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(d_&&console.log("Dispatching event "+e,i),!!i)for(const n of i)n(t)}}const Nv=x("debugdefines");go('if(!globalThis["NEEDLE_ENGINE_VERSION"]) globalThis["NEEDLE_ENGINE_VERSION"] = "0.0.0";');go('if(!globalThis["NEEDLE_ENGINE_GENERATOR"]) globalThis["NEEDLE_ENGINE_GENERATOR"] = "unknown";');go('if(!globalThis["NEEDLE_PROJECT_BUILD_TIME"]) globalThis["NEEDLE_PROJECT_BUILD_TIME"] = "unknown";');go('if(!globalThis["NEEDLE_PUBLIC_KEY"]) globalThis["NEEDLE_PUBLIC_KEY"] = "unknown";');go('globalThis["__NEEDLE_ENGINE_VERSION__"] = "4.17.0-alpha.7";');go('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";');go('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Thu Mar 26 2026 15:21:24 GMT+0000 (Coordinated Universal Time)";');go('globalThis["__NEEDLE_PUBLIC_KEY__"] = "'+NEEDLE_PUBLIC_KEY+'";');const ii="4.17.0-alpha.7",ka="undefined",_c="Thu Mar 26 2026 15:21:24 GMT+0000 (Coordinated Universal Time)";Nv&&console.log(`Engine version: ${ii} (generator: ${ka})
|
|
144
144
|
Project built at ${_c}`);const no=NEEDLE_PUBLIC_KEY,jn="needle_isActiveInHierarchy",Ho="builtin_components",ec="needle_editor_guid";function go(s){try{(0,eval)(s)}catch(e){Nv&&console.error(e)}}const qm={experimentalSmartHierarchyUpdate:!1},pi=Symbol("shadowDomOwner"),kC=x("debugpatch");function gu(s,e,t,i){const n=kC===e;if(!t&&!i)return;const o=e+"___needle";RC(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]=f_(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]=f_(l,s,e);else{const h=this[o];Vv(s,e,this,h,l),this[o]=l,$v(s,e,this,h,l)}},get:function(){const l=this[o];return typeof l=="function"&&l[o]?l[o]:l}}))}function EC(s,e,t){const i=Xm(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 u_=Symbol("Needle:Patches:WrappedFunction");function f_(s,e,t){if(s[u_])return s;const i=function(...n){Vv(e,t,this,...n);const o=s.apply(this,n);return $v(e,t,this,o,...n),o};return i[u_]=!0,i}const gd="Needle:Patches";function Up(){return globalThis[gd]||(globalThis[gd]=new WeakMap),globalThis[gd]}function Xm(s,e){const t=Up().get(s);return t?t.get(e):null}function RC(s,e,t,i){let n=Up().get(s);n||(n=new Map,Up().set(s,n));let o=n.get(e);o||(o=[],n.set(e,o)),o.push({prefix:t,postfix:i})}function Vv(s,e,t,...i){if(!t)return;const n=Xm(s,e);if(n)for(const o of n)o.prefix?.call(t,...i)}function $v(s,e,t,i,...n){if(!t)return;const o=Xm(s,e);if(o)for(const r of o)r.postfix?.call(t,i,...n)}function TC(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 A()&&console.debug("Spector available: Add '?spector=<frame>' to the URL to enable it and capture a frame.")}}function Wv(s){const e=s;return!!(e.parser&&e.parser.json)}var yu=(s=>(s[s.None=0]="None",s[s.DontExport=1]="DontExport",s))(yu||{});const Gv=Symbol("component-name");function Qm(s){return s&&s.isComponent}const AC=Symbol("object"),Tf=new _i(()=>new c.Vector3,20);class Hv{_point;_normal;_tangentVelocity;distance;impulse;friction;get point(){return Tf.get().set(this._point.x,this._point.y,this._point.z)}get normal(){return Tf.get().set(this._normal.x,this._normal.y,this._normal.z)}get tangentVelocity(){return Tf.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 qv{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 Xv{object;collider;constructor(e,t){this.object=e,this.collider=t}}class $d{constructor(e){this.context=e,this.root.style.cssText=`
|
|
145
145
|
position: absolute;
|
|
146
146
|
width: 1px; height: 1px;
|
|
@@ -271,8 +271,8 @@ TEX `+i.texture_lod;if(Bf=="density"&&(_+=`
|
|
|
271
271
|
`+(y/n.lastScreenCoverage).toFixed(0)+` dens
|
|
272
272
|
`+(n.lastScreenCoverage*100).toFixed(1)+`% cov
|
|
273
273
|
`+(n.lastCentrality*100).toFixed(1)+`% centr
|
|
274
|
-
`+(Uh.min.x.toFixed(2)+"-"+Uh.max.x.toFixed(2)+"x"+Uh.min.y.toFixed(2)+"-"+Uh.max.y.toFixed(2))+" scr"),n.lastScreenCoverage>.1){const g=e,v=g.worldForward,b=g.worldPosition,R=F(v).multiplyScalar(h*.7).add(l),O=R.distanceTo(b),M=d[Math.min(d.length-1,Math.max(0,o))]+"88",D=this.context.domHeight>0?screen.height/this.context.domHeight:1,L=e.isPerspectiveCamera?Math.tan(e.fov*Math.PI/180/2):1;B.DrawLabel(R,_,O*.012*D*L,void 0,16777215,M)}}}}}const sg={};function og(s,e){sg[s]=e}function _0(s){const e=s.getBufferIdentifier(),t=sg[e];return t(s)}function b0(s){return typeof s.guid=="function"?s.guid():null}function wl(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 T={MaterialX:wl(()=>Promise.resolve().then(()=>require("./materialx-D0XUnhBY.umd.cjs"))),RAPIER_PHYSICS:wl(()=>Promise.resolve().then(()=>require("./rapier-DQltNJbN.umd.cjs"))),POSTPROCESSING:wl(()=>Promise.resolve().then(()=>require("./postprocessing-B2wb6pzI.umd.cjs")).then(s=>s.index)),POSTPROCESSING_AO:wl(()=>Promise.resolve().then(()=>require("./postprocessing-B2wb6pzI.umd.cjs")).then(s=>s.N8AO)),PEERJS:wl(()=>Promise.resolve().then(()=>require("./vendor-BLeytgEr.umd.cjs")).then(s=>s.bundler))};let rg;function g1(){return rg}function y1(s){rg=s}async function v0(s,e){const i=(await T.PEERJS.load()).default;return e||(e={}),e={...rg,...e},s?new i(s,e):new i(e)}async function M_(){const s=await T.PEERJS.load();return s.default===void 0?s:s.default}class w0{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 M_(),i=new t(e);i.on("error",n=>{console.error(n),this._host=void 0,this.trySetupClient(e)}),i.on("open",n=>{this._host=new b1(i)})}async trySetupClient(e){const t=await M_();this._client=new t,this._client.on("error",i=>{console.error("Client error",i)}),this._client.on("open",i=>{console.log("client connected",i),this._clientData=this._client.connect(e,{metadata:{id:i}}),this._clientData.on("open",()=>{console.log("Connected to host")}),this._clientData.on("data",n=>{console.log("<<",n)})})}}class _1{_peer;constructor(e){this._peer=e}}class b1 extends _1{get isHost(){return!0}_connections=[];constructor(e){super(e),console.log("I AM THE HOST"),this._peer?.on("connection",this.onConnection.bind(this)),this._peer.on("close",()=>{this.broadcast("BYE")}),setInterval(()=>{this.broadcast("HELLO")},2e3)}onConnection(e){console.log("host connection",e),e.on("open",()=>{this._connections.push(e),this.broadcastConnection(e)})}broadcastConnection(e){const t=this._connections.map(i=>i.metadata?.id).filter(i=>i!==void 0);this.broadcast({type:"connection-list",connections:t})}broadcast(e){if(e!=null){console.log(">>",e);for(const t in this._peer.connections){const i=this._peer.connections[t];if(i)if(Array.isArray(i))for(const n of i)n&&n.send(e);else console.warn(i)}}}}const k_="https://urls.needle.tools/default-networking-backend/index";let ki="wss://networking-2.needle.tools/socket";const Yt=!!x("debugnet"),Ul=!!(Yt||x("debugowner")),Nh=x("debugnetbin");var x0=(s=>(s.ConnectionInfo="connection-start-info",s))(x0||{}),K=(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))(K||{});class v1{room;viewId;allowEditing;inRoom}class w1{room}class x1{userId}var S0=(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))(S0||{});class ag{guid;connection;get hasOwnership(){return this._hasOwnership}get isOwned(){return this._isOwned}get isConnected(){return this.connection.isConnected}_hasOwnership=!1;_isOwned=void 0;_gainSubscription;_lostSubscription;_hasOwnerResponse;constructor(e,t){this.connection=e,this.guid=t,this._gainSubscription=this.onGainedOwnership.bind(this),this._lostSubscription=this.onLostOwnership.bind(this),e.beginListen("lost-ownership",this._lostSubscription),e.beginListen("gained-ownership-broadcast",this._gainSubscription),this._hasOwnerResponse=this.onHasOwnerResponse.bind(this),e.beginListen("response-has-owner",this._hasOwnerResponse)}_isWaitingForOwnershipResponseCallback=null;updateIsOwned(){this.connection.send("request-has-owner",{guid:this.guid})}onHasOwnerResponse(e){e.guid===this.guid&&(this._isOwned=e.value)}requestOwnershipIfNotOwned(){return this._isWaitingForOwnershipResponseCallback!==null?this:(this._isWaitingForOwnershipResponseCallback=this.waitForHasOwnershipRequestResponse.bind(this),this.connection.beginListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this.connection.send("request-has-owner",{guid:this.guid}),this)}waitForHasOwnershipRequestResponse(e){e.guid===this.guid&&(this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this._isOwned=e.value,e.value||(Ul&&console.log("request ownership",this.guid),this.requestOwnership()))}requestOwnershipAsync(){return new Promise((e,t)=>{this.requestOwnership();let i=0;const n=()=>{if(i++>10)return t("Timeout");setTimeout(()=>{this.hasOwnership?e(this):n()},100)};n()})}requestOwnership(){return Ul&&console.log("Request ownership",this.guid),this.connection.send("request-ownership",{guid:this.guid}),this}freeOwnership(){return this.connection.send("remove-ownership",{guid:this.guid}),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this}destroy(){this.connection.stopListen("gained-ownership",this._gainSubscription),this.connection.stopListen("lost-ownership",this._lostSubscription),this.connection.stopListen("response-has-owner",this._hasOwnerResponse),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null)}onGainedOwnership(e){e.guid===this.guid&&(this._isOwned=!0,this.connection.connectionId===e.owner?(Ul&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(Ul&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}}class C0{context;_peer=null;constructor(e){this.context=e}get peer(){return this._peer||(this._peer=new w0),this._peer}tryGetState(e){return e==="invalid"?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return Yt}get isConnected(){return this.connected}get currentRoomName(){return this._currentRoomName}get allowEditing(){return this._currentRoomAllowEditing}get currentRoomViewId(){return this._currentRoomViewId}getViewOnlyUrl(){if(this.currentRoomViewId===null)return null;const e=new URL(window.location.href);return e.searchParams.set("view",this.currentRoomViewId),e.href}get isInRoom(){return this._isInRoom}get currentLatency(){return this._currentDelay}get currentServerUrl(){return this._ws?.url??null}sendPing(){this.send("ping",{time:this.context.time.time})}userIsInRoom(e){return this._currentInRoom.indexOf(e)!==-1}_usersInRoomCopy=[];usersInRoom(e=null){e||(e=this._usersInRoomCopy),e.length=0;for(const t of this._currentInRoom)e.push(t);return e}joinRoom(e,t=!1){return e?e.length>1024?(console.error('Room name too long, can not join: "'+e+'". Max length is 1024 characters.'),!1):(this.isInRoom&&this.currentRoomName!==e&&console.warn("Needle Engine is already connected to a networking room. Connecting to multiple rooms is not supported"),this.connect(),Yt&&console.log("join: "+e),this.send("join-room",{room:e,viewOnly:t},ln.OnConnection),!0):(console.error('Missing room name, can not join: "'+e+'"'),!1)}leaveRoom(e=null){return e||(e=this.currentRoomName),e?(this.send("leave-room",{room:e}),!0):(console.error('Missing room name, can not join: "'+e+'"'),!1)}send(e,t=null,i=ln.Queued){if(t===null&&(t={}),i===ln.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){Nh&&console.log("<< send binary",this.context.time.frame,e.length/1024+" KB"),this._ws?.send(e)}_defaultMessagesBuffer=[];_defaultMessagesBufferArray=[];sendBufferedMessagesNow(){if(!this._ws)return;this._defaultMessagesBufferArray.length=0;const e=Object.keys(this._defaultMessagesBuffer).length;for(const i in this._defaultMessagesBuffer){const n=this._defaultMessagesBuffer[i];if(e<=1){this.sendWithWebsocket(n.key,n.value,ln.Immediate);break}const o=this.toMessage(n.key,n.value);this._defaultMessagesBufferArray.push(o)}if(this._defaultMessagesBuffer.length=0,this._defaultMessagesBufferArray.length>0&&Yt&&console.log("SEND BUFFERED",this._defaultMessagesBufferArray.length),this._defaultMessagesBufferArray.length<=0)return;const t=JSON.stringify(this._defaultMessagesBufferArray);this._ws?.send(t)}beginListen(e,t){return this._listeners[e]||(this._listeners[e]=[]),this._listeners[e].push(t),t}stopListening(e,t){return this.stopListen(e,t)}stopListen(e,t){if(!t||!this._listeners[e])return;const i=this._listeners[e].indexOf(t);i>=0&&this._listeners[e].splice(i,1)}beginListenBinary(e,t){return this._listenersBinary[e]||(this._listenersBinary[e]=[]),this._listenersBinary[e].push(t),t}stopListenBinary(e,t){if(!this._listenersBinary[e])return;const i=this._listenersBinary[e].indexOf(t);i>=0&&this._listenersBinary[e].splice(i,1)}netWebSocketUrlProvider;registerProvider(e){this.netWebSocketUrlProvider=e}async connect(e){if(this.connected&&e&&e!==ki)return Promise.reject("Can not connect to different server url. Please disconnect first.");if(this.connected)return Promise.resolve(!0);e&&console.debug("Connecting to user provided url "+e);const t=e||this.netWebSocketUrlProvider?.getWebsocketUrl();return t?ki=t:dv()&&(ki="wss://"+window.location.host+"/socket"),this.connectWebsocket()}disconnect(){this._ws?.close(),this._ws=void 0,ki=void 0,this._currentRoomAllowEditing=!0,this._currentRoomName=null,this._currentRoomViewId=null,this._isInRoom=!1,this._currentInRoom.length=0,this._state={},this._currentDelay=-1}_listeners={};_listenersBinary={};connected=!1;channelId;_connectionId=null;_ws;_waitingForSocket={};_isInRoom=!1;_currentRoomName=null;_currentRoomViewId=null;_currentRoomAllowEditing=!0;_currentInRoom=[];_state={};_currentDelay=-1;_connectingToWebsocketPromise=null;connectWebsocket(){return this._connectingToWebsocketPromise?this._connectingToWebsocketPromise:this._connectingToWebsocketPromise=new Promise(async(e,t)=>{let i=!1;const n=h=>{i||(i=!0,e(h))};if(ki===void 0&&(console.log("Fetch default backend url: "+k_),ki=await(await fetch(k_)).text()),ki===void 0){n(!1);return}console.debug(`Connecting to networking backend on
|
|
275
|
-
`+ki);const o=await Promise.resolve().then(()=>require("./vendor-
|
|
274
|
+
`+(Uh.min.x.toFixed(2)+"-"+Uh.max.x.toFixed(2)+"x"+Uh.min.y.toFixed(2)+"-"+Uh.max.y.toFixed(2))+" scr"),n.lastScreenCoverage>.1){const g=e,v=g.worldForward,b=g.worldPosition,R=F(v).multiplyScalar(h*.7).add(l),O=R.distanceTo(b),M=d[Math.min(d.length-1,Math.max(0,o))]+"88",D=this.context.domHeight>0?screen.height/this.context.domHeight:1,L=e.isPerspectiveCamera?Math.tan(e.fov*Math.PI/180/2):1;B.DrawLabel(R,_,O*.012*D*L,void 0,16777215,M)}}}}}const sg={};function og(s,e){sg[s]=e}function _0(s){const e=s.getBufferIdentifier(),t=sg[e];return t(s)}function b0(s){return typeof s.guid=="function"?s.guid():null}function wl(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 T={MaterialX:wl(()=>Promise.resolve().then(()=>require("./materialx-D0XUnhBY.umd.cjs"))),RAPIER_PHYSICS:wl(()=>Promise.resolve().then(()=>require("./rapier-DQltNJbN.umd.cjs"))),POSTPROCESSING:wl(()=>Promise.resolve().then(()=>require("./postprocessing-B2wb6pzI.umd.cjs")).then(s=>s.index)),POSTPROCESSING_AO:wl(()=>Promise.resolve().then(()=>require("./postprocessing-B2wb6pzI.umd.cjs")).then(s=>s.N8AO)),PEERJS:wl(()=>Promise.resolve().then(()=>require("./vendor-Csj7XHEr.umd.cjs")).then(s=>s.bundler))};let rg;function g1(){return rg}function y1(s){rg=s}async function v0(s,e){const i=(await T.PEERJS.load()).default;return e||(e={}),e={...rg,...e},s?new i(s,e):new i(e)}async function M_(){const s=await T.PEERJS.load();return s.default===void 0?s:s.default}class w0{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 M_(),i=new t(e);i.on("error",n=>{console.error(n),this._host=void 0,this.trySetupClient(e)}),i.on("open",n=>{this._host=new b1(i)})}async trySetupClient(e){const t=await M_();this._client=new t,this._client.on("error",i=>{console.error("Client error",i)}),this._client.on("open",i=>{console.log("client connected",i),this._clientData=this._client.connect(e,{metadata:{id:i}}),this._clientData.on("open",()=>{console.log("Connected to host")}),this._clientData.on("data",n=>{console.log("<<",n)})})}}class _1{_peer;constructor(e){this._peer=e}}class b1 extends _1{get isHost(){return!0}_connections=[];constructor(e){super(e),console.log("I AM THE HOST"),this._peer?.on("connection",this.onConnection.bind(this)),this._peer.on("close",()=>{this.broadcast("BYE")}),setInterval(()=>{this.broadcast("HELLO")},2e3)}onConnection(e){console.log("host connection",e),e.on("open",()=>{this._connections.push(e),this.broadcastConnection(e)})}broadcastConnection(e){const t=this._connections.map(i=>i.metadata?.id).filter(i=>i!==void 0);this.broadcast({type:"connection-list",connections:t})}broadcast(e){if(e!=null){console.log(">>",e);for(const t in this._peer.connections){const i=this._peer.connections[t];if(i)if(Array.isArray(i))for(const n of i)n&&n.send(e);else console.warn(i)}}}}const k_="https://urls.needle.tools/default-networking-backend/index";let ki="wss://networking-2.needle.tools/socket";const Yt=!!x("debugnet"),Ul=!!(Yt||x("debugowner")),Nh=x("debugnetbin");var x0=(s=>(s.ConnectionInfo="connection-start-info",s))(x0||{}),K=(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))(K||{});class v1{room;viewId;allowEditing;inRoom}class w1{room}class x1{userId}var S0=(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))(S0||{});class ag{guid;connection;get hasOwnership(){return this._hasOwnership}get isOwned(){return this._isOwned}get isConnected(){return this.connection.isConnected}_hasOwnership=!1;_isOwned=void 0;_gainSubscription;_lostSubscription;_hasOwnerResponse;constructor(e,t){this.connection=e,this.guid=t,this._gainSubscription=this.onGainedOwnership.bind(this),this._lostSubscription=this.onLostOwnership.bind(this),e.beginListen("lost-ownership",this._lostSubscription),e.beginListen("gained-ownership-broadcast",this._gainSubscription),this._hasOwnerResponse=this.onHasOwnerResponse.bind(this),e.beginListen("response-has-owner",this._hasOwnerResponse)}_isWaitingForOwnershipResponseCallback=null;updateIsOwned(){this.connection.send("request-has-owner",{guid:this.guid})}onHasOwnerResponse(e){e.guid===this.guid&&(this._isOwned=e.value)}requestOwnershipIfNotOwned(){return this._isWaitingForOwnershipResponseCallback!==null?this:(this._isWaitingForOwnershipResponseCallback=this.waitForHasOwnershipRequestResponse.bind(this),this.connection.beginListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this.connection.send("request-has-owner",{guid:this.guid}),this)}waitForHasOwnershipRequestResponse(e){e.guid===this.guid&&(this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this._isOwned=e.value,e.value||(Ul&&console.log("request ownership",this.guid),this.requestOwnership()))}requestOwnershipAsync(){return new Promise((e,t)=>{this.requestOwnership();let i=0;const n=()=>{if(i++>10)return t("Timeout");setTimeout(()=>{this.hasOwnership?e(this):n()},100)};n()})}requestOwnership(){return Ul&&console.log("Request ownership",this.guid),this.connection.send("request-ownership",{guid:this.guid}),this}freeOwnership(){return this.connection.send("remove-ownership",{guid:this.guid}),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this}destroy(){this.connection.stopListen("gained-ownership",this._gainSubscription),this.connection.stopListen("lost-ownership",this._lostSubscription),this.connection.stopListen("response-has-owner",this._hasOwnerResponse),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null)}onGainedOwnership(e){e.guid===this.guid&&(this._isOwned=!0,this.connection.connectionId===e.owner?(Ul&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(Ul&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}}class C0{context;_peer=null;constructor(e){this.context=e}get peer(){return this._peer||(this._peer=new w0),this._peer}tryGetState(e){return e==="invalid"?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return Yt}get isConnected(){return this.connected}get currentRoomName(){return this._currentRoomName}get allowEditing(){return this._currentRoomAllowEditing}get currentRoomViewId(){return this._currentRoomViewId}getViewOnlyUrl(){if(this.currentRoomViewId===null)return null;const e=new URL(window.location.href);return e.searchParams.set("view",this.currentRoomViewId),e.href}get isInRoom(){return this._isInRoom}get currentLatency(){return this._currentDelay}get currentServerUrl(){return this._ws?.url??null}sendPing(){this.send("ping",{time:this.context.time.time})}userIsInRoom(e){return this._currentInRoom.indexOf(e)!==-1}_usersInRoomCopy=[];usersInRoom(e=null){e||(e=this._usersInRoomCopy),e.length=0;for(const t of this._currentInRoom)e.push(t);return e}joinRoom(e,t=!1){return e?e.length>1024?(console.error('Room name too long, can not join: "'+e+'". Max length is 1024 characters.'),!1):(this.isInRoom&&this.currentRoomName!==e&&console.warn("Needle Engine is already connected to a networking room. Connecting to multiple rooms is not supported"),this.connect(),Yt&&console.log("join: "+e),this.send("join-room",{room:e,viewOnly:t},ln.OnConnection),!0):(console.error('Missing room name, can not join: "'+e+'"'),!1)}leaveRoom(e=null){return e||(e=this.currentRoomName),e?(this.send("leave-room",{room:e}),!0):(console.error('Missing room name, can not join: "'+e+'"'),!1)}send(e,t=null,i=ln.Queued){if(t===null&&(t={}),i===ln.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){Nh&&console.log("<< send binary",this.context.time.frame,e.length/1024+" KB"),this._ws?.send(e)}_defaultMessagesBuffer=[];_defaultMessagesBufferArray=[];sendBufferedMessagesNow(){if(!this._ws)return;this._defaultMessagesBufferArray.length=0;const e=Object.keys(this._defaultMessagesBuffer).length;for(const i in this._defaultMessagesBuffer){const n=this._defaultMessagesBuffer[i];if(e<=1){this.sendWithWebsocket(n.key,n.value,ln.Immediate);break}const o=this.toMessage(n.key,n.value);this._defaultMessagesBufferArray.push(o)}if(this._defaultMessagesBuffer.length=0,this._defaultMessagesBufferArray.length>0&&Yt&&console.log("SEND BUFFERED",this._defaultMessagesBufferArray.length),this._defaultMessagesBufferArray.length<=0)return;const t=JSON.stringify(this._defaultMessagesBufferArray);this._ws?.send(t)}beginListen(e,t){return this._listeners[e]||(this._listeners[e]=[]),this._listeners[e].push(t),t}stopListening(e,t){return this.stopListen(e,t)}stopListen(e,t){if(!t||!this._listeners[e])return;const i=this._listeners[e].indexOf(t);i>=0&&this._listeners[e].splice(i,1)}beginListenBinary(e,t){return this._listenersBinary[e]||(this._listenersBinary[e]=[]),this._listenersBinary[e].push(t),t}stopListenBinary(e,t){if(!this._listenersBinary[e])return;const i=this._listenersBinary[e].indexOf(t);i>=0&&this._listenersBinary[e].splice(i,1)}netWebSocketUrlProvider;registerProvider(e){this.netWebSocketUrlProvider=e}async connect(e){if(this.connected&&e&&e!==ki)return Promise.reject("Can not connect to different server url. Please disconnect first.");if(this.connected)return Promise.resolve(!0);e&&console.debug("Connecting to user provided url "+e);const t=e||this.netWebSocketUrlProvider?.getWebsocketUrl();return t?ki=t:dv()&&(ki="wss://"+window.location.host+"/socket"),this.connectWebsocket()}disconnect(){this._ws?.close(),this._ws=void 0,ki=void 0,this._currentRoomAllowEditing=!0,this._currentRoomName=null,this._currentRoomViewId=null,this._isInRoom=!1,this._currentInRoom.length=0,this._state={},this._currentDelay=-1}_listeners={};_listenersBinary={};connected=!1;channelId;_connectionId=null;_ws;_waitingForSocket={};_isInRoom=!1;_currentRoomName=null;_currentRoomViewId=null;_currentRoomAllowEditing=!0;_currentInRoom=[];_state={};_currentDelay=-1;_connectingToWebsocketPromise=null;connectWebsocket(){return this._connectingToWebsocketPromise?this._connectingToWebsocketPromise:this._connectingToWebsocketPromise=new Promise(async(e,t)=>{let i=!1;const n=h=>{i||(i=!0,e(h))};if(ki===void 0&&(console.log("Fetch default backend url: "+k_),ki=await(await fetch(k_)).text()),ki===void 0){n(!1);return}console.debug(`Connecting to networking backend on
|
|
275
|
+
`+ki);const o=await Promise.resolve().then(()=>require("./vendor-Csj7XHEr.umd.cjs")).then(h=>h.index),r=o.default?.WebsocketBuilder??o.WebsocketBuilder,a=o.default?.ExponentialBackoff??o.ExponentialBackoff,l=new r(ki).withMaxRetries(10).withBackoff(new a(2e3,4)).onOpen(()=>{this._connectingToWebsocketPromise=null,this._ws=l,this.connected=!0,A()||Yt?console.log(`Connected to networking backend
|
|
276
276
|
`+ki):console.debug("Connected to networking backend",ki),n(!0),this.onSendQueued(ln.OnConnection)}).onClose(h=>{this._connectingToWebsocketPromise=null,this.connected=!1,this._isInRoom=!1,n(!1);let d="Websocket connection closed...";ki?.includes("/socket")||(d+=' Do you perhaps mean to connect to "/socket"?'),console.error(d)}).onError(h=>{console.error("Websocket connection failed..."),n(!1),ni.sendEvent(this.context,"networking",{event:"connection_error"})}).onRetry(()=>{console.log("Retry connecting to networking websocket")}).build();l.addEventListener(o.WebsocketEvent.message,(h,d)=>{this.onMessage(h,d)})})}onMessage(e,t){const i=t.data;try{if(typeof i!="string"){i.size&&this.handleIncomingBinaryMessage(i);return}const n=JSON.parse(i);if(Array.isArray(n))for(const o of n)this.handleIncomingStringMessage(o);else this.handleIncomingStringMessage(n);return}catch(n){Yt&&i==="pong"?console.log("<<",i):A()&&console.error("Failed to parse message",n)}}async handleIncomingBinaryMessage(e){Nh&&console.log("<< bin",this.context.time.frame);const t=await e.arrayBuffer();var i=new Uint8Array(t);const n=new ce.ByteBuffer(i),o=n.getBufferIdentifier(),r=this._listenersBinary[o],a=_0(n),l=b0(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(Yt&&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,ni.sendEvent(this.context,"networking",{event:"connected"}))}else console.warn("Expected connection id in "+e.key);break;case"joined-room":if(Yt&&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),(Nh||A())&&console.debug("Joined Needle Engine Room: "+r.room);const a=new URL(window.location.href);a.searchParams.has("room")&&a.searchParams.delete("room"),a.searchParams.set("view",this._currentRoomViewId),console.debug(`Room view id: ${this._currentRoomViewId}
|
|
277
277
|
${a.href}`)}this.onSendQueued(ln.OnRoomJoin),ni.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,(Nh||A())&&console.debug("Left Needle Engine Room: "+n.room)),ni.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),Yt&&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&&(Yt&&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":Yt&&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),Yt&&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=ln.OnRoomJoin){if(!this._ws){const o=this._waitingForSocket[i]||[];o.push(()=>this.sendWithWebsocket(e,t,i)),this._waitingForSocket[i]=o;return}const n=JSON.stringify(this.toMessage(e,t));Yt&&console.log(">>",e),this._ws.send(n)}onSendQueued(e){const t=this._waitingForSocket[e];if(t){for(const i of t)i();t.length=0}}}const S1=x("debugplayerview");var gs=(s=>(s.Browser="browser",s.Headset="headset",s.Handheld="handheld",s))(gs||{});class P0{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 O0{context;playerViews=new Map;constructor(e){this.context=e}setPlayerView(e,t,i){let n=this.playerViews.get(e);n||(n=new P0(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&&(S1&&console.log("REMOVE",e),i.removed=!0,this.playerViews.delete(e))}}const Hc=new Uint8Array(4);Hc[0]=255;Hc[1]=255;Hc[2]=255;Hc[3]=255;const C1=new c.DataTexture(Hc,1,1,c.RGBAFormat);function lg(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 P1(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 p=0;p<n;p++){const m=Math.floor(p/n*l),y=I.clamp(m+1,0,l-1),_=a[m],g=a[y],v=p/n*l%1;d.lerpColors(_,g,v);const b=Math.floor(d.r*255),w=Math.floor(d.g*255),R=Math.floor(d.b*255);for(let O=0;O<i;O++){const M=(p*i+O)*4;h[M+0]=b,h[M+1]=w,h[M+2]=R,h[M+3]=255}}const u=new c.DataTexture(h,i,n);return u.needsUpdate=!0,u}function Xd(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 Ff=[],E_=[];function O1(s,e){if(Ff.length===0)for(let t=0;t<27;t++)Ff.push(0);e||(e=Ff);for(let t=0;t<27;t++)E_[t]=e[t];e=E_,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 M1{vertexShader;fragmentShader;technique;constructor(e,t,i){this.vertexShader=e,this.fragmentShader=t,this.technique=i}}async function k1(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 R_(o),!r.code&&r.uri&&await R_(r),!o.code||!r.code)return null;const a=s.techniques[e];return new M1(o.code,r.code,a)}}return console.error("Shader technique not found",e),null}async function R_(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=E1(s.uri)}function E1(s){return decodeURIComponent(Array.prototype.map.call(atob(s),function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)}).join(""))}const tn=x("debugenvlight");var ba=(s=>(s[s.Skybox=0]="Skybox",s[s.Trilight=1]="Trilight",s[s.Flat=3]="Flat",s[s.Custom=4]="Custom",s))(ba||{}),Qd=(s=>(s[s.Skybox=0]="Skybox",s[s.Custom=1]="Custom",s))(Qd||{});class M0{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 Z&&(e=e.url);const t=this._sceneLightSettings?.get(e);return t?(tn&&console.log("Enable scene light settings",e,t),e!==this._currentLightSettingsId&&this._currentLightSettingsId&&this.disable(this._currentLightSettingsId),this._currentLightSettingsId=e,t.enabled=!0,!0):(tn&&console.warn("No light settings found for",e),!1)}disable(e){if(e instanceof Z&&(e=e.url),e==null)return!1;const t=this._sceneLightSettings?.get(e);return t?(tn&&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}tn&&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}tn&&console.log("Unregister "+e?.sourceId+" lighting",e),this._sceneLightSettings&&this._sceneLightSettings.delete(t)}internalRegisterReflection(e,t){tn&&console.log("Register reflection",e,t);const i=new k0(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(tn&&console.log("Enable reflection",e,t?ba[t.ambientMode]:"Unknown ambient mode",t),t?.ambientMode){case 0:case 4:const i=this.internalGetReflection(e);if(i&&i.Source){tn&&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 tn&&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=P1(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=lg(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){tn&&console.log("Not disabling reflection for",e,"because it is not the current light settings id",this.__currentReflectionId);return}tn&&console.log("Disable reflection",e);const t=this.context.scene;t.environment=null}_lighting={}}class k0{get Source(){return this._source}_source;constructor(e,t,i=1){this._source=t,t.mapping!==c.CubeUVReflectionMapping&&(t.mapping=c.EquirectangularReflectionMapping)}}const T_=x("timescale");let Xp=1;typeof T_=="number"&&(Xp=T_);class E0{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.clock.elapsedTime}get fps(){return 1/this.deltaTime}get smoothedFps(){return this._smoothedFps}get smoothedDeltaTime(){return 1/this._smoothedFps}clock=new c.Clock;_smoothedFps=0;_smoothedDeltaTime=0;_fpsSamples=[];_fpsSampleIndex=0;constructor(){typeof Xp=="number"&&(this.timeScale=Xp)}update(){this.deltaTime=this.clock.getDelta(),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 e=0;for(let t=0;t<this._fpsSamples.length;t++)e+=this._fpsSamples[t];this._smoothedDeltaTime=e/this._fpsSamples.length,this._smoothedFps=1/this._smoothedDeltaTime}}let A_=!1;function R0(s){A_||(A_=!0,R1(),T1())}function R1(){const s=`
|
|
278
278
|
float startCompression = 0.8;
|
|
@@ -876,7 +876,7 @@ Pinch: ${this.getGesture("pinch")?.value.toFixed(3)}`),n+=`
|
|
|
876
876
|
Layout: `;for(const o of Object.keys(this._layout.components||{})){const r=this.getStick(o),a=this._layout.components[o]?.gamepadIndices,l=a?Object.entries(a).map(h=>h[0][0].toUpperCase()+h[0].slice(1)+"="+h[1]).join(","):"";n+=`
|
|
877
877
|
${o}: ${this._layout.components[o]?.type} [${l}] (${r.x.toPrecision(2)},${r.y.toPrecision(2)})`}}B.DrawLabel(t,n,.006)}onUpdateFrame(e){if(this._handJointPoses.clear(),this._hand_wristDotUp=void 0,!this.xr.referenceSpace||!this.inputSource.gamepad?.connected){this._isTracking=!1;return}const t=e.getPose(this.inputSource.targetRaySpace,this.xr.referenceSpace);this._isTracking=t!=null;let i=null,n=null,o=null,r=null;if(t){const d=t.transform;this._rayMatrix.fromArray(d.matrix).premultiply(va),this._rayMatrix.decompose(this._rayPosition,this._rayQuaternion,F(1,1,1)),o=F(d.position),r=ei(d.orientation),this._rayPositionRaw.copy(o),this._rayRotationRaw.copy(r)}if(this.inputSource.gripSpace){const d=e.getPose(this.inputSource.gripSpace,this.xr.referenceSpace);if(d){const u=d.transform;if(i=F(u.position),n=ei(u.orientation),this._gripMatrix.fromArray(u.matrix).premultiply(va),this._gripMatrix.decompose(this._gripPosition,this._gripQuaternion,F(1,1,1)),"linearVelocity"in d&&d.linearVelocity){const p=d.linearVelocity;this._linearVelocity.set(p.x,p.y,p.z)}}}this.xr.context.mainCamera?.parent&&(this._object.parent!==this.xr.context.mainCamera?.parent&&this.xr.context.mainCamera.parent.add(this._object),this._gripSpaceObject!==void 0&&this._gripSpaceObject?.parent!==this.xr.context.mainCamera?.parent&&this.xr.context.mainCamera.parent.add(this._gripSpaceObject),this._raySpaceObject!==void 0&&this._raySpaceObject?.parent!==this.xr.context.mainCamera?.parent&&this.xr.context.mainCamera.parent.add(this._raySpaceObject));const a=this.hand;if(a){let d=!1;const u=a.get("wrist"),p=u&&this.getHandJointPose(u,e);if(p){d=!0;const _=p.transform.position,g=p.transform.orientation;this._object.position.set(_.x,_.y,_.z),this._object.quaternion.set(g.x,g.y,g.z,g.w).multiply(Li)}d||(this._object.position.copy(this._rayPosition),this._object.quaternion.copy(this._rayQuaternion).multiply(Li));const m=a.get("middle-finger-metacarpal"),y=m&&this.getHandJointPose(m,e);y&&(this._gripMatrix.fromArray(y.transform.matrix).premultiply(va),this._gripMatrix.decompose(this._gripPosition,this._gripQuaternion,F(1,1,1)),i=F().copy(y.transform.position),n=ei().copy(y.transform.orientation),n.multiply(tP),i.add(F(iP).applyQuaternion(n)))}else this.inputSource.gripSpace&&this.targetRayMode==="transient-pointer"&&i&&n?(this._object.position.copy(i),this._object.quaternion.copy(n).multiply(Li)):o&&r&&(this._object.position.copy(o),this._object.quaternion.copy(r).multiply(Li));Jn&&(o&&r&&(this._raySpaceObject?.position.copy(o),this._raySpaceObject?.quaternion.copy(r).multiply(Li)),i&&n&&(this._gripSpaceObject?.position.copy(i),this._gripSpaceObject?.quaternion.copy(n).multiply(Li)));const l=this.xr.context.mainCamera?.parent,h=l?pe(l):void 0;i&&n&&(this._gripWorldPosition.copy(i),l&&this._gripWorldPosition.applyMatrix4(l.matrixWorld),this._gripWorldQuaternion.copy(n),this._gripWorldQuaternion.multiply(Li),h&&this._gripWorldQuaternion.premultiply(h)),this.updateRayWorldPosition(),this.updateRayWorldQuaternion()}onDisconnected(){this._connected=!1,Jn&&console.warn("Controller disconnected",this.index);for(const e of this._object.children)this.xr.context.scene.attach(e);this._object?.removeFromParent(),this._debugAxesHelper?.removeFromParent(),this._debugGripAxesHelper?.removeFromParent(),this._debugRayAxesHelper?.removeFromParent(),this._gripSpaceObject?.removeFromParent(),this._raySpaceObject?.removeFromParent(),this.unsubscribeEvents(),this._hitTestSource&&(this._hitTestSource.cancel(),this._hitTestSource=void 0)}getButton(e){if(!this._layout)return;switch(e){case"primary-button":if(this.isLeft)e="x-button";else if(this.isRight)e="a-button";else return;break;case"primary":return this.hand?this.getGesture("pinch"):this.toNeedleGamepadButton(0,e);case"xr-standard-trigger":if(this.inputSource.gamepad)return this.toNeedleGamepadButton(0,e);break;case"xr-standard-squeeze":if(this.inputSource.gamepad)return this.toNeedleGamepadButton(1,e);break;case"xr-standard-thumbstick":if(this.inputSource.gamepad)return this.toNeedleGamepadButton(3,e);break}if(this._buttonMap.has(e))return this.toNeedleGamepadButton(this._buttonMap.get(e),e);const t=this._layout?.components[e];if(t?.gamepadIndices)switch(t.type){case"button":case"squeeze":if(this.inputSource.gamepad){const i=t.gamepadIndices.button;return this._buttonMap.set(e,i),this.toNeedleGamepadButton(i,e)}break;default:console.warn("Unsupported component type",t.type);break}this._buttonMap.set(e,void 0)}getGesture(e){const t=this.states[e];if(!t)return null;this.states[e]=t;const i=this._needleGamepadButtons[e]||new B_(void 0,e);return i.pressed=t.pressed,i.value=t.value,i.isDown=t.isDown,i.isUp=t.isUp,this._needleGamepadButtons[e]=i,i}getPointerId(e){if((e==="primary"||e==="pinch")&&(e=0),typeof e!="number"){const t=this._buttonMap.get(e);if(t===void 0)return;e=t}return this.index*10+e}_needleGamepadButtons={};toNeedleGamepadButton(e,t){if(!this.inputSource.gamepad?.buttons)return;const i=this.inputSource.gamepad?.buttons[e],n=this.states[e],o=this._needleGamepadButtons[e]||new B_(e,t);return i&&(o.pressed=i.pressed,o.value=i.value,o.touched=i.touched),n&&(o.isDown=n.isDown,o.isUp=n.isUp),this._needleGamepadButtons[e]=o,o}getStick(e){if(!this._layout)return{x:0,y:0,z:0};if(this.isHand)return{x:0,y:0,z:0};e==="primary"&&this._layout.components["xr-standard-thumbstick"]&&(e="xr-standard-thumbstick");const t=this._layout?.components[e];if(t?.gamepadIndices)switch(t.type){case"thumbstick":case"touchpad":if(this.inputSource.gamepad){const i=t.gamepadIndices.xAxis,n=t.gamepadIndices.yAxis;let o=this.inputSource.gamepad.axes[i]||0,r=this.inputSource.gamepad.axes[n]||0;o*=-1,r*=-1;const a=t.gamepadIndices.button,l=this.inputSource.gamepad?.buttons[a]?.value||0;return{x:o,y:r,z:l}}}return{x:0,y:0,z:0}}_buttonMap=new Map;_motioncontroller;_layout;getMotionController;initialize(){if(this._hasSelectEvent=this.profiles.includes("generic-hand-select")||this.profiles.some(e=>e.startsWith("generic-trigger")),this._isMetaQuestTouchController=this.profiles.includes("meta-quest-touch-plus")||this.profiles.includes("oculus-touch-v3"),this._isMxInk=this.profiles.includes("logitech-mx-ink"),!this._layout){if(this.inputSource.targetRayMode==="transient-pointer")return;const e=ce.fetchProfile(this.inputSource,J1,eP);this.getMotionController=e.then(t=>{if(!this.connected)return null;this._motioncontroller=new ce.MotionController(this.inputSource,t.profile,t.assetPath||"");const n=t.profile.layouts[this.inputSource.handedness];if(this._layout=n,this._layout){if(!this._layout.gamepad?.length){this._layout.gamepad=[];for(const o in this._layout.components){const r=this._layout.components[o];this._layout.gamepad[r.gamepadIndices.button]=o}}this.profiles.length>=1&&this.profiles[0]==="htc-vive-focus-plus"&&this.inputSource.gamepad&&this.inputSource.gamepad.axes.length===4&&!this._layout.components["xr-standard-thumbstick"]&&(this._layout.components["xr-standard-thumbstick"]={type:"thumbstick",gamepadIndices:{xAxis:2,yAxis:3}})}return this._motioncontroller}).catch(t=>(this.inputSource&&console.warn("Couldn't initialize motion controller profile for ",this.inputSource,t),null))}}emitPointerDownEvent=!0;emitPointerUpEvent=!0;emitPointerMoveEvent=!0;pointerMoveDistanceThreshold=.03;pointerMoveAngleThreshold=.05;subscribeEvents(){this.xr.session.addEventListener("selectstart",this.onSelectStart),this.xr.session.addEventListener("selectend",this.onSelectEnd),this.xr.session.addEventListener("squeezestart",this.onSequeezeStart),this.xr.session.addEventListener("squeezeend",this.onSequeezeEnd)}unsubscribeEvents(){this.xr.session.removeEventListener("selectstart",this.onSelectStart),this.xr.session.removeEventListener("selectend",this.onSelectEnd),this.xr.session.removeEventListener("squeezestart",this.onSequeezeStart),this.xr.session.removeEventListener("squeezeend",this.onSequeezeEnd)}_selectButtonIndex=void 0;_squeezeButtonIndex=void 0;onSelectStart=e=>{if(!this.emitPointerDownEvent||this.inputSource!==e.inputSource)return;this.onUpdateFrame(e.frame),this._hasSelectEvent=!0;const t=this._layout?.selectComponentId,i=this._layout?.components[t]?.gamepadIndices?.button;i!==void 0&&(this._selectButtonIndex=i),!$h&&(Jn&&B.DrawDirection(this.rayWorldPosition,F(0,.01,1).applyQuaternion(this.rayWorldQuaternion),16711680,10),this.emitPointerEvent(Pe.PointerDown,this._selectButtonIndex||0,"xr-standard-trigger",!0,e))};onSelectEnd=e=>{this.emitPointerUpEvent&&($h||this.inputSource===e.inputSource&&this.emitPointerEvent(Pe.PointerUp,this._selectButtonIndex||0,"xr-standard-trigger",!0,e))};onSequeezeStart=e=>{this.emitPointerDownEvent&&this.inputSource===e.inputSource&&(this._squeezeButtonIndex=this._layout?.components["xr-standard-squeeze"]?.gamepadIndices?.button,this._squeezeButtonIndex!==void 0&&(Jn&&B.DrawDirection(this.rayWorldPosition,F(0,.01,1).applyQuaternion(this.rayWorldQuaternion),255,10),this.emitPointerEvent(Pe.PointerDown,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,e)))};onSequeezeEnd=e=>{this.emitPointerUpEvent&&this.inputSource===e.inputSource&&this._squeezeButtonIndex!==void 0&&this.emitPointerEvent(Pe.PointerUp,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,e)};states={};updateInputEvents(){if(this.gamepad?.buttons){for(let e=0;e<this.gamepad.buttons.length;e++){const t=this.gamepad.buttons[e],i=this.states[e]||new j_;let n=null;this._isMxInk&&(e===4||e===5)?(t.value>0&&!i.pressed?(n="pointerdown",i.isDown=!0,i.isUp=!1):t.value===0&&i.pressed?(n="pointerup",i.isDown=!1,i.isUp=!0):i.pressed&&(n="pointermove",i.isDown=!1,i.isUp=!1),i.pressed=t.value>0,i.value=t.value):(t.pressed&&!i.pressed?(n="pointerdown",i.isDown=!0,i.isUp=!1):!t.pressed&&i.pressed?(n="pointerup",i.isDown=!1,i.isUp=!0):(i.isDown=!1,i.isUp=!1),i.pressed=t.pressed,i.value=t.value),this.states[e]=i;const o=e!==this._selectButtonIndex&&e!==this._squeezeButtonIndex;if(n!=null&&o){let r=this._layout?.gamepad[e];this._isMxInk&&e===4&&(r="stylus-touch"),this._isMxInk&&e===5&&(r="stylus-tip"),(Jn||$h)&&console.log("Emitting pointer event",n,e,r,t.value,this.gamepad,this._layout),this.emitPointerEvent(n,e,r??"none",!1,null,t.value)}}if(this._isMetaQuestTouchController){const e=this.gamepad.buttons.length-1,t=this.states[e];if(t&&t.isDown){const i=this.context.menu;i.spatialMenuIsVisible?i.setSpatialMenuVisible(!1):this.context.menu.setSpatialMenuVisible(!0)}}}if(this.hand){const e=this.handObject;if(e){const t=e.joints["index-finger-tip"],i=e.joints["thumb-tip"];if(t&&i){const n=t.position.distanceTo(i.position);this._pinchPosition.lerpVectors(t.position,i.position,.5);const o=this.xr.context.mainCamera?.parent;if(o&&this._pinchPosition.applyMatrix4(o.matrixWorld),n!==0){const l=this.states.pinch||new j_,h=(.02+.01)*1.5;l.value=1-(n-.02)/h;const d=n<.02-.01,u=n>.02+.01;d&&!l.pressed?($h&&console.log("pinch start",n),l.isDown=!0,l.isUp=!1,l.pressed=!0):u&&l.pressed?(l.isDown=!1,l.isUp=!0,l.pressed=!1):(l.isDown=!1,l.isUp=!1),this.states.pinch=l}}}}}_didMoveLastFrame=!1;_lastPointerMovePosition=new c.Vector3;_lastPointerMoveQuaternion=new c.Quaternion;onUpdateMove(){if(!this.emitPointerMoveEvent)return;let e=!1;if(this._lastPointerMovePosition.distanceTo(this.gripWorldPosition)>this.pointerMoveDistanceThreshold*this.xr.rigScale&&(e=!0),e||this._lastPointerMoveQuaternion.angleTo(this.gripWorldQuaternion)>this.pointerMoveAngleThreshold&&(e=!0),e){this._didMoveLastFrame=!0,this._lastPointerMovePosition.copy(this.gripWorldPosition),this._lastPointerMoveQuaternion.copy(this.gripWorldQuaternion),Jn&&B.DrawLabel(this.rayWorldPosition.add(this.object.worldForward.multiplyScalar(.1)),"move",.01);let i=this.xr.context.input.getFirstPressedButtonForPointer(this.index);i===void 0&&(i=0);const n=this.gamepad?.buttons[i]?.value;this.emitPointerEvent("pointermove",i,"none",!1,null,n)}else this._didMoveLastFrame=!1}pointerInit;emitPointerEvent(e,t,i,n,o=null,r){if(!this.emitEvents){Jn&&e!==Pe.PointerMove&&console.warn("Pointer events are disabled for this controller",this.index,e,t);return}if(this.xr.mode==="immersive-vr"||this.xr.isPassThrough){this.pointerInit.origin=this,this.pointerInit.pointerId=this.getPointerId(t),this.pointerInit.pointerType=this.hand?"hand":"controller",this.pointerInit.button=t,this.pointerInit.buttonName=i,this.pointerInit.isPrimary=n,this.pointerInit.mode=this.inputSource.targetRayMode,this.pointerInit.ray=this.ray,this.pointerInit.device=this.object,this.pointerInit.pressure=r,this.pointerInit.clientX=this._rayPosition.x/this.xr.rigScale,this.pointerInit.clientY=this._rayPosition.y/this.xr.rigScale,this.pointerInit.clientZ=this._rayPosition.z/this.xr.rigScale;const a=U.Current;U.Current=this.xr.context,Jn&&e!=="pointermove"&&console.warn("Pointer event",e,t,i,{...this.pointerInit}),this.xr.context.input.createInputEvent(new ss(e,o,this.pointerInit)),U.Current=a}}}class j_{isDown=!1;isUp=!1;pressed=!1;value=0}class B_{index;name;touched=!1;pressed=!1;value=0;isDown=!1;isUp=!1;constructor(e,t){this.index=e,this.name=t}}const nc=x("debugwebxr");class Nf{controllerStates=[];userId;context;userStateEvtName;constructor(e,t){this.userId=e,this.context=t,this.userStateEvtName="xr-sync-user-state-"+e,this.context.connection.beginListen(this.userStateEvtName,this.onReceivedControllerState)}dispose(){this.context.connection.stopListen(this.userStateEvtName,this.onReceivedControllerState)}onReceivedControllerState=e=>{nc&&console.log(`XRSync: Received change for ${this.userId}: ${e.type} ${e.handedness}; tracked=${e.isTracking}`);let t=!1;for(let i=0;i<this.controllerStates.length;i++)if(this.controllerStates[i].index===e.index){this.controllerStates[i]=e,t=!0;break}t||this.controllerStates.push(e)};update(e){if(this.context.connection.isConnected!=!1){for(let t=this.controllerStates.length-1;t>=0;t--){const i=this.controllerStates[t];let n=!1;for(let o=0;o<e.controllers.length;o++)e.controllers[o].index===i.index&&(n=!0);n||(nc&&console.log(`XRSync: ${i.type} ${i.handedness} removed`,i.index),this.controllerStates.splice(t,1),this.sendControllerRemoved(i))}for(const t of e.controllers)this.updateControllerStates(t)}}onExitXR(e){for(const t of this.controllerStates)this.sendControllerRemoved(t);this.controllerStates.length=0}sendControllerRemoved(e){e.isTracking=!1,e.guid="",this.context.connection.send(this.userStateEvtName,e),this.context.connection.sendDeleteRemoteState(e.guid)}updateControllerStates(e){const t=this.controllerStates.find(i=>i.index===e.index);if(t){let i=!1;i||=t.isTracking!=e.isTracking,i&&(t.isTracking=e.isTracking,this.context.connection.send(this.userStateEvtName,t))}else{const i={guid:this.userId+"-"+e.index,isTracking:e.isTracking,handedness:e.side,index:e.index,type:e.hand?"hand":"controller"};this.controllerStates.push(i),this.context.connection.send(this.userStateEvtName,i),nc&&console.log(`XRSync: ${i.type} ${i.handedness} added`,i.index)}}}class U0{hasState(e){return e?this._states.has(e):!1}isTracking(e,t){if(!e)return;const i=this._states.get(e);return i?i.controllerStates.find(o=>o.handedness===t)?.isTracking||!1:void 0}getDeviceType(e,t){if(!e)return;const i=this._states.get(e);return i?i.controllerStates.find(o=>o.handedness===t)?.type||"unknown":void 0}context;constructor(e){this.context=e,this.context.connection.beginListen(K.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(K.LeftRoom,this.onLeftRoom),this.context.connection.beginListen(K.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.beginListen(K.UserLeftRoom,this.onOtherUserLeftRoom)}destroy(){this.context.connection.stopListen(K.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(K.LeftRoom,this.onLeftRoom),this.context.connection.stopListen(K.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.stopListen(K.UserLeftRoom,this.onOtherUserLeftRoom)}onJoinedRoom=()=>{if(this.context.connection.connectionId){this._states.has(this.context.connection.connectionId)||(nc&&console.log("XRSync: Local user joined room",this.context.connection.connectionId),this._states.set(this.context.connection.connectionId,new Nf(this.context.connection.connectionId,this.context)));for(const e of this.context.connection.usersInRoom())this._states.has(e)||this._states.set(e,new Nf(e,this.context))}};onLeftRoom=()=>{this.context.connection.connectionId&&(this._states.has(this.context.connection.connectionId)||(this._states.get(this.context.connection.connectionId)?.dispose(),this._states.delete(this.context.connection.connectionId)))};onOtherUserJoinedRoom=e=>{const t=e.userId;this._states.has(t)||(nc&&console.log("XRSync: Remote user joined room",t),this._states.set(t,new Nf(t,this.context)))};onOtherUserLeftRoom=e=>{const t=e.userId;this._states.has(t)||(this._states.get(t)?.dispose(),this._states.delete(t))};_states=new Map;onUpdate(e){this.context.connection.isConnected&&this.context.connection.connectionId&&this._states.get(this.context.connection.connectionId)?.update(e)}onExitXR(e){this.context.connection.isConnected&&this.context.connection.connectionId&&this._states.get(this.context.connection.connectionId)?.onExitXR(e)}}class F_{_fadeToColorQuad;_fadeToColorMaterial;constructor(){this._fadeToColorMaterial=new c.MeshBasicMaterial({color:0,transparent:!0,depthTest:!1,fog:!1,side:c.DoubleSide}),this._fadeToColorQuad=new c.Mesh(new c.PlaneGeometry(10,10),this._fadeToColorMaterial)}dispose(){this._fadeToColorQuad.geometry.dispose(),this._fadeToColorMaterial.dispose()}update(e,t){const i=this._fadeToColorQuad,n=this._fadeToColorMaterial;i.parent!==e&&n.opacity>0?e.add(i):n.opacity===0&&i.removeFromParent(),i.layers.set(2),i.material=this._fadeToColorMaterial,i.position.z=-1,i.renderOrder=1/0;const o=this._requestedFadeValue;n.opacity=I.lerp(n.opacity,o,t/.03),Math.abs(n.opacity-o)<=.01&&this._transitionResolve&&(this._transitionResolve(),this._transitionResolve=null,this._transitionPromise=null,this._requestedFadeValue=0)}remove(){this._fadeToColorQuad.removeFromParent()}fadeTransition(){if(this._transitionPromise)return this._transitionPromise;this._requestedFadeValue=1;const e=new Promise(t=>{this._transitionResolve=t});return this._transitionPromise=e,e}_requestedFadeValue=0;_transitionPromise=null;_transitionResolve=null}class Da{static _active=null;static get active(){return this._active}static _requestInFlight=!1;static async start(e,t){if(this._active)return console.error("Cannot start a new XR session while one is already active"),null;if(this._requestInFlight)return console.error("Cannot start a new XR session while a request is already in flight"),null;if("xr"in navigator&&navigator.xr){if(!t)return console.error("XRSessionInit must be provided"),null;this._requestInFlight=!0;const i=await navigator.xr.requestSession(e,t).catch(n=>{console.error("Failed to start temporary XR session:",n)});return i?(i.addEventListener("end",()=>{this._active=null}),this._requestInFlight?(this._requestInFlight=!1,this._active=new Da(e,t,i),this._active):(i.end(),null)):(this._requestInFlight=!1,null)}return null}static async handoff(){return this._active?this._active.handoff():null}static async stop(){this._requestInFlight=!1,this._active&&(await this._active.end(),await _s(100)),this._active=null}_session;_mode;_init;get isAR(){return this._mode==="immersive-ar"}get isVR(){return this._mode==="immersive-vr"}_renderer;_camera;_scene;constructor(e,t,i){this._mode=e,this._init=t,this._session=i,this._session.addEventListener("end",this.onEnd),this._renderer=new c.WebGLRenderer({alpha:!0,antialias:!0}),this._renderer.outputColorSpace="srgb",this._renderer.setPixelRatio(Math.min(2,window.devicePixelRatio)),this._renderer.setSize(window.innerWidth,window.innerHeight,!0),exports.DeviceUtilities.isNeedleAppClip()&&window.requestAnimationFrame(()=>{const n=Math.min(2,window.devicePixelRatio),o=Math.floor(window.innerWidth*n),r=Math.floor(window.innerHeight*n);this._renderer.domElement.width=o,this._renderer.domElement.height=r}),this._renderer.setAnimationLoop(this.onFrame),this._renderer.xr.setSession(i),this._renderer.xr.enabled=!0,this._camera=new c.PerspectiveCamera,this._scene=new c.Scene,this._scene.fog=new c.Fog(4473924,10,250),this._scene.add(this._camera),this.setupScene()}end(){return this._session?this._session.end():Promise.resolve()}async handoff(){if(!this._session)throw new Error("Cannot handoff a session that has already ended");const e={session:this._session,mode:this._mode,init:this._init};return await this.onBeforeHandoff(),this.onEnd(),this._session=null,e}onEnd=()=>{this._session?.removeEventListener("end",this.onEnd),this._renderer.setAnimationLoop(null),this._renderer.dispose(),this._scene.clear()};_lastTime=0;_frames=0;onFrame=(e,t)=>{const i=e-this._lastTime;this.update(e,i),this._camera.parent!==this._scene&&this._scene.add(this._camera),this._renderer.render(this._scene,this._camera),this._lastTime=e,this._frames++};_roomFlyObjects=[];_logoObject=null;get _logoDistance(){return this.isAR?.3:5}get _logoScale(){return this.isAR?.04:1}update(e,t){const i=e*4e-4;for(let r=0;r<this._roomFlyObjects.length;r++){const a=this._roomFlyObjects[r];a.position.y+=Math.sin(i+r*.5)*.005,a.rotateY(.002)}const n=this._logoObject,o=this._renderer.xr.getCamera();if(n){const r=new c.Vector3;o.getWorldDirection(r);const a=o.position.clone().addScaledVector(r,this._logoDistance),l=this.isAR?.005:1e-5;n.position.lerp(a,this._frames<=2?1:t*l),n.lookAt(this._camera.position)}}async onBeforeHandoff(){await _s(1e3),this._scene.clear()}setupScene(){this._scene.background=new c.Color(0);let e=Aa;if($n()){const d=document.querySelector("needle-engine");if(d){const u=d.getAttribute("logo-src");u?.length&&(e=u,A()&&console.debug("[XR] Using custom loading logo from license:",e))}}const t=this._logoObject=new c.Mesh(new c.PlaneGeometry(1,1,1,1),new c.MeshBasicMaterial({transparent:!0,side:2}));t.scale.multiplyScalar(this._logoScale*window.devicePixelRatio),t.renderOrder=1e3,t.material.opacity=0,this._scene.add(t);const i=document.createElement("canvas"),n=i.getContext("2d"),o=new Image,r=d=>{if(!n)return;t.material.opacity=1;const u=1024;i.width=u,i.height=u,n.imageSmoothingQuality="high";const p=u*.19,m=o.width/o.height;{const w=i.height-p*1.5,R=w*m,O=(i.width-R)/2;n.drawImage(o,O,0,R,w)}const y=u*.12,_="Loading...";n.shadowBlur=0,n.fillStyle=this.isAR?"white":"rgba(255,255,255,0.4)",n.font=`${y}px Arial`,n.shadowBlur=u*.02,n.shadowColor="rgba(0,0,0,0.5)",n.shadowOffsetX=0,n.shadowOffsetY=0;const g=n.measureText(_);n.fillText(_,i.width/2-g.width/2,i.height-p/4),n.font=`${y}px Arial`,n.fillText(_,i.width/2-g.width/2,i.height-p/4);const v=new c.TextureLoader().load(i.toDataURL());v.generateMipmaps=!0,v.colorSpace="srgb",v.anisotropy=4;const b=i.width/i.height;t.scale.x=this._logoScale*b*window.devicePixelRatio,t.scale.y=this._logoScale*window.devicePixelRatio,t.material.map=v,t.material.needsUpdate=!0};o.onload=()=>r(),o.onerror=d=>{console.error("Failed to load temporary XR logo:",e,d),o.src=Aa},o.crossOrigin="anonymous",o.src=e;const a=new c.DirectionalLight(16777215,1);a.position.set(0,20,0),a.castShadow=!1,this._scene.add(a);const l=new c.DirectionalLight(16777215,1);l.position.set(0,-1,0),l.castShadow=!1,this._scene.add(l);const h=new c.PointLight(16777215,1,100,1);if(h.position.set(0,2,0),h.castShadow=!1,h.distance=200,this._scene.add(h),this.isAR===!1)for(let u=0;u<100;u++){const p=new c.MeshStandardMaterial({color:2236962,metalness:1,roughness:.8}),m=Na.Sphere,y=_o.createPrimitive(m,{material:p});y.position.x=I.random(-50,50),y.position.y=I.random(-2,50),y.position.z=I.random(-50,50),y.rotation.x=I.random(0,Math.PI*2),y.rotation.y=I.random(0,Math.PI*2),y.rotation.z=I.random(0,Math.PI*2),y.scale.multiplyScalar(.5+Math.random()*10);const _=y.position.distanceTo(this._camera.position)-y.scale.x;_<10&&(y.position.z+=5,y.position.multiplyScalar(1+1/_)),this._roomFlyObjects.push(y),this._scene.add(y)}}}var wc;(s=>{const e=[];function t(){e?.length||A()&&console.warn("No USDZ exporters found – cannot export USDZ for QuickLook.");for(const o of e)o.exportAndOpen();return!0}s.exportAndOpen=t;function i(o){e.push(o)}s.registerExporter=i;function n(o){if(!e)return;const r=e.indexOf(o);r>=0&&e.splice(r,1)}s.unregisterExporter=n})(wc||(wc={}));const Ue=x("debugwebxr"),U_=x("stats");let Vf=0;function nP(s){let e=null;const t=s;return t.getAROverlayContainer?e=t.getAROverlayContainer():e=s,e}sP();async function sP(){let s="immersive-vr";try{if(exports.DeviceUtilities.isNeedleAppClip()?s="immersive-ar":await navigator.xr?.isSessionSupported("immersive-vr")||(s="immersive-ar"),!await navigator.xr?.isSessionSupported("immersive-ar")&&s==="immersive-ar")return}catch(e){console.debug("[NeedleXRSession:granted] Error while checking XR support:",e);return}if(x("debugasap")){let e=globalThis["needle:XRSession"];if(e instanceof Promise){delete globalThis["needle:XRSession"],le.addContextCreatedCallback(async t=>{if(!e)return;ya(!0);const i=await e;if(i){const n=q.getDefaultSessionInit(s);q.setSession(s,i,n,t.context)}else console.error("[NeedleXRSession:granted] ASAP session was rejected");e=void 0});return}}if("xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent)){console.warn("WebXRViewer does not support addEventListener");return}navigator.xr?.addEventListener("sessiongranted",async()=>{const e=sessionStorage.getItem("needle_xr_session_mode"),t=sessionStorage.getItem("needle_xr_session_init")??null,i=t?JSON.parse(t):null;let n=null;if(z0()&&(await Da.start(e||s,i||q.getDefaultSessionInit(s)).catch(o=>console.warn("[NeedleXRSession:granted] TemporaryXRContext start failed:",o)),await aP(),n=await Da.handoff()),n)q.setSession(n.mode,n.session,n.init,U.Current);else if(e&&t){console.log("[NeedleXRSession:granted] Restore last session");const o=JSON.parse(t);q.start(e,o).catch(r=>console.warn(r))}else q.start(s).catch(o=>console.warn("[NeedleXRSession:granted] failed:",o))},{once:!0})}}function oP(s,e){sessionStorage.setItem("needle_xr_session_mode",s),sessionStorage.setItem("needle_xr_session_init",JSON.stringify(e))}function rP(){sessionStorage.removeItem("needle_xr_session_mode"),sessionStorage.removeItem("needle_xr_session_init")}const ug=new Set;le.registerCallback(ae.ContextCreationStart,async s=>{ug.add(s.context)});le.registerCallback(ae.ContextCreated,async s=>{ug.delete(s.context);const e=s.context?.domElement.getAttribute("autostart")||null;lP(e)});function z0(){return ug.size>0}function aP(){return new Promise(s=>{const e=Date.now(),t=setInterval(()=>{(!z0()||Date.now()-e>6e4)&&(clearInterval(t),s())},100)})}exports.DeviceUtilities.isDesktop()&&A()&&window.addEventListener("keydown",s=>{(s.key==="x"||s.key==="Escape")&&q.active&&q.stop()});function lP(s){s&&s?.toLowerCase()==="ar"&&fn.registerWaitForInteraction(()=>{q.start("ar")})}const Wh=Symbol("initial-fov"),$f=Symbol("initial-near");class q{static _sync=null;static getXRSync(e){return this._sync||(this._sync=new U0(e)),this._sync}static get currentSessionRequest(){return this._currentSessionRequestMode}static _currentSessionRequestMode=null;static get active(){return this._activeSession}static get activeMode(){return this._activeSession?.mode??null}static get xrSystem(){return"xr"in navigator?navigator.xr:void 0}static isXRSupported(){return Promise.all([this.isVRSupported(),this.isARSupported()]).then(e=>e.some(t=>t)).catch(()=>!1)}static isVRSupported(){return this.isSessionSupported("immersive-vr")}static isARSupported(){return this.isSessionSupported("immersive-ar")}static isSessionSupported(e){return this.xrSystem?.isSessionSupported(e).catch(t=>(Ue&&console.error(t),!1))??Promise.resolve(!1)}static _currentSessionRequest;static _activeSession;static onSessionRequestStart(e){this._sessionRequestStartListeners.push(e)}static offSessionRequestStart(e){const t=this._sessionRequestStartListeners.indexOf(e);t>=0&&this._sessionRequestStartListeners.splice(t,1)}static _sessionRequestStartListeners=[];static onSessionRequestEnd(e){this._sessionRequestEndListeners.push(e)}static offSessionRequestEnd(e){const t=this._sessionRequestEndListeners.indexOf(e);t>=0&&this._sessionRequestEndListeners.splice(t,1)}static _sessionRequestEndListeners=[];static onXRSessionStart(e){this._xrStartListeners.push(e)}static offXRSessionStart(e){const t=this._xrStartListeners.indexOf(e);t>=0&&this._xrStartListeners.splice(t,1)}static _xrStartListeners=[];static onXRSessionEnd(e){this._xrEndListeners.push(e)}static offXRSessionEnd(e){const t=this._xrEndListeners.indexOf(e);t>=0&&this._xrEndListeners.splice(t,1)}static _xrEndListeners=[];static onControllerAdded(e){this._controllerAddedListeners.push(e)}static offControllerAdded(e){const t=this._controllerAddedListeners.indexOf(e);t>=0&&this._controllerAddedListeners.splice(t,1)}static _controllerAddedListeners=[];static onControllerRemoved(e){this._controllerRemovedListeners.push(e)}static offControllerRemoved(e){const t=this._controllerRemovedListeners.indexOf(e);t>=0&&this._controllerRemovedListeners.splice(t,1)}static _controllerRemovedListeners=[];static offerSession(e,t,i){return"xr"in navigator&&navigator.xr&&"offerSession"in navigator.xr?(typeof navigator.xr.offerSession=="function"&&(console.log("WebXR offerSession is available - requesting mode: "+e),t=="default"&&(t=this.getDefaultSessionInit(e)),navigator.xr.offerSession(e,{...t}).then(n=>q.setSession(e,n,t,i)).catch(n=>{console.log("XRSession offer rejected (perhaps because another call to offerSession was made or a call to requestSession was made)")})),!0):!1}static getDefaultSessionInit(e){switch(e){case"immersive-ar":const t=["anchors","local-floor","layers","dom-overlay","hit-test","unbounded"];return exports.DeviceUtilities.isVisionOS()||t.push("hand-tracking"),{optionalFeatures:t};case"immersive-vr":const i=["local-floor","bounded-floor","high-fixed-foveation-level","layers"];return exports.DeviceUtilities.isVisionOS()||i.push("hand-tracking"),{optionalFeatures:i};default:return console.warn("No default session init for mode",e),{}}}static async start(e,t,i){if(t||(t={}),exports.DeviceUtilities.isiOS()){const a=await this.isARSupported().catch(()=>!1);if(exports.DeviceUtilities.isVisionOS()&&!a&&(e==="ar"||e==="immersive-ar")&&(e="quicklook"),e==="quicklook")return ni.sendEvent(U.Current,"xr",{action:"quicklook_export",source:"NeedleXRSession.start"}),wc.exportAndOpen(),null;if(!a&&(e==="immersive-ar"||e==="ar")){this.invokeSessionRequestStart("immersive-ar",t);const l=new URL("https://appclip.apple.com/id?p=tools.needle.launch-app.Clip");l.searchParams.set("url",location.href);const h=l.toString();ni.sendEvent(U.Current,"xr",{action:"app_clip_launch",source:"NeedleXRSession.start",url:h});const d=window.top||window;try{console.debug("iOS device detected - opening Needle App Clip for AR experience",{mode:e,init:t,url:l}),d.location.href=h}catch(u){console.warn("Error navigating to AppClip "+h+`
|
|
878
878
|
`,u),window!==window.top?window.open(h,"_blank"):window.location.href=h}return setTimeout(()=>{this.invokeSessionRequestEnd("immersive-ar",t||{},null)},3e3),null}}if(e==="quicklook")return console.warn("QuickLook mode is only supported on iOS devices"),null;if(e=="ar"&&(e="immersive-ar"),A()&&x("debugxrpreroom"))return console.warn("Debug: Starting temporary XR session"),await Da.start(e,t||q.getDefaultSessionInit(e)),null;if(this._currentSessionRequest)return console.warn("A XRSession is already being requested"),(Ue||A())&&fe("A XRSession is already being requested"),this._currentSessionRequest.then(()=>this._activeSession);if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;if(i||(i=U.Current),i||(i=le.All[0]),!i)throw new Error("No Needle Engine Context found");switch(e){case"immersive-ar":{if(await this.xrSystem?.isSessionSupported("immersive-ar")!==!0)return console.error(e+" is not supported by this browser."),null;const l=this.getDefaultSessionInit(e),h=nP(i.domElement);h&&!exports.DeviceUtilities.isQuest()&&(l.domOverlay={root:h},l.optionalFeatures.push("dom-overlay")),t={...l,...t}}break;case"immersive-vr":{if(await this.xrSystem?.isSessionSupported("immersive-vr")!==!0)return console.error(e+" is not supported by this browser."),null;t={...this.getDefaultSessionInit(e),...t}}break;default:console.warn("No default session init for mode",e);break}t.optionalFeatures??=[],t.requiredFeatures??=[],await Da.stop();const n=e=="immersive-ar"?i.scripts_immersive_ar:i.scripts_immersive_vr;Ue?console.log(`%cRequesting ${e} session`,"font-weight:bold;",t,n):console.log(`%cRequesting ${e} session`,"font-weight:bold;");for(const a of n)a.onBeforeXR&&a.activeAndEnabled&&!a.destroyed&&a.onBeforeXR(e,t);this.invokeSessionRequestStart(e,t),Ue&&Se("Requesting "+e+" session ("+Date.now()+")"),ni.sendEvent(U.Current,"xr",{action:"session_request",mode:e,features:(t.requiredFeatures??[]).concat(t.optionalFeatures??[]).join(","),source:"NeedleXRSession.start"}),this._currentSessionRequest=navigator?.xr?.requestSession(e,t),this._currentSessionRequestMode=e;const o=await this._currentSessionRequest?.catch(a=>{console.error(a,"Code: "+a?.code),a?.code===9&&fe("Couldn't start XR session. Make sure you allow the required permissions."),console.log("If the specified XR configuration is not supported (e.g. entering AR doesnt work) - make sure you access the website on a secure connection (HTTPS) and your device has the required permissions (e.g. camera access)"),location.protocol==="http:"&&fe("XR requires a secure connection (HTTPS)")});return this._currentSessionRequest=void 0,this._currentSessionRequestMode=null,this.invokeSessionRequestEnd(e,t,o),o?this.setSession(e,o,t,i):(console.warn("XR Session request was rejected"),null)}static invokeSessionRequestStart(e,t){for(const i of this._sessionRequestStartListeners)i({mode:e,init:t})}static invokeSessionRequestEnd(e,t,i){for(const n of this._sessionRequestEndListeners)n({mode:e,init:t,newSession:i||null})}static setSession(e,t,i,n){if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;const o=e=="immersive-ar"?n.scripts_immersive_ar:n.scripts_immersive_vr;return this._activeSession=new q(e,t,n,{scripts:o,controller_added:this._controllerAddedListeners,controller_removed:this._controllerRemovedListeners,init:i}),t.addEventListener("end",this.onEnd),Ue?console.log(`%cStarted ${e} session`,"font-weight:bold;",o):console.log(`%cStarted ${e} session`,"font-weight:bold;"),this._activeSession}static $_stop_request=Symbol();static stop(){const e=this._activeSession;e&&(e[this.$_stop_request]===void 0?(Ue&&console.log("[NeedleXRSession] Stopping XR Session... (new)"),e[this.$_stop_request]=setTimeout(()=>{e.end()})):Ue&&console.warn("[NeedleXRSession] XR Session stop already requested"))}static onEnd=()=>{Ue&&console.log("XR Session ended"),this._activeSession=null};context;get sync(){return q._sync}get running(){return!this._ended&&this.session!=null}session;mode;get interactionMode(){return this.session.interactionMode}get visibilityState(){return this.session.visibilityState}get isVisibleBlurred(){return this.session.visibilityState==="visible-blurred"}get isSystemKeyboardSupported(){return this.session.isSystemKeyboardSupported}get environmentBlendMode(){return this.session.environmentBlendMode}get frame(){return this.context.xrFrame}controllers=[];get leftController(){return this.controllers.find(e=>e.side==="left")}get rightController(){return this.controllers.find(e=>e.side==="right")}getController(e){return typeof e=="number"?this.controllers[e]||null:this.controllers.find(t=>t.side===e)||null}get isPassThrough(){return!!(this.environmentBlendMode!=="opaque"&&this.interactionMode==="world-space"||this.mode==="immersive-ar"&&this.environmentBlendMode!=="opaque"&&this.controllers.some(e=>e.inputSource.targetRayMode==="tracked-pointer")||A()&&exports.DeviceUtilities.isDesktop()&&this.mode==="immersive-ar")}get isAR(){return this.mode==="immersive-ar"}get isVR(){return this.mode==="immersive-vr"}get isScreenBasedAR(){return this.isAR&&!this.isPassThrough}get posePosition(){return this._transformPosition}get poseOrientation(){return this._transformOrientation}get referenceSpace(){return this.context.renderer.xr.getReferenceSpace()}get viewerPose(){return this._viewerPose}get isTrackingImages(){if(this.frame&&"getImageTrackingResults"in this.frame&&typeof this.frame.getImageTrackingResults=="function")try{const e=this.frame.getImageTrackingResults();for(const t of e)if(t.trackingState==="tracked")return!0}catch{return!1}return!1}get rig(){const e=this._rigs[0]??null;return e?.gameObject&&dr(e.gameObject)||e?.isActive===!1?(this.updateActiveXRRig(),this._rigs[0]??null):e}_rigScale=1;_lastRigScaleUpdate=-1;get rigScale(){return this._rigs[0]?(this._lastRigScaleUpdate!==this.context.time.frame&&(this._lastRigScaleUpdate=this.context.time.frame,this._rigScale=this._rigs[0].gameObject.worldScale.x),this._rigScale):1}addRig(e){this._rigs.indexOf(e)>=0||(e.priority===void 0&&(e.priority=0),this._rigs.push(e),this.updateActiveXRRig())}removeRig(e){const t=this._rigs.indexOf(e);t!==-1&&(this._rigs.splice(t,1),this.updateActiveXRRig())}setRigActive(e){const t=this._rigs.indexOf(e),i=this._rigs[0];this._rigs.splice(t,1),this._rigs.unshift(e),e.priority=i?.priority??0,this.updateActiveXRRig()}getUserOffsetInRig(){const e=this.context.mainCamera?.position;if(!e||!this.rig)return F(0,0,0);const t=F(e);return t.x*=-1,t.z*=-1,t.applyQuaternion(ei(this.rig.gameObject.quaternion)),t}updateActiveXRRig(){const e=this._rigs[0]??null;this._defaultRig.gameObject.parent!==this.context.scene&&this.context.scene.add(this._defaultRig.gameObject),this._defaultRig.gameObject.visible=!0,this._rigs.includes(this._defaultRig)||this._rigs.push(this._defaultRig);let t=this._rigs[0];t&&t.priority===void 0&&(t.priority=0);for(let i=1;i<this._rigs.length;i++){const n=this._rigs[i];if(n.isActive){if(dr(n.gameObject)){this._rigs.splice(i,1),i--;continue}(!t||t.isActive===!1||n.priority!==void 0&&n.priority>t.priority)&&(t=n)}}if(e!==t){const i=this._rigs.indexOf(t);i>=0&&this._rigs.splice(i,1),this._rigs.unshift(t)}Ue&&(e===t?console.log("Updated Active XR Rig:",t,"prev:",e):console.log("Updated Active XRRig:",t," (the same as before)"))}_rigs=[];_viewerHitTestSource=null;getHitTest(e){if(e)return this.getControllerHitTest(e);if(!this._viewerHitTestSource)return null;const t=this._viewerHitTestSource,i=this.frame.getHitTestResults(t);if(i.length>0){const n=i[0];return this.convertHitTestResult(n)}return null}getControllerHitTest(e){const t=e.getHitTestSource();if(!t)return null;const i=this.frame.getHitTestResultsForTransientInput(t);for(const n of i)if(n.inputSource===e.inputSource)for(const o of n.results)return this.convertHitTestResult(o);return null}convertHitTestResult(e){const t=this.context.renderer.xr.getReferenceSpace(),i=t&&e.getPose(t);if(i){const n=F(i.transform.position),o=ei(i.transform.orientation),r=this.context.mainCamera;if(r?.parent!==this._cameraRenderParent&&n.applyMatrix4(va),r?.parent){n.applyMatrix4(r.parent.matrixWorld),o.multiply(Li);const a=pe(r.parent);a.premultiply(Li),o.premultiply(a)}return{hit:e,position:n,quaternion:o}}return null}convertSpace(e){const t=F(e.position);t.applyMatrix4(va);const i=ei(e.orientation);return i.premultiply(Li),{position:t,quaternion:i}}_defaultRig;_xr_scripts;_xr_update_scripts=[];_inactive_scripts=[];_controllerAdded;_controllerRemoved;_originalCameraWorldPosition;_originalCameraWorldRotation;_originalCameraWorldScale;_originalCameraParent;_mainCamera=null;constructor(e,t,i,n){oP(e,n.init),this.session=t,this.mode=e,this.context=i,(Ue||x("console"))&&ya(!0),this._xr_scripts=[...n.scripts],this._xr_update_scripts=this._xr_scripts.filter(o=>typeof o.onUpdateXR=="function"),this._controllerAdded=n.controller_added,this._controllerRemoved=n.controller_removed,xs(this.onBefore,ge.LateUpdate),this.context.pre_render_callbacks.push(this.onBeforeRender),this.context.post_render_callbacks.push(this.onAfterRender),(n.init.optionalFeatures?.includes("hit-test")||n.init.requiredFeatures?.includes("hit-test"))&&t.requestReferenceSpace("viewer").then(o=>t.requestHitTestSource?.call(t,{space:o})?.then(r=>this._viewerHitTestSource=r).catch(r=>console.error(r))).catch(o=>console.error(o)),this.context.mainCamera&&(this._originalCameraWorldPosition=Y(this.context.mainCamera,new c.Vector3),this._originalCameraWorldRotation=pe(this.context.mainCamera,new c.Quaternion),this._originalCameraWorldScale=je(this.context.mainCamera,new c.Vector3),this._originalCameraParent=this.context.mainCamera.parent,this.context.mainCamera instanceof c.PerspectiveCamera&&(this.context.mainCamera[Wh]=this.context.mainCamera.fov)),this._defaultRig=new Z1,this.context.scene.add(this._defaultRig.gameObject),this.addRig(this._defaultRig);for(let o=0;o<t.inputSources.length;o++){const r=t.inputSources[o];if(!r.handedness){console.warn("Input source in xr session has no handedness - ignoring",o);continue}this.onInputSourceAdded(r)}this.session.addEventListener("end",this.onEnd),this.session.addEventListener("inputsourceschange",o=>{for(const r of o.removed)this.disconnectInputSource(r);for(const r of o.added)this.onInputSourceAdded(r)}),this.context.xr=this,this.context.renderer.xr.setSession(this.session).then(this.onRendererSessionSet),"controllerAutoUpdate"in this.context.renderer.xr?(console.debug("Disabling three.js controllerAutoUpdate"),this.context.renderer.xr.controllerAutoUpdate=!1):Ue&&console.warn("controllerAutoUpdate is not available in three.js - cannot disable it"),exports.DeviceUtilities.isNeedleAppClip()&&window.requestAnimationFrame(()=>{const o=this.context.renderer.domElement,r=window.devicePixelRatio||1,a=o.width,l=o.height,h=Math.floor(window.innerWidth*r),d=Math.floor(window.innerHeight*r);(Math.abs(a-h)>2||Math.abs(l-d)>2)&&(o.width=h,o.height=d,console.debug("Applied DPR scaling for Needle AppClip XR session",r,o.width,o.height))})}onRendererSessionSet=()=>{this.running&&(this.context.renderer.xr.enabled=!0,this.context.renderer.xr.updateCamera(this.context.mainCamera),this.context.mainCameraComponent?.applyClearFlags())};onInputSourceAdded=e=>{if(e.targetRayMode==="screen")return;let t=0;for(let n=0;n<this.session.inputSources.length;n++)if(this.session.inputSources[n]===e){t=n;break}if(this.controllers.find(n=>n.inputSource===e)){console.debug("Controller already exists for input source",t);return}else if(this._newControllers.find(n=>n.inputSource===e)){console.debug("Controller already registered for input source",t);return}const i=new dg(this,e,t);this._newControllers.push(i)};disconnectInputSource(e){const t=(o,r)=>{if(o.inputSource===e){Ue&&console.log("Disconnecting controller",o.index);const a=r.indexOf(o);a>=0&&r.splice(a,1),this.invokeControllerEvent(o,this._controllerRemoved,"removed");const l={xr:this,controller:o,change:"removed"};for(const h of this._xr_scripts)h.onXRControllerRemoved&&h.onXRControllerRemoved(l);o.onDisconnected()}},i=[...this.controllers];for(let o=i.length-1;o>=0;o--){const r=i[o];t(r,this.controllers)}const n=[...this._newControllers];for(let o=n.length-1;o>=0;o--){const r=n[o];t(r,this._newControllers)}}end(){this._ended||this.session.end().catch(e=>console.warn(e))}_ended=!1;_newControllers=[];onEnd=e=>{if(this._ended)return;this._ended=!0,console.debug("XR Session ended"),ni.sendEvent(U.Current,"xr",{action:"session_end",mode:this.mode,source:"NeedleXRSession.onEnd"}),rP(),this.onAfterRender(),this.revertCustomForward(),this._didStart=!1,this._previousCameraParent=null,this.requestedCameraNearPlane=null,yo(this.onBefore,ge.LateUpdate);const t=this.context.pre_render_callbacks.indexOf(this.onBeforeRender);t>=0&&this.context.pre_render_callbacks.splice(t,1);const i=this.context.post_render_callbacks.indexOf(this.onAfterRender);i>=0&&this.context.post_render_callbacks.splice(i,1),this.context.xr=null,this.context.renderer.xr.enabled=!1,this.context.pre_update_oneshot_callbacks.push(()=>{this.context.mainCameraComponent?.applyClearFlags(),this.context.mainCameraComponent?.applyClippingPlane()}),D0({session:this});for(const o of q._xrEndListeners)o({xr:this});const n=[...this.controllers];for(let o=0;o<n.length;o++)this.disconnectInputSource(n[o].inputSource);this.controllers.length=0,this._newControllers.length=0;for(const o of this._xr_scripts)o?.onLeaveXR?.({xr:this});this.sync?.onExitXR(this),this.context.mainCamera&&(this._originalCameraParent?.add(this.context.mainCamera),this._originalCameraWorldPosition&&at(this.context.mainCamera,this._originalCameraWorldPosition),this._originalCameraWorldRotation&&dn(this.context.mainCamera,this._originalCameraWorldRotation),this._originalCameraWorldScale&&Ma(this.context.mainCamera,this._originalCameraWorldScale),this.context.mainCamera instanceof c.PerspectiveCamera&&(this.context.mainCamera[Wh]&&(this.context.mainCamera.fov=this.context.mainCamera[Wh],this.context.mainCamera[Wh]=0),this.context.mainCamera[$f]&&(this.context.mainCamera.near=this.context.mainCamera[$f],this.context.mainCamera[$f]=0))),this.context.requestSizeUpdate(),this._defaultRig.gameObject.removeFromParent(),ya(!1)};_didStart=!1;onBefore=e=>{const t=e.xrFrame;if(!t)return;this.context.xr=this,this.context.mainCameraComponent&&this.context.mainCameraComponent!==this._mainCamera&&(this._mainCamera=this.context.mainCameraComponent),this.rig?.isActive==!1&&(Ue&&console.warn("Latest rig is not active - trying to activate a different rig",this.rig),this.updateActiveXRRig()),this.rig&&this._mainCamera?.gameObject&&this._mainCamera?.gameObject?.parent!==this.rig.gameObject&&this.rig.gameObject.add(this._mainCamera?.gameObject),this.internalUpdateState(),this.applyCustomForward();const i={xr:this};if(this._didStart){if(this.context.new_scripts_xr.length>0){const n=[...this.context.new_scripts_xr];for(let o=0;o<n.length;o++){const r=this.context.new_scripts_xr[o];if(!r||r.destroyed||r.supportsXR?.(this.mode)==!1){this.context.new_scripts_xr.splice(o,1);continue}if(!r.activeAndEnabled){this.context.new_scripts_xr.splice(o,1),this.markInactive(r);continue}if(this.addScript(r)){this.invokeCallback_EnterXR(r);for(const a of this.controllers)this.invokeCallback_ControllerAdded(r,a)}}}}else{if(this._didStart=!0,this.mode==="immersive-vr"){const o=ri(this.context.scene.children);if(o){const r=o.getSize(F());if(r.length()>0){const a=this._defaultRig.gameObject;a.position.set(o.min.x+r.x*.5,o.min.y,o.max.z+r.z*.5+1.5);const l=o.getCenter(F());l.y=a.position.y,a.lookAt(l)}}}A0({session:this}),_r();for(const o of q._xrStartListeners)o(i);const n=[...this._xr_scripts];Ue&&console.log("NeedleXRSession start, handle scripts:",n);for(const o of n){if(o.destroyed){this._script_to_remove.push(o);continue}if(!o.activeAndEnabled){this.markInactive(o);continue}this.invokeCallback_EnterXR(o);for(const r of this.controllers)this.invokeCallback_ControllerAdded(o,r)}}this.syncCameraCullingMask();for(const n of this.controllers)n.onUpdate(t);if(this._newControllers.length>0){const n=[...this._newControllers];this._newControllers.length=0;for(const o of n){if(!o.connected){console.warn("New controller is not connected",o);continue}this.controllers.push(o);for(const r of this._xr_scripts){if(r.destroyed){this._script_to_remove.push(r);continue}r.activeAndEnabled!==!1&&this.invokeCallback_ControllerAdded(r,o)}}this.controllers.sort((o,r)=>o.index-r.index)}Ue&&this.context.time.frame%30===0&&this.controllers.length<=0&&this.session.inputSources.length>0&&(ya(!0),console.error("XRControllers are not added but inputSources are present"));for(const n of this._xr_update_scripts){if(n.destroyed===!0){this._script_to_remove.push(n);continue}if(n.activeAndEnabled===!1){this.markInactive(n);continue}n.onUpdateXR&&n.onUpdateXR(i)}if(this.handleInactiveScripts(),this._script_to_remove.length>0){const n=[...new Set(this._script_to_remove)];this._script_to_remove.length=0;for(const o of n)!o.destroyed&&this.running&&o.onLeaveXR?.(i),this.removeScript(o)}this.sync?.onUpdate(this),this.onRenderDebug()};onRenderDebug(){if(Ue)for(const e of this.controllers)e.onRenderDebug();if((Ue||U_)&&this.rig&&(Vf++,Vf>=20)){const e=this.rig.gameObject.worldPosition,t=this.rig.gameObject.worldForward;e.add(t.multiplyScalar(1.5));const i=this.rig.gameObject.worldUp;e.add(i.multiplyScalar(2.5));let n="";if(n+=`${this.context.time.smoothedFps.toFixed(0)} FPS`,n+=`, calls: ${this.context.renderer.info.render.calls}, tris: ${this.context.renderer.info.render.triangles.toLocaleString()}`,Ue||U_)for(const o of this.controllers)n+=`
|
|
879
|
-
${o.hand?"hand":"ctrl"} ${o.inputSource.handedness}[${o.index}] con:${o.connected} tr:${o.isTracking} hts:${o.hasHitTestSource?"yes":"no"}`;Vf=0,B.DrawLabel(e,n,void 0,1/60*20)}}onBeforeRender=()=>{this.context.mainCamera&&(this.updateFade(this.context.mainCamera),this.requestedCameraNearPlane!==null&&this.context.mainCamera instanceof c.PerspectiveCamera&&(this.context.mainCamera.near=this.requestedCameraNearPlane,this.requestedCameraNearPlane=null))};onAfterRender=()=>{if(this.onUpdateFade_PostRender(),exports.DeviceUtilities.isDesktop()||!this._renderOnceOnDevice){const e=this.context.renderer;if(e.xr.isPresenting&&this.context.mainCamera){this._renderOnceOnDevice=!0;const t=e.xr.enabled,i=e.getRenderTarget(),n=this.context.scene.background;e.xr.enabled=!1,e.setRenderTarget(null),this.isPassThrough&&(this.context.scene.background=null),this.context.composer?this.context.composer.render(this.context.time.deltaTime):e.render(this.context.scene,this.context.mainCamera),e.xr.enabled=t,e.setRenderTarget(i),this.context.scene.background=n}}};addScript(e){return this._xr_scripts.includes(e)?!1:(Ue&&console.log("Register new XRScript",e),this._xr_scripts.push(e),typeof e.onUpdateXR=="function"&&this._xr_update_scripts.push(e),!0)}markInactive(e){if(!(this._inactive_scripts.indexOf(e)>=0)){this.removeScript(e,!1),this._inactive_scripts.push(e);for(const t of this.controllers)this.invokeCallback_ControllerRemoved(e,t);this.invokeCallback_LeaveXR(e)}}handleInactiveScripts(){if(this._inactive_scripts.length>0)for(let e=this._inactive_scripts.length-1;e>=0;e--){const t=this._inactive_scripts[e];if(t.activeAndEnabled){this._inactive_scripts.splice(e,1),this.addScript(t),this.invokeCallback_EnterXR(t);for(const i of this.controllers)this.invokeCallback_ControllerAdded(t,i)}}}_script_to_remove=[];removeScript(e,t=!0){Ue&&console.log("Remove XRScript",e);const i=this._xr_scripts.indexOf(e);i>=0&&this._xr_scripts.splice(i,1);const n=this._xr_update_scripts.indexOf(e);if(n>=0&&this._xr_update_scripts.splice(n,1),t){const o=this._inactive_scripts.indexOf(e);o>=0&&this._inactive_scripts.splice(o,1)}}invokeCallback_EnterXR(e){e.onEnterXR&&e.onEnterXR({xr:this})}invokeCallback_ControllerAdded(e,t){e.onXRControllerAdded&&e.onXRControllerAdded({xr:this,controller:t,change:"added"})}invokeCallback_ControllerRemoved(e,t){e.onXRControllerRemoved&&e.onXRControllerRemoved({xr:this,controller:t,change:"removed"})}invokeCallback_LeaveXR(e){e.onLeaveXR&&!e.destroyed&&e.onLeaveXR({xr:this})}syncCameraCullingMask(){const e=this.context.xrCamera,t=this.context.mainCameraComponent?.cullingMask;if(e&&t!==void 0){for(const i of e.cameras)i.layers.mask=t;e.layers.mask=t}else if(e){for(const i of e.cameras)i.layers.enableAll();e.layers.enableAll()}}invokeControllerEvent(e,t,i){for(let n=t.length-1;n>=0;n--){const o=t[n];if(o)try{o({xr:this,controller:e,change:i})}catch(r){console.error(r)}}}_camera;_cameraRenderParent=new c.Object3D().rotateY(Math.PI);_previousCameraParent;_customforward=!0;originalCameraNearPlane;requestedCameraNearPlane=null;applyCustomForward(){if(this.context.mainCamera&&this._customforward){this._camera=this.context.mainCamera,this._camera.parent!==this._cameraRenderParent&&(this._previousCameraParent=this._camera.parent,this._previousCameraParent?.add(this._cameraRenderParent)),this._cameraRenderParent.name="XR Camera Render Parent",this._cameraRenderParent.add(this._camera);{let e=.02;const t=.001;if(this.rig){const i=je(this.rig.gameObject);e*=i.x}this._camera instanceof c.PerspectiveCamera&&Math.abs(this._camera.near-e)>t&&(this.isAR?this.originalCameraNearPlane=this._camera.near:this._camera.near=e,Ue&&console.debug(`Setting camera near plane to ${e} (was ${this.originalCameraNearPlane}) to account for XR rendering scale`))}}}revertCustomForward(){this._camera&&this._previousCameraParent&&this._previousCameraParent.add(this._camera),this._previousCameraParent=null,this._camera instanceof c.PerspectiveCamera&&this.originalCameraNearPlane!=null&&(this._camera.near=this.originalCameraNearPlane,this.originalCameraNearPlane=void 0)}_viewerPose;_transformOrientation=new c.Quaternion;_transformPosition=new c.Vector3;internalUpdateState(){const e=this.context.renderer.xr.getReferenceSpace();if(!e){this._viewerPose=void 0;return}if(this._viewerPose=this.frame.getViewerPose(e),this._viewerPose){const t=this._viewerPose.transform;this._transformPosition.set(t.position.x,t.position.y,t.position.z),this._transformOrientation.set(t.orientation.x,t.orientation.y,t.orientation.z,t.orientation.w)}}_transition;get transition(){return this._transition||(this._transition=new F_),this._transition}fadeTransition(){return this._transition||(this._transition=new F_),this._transition.fadeTransition()}updateFade(e){this._transition&&e instanceof c.PerspectiveCamera&&this._transition.update(e,this.context.time.deltaTime)}onUpdateFade_PostRender(){this._transition?.remove()}}const Wf=x("debugwebxr");class N0{static tryFindAvatarObjects(e,t,i){if(i.head&&i.leftHand&&i.rightHand)return;const n=e.name.toLocaleLowerCase();!i.head&&n.includes("head")&&(Wf&&console.log("FOUND AVATAR HEAD",e.name),i.head=new Z("",t,e)),n.includes("hand")&&(!i.leftHand&&n.includes("left")&&(Wf&&console.log("FOUND AVATAR LEFT HAND",e.name),i.leftHand=new Z("",t,e)),!i.rightHand&&n.includes("right")&&(Wf&&console.log("FOUND AVATAR RIGHT HAND",e.name),i.rightHand=new Z("",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 te extends c.Color{alpha=1;get isRGBAColor(){return!0}set a(e){this.alpha=e}get a(){return this.alpha}constructor(e,t,i,n){super(),typeof e=="number"&&typeof t=="number"&&typeof i=="number"?(this.set(e,t,i),this.alpha=typeof n=="number"?n:1):e!==void 0&&(this.set(e),this.alpha=1)}clone(){const e=super.clone();return e.alpha=this.alpha,e}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,"alpha"in e&&typeof e.alpha=="number"?this.alpha=e.alpha:typeof e.a=="number"&&(this.alpha=e.a),this}lerp(e,t){const i=e;return i.alpha!=null&&(this.alpha=I.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=I.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 te(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 te(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 te(i/255,n/255,o/255,1)}else if(e.startsWith("rgba")){const t=e.slice(5,-1).split(",").map(Number);return new te(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 te(t[0]/255,t[1]/255,t[2]/255,1)}}else if(Array.isArray(e)){if(e.length===4)return new te(e[0],e[1],e[2],e[3]);if(e.length===3)return new te(e[0],e[1],e[2],1);console.error("Invalid color array length. Expected 3 or 4, got "+e.length)}return new te(e)}}const Mt=new c.Vector3,z_=new c.Vector3,N_=new c.Quaternion,cP=x("debuggizmos"),nn=8947848,Gf=32;class B{constructor(){}static enabled=!0;static isGizmo(e){return e[Zp]!==void 0}static setVisible(e){for(const t of Ei.timedObjectsBuffer)t.visible=e}static DrawLabel(e,t,i=.05,n=0,o,r,a){if(!B.enabled)return null;o||(o=nn);const l=q.active?.rigScale??1,h=Ei.getTextLabel(n,t,i*l,o,r);return a instanceof c.Object3D&&a.add(h),h.position.x=e.x,h.position.y=e.y,h.position.z=e.z,h}static DrawRay(e,t,i=nn,n=0,o=!0){if(!B.enabled)return;const r=Ei.getLine(n),a=r.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),Mt.set(t.x,t.y,t.z).multiplyScalar(999999999),a.setXYZ(1,e.x+Mt.x,e.y+Mt.y,e.z+Mt.z),a.needsUpdate=!0,r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1,rn(r.material,i)}static DrawDirection(e,t,i=nn,n=0,o=!0,r=1){if(!B.enabled)return;const a=Ei.getLine(n),l=a.geometry.getAttribute("position");l.setXYZ(0,e.x,e.y,e.z),t.w!==void 0?(Mt.set(0,0,-r),N_.set(t.x,t.y,t.z,t.w),Mt.applyQuaternion(N_)):(Mt.set(t.x,t.y,t.z),Mt.multiplyScalar(r)),l.setXYZ(1,e.x+Mt.x,e.y+Mt.y,e.z+Mt.z),l.needsUpdate=!0,a.material.depthTest=o,a.material.depthWrite=!1,rn(a.material,i)}static DrawLine(e,t,i=nn,n=0,o=!0){if(!B.enabled)return;const r=Ei.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,rn(r.material,i)}static DrawCircle(e,t,i,n=nn,o=0,r=!0){if(!B.enabled)return;const a=Ei.getCircle(o);a.position.set(e.x,e.y,e.z),a.scale.set(i,i,i),a.quaternion.setFromUnitVectors(this._up,Mt.set(t.x,t.y,t.z).normalize()),a.material.depthTest=r,a.material.depthWrite=!1,a.material.fog=!1,rn(a.material,n)}static DrawWireSphere(e,t,i=nn,n=0,o=!0){if(!B.enabled)return;const r=Ei.getSphere(t,n,!0);hr(r,e.x,e.y,e.z),r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1,rn(r.material,i)}static DrawSphere(e,t,i=nn,n=0,o=!0){if(!B.enabled)return;const r=Ei.getSphere(t,n,!1);hr(r,e.x,e.y,e.z),r.material.depthTest=o,r.material.depthWrite=!1,rn(r.material,i)}static DrawWireBox(e,t,i=nn,n=0,o=!0,r=void 0){if(!B.enabled)return;const a=Ei.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,rn(a.material,i)}static DrawWireBox3(e,t=nn,i=0,n=!0){if(!B.enabled)return;const o=Ei.getBox(i);o.position.copy(e.getCenter(Mt)),o.scale.copy(e.getSize(Mt)),o.material.depthTest=n,o.material.wireframe=!0,o.material.depthWrite=!1,o.material.fog=!1,rn(o.material,t)}static _up=new c.Vector3(0,1,0);static DrawArrow(e,t,i=nn,n=0,o=!0,r=!1){if(!B.enabled)return;const a=Ei.getArrowHead(n);a.position.set(t.x,t.y,t.z),a.quaternion.setFromUnitVectors(this._up.set(0,1,0),Mt.set(t.x,t.y,t.z).sub(z_.set(e.x,e.y,e.z)).normalize());const h=Mt.set(t.x,t.y,t.z).sub(z_.set(e.x,e.y,e.z)).length()*.1;a.scale.set(h,h,h),a.material.depthTest=o,a.material.wireframe=r,rn(a.material,i),this.DrawLine(e,t,i,n,o)}static DrawWireMesh(e){const t=Ei.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,rn(t.material,e.color??nn)}}const hP=new c.BoxGeometry(1,1,1);function fg(s=null){const e=new c.Color(s??14540253),t=new c.EdgesGeometry(hP);return new c.LineSegments(t,new c.LineBasicMaterial({color:e}))}function rn(s,e){if(Array.isArray(s)){for(const i of s)rn(i,e);return}const t=e instanceof te?e.a:1;s.color.set(e),s.opacity=t,s.transparent=t<1}const Zp=Symbol("GizmoCache");class Ei{static familyName="needle-gizmos";static ensureFont(){let e=ie.__webpack_exports__default.FontLibrary.getFontFamily(this.familyName);e||(e=ie.__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",()=>{ie.__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),cP&&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 ie.__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(U.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(U.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(U.Current,t,e,this.linesCache),t}static getCircle(e){let t=this.circlesCache.pop();if(!t){t=new c.Line;let i=t.geometry.getAttribute("position");if(!i){i=new c.BufferAttribute(new Float32Array(Gf*3),3),t.geometry.setAttribute("position",i);const n=F(0,1,0),o=F(0,0,1),r=F(o);r.cross(n).normalize();const a=F(r),l=Math.PI*2/(Gf-1);for(let h=0;h<Gf+1;h++){const d=l*h;n.copy(a).multiplyScalar(Math.cos(d)*1),r.copy(o).multiplyScalar(Math.sin(d)*1);const u=n.add(r);i.setXYZ(h,u.x,u.y,u.z)}}}return t.frustumCulled=!1,this.registerTimedObject(U.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(U.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(U.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(U.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[Zp]=n,t.castShadow=!1,t.receiveShadow=!1,t.isGizmo=!0,this.timedObjectsBuffer.push(t),this.timesBuffer.push(U.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,ie.__webpack_exports__default.update());for(let i=0;i<t.length;i++){const n=t[i];if(e.mainCamera&&n instanceof ie.__webpack_exports__default.MeshUIBaseElement){if(dr(n))continue;const o=e.isInVR,r=!1,a=!o;zc(n,e.mainCamera,r,a)}}}static onPostRender(e,t,i){const n=e.time.realtimeSinceStartup;for(let o=t.length-1;o>=0;o--){const r=t[o];n>=i[o]-1e-6&&(t.splice(o,1),i.splice(o,1),r.removeFromParent(),dr(r)!=!0&&r[Zp].push(r))}}}const Vt=x("debugphysics"),dP=x("debugworker"),V_=new c.Layers;class bo{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){V_.set(e),this.layerMask=V_}setMask(e){this.layerMask||(this.layerMask=new c.Layers);const t=this.layerMask;t?t.mask=e:this.layerMask=e}}class pg{distance;point;object;constructor(e,t,i){this.object=e,this.distance=t,this.point=i}}class La{static _raycasting=0;static get raycasting(){return this._raycasting>0}raycastPhysicsFast(e,t=void 0,i=1/0,n=!0){return this.context.physics.engine?.raycast(e,t,{maxDistance:i,solid:n})??null}raycastPhysicsFastAndGetNormal(e,t=void 0,i=1/0,n=!0){return this.context.physics.engine?.raycastAndGetNormal(e,t,{maxDistance:i,solid:n})??null}sphereOverlapPhysics(e,t){return this.context.physics.engine?.sphereOverlap(e,t)??null}context;engine;constructor(e){this.context=e}raycaster=new c.Raycaster;defaultRaycastOptions=new bo;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){Vt&&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 Vt&&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)),Vt&&console.time("raycast"),o.length=0,La._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))),La._raycasting--,Vt&&(console.timeEnd("raycast"),console.warn("#"+this.context.time.frame+", hits:",o?.length?[...o]:"nothing"),performance.mark("raycast.end"),performance.measure("raycast","raycast.start","raycast.end")),o}intersect(e,t,i,n){for(const o of t){if(!o||o.visible===!1||B.isGizmo(o)||n.lineThreshold!==void 0&&n.lineThreshold<0&&o instanceof c.Line)continue;let r=!0;const a=o,l=a.geometry;if(o.raycastAllowed===!1&&(r=!1),r&&n.testObject){const h=n.testObject?.(o);if(h===!1)continue;h==="continue in children"&&(r=!1)}else r&&(l&&$_(l)||(r=!1));if(r){const h=i.length,d=o.raycastPreference||"lod";let u=d!=="bounds";if(n.precise===!1&&(u=!1),l&&(u||=l.getAttribute("position")?.array?.length<64),a instanceof X.GroundedSkybox&&(u=!1),d==="lod"){const p=re.getRaycastMesh(o);p&&(a.geometry=p)}if(!u&&fP(a,e,i)||(n.useAcceleratedRaycast!==!1?Kd.runMeshBVHRaycast(e,a,i,this.context,n):e.intersectObject(a,!1,i)),a.geometry=l,Vt&&i.length!=h){const p=i[i.length-1];B.DrawWireSphere(p.point,.1,7798784,1,!1),B.DrawWireMesh({mesh:o,depthTest:!1,duration:.2,color:7798784})}}n.recursive!==!1&&this.intersect(e,o.children,i,n)}return i}tempBoundingBox=new c.Box3;intersectSphere(e,t,i,n,o,r,a,l){let h=e&&e.isMesh&&e.layers.test(n)&&!B.isGizmo(e);h&&=e.visible,h&&=!(e instanceof c.Line),h&&=!(e instanceof X.GroundedSkybox);const d=e,u=d.geometry;if(h&&l){const p=l(e);if(p===!1)return;p==="continue in children"&&(h=!1)}if(u&&$_(u)||(h=!1),h){if(a){const p=this.sphere;p.center.copy(t),p.radius=i;const m=o.length;if(Kd.runMeshBVHRaycast(this.sphere,d,o,this.context,{}),m!=o.length&&!r)return}else if(u.boundingBox||u.computeBoundingBox(),u.boundingBox){d.matrixWorldNeedsUpdate&&d.updateWorldMatrix(!1,!1);const p=this.tempBoundingBox.copy(u.boundingBox).applyMatrix4(d.matrixWorld),m=this.sphere;if(m.center.copy(t),m.radius=i,m.intersectsBox(p)){const y=Y(e),_=y.distanceTo(m.center),g=new pg(e,_,y);if(o.push(g),!r)return}}}if(e.children)for(const p of e.children){const m=o.length;if(this.intersectSphere(p,t,i,n,o,r,a,l),m!=o.length&&!r)return}}}function $_(s){return!(s.index&&s.index.array.length<3)}const jo=new c.Sphere,Gh=new c.Plane,uP=new c.Matrix3;function fP(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 X.GroundedSkybox){Gh.setFromNormalAndCoplanarPoint(F(0,1,0),F(0,-l.position.y,0)),Gh.applyMatrix4(l.matrixWorld,uP);const u=o.ray.intersectPlane(Gh,F());if(u){jo.copy(h),jo.applyMatrix4(l.matrixWorld);const m=F(u).sub(o.ray.origin).length(),y=jo.radius*.5;m<y&&r.push({distance:m,point:u,object:l,normal:Gh.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),p=u.length();if(p>jo.radius){const m=u.clone().normalize();r.push({distance:p,point:d,object:l,normal:m})}}}}),s._computeIntersections=n,e.intersectObject(s,!1,t),s._computeIntersections=i,!0}var Kd;(s=>{let e=0;function t(b,w,R,O,M){if(!w.geometry||!w.geometry.hasAttribute("position"))return!1;const D=w.geometry;if(w?.isSkinnedMesh){const L=w,j=L.bvhNeedsUpdate;if(!L.staticGenerator)l(),r&&(L.staticGenerator=new r(w),L.staticGenerator.applyWorldTransforms=!1,L.staticGeometry=L.staticGenerator.generate(),D.boundsTree=a?.call(L.staticGeometry),L.staticGeometryLastUpdate=performance.now()+Math.random()*200,L.bvhNeedsUpdate=!0);else if(D.boundsTree&&(L.autoUpdateMeshBvhInterval!==void 0&&L.autoUpdateMeshBvhInterval>=0||j===!0)){const V=performance.now(),W=V-L.staticGeometryLastUpdate,k=L.autoUpdateMeshBvhInterval??100;(j||W>k)&&(Vt&&console.warn(`Physics: updating skinned mesh bvh for ${w.name} after ${W.toFixed(2)}ms`),L.bvhNeedsUpdate=!1,L.staticGeometryLastUpdate=V,L.staticGenerator?.generate(L.staticGeometry),D.boundsTree.refit())}}else if(!D.boundsTree){d||v();let L=!0;if((O.xr||D[y]===!1||D.getAttribute("position")?.isInterleavedBufferAttribute||D.index&&D.index?.isInterleavedBufferAttribute||e>10)&&(L=!1),L&&p){if(D[m]===void 0){let j=null;if(g.length>0){const V=g.shift();V&&!V.running&&(j=V)}if(!j&&_.length<3)try{dP&&console.warn("[GenerateMeshBVHWorker] Creating worker with import.meta.url:",typeof document>"u"?require("url").pathToFileURL(__filename).href:ga&&ga.tagName.toUpperCase()==="SCRIPT"&&ga.src||new URL("needle-engine.bundle-BVgcWaGl.umd.cjs",document.baseURI).href),j=new p,_.push(j)}catch(V){V instanceof DOMException&&V.name==="SecurityError"?(console.warn("Failed to create MeshBVH worker, falling back to main thread generation. This can happen when running from file://, if the browser does not support workers or if the browser is blocking workers for other reasons."),console.debug(V),e+=10):(console.error("Failed to create MeshBVH worker. Please see below for more details:"),console.log(V)),e++}if(j!=null&&!j.running){const V=w.name;Vt&&console.log("<<<< worker start",V,j),D[m]="queued",performance.mark("bvh.create.start");const W=D.clone();try{j.generate(W).then(k=>{D[m]="done",D.boundsTree=k}).catch(k=>{D[m]="failed - "+k?.message,D[y]=!1,Vt&&console.error("Failed to generate mesh bvh on worker",k)}).finally(()=>{Vt&&console.log(">>>>> worker done",V,{hasBoundsTre:D.boundsTree!=null}),g.push(j),W.dispose(),performance.mark("bvh.create.end"),performance.measure("bvh.create (worker)","bvh.create.start","bvh.create.end")})}catch(k){console.error("Failed to generate mesh bvh on worker",k)}}else Vt&&console.warn("No worker available")}}else(!u||!L)&&(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 L=b,j=w.raycast;if(D.boundsTree)l(),n&&(w.acceleratedRaycast||(w.acceleratedRaycast=n.bind(w),Vt&&console.debug(`Physics: bind acceleratedRaycast fn to "${w.name}"`)),w.raycast=w.acceleratedRaycast);else if(Vt&&console.warn("No bounds tree found for mesh",w.name,{workerTask:D[m],hasAcceleratedRaycast:n!=null}),M.allowSlowRaycastFallback===!1&&(D.getAttribute("position")?.array?.length??0)>2e3)return Vt&&console.warn("Skipping raycast because no bounds tree is available and allowSlowRaycastFallback is false"),!1;const V=L.firstHitOnly;return L.firstHitOnly=!1,L.intersectObject(w,!1,R),L.firstHitOnly=V,w.raycast=j,!0}else if(b instanceof c.Sphere){const L=D.boundsTree;if(L){const j=b;if(h.copy(w.matrixWorld).invert(),j.applyMatrix4(h),L.intersectsSphere(j)){const W=Y(w),k=W.distanceTo(j.center),N=new pg(w,k,W);R.push(N)}}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-BLeytgEr.umd.cjs")).then(b=>b.index$1).then(b=>{n=b.acceleratedRaycast,o=b.MeshBVH,r=b.StaticGeometryGenerator,a=b.computeBoundsTree}).catch(b=>{(Vt||A())&&console.error("Failed to load BVH library...",b.message)}))}const h=new c.Matrix4;let d=!1,u=!1,p=null;const m=Symbol("Needle:MeshBVH-Worker"),y=Symbol("Needle:MeshBVH-CanUseWorker"),_=[],g=[];function v(){d=!0,u=!0,Promise.resolve().then(()=>kA).then(b=>{p=b.GenerateMeshBVHWorker}).catch(b=>{Vt||A()?console.warn("Failed to setup mesh bvh worker"):console.debug("Failed to setup mesh bvh worker",b)}).finally(()=>{u=!1})}})(Kd||(Kd={}));const W_=Symbol("gltf-loader-internal-usage-tracker"),pP=x("debugusers");class wa{get name(){return"NEEDLE_internal_usage_tracker"}static isLoading(e){return wa._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(){wa._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[W_]=e._loadingId),r)),o},null}afterRoot(e){wa._loadingProcesses--,this.parser.getDependency=this._getDependency;for(const t of this._loadedObjects)delete t[W_],t instanceof c.Object3D&&(t.parent||t instanceof c.Mesh&&setTimeout(()=>{pP&&console.warn("> GLTF LOADER: Mesh not used in scene!",t),t.material=null,t.geometry=null},1e3));return null}}class V0{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:
|
|
879
|
+
${o.hand?"hand":"ctrl"} ${o.inputSource.handedness}[${o.index}] con:${o.connected} tr:${o.isTracking} hts:${o.hasHitTestSource?"yes":"no"}`;Vf=0,B.DrawLabel(e,n,void 0,1/60*20)}}onBeforeRender=()=>{this.context.mainCamera&&(this.updateFade(this.context.mainCamera),this.requestedCameraNearPlane!==null&&this.context.mainCamera instanceof c.PerspectiveCamera&&(this.context.mainCamera.near=this.requestedCameraNearPlane,this.requestedCameraNearPlane=null))};onAfterRender=()=>{if(this.onUpdateFade_PostRender(),exports.DeviceUtilities.isDesktop()||!this._renderOnceOnDevice){const e=this.context.renderer;if(e.xr.isPresenting&&this.context.mainCamera){this._renderOnceOnDevice=!0;const t=e.xr.enabled,i=e.getRenderTarget(),n=this.context.scene.background;e.xr.enabled=!1,e.setRenderTarget(null),this.isPassThrough&&(this.context.scene.background=null),this.context.composer?this.context.composer.render(this.context.time.deltaTime):e.render(this.context.scene,this.context.mainCamera),e.xr.enabled=t,e.setRenderTarget(i),this.context.scene.background=n}}};addScript(e){return this._xr_scripts.includes(e)?!1:(Ue&&console.log("Register new XRScript",e),this._xr_scripts.push(e),typeof e.onUpdateXR=="function"&&this._xr_update_scripts.push(e),!0)}markInactive(e){if(!(this._inactive_scripts.indexOf(e)>=0)){this.removeScript(e,!1),this._inactive_scripts.push(e);for(const t of this.controllers)this.invokeCallback_ControllerRemoved(e,t);this.invokeCallback_LeaveXR(e)}}handleInactiveScripts(){if(this._inactive_scripts.length>0)for(let e=this._inactive_scripts.length-1;e>=0;e--){const t=this._inactive_scripts[e];if(t.activeAndEnabled){this._inactive_scripts.splice(e,1),this.addScript(t),this.invokeCallback_EnterXR(t);for(const i of this.controllers)this.invokeCallback_ControllerAdded(t,i)}}}_script_to_remove=[];removeScript(e,t=!0){Ue&&console.log("Remove XRScript",e);const i=this._xr_scripts.indexOf(e);i>=0&&this._xr_scripts.splice(i,1);const n=this._xr_update_scripts.indexOf(e);if(n>=0&&this._xr_update_scripts.splice(n,1),t){const o=this._inactive_scripts.indexOf(e);o>=0&&this._inactive_scripts.splice(o,1)}}invokeCallback_EnterXR(e){e.onEnterXR&&e.onEnterXR({xr:this})}invokeCallback_ControllerAdded(e,t){e.onXRControllerAdded&&e.onXRControllerAdded({xr:this,controller:t,change:"added"})}invokeCallback_ControllerRemoved(e,t){e.onXRControllerRemoved&&e.onXRControllerRemoved({xr:this,controller:t,change:"removed"})}invokeCallback_LeaveXR(e){e.onLeaveXR&&!e.destroyed&&e.onLeaveXR({xr:this})}syncCameraCullingMask(){const e=this.context.xrCamera,t=this.context.mainCameraComponent?.cullingMask;if(e&&t!==void 0){for(const i of e.cameras)i.layers.mask=t;e.layers.mask=t}else if(e){for(const i of e.cameras)i.layers.enableAll();e.layers.enableAll()}}invokeControllerEvent(e,t,i){for(let n=t.length-1;n>=0;n--){const o=t[n];if(o)try{o({xr:this,controller:e,change:i})}catch(r){console.error(r)}}}_camera;_cameraRenderParent=new c.Object3D().rotateY(Math.PI);_previousCameraParent;_customforward=!0;originalCameraNearPlane;requestedCameraNearPlane=null;applyCustomForward(){if(this.context.mainCamera&&this._customforward){this._camera=this.context.mainCamera,this._camera.parent!==this._cameraRenderParent&&(this._previousCameraParent=this._camera.parent,this._previousCameraParent?.add(this._cameraRenderParent)),this._cameraRenderParent.name="XR Camera Render Parent",this._cameraRenderParent.add(this._camera);{let e=.02;const t=.001;if(this.rig){const i=je(this.rig.gameObject);e*=i.x}this._camera instanceof c.PerspectiveCamera&&Math.abs(this._camera.near-e)>t&&(this.isAR?this.originalCameraNearPlane=this._camera.near:this._camera.near=e,Ue&&console.debug(`Setting camera near plane to ${e} (was ${this.originalCameraNearPlane}) to account for XR rendering scale`))}}}revertCustomForward(){this._camera&&this._previousCameraParent&&this._previousCameraParent.add(this._camera),this._previousCameraParent=null,this._camera instanceof c.PerspectiveCamera&&this.originalCameraNearPlane!=null&&(this._camera.near=this.originalCameraNearPlane,this.originalCameraNearPlane=void 0)}_viewerPose;_transformOrientation=new c.Quaternion;_transformPosition=new c.Vector3;internalUpdateState(){const e=this.context.renderer.xr.getReferenceSpace();if(!e){this._viewerPose=void 0;return}if(this._viewerPose=this.frame.getViewerPose(e),this._viewerPose){const t=this._viewerPose.transform;this._transformPosition.set(t.position.x,t.position.y,t.position.z),this._transformOrientation.set(t.orientation.x,t.orientation.y,t.orientation.z,t.orientation.w)}}_transition;get transition(){return this._transition||(this._transition=new F_),this._transition}fadeTransition(){return this._transition||(this._transition=new F_),this._transition.fadeTransition()}updateFade(e){this._transition&&e instanceof c.PerspectiveCamera&&this._transition.update(e,this.context.time.deltaTime)}onUpdateFade_PostRender(){this._transition?.remove()}}const Wf=x("debugwebxr");class N0{static tryFindAvatarObjects(e,t,i){if(i.head&&i.leftHand&&i.rightHand)return;const n=e.name.toLocaleLowerCase();!i.head&&n.includes("head")&&(Wf&&console.log("FOUND AVATAR HEAD",e.name),i.head=new Z("",t,e)),n.includes("hand")&&(!i.leftHand&&n.includes("left")&&(Wf&&console.log("FOUND AVATAR LEFT HAND",e.name),i.leftHand=new Z("",t,e)),!i.rightHand&&n.includes("right")&&(Wf&&console.log("FOUND AVATAR RIGHT HAND",e.name),i.rightHand=new Z("",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 te extends c.Color{alpha=1;get isRGBAColor(){return!0}set a(e){this.alpha=e}get a(){return this.alpha}constructor(e,t,i,n){super(),typeof e=="number"&&typeof t=="number"&&typeof i=="number"?(this.set(e,t,i),this.alpha=typeof n=="number"?n:1):e!==void 0&&(this.set(e),this.alpha=1)}clone(){const e=super.clone();return e.alpha=this.alpha,e}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,"alpha"in e&&typeof e.alpha=="number"?this.alpha=e.alpha:typeof e.a=="number"&&(this.alpha=e.a),this}lerp(e,t){const i=e;return i.alpha!=null&&(this.alpha=I.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=I.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 te(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 te(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 te(i/255,n/255,o/255,1)}else if(e.startsWith("rgba")){const t=e.slice(5,-1).split(",").map(Number);return new te(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 te(t[0]/255,t[1]/255,t[2]/255,1)}}else if(Array.isArray(e)){if(e.length===4)return new te(e[0],e[1],e[2],e[3]);if(e.length===3)return new te(e[0],e[1],e[2],1);console.error("Invalid color array length. Expected 3 or 4, got "+e.length)}return new te(e)}}const Mt=new c.Vector3,z_=new c.Vector3,N_=new c.Quaternion,cP=x("debuggizmos"),nn=8947848,Gf=32;class B{constructor(){}static enabled=!0;static isGizmo(e){return e[Zp]!==void 0}static setVisible(e){for(const t of Ei.timedObjectsBuffer)t.visible=e}static DrawLabel(e,t,i=.05,n=0,o,r,a){if(!B.enabled)return null;o||(o=nn);const l=q.active?.rigScale??1,h=Ei.getTextLabel(n,t,i*l,o,r);return a instanceof c.Object3D&&a.add(h),h.position.x=e.x,h.position.y=e.y,h.position.z=e.z,h}static DrawRay(e,t,i=nn,n=0,o=!0){if(!B.enabled)return;const r=Ei.getLine(n),a=r.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),Mt.set(t.x,t.y,t.z).multiplyScalar(999999999),a.setXYZ(1,e.x+Mt.x,e.y+Mt.y,e.z+Mt.z),a.needsUpdate=!0,r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1,rn(r.material,i)}static DrawDirection(e,t,i=nn,n=0,o=!0,r=1){if(!B.enabled)return;const a=Ei.getLine(n),l=a.geometry.getAttribute("position");l.setXYZ(0,e.x,e.y,e.z),t.w!==void 0?(Mt.set(0,0,-r),N_.set(t.x,t.y,t.z,t.w),Mt.applyQuaternion(N_)):(Mt.set(t.x,t.y,t.z),Mt.multiplyScalar(r)),l.setXYZ(1,e.x+Mt.x,e.y+Mt.y,e.z+Mt.z),l.needsUpdate=!0,a.material.depthTest=o,a.material.depthWrite=!1,rn(a.material,i)}static DrawLine(e,t,i=nn,n=0,o=!0){if(!B.enabled)return;const r=Ei.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,rn(r.material,i)}static DrawCircle(e,t,i,n=nn,o=0,r=!0){if(!B.enabled)return;const a=Ei.getCircle(o);a.position.set(e.x,e.y,e.z),a.scale.set(i,i,i),a.quaternion.setFromUnitVectors(this._up,Mt.set(t.x,t.y,t.z).normalize()),a.material.depthTest=r,a.material.depthWrite=!1,a.material.fog=!1,rn(a.material,n)}static DrawWireSphere(e,t,i=nn,n=0,o=!0){if(!B.enabled)return;const r=Ei.getSphere(t,n,!0);hr(r,e.x,e.y,e.z),r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1,rn(r.material,i)}static DrawSphere(e,t,i=nn,n=0,o=!0){if(!B.enabled)return;const r=Ei.getSphere(t,n,!1);hr(r,e.x,e.y,e.z),r.material.depthTest=o,r.material.depthWrite=!1,rn(r.material,i)}static DrawWireBox(e,t,i=nn,n=0,o=!0,r=void 0){if(!B.enabled)return;const a=Ei.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,rn(a.material,i)}static DrawWireBox3(e,t=nn,i=0,n=!0){if(!B.enabled)return;const o=Ei.getBox(i);o.position.copy(e.getCenter(Mt)),o.scale.copy(e.getSize(Mt)),o.material.depthTest=n,o.material.wireframe=!0,o.material.depthWrite=!1,o.material.fog=!1,rn(o.material,t)}static _up=new c.Vector3(0,1,0);static DrawArrow(e,t,i=nn,n=0,o=!0,r=!1){if(!B.enabled)return;const a=Ei.getArrowHead(n);a.position.set(t.x,t.y,t.z),a.quaternion.setFromUnitVectors(this._up.set(0,1,0),Mt.set(t.x,t.y,t.z).sub(z_.set(e.x,e.y,e.z)).normalize());const h=Mt.set(t.x,t.y,t.z).sub(z_.set(e.x,e.y,e.z)).length()*.1;a.scale.set(h,h,h),a.material.depthTest=o,a.material.wireframe=r,rn(a.material,i),this.DrawLine(e,t,i,n,o)}static DrawWireMesh(e){const t=Ei.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,rn(t.material,e.color??nn)}}const hP=new c.BoxGeometry(1,1,1);function fg(s=null){const e=new c.Color(s??14540253),t=new c.EdgesGeometry(hP);return new c.LineSegments(t,new c.LineBasicMaterial({color:e}))}function rn(s,e){if(Array.isArray(s)){for(const i of s)rn(i,e);return}const t=e instanceof te?e.a:1;s.color.set(e),s.opacity=t,s.transparent=t<1}const Zp=Symbol("GizmoCache");class Ei{static familyName="needle-gizmos";static ensureFont(){let e=ie.__webpack_exports__default.FontLibrary.getFontFamily(this.familyName);e||(e=ie.__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",()=>{ie.__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),cP&&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 ie.__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(U.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(U.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(U.Current,t,e,this.linesCache),t}static getCircle(e){let t=this.circlesCache.pop();if(!t){t=new c.Line;let i=t.geometry.getAttribute("position");if(!i){i=new c.BufferAttribute(new Float32Array(Gf*3),3),t.geometry.setAttribute("position",i);const n=F(0,1,0),o=F(0,0,1),r=F(o);r.cross(n).normalize();const a=F(r),l=Math.PI*2/(Gf-1);for(let h=0;h<Gf+1;h++){const d=l*h;n.copy(a).multiplyScalar(Math.cos(d)*1),r.copy(o).multiplyScalar(Math.sin(d)*1);const u=n.add(r);i.setXYZ(h,u.x,u.y,u.z)}}}return t.frustumCulled=!1,this.registerTimedObject(U.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(U.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(U.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(U.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[Zp]=n,t.castShadow=!1,t.receiveShadow=!1,t.isGizmo=!0,this.timedObjectsBuffer.push(t),this.timesBuffer.push(U.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,ie.__webpack_exports__default.update());for(let i=0;i<t.length;i++){const n=t[i];if(e.mainCamera&&n instanceof ie.__webpack_exports__default.MeshUIBaseElement){if(dr(n))continue;const o=e.isInVR,r=!1,a=!o;zc(n,e.mainCamera,r,a)}}}static onPostRender(e,t,i){const n=e.time.realtimeSinceStartup;for(let o=t.length-1;o>=0;o--){const r=t[o];n>=i[o]-1e-6&&(t.splice(o,1),i.splice(o,1),r.removeFromParent(),dr(r)!=!0&&r[Zp].push(r))}}}const Vt=x("debugphysics"),dP=x("debugworker"),V_=new c.Layers;class bo{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){V_.set(e),this.layerMask=V_}setMask(e){this.layerMask||(this.layerMask=new c.Layers);const t=this.layerMask;t?t.mask=e:this.layerMask=e}}class pg{distance;point;object;constructor(e,t,i){this.object=e,this.distance=t,this.point=i}}class La{static _raycasting=0;static get raycasting(){return this._raycasting>0}raycastPhysicsFast(e,t=void 0,i=1/0,n=!0){return this.context.physics.engine?.raycast(e,t,{maxDistance:i,solid:n})??null}raycastPhysicsFastAndGetNormal(e,t=void 0,i=1/0,n=!0){return this.context.physics.engine?.raycastAndGetNormal(e,t,{maxDistance:i,solid:n})??null}sphereOverlapPhysics(e,t){return this.context.physics.engine?.sphereOverlap(e,t)??null}context;engine;constructor(e){this.context=e}raycaster=new c.Raycaster;defaultRaycastOptions=new bo;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){Vt&&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 Vt&&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)),Vt&&console.time("raycast"),o.length=0,La._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))),La._raycasting--,Vt&&(console.timeEnd("raycast"),console.warn("#"+this.context.time.frame+", hits:",o?.length?[...o]:"nothing"),performance.mark("raycast.end"),performance.measure("raycast","raycast.start","raycast.end")),o}intersect(e,t,i,n){for(const o of t){if(!o||o.visible===!1||B.isGizmo(o)||n.lineThreshold!==void 0&&n.lineThreshold<0&&o instanceof c.Line)continue;let r=!0;const a=o,l=a.geometry;if(o.raycastAllowed===!1&&(r=!1),r&&n.testObject){const h=n.testObject?.(o);if(h===!1)continue;h==="continue in children"&&(r=!1)}else r&&(l&&$_(l)||(r=!1));if(r){const h=i.length,d=o.raycastPreference||"lod";let u=d!=="bounds";if(n.precise===!1&&(u=!1),l&&(u||=l.getAttribute("position")?.array?.length<64),a instanceof X.GroundedSkybox&&(u=!1),d==="lod"){const p=re.getRaycastMesh(o);p&&(a.geometry=p)}if(!u&&fP(a,e,i)||(n.useAcceleratedRaycast!==!1?Kd.runMeshBVHRaycast(e,a,i,this.context,n):e.intersectObject(a,!1,i)),a.geometry=l,Vt&&i.length!=h){const p=i[i.length-1];B.DrawWireSphere(p.point,.1,7798784,1,!1),B.DrawWireMesh({mesh:o,depthTest:!1,duration:.2,color:7798784})}}n.recursive!==!1&&this.intersect(e,o.children,i,n)}return i}tempBoundingBox=new c.Box3;intersectSphere(e,t,i,n,o,r,a,l){let h=e&&e.isMesh&&e.layers.test(n)&&!B.isGizmo(e);h&&=e.visible,h&&=!(e instanceof c.Line),h&&=!(e instanceof X.GroundedSkybox);const d=e,u=d.geometry;if(h&&l){const p=l(e);if(p===!1)return;p==="continue in children"&&(h=!1)}if(u&&$_(u)||(h=!1),h){if(a){const p=this.sphere;p.center.copy(t),p.radius=i;const m=o.length;if(Kd.runMeshBVHRaycast(this.sphere,d,o,this.context,{}),m!=o.length&&!r)return}else if(u.boundingBox||u.computeBoundingBox(),u.boundingBox){d.matrixWorldNeedsUpdate&&d.updateWorldMatrix(!1,!1);const p=this.tempBoundingBox.copy(u.boundingBox).applyMatrix4(d.matrixWorld),m=this.sphere;if(m.center.copy(t),m.radius=i,m.intersectsBox(p)){const y=Y(e),_=y.distanceTo(m.center),g=new pg(e,_,y);if(o.push(g),!r)return}}}if(e.children)for(const p of e.children){const m=o.length;if(this.intersectSphere(p,t,i,n,o,r,a,l),m!=o.length&&!r)return}}}function $_(s){return!(s.index&&s.index.array.length<3)}const jo=new c.Sphere,Gh=new c.Plane,uP=new c.Matrix3;function fP(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 X.GroundedSkybox){Gh.setFromNormalAndCoplanarPoint(F(0,1,0),F(0,-l.position.y,0)),Gh.applyMatrix4(l.matrixWorld,uP);const u=o.ray.intersectPlane(Gh,F());if(u){jo.copy(h),jo.applyMatrix4(l.matrixWorld);const m=F(u).sub(o.ray.origin).length(),y=jo.radius*.5;m<y&&r.push({distance:m,point:u,object:l,normal:Gh.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),p=u.length();if(p>jo.radius){const m=u.clone().normalize();r.push({distance:p,point:d,object:l,normal:m})}}}}),s._computeIntersections=n,e.intersectObject(s,!1,t),s._computeIntersections=i,!0}var Kd;(s=>{let e=0;function t(b,w,R,O,M){if(!w.geometry||!w.geometry.hasAttribute("position"))return!1;const D=w.geometry;if(w?.isSkinnedMesh){const L=w,j=L.bvhNeedsUpdate;if(!L.staticGenerator)l(),r&&(L.staticGenerator=new r(w),L.staticGenerator.applyWorldTransforms=!1,L.staticGeometry=L.staticGenerator.generate(),D.boundsTree=a?.call(L.staticGeometry),L.staticGeometryLastUpdate=performance.now()+Math.random()*200,L.bvhNeedsUpdate=!0);else if(D.boundsTree&&(L.autoUpdateMeshBvhInterval!==void 0&&L.autoUpdateMeshBvhInterval>=0||j===!0)){const V=performance.now(),W=V-L.staticGeometryLastUpdate,k=L.autoUpdateMeshBvhInterval??100;(j||W>k)&&(Vt&&console.warn(`Physics: updating skinned mesh bvh for ${w.name} after ${W.toFixed(2)}ms`),L.bvhNeedsUpdate=!1,L.staticGeometryLastUpdate=V,L.staticGenerator?.generate(L.staticGeometry),D.boundsTree.refit())}}else if(!D.boundsTree){d||v();let L=!0;if((O.xr||D[y]===!1||D.getAttribute("position")?.isInterleavedBufferAttribute||D.index&&D.index?.isInterleavedBufferAttribute||e>10)&&(L=!1),L&&p){if(D[m]===void 0){let j=null;if(g.length>0){const V=g.shift();V&&!V.running&&(j=V)}if(!j&&_.length<3)try{dP&&console.warn("[GenerateMeshBVHWorker] Creating worker with import.meta.url:",typeof document>"u"?require("url").pathToFileURL(__filename).href:ga&&ga.tagName.toUpperCase()==="SCRIPT"&&ga.src||new URL("needle-engine.bundle-DDZfnvgI.umd.cjs",document.baseURI).href),j=new p,_.push(j)}catch(V){V instanceof DOMException&&V.name==="SecurityError"?(console.warn("Failed to create MeshBVH worker, falling back to main thread generation. This can happen when running from file://, if the browser does not support workers or if the browser is blocking workers for other reasons."),console.debug(V),e+=10):(console.error("Failed to create MeshBVH worker. Please see below for more details:"),console.log(V)),e++}if(j!=null&&!j.running){const V=w.name;Vt&&console.log("<<<< worker start",V,j),D[m]="queued",performance.mark("bvh.create.start");const W=D.clone();try{j.generate(W).then(k=>{D[m]="done",D.boundsTree=k}).catch(k=>{D[m]="failed - "+k?.message,D[y]=!1,Vt&&console.error("Failed to generate mesh bvh on worker",k)}).finally(()=>{Vt&&console.log(">>>>> worker done",V,{hasBoundsTre:D.boundsTree!=null}),g.push(j),W.dispose(),performance.mark("bvh.create.end"),performance.measure("bvh.create (worker)","bvh.create.start","bvh.create.end")})}catch(k){console.error("Failed to generate mesh bvh on worker",k)}}else Vt&&console.warn("No worker available")}}else(!u||!L)&&(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 L=b,j=w.raycast;if(D.boundsTree)l(),n&&(w.acceleratedRaycast||(w.acceleratedRaycast=n.bind(w),Vt&&console.debug(`Physics: bind acceleratedRaycast fn to "${w.name}"`)),w.raycast=w.acceleratedRaycast);else if(Vt&&console.warn("No bounds tree found for mesh",w.name,{workerTask:D[m],hasAcceleratedRaycast:n!=null}),M.allowSlowRaycastFallback===!1&&(D.getAttribute("position")?.array?.length??0)>2e3)return Vt&&console.warn("Skipping raycast because no bounds tree is available and allowSlowRaycastFallback is false"),!1;const V=L.firstHitOnly;return L.firstHitOnly=!1,L.intersectObject(w,!1,R),L.firstHitOnly=V,w.raycast=j,!0}else if(b instanceof c.Sphere){const L=D.boundsTree;if(L){const j=b;if(h.copy(w.matrixWorld).invert(),j.applyMatrix4(h),L.intersectsSphere(j)){const W=Y(w),k=W.distanceTo(j.center),N=new pg(w,k,W);R.push(N)}}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-Csj7XHEr.umd.cjs")).then(b=>b.index$1).then(b=>{n=b.acceleratedRaycast,o=b.MeshBVH,r=b.StaticGeometryGenerator,a=b.computeBoundsTree}).catch(b=>{(Vt||A())&&console.error("Failed to load BVH library...",b.message)}))}const h=new c.Matrix4;let d=!1,u=!1,p=null;const m=Symbol("Needle:MeshBVH-Worker"),y=Symbol("Needle:MeshBVH-CanUseWorker"),_=[],g=[];function v(){d=!0,u=!0,Promise.resolve().then(()=>kA).then(b=>{p=b.GenerateMeshBVHWorker}).catch(b=>{Vt||A()?console.warn("Failed to setup mesh bvh worker"):console.debug("Failed to setup mesh bvh worker",b)}).finally(()=>{u=!1})}})(Kd||(Kd={}));const W_=Symbol("gltf-loader-internal-usage-tracker"),pP=x("debugusers");class wa{get name(){return"NEEDLE_internal_usage_tracker"}static isLoading(e){return wa._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(){wa._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[W_]=e._loadingId),r)),o},null}afterRoot(e){wa._loadingProcesses--,this.parser.getDependency=this._getDependency;for(const t of this._loadedObjects)delete t[W_],t instanceof c.Object3D&&(t.parent||t instanceof c.Mesh&&setTimeout(()=>{pP&&console.warn("> GLTF LOADER: Mesh not used in scene!",t),t.material=null,t.geometry=null},1e3));return null}}class V0{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:
|
|
880
880
|
`+i.src),e.preventDefault())}})}}const Cu=x("trackresources");function $0(){return Cu==="dispose"}let br=!0;Cu===0&&(br=!1);function mP(s){br=s}function W0(){return br}const G0=Symbol("disposable");function H0(s,e){s&&(s[G0]=e,nr&&console.warn("Set disposable",e,s))}const q0=Symbol("disposed");function gP(s){return s[q0]===!0}function we(s){if(s){if(s[G0]===!1){nr&&console.warn("Object is marked as not disposable",s);return}if(typeof s=="object"&&(s[q0]=!0),s instanceof c.Scene)we(s.environment),we(s.background),we(s.customDepthMaterial),we(s.customDistanceMaterial);else if(s instanceof c.SkinnedMesh)we(s.geometry),we(s.material),we(s.skeleton),we(s.bindMatrix),we(s.bindMatrixInverse),we(s.customDepthMaterial),we(s.customDistanceMaterial),s.visible=!1;else if(s instanceof c.Mesh)we(s.geometry),we(s.material),we(s.customDepthMaterial),we(s.customDistanceMaterial),s.visible=!1;else if(s instanceof c.Object3D)s.visible=!1;else if(s instanceof c.BufferGeometry){Gr(s);for(const e of Object.keys(s.attributes)){const t=s.attributes[e];we(t)}}else if(s instanceof c.BufferAttribute||s instanceof c.InterleavedBufferAttribute)nr&&console.warn("BufferAttribute dispose not supported",s.count);else if(s instanceof Array)for(const e of s)e instanceof c.Material&&we(e);else if(s instanceof c.Material){Gr(s);for(const t of Object.keys(s)){const i=s[t];i instanceof c.Texture&&we(i)}const e=s.uniforms;if(e)for(const t of Object.keys(e)){const i=e[t];i instanceof c.Texture?we(i):i instanceof c.Uniform$1&&we(i.value)}}else s instanceof c.Texture?(Gr(s),Gr(s.source),s.source?.data instanceof ImageBitmap&&Gr(s.source.data)):s instanceof c.Skeleton?(Gr(s.boneTexture),s.boneTexture=null):s instanceof c.Bone||!(s instanceof c.Object3D)&&nr&&console.warn("Unknown object type",s)}}function Gr(s){s&&((nr||$0()||Cu)&&console.warn("🧨 FREE",s),s instanceof ImageBitmap||"dispose"in s&&typeof s.dispose=="function"&&s.dispose())}function yP(s){}const _P=new Set;function mg(s,e,t=null,i){if(i||(i=_P,i.clear()),!s)return i;const n=s[xc];if(n)for(const o of n)i.has(o)||t?.call(null,o)!==!1&&(i.add(o),e&&mg(o,!0,t,i));return i}function bP(s){return s[zl]}const nr=x("debugresourceusers")||x("debugmemory"),xc=Symbol("needle-resource-users"),zl=Symbol("needle-resource-users-count");function Bt(s,e){gu(s,e,function(t,i){br&&!La.raycasting&&(Zd(xc,this,t,!1),Zd(xc,this,i,!0))})}br&&(Bt(c.Mesh.prototype,"material"),Bt(c.Mesh.prototype,"geometry"),Bt(c.Material.prototype,"map"),Bt(c.Material.prototype,"bumpMap"),Bt(c.Material.prototype,"alphaMap"),Bt(c.Material.prototype,"normalMap"),Bt(c.Material.prototype,"displacementMap"),Bt(c.Material.prototype,"roughnessMap"),Bt(c.Material.prototype,"metalnessMap"),Bt(c.Material.prototype,"emissiveMap"),Bt(c.Material.prototype,"specularMap"),Bt(c.Material.prototype,"envMap"),Bt(c.Material.prototype,"lightMap"),Bt(c.Material.prototype,"aoMap"),Bt(c.Material.prototype,"gradientMap"));function vP(s){if(br===!1)return;const e=s[xc];if(e)for(const t of e)Zd(xc,t,s,!1)}br&&gu(c.Material.prototype,"dispose",function(){vP(this)});let Jp=0;function Zd(s,e,t,i){if(Jp>0)return;if(Array.isArray(t)){for(const o of t)Zd(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[zl]||0;o+=1,t[zl]=o,nr&&console.warn(`🟢 Added user of "${t.type}"`,e,t,o,"users:",n)}}else if(e&&n.has(e)){n.delete(e);let o=t[zl]||0;o>0&&(o-=1,t[zl]=o),nr&&console.warn(`🔴 Removed user of "${t.type}"`,e,t,o,"users:",n),o<=0&&(wa.isLoading(t)||(Cu&&console.warn(`🔴 Removed all user of "${t.type}"`,t),$0()&&we(t)))}t[s]=n}try{gu(c.WebGLRenderer.prototype,"render",function(){Jp++},function(){Jp--})}catch(s){console.warn("Could not wrap WebGLRenderer.render",s)}const Sc=Symbol("NEEDLE_NEED_UPDATE_INSTANCE"),X0=Symbol("isUsingInstancing"),Q0=Symbol("instancingRenderer"),Nl=Symbol("instancingAutoUpdateBounds");class Ni{static isUsingInstancing(e){return e[X0]===!0}static getRenderer(e){return e[Q0]||null}setAutoUpdateBounds(e,t){const i=Ni.getRenderer(e);i&&(i[Nl]=t)}static markDirty(e,t=!0){if(e&&(this.isUsingInstancing(e)&&(e[Sc]=!0,e.matrixWorldNeedsUpdate=!0),t))for(const i of e.children)Ni.markDirty(i,!0)}}const Y0=new Map;function K0(s,e){if(!s)return;if(!e){console.warn("No prototype found",s,s.prototype,s.constructor);return}const t=Y0.get(e);t&&t.apply(s)}function gg(s){const e=wP(s.prototype);Y0.set(s,e)}function wP(s){return new xP(s)}class xP{$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 Pu(s){s&&s.isObject3D===!0&&K0(s,c.Object3D)}let G_=!1;function SP(){if(G_)return;if(G_=!0,qm.experimentalSmartHierarchyUpdate){const i=c.Object3D.prototype.add;c.Object3D.prototype.add=function(...r){return qf(),i.apply(this,r)};const n=c.Object3D.prototype.attach;c.Object3D.prototype.attach=function(...r){return qf(),n.apply(this,r)};const o=c.Object3D.prototype.remove;c.Object3D.prototype.remove=function(...r){return qf(),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(){bi(this)},c.Object3D.prototype.addComponent=function(i,n){return hn(this,i,n)},c.Object3D.prototype.addNewComponent=function(i,n){return hn(this,i,n)},c.Object3D.prototype.removeComponent=function(i){return bg(this,i)},c.Object3D.prototype.getOrAddComponent=function(i,n){return qc(this,i,n)},c.Object3D.prototype.getComponent=function(i){return vr(this,i)},c.Object3D.prototype.getComponents=function(i,n){return Xc(this,i,n)},c.Object3D.prototype.getComponentInChildren=function(i,n=!1){return Qc(this,i,n)},c.Object3D.prototype.getComponentsInChildren=function(i,n){return $a(this,i,n)},c.Object3D.prototype.getComponentInParent=function(i,n=!1){return Cc(this,i,n)},c.Object3D.prototype.getComponentsInParent=function(i,n){return ku(this,i,n)},Object.getOwnPropertyDescriptor(c.Object3D.prototype,"activeSelf")||Object.defineProperty(c.Object3D.prototype,"activeSelf",{get:function(){return Va(this)},set:function(i){sc(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 X.TransformControlsGizmo?Y(this.object):Y(this)},set:function(i){at(this,i)}}),Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldQuaternion")||Object.defineProperty(c.Object3D.prototype,"worldQuaternion",{get:function(){return this instanceof X.TransformControlsGizmo?pe(this.object):pe(this)},set:function(i){dn(this,i)}}),Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldRotation")||Object.defineProperty(c.Object3D.prototype,"worldRotation",{get:function(){return pu(this)},set:function(i){Ev(this,i)}}),Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldScale")||Object.defineProperty(c.Object3D.prototype,"worldScale",{get:function(){return je(this)},set:function(i){Ma(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(pe(this))},set:function(i){const n=ei().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(pe(this))}}),Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldUp")||Object.defineProperty(c.Object3D.prototype,"worldUp",{get:function(){return F().set(0,1,0).applyQuaternion(pe(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}}),gg(c.Object3D)}const bd=x("debuggetcomponent"),sr=x("debuginstantiate");class gn{idProvider;parent;keepWorldPosition;position;rotation;scale;visible;context;components;clone(){const e=new gn;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 Va(s){return s.visible}function sc(s,e){return typeof e=="number"&&(e=e>.5),s.visible=e,s.visible}function Z0(s){return s[jn]||Ou(s)}function J0(s,e){s[X0]=e}function Ou(s){return Ni.isUsingInstancing(s)}function yg(s,e){return Oa(s,e,!0,!0)}const ew=Symbol("isDestroyed");function dr(s){return s[ew]}function tw(s,e){s[ew]=e}const em=Symbol("isDontDestroy");function ta(s,e=!0){s[em]=e}const vd=[],wd=[];function bi(s,e=!0,t=!1){vd.length=0,wd.length=0,tm(s,e,!0);for(const i of vd)i.gameObject=null,i.context=null;for(const i of wd)tw(i,!0),t&&we(i);wd.length=0,vd.length=0}function tm(s,e=!0,t=!0){if(s==null)return;const i=s;if(i.isComponent){if(i[em])return;vd.push(i);const r=i.gameObject;i.__internalDisable(),i.__internalDestroy(),i.gameObject=r;return}if(s[em])return;const n=s;bd&&console.log(n),wd.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];tm(l,e,!1),o.length<r&&(r=o.length,a--)}}if(e&&n.children)for(const r of n.children)tm(r,e,!1);t&&n.removeFromParent()}function ur(s,e,t=!0){return iw(s,e,t)}function*Mu(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*Mu(o,e,!0,i,n+1)}}function iw(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=iw(r,e,t,n);if(a!==void 0)return a}}}}function ho(s,e){if("isAssetReference"in s)return s.instantiate(e??void 0);let t=null;e!=null&&(e.x!==void 0?(t=new gn,t.position=e):t=e);let i=U.Current;t?.context&&(i=t.context),bd&&i.alias&&console.log("context",i.alias),t&&!t.idProvider&&(t.idProvider=new xt(Date.now()));const n=[],o={},r={},a=nw(i,s,t,n,o,r);a&&(OP(a,o),PP(r,o)),bd&&(Nd(s,!0),Nd(a,!0));const l={};if(t?.components!==!1){for(const h in n){const d=n[h],u=d.guid;t&&t.idProvider&&(d.guid=t.idProvider.generateUUID(),l[u]=d.guid,bd&&console.log(d.name,d.guid)),Su(d,i),d.__internalNewInstanceCreated&&d.__internalNewInstanceCreated()}for(const h in n){const d=n[h];d.resolveGuids&&d.resolveGuids(l),d.enabled!==!1&&(d.enabled=!0)}Jd(i)}return a}function nw(s,e,t,i,n,o){if(!e||e[pi])return null;const r=e.userData;e.userData={};const a=e.children;e.children=[];const l=e.clone(!1);if(Pu(l),e.userData=r,e.children=a,n[e.uuid]={original:e,clone:l},sr&&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){l.uuid=t.idProvider.generateUUID();const d=l;d&&(d.guid=l.uuid)}e.animations&&e.animations.length>0&&(l.animations=[...e.animations]);const h=e.parent;if(h&&h.add(l),t?.position)if(Array.isArray(t.position)){const d=new c.Vector3;d.fromArray(t.position),l.worldPosition=d}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=ei().setFromEuler(t.rotation);else if(Array.isArray(t.rotation)){const d=new c.Euler;d.fromArray(t.rotation),l.worldQuaternion=ei().setFromEuler(d)}}else l.quaternion.copy(e.quaternion);if(t?.scale)if(Array.isArray(t.scale)){const d=new c.Vector3;d.fromArray(t.scale),t.scale=d}else l.scale.copy(t.scale);else l.scale.copy(e.scale);if(t?.parent&&t.parent!=="scene"){let d=null;if(typeof t.parent=="string"?d=Oa(t.parent,s.scene,!0):d=t.parent,d){const u=t.keepWorldPosition===!0?d.attach:d.add;u?u.call(d,l):console.error("Invalid parent object",d,"received when instantiating:",e)}else console.warn("could not find parent:",t.parent)}for(const[d,u]of Object.entries(e.userData))d!=="components"&&(l.userData[d]=u);if(e.userData?.components){const d=e.userData.components,u=[];l.userData.components=u;for(let p=0;p<d.length;p++){const m=d[p],y=new m.constructor;CP(m,y),m[ec]!==void 0&&(y[ec]=m[ec]),u.push(y),y.gameObject=l,i.push(y),n[m.guid]={original:m,clone:y},mu.dispatchComponentLifecycleEvent("component-added",y)}}t&&(t.position=void 0,t.rotation=void 0,t.scale=void 0,t.parent=void 0,t.visible=void 0);for(const d in e.children){const u=e.children[d],p=nw(s,u,t,i,n,o);p&&(n[p.uuid]={original:u,clone:p},l.add(p))}return l}function CP(s,e,t){Ea(e,s,void 0,{})}function PP(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 OP(s,e){for(const t in e){const n=e[t].clone;if(n?.isObject3D&&n?.userData?.components)for(let o=0;o<n.userData.components.length;o++){const r=n.userData.components[o],a=Object.entries(r);for(const[l,h]of a)if(Array.isArray(h)){const d=[];r[l]=d;for(let u=0;u<h.length;u++){const p=h[u];if(typeof p!="object"){d.push(p);continue}const m=H_(r,l,p,e);m!==void 0?(sr&&console.log("Found new instance for",l,p,"->",m),d.push(m)):(sr&&console.warn("Could not find new instance for",l,p),d.push(p))}}else if(typeof h=="object"){const d=H_(r,l,h,e);d!==void 0?r[l]=d:sr&&console.warn("Could not find new instance for",l,h)}}}}function H_(s,e,t,i){if(t!=null)if(t.isComponent===!0){const n=t.gameObject;if(n){const o=n.uuid,r=i[o]?.clone;if(!r){sr&&console.log("reference did not change",e,s,t);return}const a=n.userData.components.indexOf(t);if(a>=0&&r.isObject3D)return sr&&console.log(e,o),r.userData.components[a];console.warn("could not find component",e,t)}}else if(t.isObject3D===!0){if(e==="gameObject")return;const n=t;if(n){const o=n.uuid,r=i[o]?.clone;if(r)return sr&&console.log(e,"old",t,"new",r),r}}else{if(t.isVector4||t.isVector3||t.isVector2||t.isQuaternion||t.isEuler)return t.clone();if(t.isColor===!0)return t.clone();if(t.isEventList===!0)return t.__internalOnInstantiate(i)}}function oc(s,e){try{e||s()}catch(t){return console.error(t),!1}return!0}const im=x("debugnewscripts"),MP=x("debughierarchy"),Ce=[];function kP(){return Ce.length>0}function Jd(s){if(im&&console.log("Register new components",s.new_scripts.length,[...s.new_scripts],s.alias?"element: "+s.alias:s.hash,s),s.new_scripts_pre_setup_callbacks.length>0){for(const e of s.new_scripts_pre_setup_callbacks)e&&e();s.new_scripts_pre_setup_callbacks.length=0}if(!(s.new_scripts.length<=0)){Ce.length=0,s.new_scripts.length>0&&Ce.push(...s.new_scripts),s.new_scripts.length=0;for(let e=0;e<Ce.length;e++)try{const t=Ce[e];if(t.isComponent!==!0){(A()||im)&&console.error(`Registered script is not a Needle Engine component.
|
|
881
881
|
The script will be ignored. Please make sure your component extends "Behaviour" imported from "@needle-tools/engine"
|
|
882
882
|
`,t),Ce.splice(e,1),e--;continue}if(t.destroyed)continue;if(!t.gameObject){console.warn(`Component can not be initialized: no GameObject assigned.
|
|
@@ -997,7 +997,7 @@ Consider registering a custom loader via the 'onCreateCustomModelLoader' callbac
|
|
|
997
997
|
Content-Type: "${t.headers.get("content-type")}"
|
|
998
998
|
"Text: "${o}"
|
|
999
999
|
Binary:`,i)}else ke&&console.debug("Could not determine file type from binary data");return"unknown"}const ep=x("debugstencil");function SM(s,e){return(s&1<<e.layer)!=0}const CM=Symbol("stencils");class to{get name(){return"NEEDLE_render_objects"}static stencils={};static applyStencil(e){if(!e)return;const t=e.sourceId;if(ep&&console.log(t,to.stencils),!t)return;const i=to.stencils[t];if(i)for(let n=i.length-1;n>=0;n--){const o=i[n];if(SM(o.layer,e)){ep&&console.log(o),setTimeout(()=>{yi()&&Ou(e.gameObject)&&(fe("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[CM]=!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[OM];if(i){ep&&console.log(i);const n=i.stencil;if(n&&Array.isArray(n))for(const o of n){const r={...o};r.compareFunc=PM(r.compareFunc),r.passOp=tp(r.passOp),r.failOp=tp(r.failOp),r.zFailOp=tp(r.zFailOp),to.stencils[this.source]||(to.stencils[this.source]=[]),to.stencils[this.source].push(r)}}}return null}}function tp(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 PM(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 OM="NEEDLE_render_objects";class MM{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 ps=new MM;class ys{_overrides=[];_defines={};_object=null;get object(){return this._object}constructor(e=null){this._object=e}static get(e){let t=ps.getBlock(e);return t||(t=new ys(e),ps.setBlock(e,t),RM(e,t)),t}static hasOverrides(e){const t=ps.getBlock(e);return t?t.hasOverrides():!1}dispose(){this._object&&ps.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)}removeOveride(e){const t=this._overrides.findIndex(i=>i.name===e);t>=0&&this._overrides.splice(t,1)}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 Ed=Symbol("originalValues"),Rd=Symbol("savedTextureTransforms");function jw(s){let e=ps.getBlock(s);if(e)return{block:e,owner:s};if(s.parent&&s.parent.type==="Group"&&(e=ps.getBlock(s.parent),e))return{block:e,owner:s.parent}}const xa=Symbol("beforeRenderingFlag"),um=new WeakMap,fm=new WeakMap,kM=function(s,e,t,i){const n=ps.getBlock(s);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&&(fm.set(this,t.transmission),t.transmission=o),r!==void 0&&typeof r=="boolean"&&r!==t.transparent&&(um.set(this,t.transparent),t.transparent=r)}},EM=function(s,e,t,i){const n=um.get(s);n!==void 0&&(um.delete(s),t.transparent=n);const o=fm.get(s);o!==void 0&&(fm.delete(s),t.transmission=o)},pb=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[xa]===void 0&&(this[xa]=new WeakSet),this[xa].add(n);const a=jw(this);if(!a)return;const{block:l,owner:h}=a,d=l.overrides,u=n,p=l.getDefines(),m=Object.keys(p);if(m.length>0){u.defines||(u.defines={});for(const g of m){const v=p[g];v!==void 0&&(u.defines[g]=v)}}if(d.length===0&&m.length===0)return;let y=m.length>0;u[Ed]||(u[Ed]=[]);const _=u[Ed];for(const g of d){if(g.value===null)continue;const v=u[g.name],b=_.find(w=>w.name===g.name);if(b?b.value=v:_.push({name:g.name,value:v}),!y&&!!v!=!!g.value&&(y=!0),u[g.name]=g.value,g.textureTransform&&g.value instanceof c.Texture){const w=g.value;u[Rd]||(u[Rd]=[]),u[Rd].push({name:g.name,offsetX:w.offset.x,offsetY:w.offset.y,repeatX:w.repeat.x,repeatY:w.repeat.y});const R=g.textureTransform;R.offset&&w.offset.copy(R.offset),R.repeat&&w.repeat.copy(R.repeat)}}y&&(u.needsUpdate=!0),u._forceRefresh=!0},mb=function(s,e,t,i,n,o){if(this[xa]===void 0||!this[xa].has(n))return;this[xa].delete(n);const r=jw(this);if(!r)return;const{block:a,owner:l}=r,h=a.overrides,d=n,u=d[Ed],p=a.getDefines(),m=Object.keys(p);let y=!1;if(m.length>0&&d.defines){for(const g of m)delete d.defines[g];y=!0}if(h.length===0){y&&(d.needsUpdate=!0,d._forceRefresh=!0);return}if(!u)return;const _=d[Rd];if(_&&_.length>0){for(const g of _){const v=h.find(b=>b.name===g.name);v?.value instanceof c.Texture&&(v.value.offset.set(g.offsetX,g.offsetY),v.value.repeat.set(g.repeatX,g.repeatY))}_.length=0}for(const g of h){const v=u.find(b=>b.name===g.name);v&&(!y&&!!g.value!=!!v.value&&(y=!0),d[g.name]=v.value)}y&&(d.needsUpdate=!0),d._forceRefresh=!0};function RM(s,e){s.type==="Group"?s.children.forEach(t=>{(t.type==="Mesh"||t.type==="SkinnedMesh")&&gb(t,s,e)}):(s.type==="Mesh"||s.type==="SkinnedMesh")&&gb(s,s,e)}function gb(s,e,t){if(!ps.isHooked(s,e)){if(ps.addHook(s,e),s["needle:materialPropertyBlock"]=t,!s.onBeforeRender)s.onBeforeRender=pb;else{const i=s.onBeforeRender;s.onBeforeRender=function(n,o,r,a,l,h){i.call(this,n,o,r,a,l,h),pb.call(this,n,o,r,a,l,h)}}if(!s.onAfterRender)s.onAfterRender=mb;else{const i=s.onAfterRender;s.onAfterRender=function(n,o,r,a,l,h){mb.call(this,n,o,r,a,l,h),i.call(this,n,o,r,a,l,h)}}s.onBeforeRenderListPush=kM,s.onAfterRenderListPush=EM}}var TM=Object.defineProperty,AM=Object.getOwnPropertyDescriptor,$u=(s,e,t,i)=>{for(var n=i>1?void 0:i?AM(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&TM(e,t,n),n};const Hr=x("debugreflectionprobe"),yb=x("noreflectionprobe");let Bo=null;const DM=Symbol("reflectionProbeKey"),rh=class an extends E{static _probes=new Map;static testBox=new c.Box3;static isUsingReflectionProbe(e){return!!e[DM]}static onEnabled=new ne;static onDisabled=new ne;static get(e,t,i,n){if(!e||e.isObject3D!==!0||yb)return null;const o=an._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 Hr&&console.log("Found reflection probe",e.name,r.name),r}}return Hr&&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"){Hr&&console.debug(`[ReflectionProbe] Loading reflection probe texture from URL: ${e}`),this._textureUrlInFlight=e;const t=ws(this.sourceId,e);Mg(t,this.context.renderer).then(i=>{this._textureUrlInFlight===e&&i&&(this._textureUrlInFlight=void 0,Hr&&console.debug(`[ReflectionProbe] Successfully loaded reflection probe texture: ${e}`),this.texture=i)});return}this.__didAwake&&(this._textureUrlInFlight=void 0),this._texture=e,Hr&&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 Bo??=new c.Box3,Bo.setFromCenterAndSize(this.gameObject.worldPosition.add(this.center),this.size),ri([e],void 0,void 0,an.testBox),an.testBox.isEmpty()?Bo.containsPoint(e.worldPosition):Bo?.intersectsBox(an.testBox)}constructor(){super(),an._probes.has(this.context)||an._probes.set(this.context,[]),an._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(){Hr&&(Bo??=new c.Box3,Bo.setFromCenterAndSize(this.gameObject.worldPosition.add(this.center),this.size),B.DrawWireBox3(Bo,5592320))}onEnable(){an.onEnabled?.invoke(this)}onDisable(){an.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=an._probes.get(this.context);if(e){const t=e.indexOf(this);t>=0&&e.splice(t,1)}}apply(e){if(yb||!this.enabled||!this.texture)return;const t=ys.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=ys.get(e);t&&t.getOverride("envMap")?.value===this.texture&&t.removeOveride("envMap")}};$u([f([c.Texture,String])],rh.prototype,"texture",1);$u([f()],rh.prototype,"intensity",2);$u([f(c.Vector3)],rh.prototype,"center",2);$u([f(c.Vector3)],rh.prototype,"size",2);let os=rh;const ip=x("debugexr");class LM{get name(){return"EXT_texture_exr"}parser;constructor(e){this.parser=e,ip&&console.log(e)}loadTexture(e){const t=this.name,i=this.parser,o=i.json.textures[e];if(ip&&console.log("EXT_texture_exr.loadTexture",e,o),!o.extensions||!o.extensions[t])return null;const r=o.extensions[t],a=new X.EXRLoader(i.options.manager);return ip&&console.log("EXT_texture_exr.loadTexture",r),i.loadTextureImage(e,r.source,a)}}typeof window<"u"&&window.addEventListener("unhandledrejection",s=>{});const Cn=rt,Yh="$___Export_Components",IM="NEEDLE_components";class jM{[Ho]}class BM{node;nodeIndex;nodeDef;constructor(e,t,i){this.node=e,this.nodeIndex=t,this.nodeDef=i}}class Bw{get name(){return IM}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[Yh]=i,!0)}afterSerializeUserData(e,t){if(e.type==="Scene"&&Cn&&console.log("DONE",JSON.stringify(t)),e[Yh]===void 0)return;const i=e[Yh];delete e[Yh],i!==null&&(e.userData.components=i)}writeNode(e,t){const i=this.writer.json.nodes.length;Cn&&console.log(e.name,i,e.uuid);const n=new BM(e,i,t);this.exportContext[i]=n,this.objectToNodeMap[e.uuid]=i}afterParse(e){Cn&&console.log("AFTER",e);for(const t in this.exportContext){const i=this.exportContext[t],n=i.node,o=i.nodeDef,r=i.nodeIndex,a=n.userData?.components;if(!a||a.length<=0)continue;const l=new jM;o.extensions=o.extensions||{},o.extensions[this.name]=l,this.context.object=n,this.context.nodeId=r,this.context.objectToNode=this.objectToNodeMap;const h=[];for(const d of a){this.context.target=d;const u=un().writeBuiltinComponentData(d,this.context);u!==null&&h.push(u)}h.length>0&&(l[Ho]=h,Cn&&console.log("DID WRITE",n,"nodeIndex",r,h))}}parser;nodeToObjectMap={};gltf=null;beforeRoot(){return Cn&&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];Cn&&console.log("After root",e,this.parser,i);const o=[];if(n===!0){const r=t.json.nodes;if(r){for(let a=0;a<r.length;a++){const l=await t.getDependency("node",a);this.nodeToObjectMap[a]=l}for(let a=0;a<r.length;a++){const l=r[a],h=a,d=l.extensions;if(!d)continue;const u=d[this.name];if(!u)continue;Cn&&console.log("NODE",l);const p=this.nodeToObjectMap[h];if(!p){console.error("Could not find object for node index: "+h,l,t);continue}Pu(p),o.push(this.createComponents(e,l,p,u))}}}await Promise.all(o);for(const r of t.associations.keys()){const a=t.associations.get(r);if(a?.materials!=null){const l="/materials/"+a.materials;QC(r,l)}}}async createComponents(e,t,i,n){if(!n)return;const o=n[Ho];if(o){const r=new Array;Cn&&console.log(i.name,o);for(const a in o){const l=o[a];if(Cn&&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(p=>"/materials/"+(p.material??0)),h=!0)}}!h&&(Cn||A())&&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(tg(this.parser,l).catch(h=>console.error(`Error while resolving references (see console for details)
|
|
1000
|
-
`,h,i,l))),i.userData=i.userData||{},i.userData[Ho]=i.userData[Ho]||[],i.userData[Ho].push(l)}await Promise.all(r).catch(a=>{console.error("Error while loading components",a)})}}}const _b="NEEDLE_gameobject_data";class FM{get name(){return _b}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[_b];if(o){const r=this.findAndApplyExtensionData(i,o);t.push(r)}}}return Promise.all(t).then(()=>null)}async findAndApplyExtensionData(e,t){const i=await this.parser.getDependency("node",e);i&&this.applyExtensionData(i,t)}applyExtensionData(e,t){t.layers===void 0&&(t.layers=0),e.userData.layer=t.layers,e.layers.disableAll(),e.layers.set(t.layers),e.userData.tag=t.tag??"none",e.hideFlags=0,e.userData.static=t.static??!1,e.visible=t.activeSelf??!0,e.guid=t.guid}}const bb="NEEDLE_lighting_settings",sa=x("debugenvlight");class UM{get name(){return bb}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[bb];if(i){sa&&console.log('Loaded "'+this.name+'", src: "'+this.sourceId+'"',i);let n;if(e.scene.children.length===1){const o=e.scene.children[0];n=S.addComponent(o,su,{},{callAwake:!1})}else{const o=new c.Object3D;o.name="LightSettings "+this.sourceId,e.scene.add(o),n=S.addComponent(o,su,{},{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}}le.registerCallback(ae.ContextCreated,s=>{const e=s.context,t=S.findObjectOfType(su,e);t?.sourceId&&(t.enabled=!0)});class su extends E{ambientMode=ba.Skybox;ambientLight;ambientTrilight;ambientIntensity=1;environmentReflectionSource=Qd.Skybox;_hasReflection=!1;_ambientLightObj;_hemisphereLightObj;awake(){if(this.sourceId){const t=this.environmentReflectionSource===Qd.Skybox?Tn.Skybox:Tn.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),sa&&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*I.lerp(0,1.33,t)}onEnable(){if(sa&&console.warn("💡🟡 >>> Enable lighting",this.sourceId,this.enabled,this),this.ambientMode==ba.Flat){if(this.ambientLight&&!this._ambientLightObj){const e=this.calculateIntensityFactor(this.ambientLight);this._ambientLightObj=new c.AmbientLight(this.ambientLight,this.ambientIntensity*e),sa&&console.log("Created ambient light",this.sourceId,this._ambientLightObj,this.ambientIntensity,e)}this._ambientLightObj&&this.gameObject.add(this._ambientLightObj)}else if(this.ambientMode===ba.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),sa&&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(){sa&&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 T.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 zM 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 _o.createPrimitive("ShaderBall",{material:e})}}class NM{constructor(e,t,i,n){this.context=e,this.loader=t,this.url=i,this.parser=n}get name(){return"materialx-loading-helper"}mtlxLoader;async beforeRoot(){if(this.parser.json.extensions?.NEEDLE_materials_mtlx){const t=await T.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 Fw=(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))(Fw||{});const kn=x("debugcustomshader"),qr="NEEDLE_techniques_webgl";class VM{objectToWorldMatrix=new c.Matrix4;worldToObjectMatrix=new c.Matrix4;objectToWorld=new Array;worldToObject=new Array;updateFrom(e){this.objectToWorldMatrix.copy(e.matrixWorld),Xd(this.objectToWorldMatrix,this.objectToWorld),this.worldToObjectMatrix.copy(e.matrixWorld).invert(),Xd(this.worldToObjectMatrix,this.worldToObject)}}class ve extends c.RawShaderMaterial{identifier;onBeforeRenderSceneCallback=this.onBeforeRenderScene.bind(this);clone(){const e=super.clone();return Uw(e),e}constructor(e,...t){super(...t),this.identifier=e,kn&&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)&&U.Current.pre_render_callbacks.push(this.onBeforeRenderSceneCallback)}dispose(){super.dispose();const e=U.Current.pre_render_callbacks.indexOf(this.onBeforeRenderSceneCallback);e>=0&&U.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 VM;get depthTextureUniform(){if(this.uniforms)return this.uniforms._CameraDepthTexture}get opaqueTextureUniform(){if(this.uniforms)return this.uniforms._CameraOpaqueTexture}onBeforeRenderScene(){this.opaqueTextureUniform&&U.Current.setRequireColor(!0),this.depthTextureUniform&&U.Current.setRequireDepth(!0)}onBeforeRender(e,t,i,n,o,r){n.attributes.tangent||n.computeTangents(),this.onUpdateUniforms(i,o)}onUpdateUniforms(e,t){const i=U.Current;if(e&&(ve.viewProjection&&this.uniforms[this._viewProjectionName]&&(ve.viewProjection.copy(e.projectionMatrix).multiply(e.matrixWorldInverse),Xd(ve.viewProjection,ve._viewProjectionValues)),ve.viewMatrix&&this.uniforms[this._viewMatrixName]&&(ve.viewMatrix.copy(e.matrixWorldInverse),Xd(ve.viewMatrix,ve._viewMatrixValues)),this.uniforms[ve._worldSpaceCameraPosName]&&ve._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=Y(n.gameObject,ve._mainLightPosition);this.uniforms._MainLightPosition={value:a.normalize()},ve._mainLightColor.set(n.color.r,n.color.g,n.color.b,0),this.uniforms._MainLightColor={value:ve._mainLightColor};const l=n.intensity;ve._lightData.z=l,this.uniforms.unity_LightData={value:ve._lightData}}if(e&&(ve.viewProjection&&this.uniforms[this._viewProjectionName]&&(this.uniforms[this._viewProjectionName].value=ve._viewProjectionValues),ve.viewMatrix&&this.uniforms[this._viewMatrixName]&&(this.uniforms[this._viewMatrixName].value=ve._viewMatrixValues),this.uniforms[ve._worldSpaceCameraPosName]&&(this.uniforms[ve._worldSpaceCameraPosName]={value:ve._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 $M{get name(){return qr}parser;identifier;constructor(e,t){this.parser=e,this.identifier=t}loadMaterial(e){const t=this.parser.json.materials[e];if(!t)return kn&&console.log(e,this.parser.json.materials),null;if(!t.extensions||!t.extensions[qr])return kn&&console.log(`Material ${e} does not use NEEDLE_techniques_webgl`),null;kn&&console.log(`Material ${e} uses NEEDLE_techniques_webgl`,t);const i=t.extensions[qr].technique;if(i<0)return console.debug(`Material ${e} does not have a valid technique index`),null;const n=this.parser.json.extensions[qr];if(!n)return kn?console.error("Missing shader data",this.parser.json.extensions):console.debug("Missing custom shader data in parser.json.extensions"),null;kn&&console.log(n);const o=n.techniques[i];return o?new Promise(async(r,a)=>{const l=await k1(n,o.program),h=l?.fragmentShader,d=l?.vertexShader;if(!h||!d)return a();kn&&console.log("loadMaterial",t,l);const u={},p=o.uniforms;(d.includes("_Time")||h.includes("_Time"))&&(u._Time={value:new c.Vector4(0,0,0,0)}),(d.includes("_SinTime")||h.includes("_SinTime"))&&(u._SinTime={value:new c.Vector4(0,0,0,0)}),(d.includes("_CosTime")||h.includes("_CosTime"))&&(u._CosTime={value:new c.Vector4(0,0,0,0)}),(d.includes("unity_DeltaTime")||h.includes("unity_DeltaTime"))&&(u.unity_DeltaTime={value:new c.Vector4(0,0,0,0)});for(const v in p){const b=v;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[qr]){const v=t.extensions[qr];if(v.technique===i){kn&&console.log(t.name,"Material Properties",v);for(const b in v.values){const w=v.values[b];if(typeof w=="string"){if(w.startsWith("/textures/")){const R=w.substring(10),O=Number.parseInt(R);if(O>=0){const M=await this.parser.getDependency("texture",O);M instanceof c.Texture&&(M.colorSpace=c.LinearSRGBColorSpace,M.needsUpdate=!0),u[b]={value:M};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 y=new ve(this.identifier,{name:t.name??"",uniforms:u,vertexShader:d,fragmentShader:h,lights:!1});switch(y.glslVersion=c.GLSL3,y.vertexShader=y.vertexShader.replace("#version 300 es",""),y.fragmentShader=y.fragmentShader.replace("#version 300 es",""),u._Cull?.value){case 0:y.side=c.DoubleSide;break;case 1:y.side=c.BackSide;break;case 2:y.side=c.FrontSide;break;default:y.side=c.FrontSide;break}switch(u._ZTest?.value){case 3:y.depthTest=!0,y.depthFunc=c.EqualDepth;break;case 6:y.depthTest=!0,y.depthFunc=c.NotEqualDepth;break;case 2:y.depthTest=!0,y.depthFunc=c.LessDepth;break;case 4:y.depthTest=!0,y.depthFunc=c.LessEqualDepth;break;case 5:y.depthTest=!0,y.depthFunc=c.GreaterDepth;break;case 7:y.depthTest=!0,y.depthFunc=c.GreaterEqualDepth;break;case 8:y.depthTest=!1,y.depthFunc=c.AlwaysDepth;break}y.transparent=m,m&&(y.depthWrite=!1),O1(u),y.onUpdateUniforms();for(const v in p){const b=v,w=p[v].type;u[b]?.value===void 0&&(w===Fw.SAMPLER_2D?(u[b]={value:C1},console.warn("Missing/unassigned texture, fallback to white: "+b)):b==="unity_OrthoParams"||console.warn("TODO: EXPECTED UNIFORM / fallback NOT SET: "+b,p[v]))}kn&&console.log(y.uuid,u),Uw(y),r(y)}):null}}function Uw(s){if(s.uniforms){kn&&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 WM=x("debugextensions");let ou;const GM=Promise.resolve().then(()=>require("./vendor-BLeytgEr.umd.cjs")).then(s=>s.index$2).then(async s=>(ou=s.GLTFAnimationPointerExtension,ou)).catch(s=>{console.warn("Failed to import GLTFLoaderAnimationPointer. Please use @needle-tools/three-animationpointer for full KHR_animation support",s)}),mr=new Array;function HM(s){mr.includes(s)||mr.push(s)}function qM(s){const e=mr.indexOf(s);e>=0&&mr.splice(e,1)}function zg(s){if(s instanceof X.GLTFLoader){const e=new Bw;return s.register(t=>(e.parser=t,e)),e}return null}class XM{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 ru(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 FM(o)),s.register(o=>new KC(o)),s.register(o=>new f1(o,e.lightmaps,i)),s.register(o=>new UM(o,i,e)),s.register(o=>new $M(o,i)),s.register(o=>new to(o,i)),s.register(o=>new re.NEEDLE_progressive(o)),s.register(o=>new LM(o)),s.register(o=>new vu(o)),s.register(o=>new NM(e,s,t,o)),W0()&&s.register(o=>new wa(o)),await GM.catch(o=>{}),s.register(o=>{if(ou){const r=new ou(o);return r.setAnimationPointerResolver.bind(r)(new XM),r}else return(WM||A())&&console.error("Missing KHR_animation_pointer extension..."),{name:"KHR_animation_pointer_NOT_AVAILABLE"}});for(const o of mr)o.onImport&&o.onImport(s,t,e)}function Ng(s,e){for(const t of mr)t.onExport&&t.onExport(s,e)}function zw(s,e,t){for(const i of mr)i.onLoaded&&i.onLoaded(s,e,t)}const kt=x("debuginstancing");class gr{static instance=new gr;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(u=>re.NEEDLE_progressive.assignTextureLOD(u,0)):re.NEEDLE_progressive.assignTextureLOD(l,0);const h=a.object,d=h.geometry;re.NEEDLE_progressive.assignMeshLOD(h,0).then(u=>{u&&d!=u&&a.setGeometry(u)})}else if(r<=0&&t.type!=="Mesh"){const l=r+1;for(const h of t.children)n=this.setup(e,h,i,n,o,l)}return r===0&&o.useMatrixWorldAutoUpdate&&n&&n.length>=0&&this.autoUpdateInstanceMatrix(t),n}tryCreateOrAddInstance(e,t,i){if(e.type==="Mesh"){const n=i.foundMeshes;if(i.foundMeshes+=1,!i.rend.enableInstancing)return null;if(i.rend.enableInstancing!==!0){if(n>=i.rend.enableInstancing.length)return kt&&console.error("Something is wrong with instance setup",e,i.rend.enableInstancing,n),null;if(!i.rend.enableInstancing[n])return null}const o=e,r=o.material;for(const u of this.objs){if(!u.canAdd(o.geometry,r))continue;return u.addInstance(o)}let a=gr.getStartInstanceCount(e);(!a||a<0)&&(a=4);let l=e.name;l?.length||(l=pv());const h=new QM(l,o.geometry,r,a,t);return this.objs.push(h),h.addInstance(o)}return null}autoUpdateInstanceMatrix(e){const t=e.matrixWorld.multiplyMatrices.bind(e.matrixWorld),i=e.matrixWorld.clone(),n=(o,r)=>{const a=t(o,r);return(e[Sc]||i.equals(a)===!1)&&(i.copy(a),e[Sc]=!0),a};e.matrixWorld.multiplyMatrices=n}}class cr{static all=[];get name(){return this.object.name}get isActive(){return this.__instanceIndex>=0}get vertexCount(){return this.object.geometry.attributes.position.count}get maxVertexCount(){return Math.max(this.meshInformation.vertexCount,this.vertexCount)}get reservedVertexCount(){return this.__reservedVertexRange}get indexCount(){return this.object.geometry.index?this.object.geometry.index.count:0}get maxIndexCount(){return Math.max(this.meshInformation.indexCount,this.indexCount)}get reservedIndexCount(){return this.__reservedIndexRange}object;renderer;__instanceIndex=-1;__reservedVertexRange=0;__reservedIndexRange=0;__geometryIndex=-1;meshInformation;constructor(e,t){this.__instanceIndex=-1,this.object=e,this.renderer=t,e[Q0]=t,this.meshInformation=qo(e.geometry),cr.all.push(this)}updateMeshInformation(){const e=qo(this.object.geometry),t=this.meshInformation.vertexCount,i=this.meshInformation.indexCount;return Object.assign(this.meshInformation,e),t!==this.meshInformation.vertexCount||i!==this.meshInformation.indexCount}updateInstanceMatrix(e=!1,t=!0){this.__instanceIndex<0||(t&&this.object.updateWorldMatrix(!0,e),this.renderer.updateInstance(this.object.matrixWorld,this.__instanceIndex))}setMatrix(e){this.__instanceIndex<0||this.renderer.updateInstance(e,this.__instanceIndex)}setGeometry(e){if(this.__geometryIndex<0)return!1;const t=this;if(this.vertexCount>this.__reservedVertexRange)return i(`Instancing: Can not update geometry (${this.name}), reserved vertex range is too small: ${this.__reservedVertexRange.toLocaleString()} < ${this.vertexCount.toLocaleString()} vertices for ${this.name}`);if(this.indexCount>this.__reservedIndexRange)return i(`Instancing: Can not update geometry (${this.name}), reserved index range is too small: ${this.__reservedIndexRange.toLocaleString()} < ${this.indexCount.toLocaleString()} indices for ${this.name}`);return this.renderer.updateGeometry(e,this.__geometryIndex);function i(n){return t.updateMeshInformation()&&(t.renderer.remove(t,!0),t.renderer.add(t))?!0:((A()||kt)&&console.error(n),!1)}}add(){this.__instanceIndex>=0||(this.renderer.add(this),S.markAsInstancedRendered(this.object,!0))}remove(e){if(!(this.__instanceIndex<0)&&(this.renderer.remove(this,e),S.markAsInstancedRendered(this.object,!1),e)){const t=cr.all.indexOf(this);t>=0&&cr.all.splice(t,1)}}}class QM{get batchedMesh(){return this._batchedMesh}get visible(){return this._batchedMesh.visible}set visible(e){this._batchedMesh.visible=e}get castShadow(){return this._batchedMesh.castShadow}set castShadow(e){this._batchedMesh.castShadow=e}set receiveShadow(e){this._batchedMesh.receiveShadow=e}allowResize=!0;name="";geometry;material;get count(){return this._currentInstanceCount}updateBounds(e=!0,t=!0){if(this._needUpdateBounds=!1,e&&this._batchedMesh.computeBoundingBox(),t&&this._batchedMesh.computeBoundingSphere(),kt&&this._batchedMesh.boundingSphere){const i=this._batchedMesh.boundingSphere;B.DrawWireSphere(i.center,i.radius,65280)}}_context;_batchedMesh;_handles=[];_geometryIds=new WeakMap;_maxInstanceCount;_currentInstanceCount=0;_currentVertexCount=0;_currentIndexCount=0;_maxVertexCount;_maxIndexCount;static nullMatrix=new c.Matrix4;canAdd(e,t){return this._maxVertexCount>1e7||t!==this.material||!this.validateGeometry(e)?!1:!!(!this.mustGrow(e)||this.allowResize)}_needUpdateBounds=!1;_debugMaterial=null;getBatchedMeshName(){return this.name?`${this.name} (BatchedMesh)`:"BatchedMesh"}constructor(e,t,i,n,o){this.name=e,this.geometry=t,this.material=i,this._context=o,this._maxInstanceCount=Math.max(2,n),kt&&(this._debugMaterial=vb());const r=this.tryEstimateVertexCountSize(this._maxInstanceCount,[t],n);this._maxVertexCount=r.vertexCount,this._maxIndexCount=r.indexCount,this._batchedMesh=new c.BatchedMesh(this._maxInstanceCount,this._maxVertexCount,this._maxIndexCount,this._debugMaterial??this.material),this._batchedMesh.name=this.getBatchedMeshName(),this._batchedMesh[Nl]=!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),kt&&console.log(`Instanced renderer (${this.name}) created with ${this._maxInstanceCount} instances, ${this._maxVertexCount} max vertices and ${this._maxIndexCount} max indices for "${e}"`)}dispose(){kt&&console.warn("Dispose instanced renderer",this.name),this._context.scene.remove(this._batchedMesh),this._batchedMesh.dispose(),this._batchedMesh=null,this._handles=[]}addInstance(e){const t=new cr(e,this);e.castShadow===!0&&this._batchedMesh.castShadow===!1&&(this._batchedMesh.castShadow=!0),e.receiveShadow===!0&&this._batchedMesh.receiveShadow===!1&&(this._batchedMesh.receiveShadow=!0);try{this.add(t)}catch(i){if(console.error(`Failed adding mesh to instancing (object name: "${e.name}", instances: ${this._currentInstanceCount.toLocaleString()}/${this._maxInstanceCount.toLocaleString()}, vertices: ${this._currentVertexCount.toLocaleString()}/${this._maxVertexCount.toLocaleString()}, indices: ${this._currentIndexCount.toLocaleString()}/${this._maxIndexCount.toLocaleString()})
|
|
1000
|
+
`,h,i,l))),i.userData=i.userData||{},i.userData[Ho]=i.userData[Ho]||[],i.userData[Ho].push(l)}await Promise.all(r).catch(a=>{console.error("Error while loading components",a)})}}}const _b="NEEDLE_gameobject_data";class FM{get name(){return _b}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[_b];if(o){const r=this.findAndApplyExtensionData(i,o);t.push(r)}}}return Promise.all(t).then(()=>null)}async findAndApplyExtensionData(e,t){const i=await this.parser.getDependency("node",e);i&&this.applyExtensionData(i,t)}applyExtensionData(e,t){t.layers===void 0&&(t.layers=0),e.userData.layer=t.layers,e.layers.disableAll(),e.layers.set(t.layers),e.userData.tag=t.tag??"none",e.hideFlags=0,e.userData.static=t.static??!1,e.visible=t.activeSelf??!0,e.guid=t.guid}}const bb="NEEDLE_lighting_settings",sa=x("debugenvlight");class UM{get name(){return bb}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[bb];if(i){sa&&console.log('Loaded "'+this.name+'", src: "'+this.sourceId+'"',i);let n;if(e.scene.children.length===1){const o=e.scene.children[0];n=S.addComponent(o,su,{},{callAwake:!1})}else{const o=new c.Object3D;o.name="LightSettings "+this.sourceId,e.scene.add(o),n=S.addComponent(o,su,{},{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}}le.registerCallback(ae.ContextCreated,s=>{const e=s.context,t=S.findObjectOfType(su,e);t?.sourceId&&(t.enabled=!0)});class su extends E{ambientMode=ba.Skybox;ambientLight;ambientTrilight;ambientIntensity=1;environmentReflectionSource=Qd.Skybox;_hasReflection=!1;_ambientLightObj;_hemisphereLightObj;awake(){if(this.sourceId){const t=this.environmentReflectionSource===Qd.Skybox?Tn.Skybox:Tn.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),sa&&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*I.lerp(0,1.33,t)}onEnable(){if(sa&&console.warn("💡🟡 >>> Enable lighting",this.sourceId,this.enabled,this),this.ambientMode==ba.Flat){if(this.ambientLight&&!this._ambientLightObj){const e=this.calculateIntensityFactor(this.ambientLight);this._ambientLightObj=new c.AmbientLight(this.ambientLight,this.ambientIntensity*e),sa&&console.log("Created ambient light",this.sourceId,this._ambientLightObj,this.ambientIntensity,e)}this._ambientLightObj&&this.gameObject.add(this._ambientLightObj)}else if(this.ambientMode===ba.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),sa&&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(){sa&&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 T.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 zM 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 _o.createPrimitive("ShaderBall",{material:e})}}class NM{constructor(e,t,i,n){this.context=e,this.loader=t,this.url=i,this.parser=n}get name(){return"materialx-loading-helper"}mtlxLoader;async beforeRoot(){if(this.parser.json.extensions?.NEEDLE_materials_mtlx){const t=await T.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 Fw=(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))(Fw||{});const kn=x("debugcustomshader"),qr="NEEDLE_techniques_webgl";class VM{objectToWorldMatrix=new c.Matrix4;worldToObjectMatrix=new c.Matrix4;objectToWorld=new Array;worldToObject=new Array;updateFrom(e){this.objectToWorldMatrix.copy(e.matrixWorld),Xd(this.objectToWorldMatrix,this.objectToWorld),this.worldToObjectMatrix.copy(e.matrixWorld).invert(),Xd(this.worldToObjectMatrix,this.worldToObject)}}class ve extends c.RawShaderMaterial{identifier;onBeforeRenderSceneCallback=this.onBeforeRenderScene.bind(this);clone(){const e=super.clone();return Uw(e),e}constructor(e,...t){super(...t),this.identifier=e,kn&&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)&&U.Current.pre_render_callbacks.push(this.onBeforeRenderSceneCallback)}dispose(){super.dispose();const e=U.Current.pre_render_callbacks.indexOf(this.onBeforeRenderSceneCallback);e>=0&&U.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 VM;get depthTextureUniform(){if(this.uniforms)return this.uniforms._CameraDepthTexture}get opaqueTextureUniform(){if(this.uniforms)return this.uniforms._CameraOpaqueTexture}onBeforeRenderScene(){this.opaqueTextureUniform&&U.Current.setRequireColor(!0),this.depthTextureUniform&&U.Current.setRequireDepth(!0)}onBeforeRender(e,t,i,n,o,r){n.attributes.tangent||n.computeTangents(),this.onUpdateUniforms(i,o)}onUpdateUniforms(e,t){const i=U.Current;if(e&&(ve.viewProjection&&this.uniforms[this._viewProjectionName]&&(ve.viewProjection.copy(e.projectionMatrix).multiply(e.matrixWorldInverse),Xd(ve.viewProjection,ve._viewProjectionValues)),ve.viewMatrix&&this.uniforms[this._viewMatrixName]&&(ve.viewMatrix.copy(e.matrixWorldInverse),Xd(ve.viewMatrix,ve._viewMatrixValues)),this.uniforms[ve._worldSpaceCameraPosName]&&ve._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=Y(n.gameObject,ve._mainLightPosition);this.uniforms._MainLightPosition={value:a.normalize()},ve._mainLightColor.set(n.color.r,n.color.g,n.color.b,0),this.uniforms._MainLightColor={value:ve._mainLightColor};const l=n.intensity;ve._lightData.z=l,this.uniforms.unity_LightData={value:ve._lightData}}if(e&&(ve.viewProjection&&this.uniforms[this._viewProjectionName]&&(this.uniforms[this._viewProjectionName].value=ve._viewProjectionValues),ve.viewMatrix&&this.uniforms[this._viewMatrixName]&&(this.uniforms[this._viewMatrixName].value=ve._viewMatrixValues),this.uniforms[ve._worldSpaceCameraPosName]&&(this.uniforms[ve._worldSpaceCameraPosName]={value:ve._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 $M{get name(){return qr}parser;identifier;constructor(e,t){this.parser=e,this.identifier=t}loadMaterial(e){const t=this.parser.json.materials[e];if(!t)return kn&&console.log(e,this.parser.json.materials),null;if(!t.extensions||!t.extensions[qr])return kn&&console.log(`Material ${e} does not use NEEDLE_techniques_webgl`),null;kn&&console.log(`Material ${e} uses NEEDLE_techniques_webgl`,t);const i=t.extensions[qr].technique;if(i<0)return console.debug(`Material ${e} does not have a valid technique index`),null;const n=this.parser.json.extensions[qr];if(!n)return kn?console.error("Missing shader data",this.parser.json.extensions):console.debug("Missing custom shader data in parser.json.extensions"),null;kn&&console.log(n);const o=n.techniques[i];return o?new Promise(async(r,a)=>{const l=await k1(n,o.program),h=l?.fragmentShader,d=l?.vertexShader;if(!h||!d)return a();kn&&console.log("loadMaterial",t,l);const u={},p=o.uniforms;(d.includes("_Time")||h.includes("_Time"))&&(u._Time={value:new c.Vector4(0,0,0,0)}),(d.includes("_SinTime")||h.includes("_SinTime"))&&(u._SinTime={value:new c.Vector4(0,0,0,0)}),(d.includes("_CosTime")||h.includes("_CosTime"))&&(u._CosTime={value:new c.Vector4(0,0,0,0)}),(d.includes("unity_DeltaTime")||h.includes("unity_DeltaTime"))&&(u.unity_DeltaTime={value:new c.Vector4(0,0,0,0)});for(const v in p){const b=v;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[qr]){const v=t.extensions[qr];if(v.technique===i){kn&&console.log(t.name,"Material Properties",v);for(const b in v.values){const w=v.values[b];if(typeof w=="string"){if(w.startsWith("/textures/")){const R=w.substring(10),O=Number.parseInt(R);if(O>=0){const M=await this.parser.getDependency("texture",O);M instanceof c.Texture&&(M.colorSpace=c.LinearSRGBColorSpace,M.needsUpdate=!0),u[b]={value:M};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 y=new ve(this.identifier,{name:t.name??"",uniforms:u,vertexShader:d,fragmentShader:h,lights:!1});switch(y.glslVersion=c.GLSL3,y.vertexShader=y.vertexShader.replace("#version 300 es",""),y.fragmentShader=y.fragmentShader.replace("#version 300 es",""),u._Cull?.value){case 0:y.side=c.DoubleSide;break;case 1:y.side=c.BackSide;break;case 2:y.side=c.FrontSide;break;default:y.side=c.FrontSide;break}switch(u._ZTest?.value){case 3:y.depthTest=!0,y.depthFunc=c.EqualDepth;break;case 6:y.depthTest=!0,y.depthFunc=c.NotEqualDepth;break;case 2:y.depthTest=!0,y.depthFunc=c.LessDepth;break;case 4:y.depthTest=!0,y.depthFunc=c.LessEqualDepth;break;case 5:y.depthTest=!0,y.depthFunc=c.GreaterDepth;break;case 7:y.depthTest=!0,y.depthFunc=c.GreaterEqualDepth;break;case 8:y.depthTest=!1,y.depthFunc=c.AlwaysDepth;break}y.transparent=m,m&&(y.depthWrite=!1),O1(u),y.onUpdateUniforms();for(const v in p){const b=v,w=p[v].type;u[b]?.value===void 0&&(w===Fw.SAMPLER_2D?(u[b]={value:C1},console.warn("Missing/unassigned texture, fallback to white: "+b)):b==="unity_OrthoParams"||console.warn("TODO: EXPECTED UNIFORM / fallback NOT SET: "+b,p[v]))}kn&&console.log(y.uuid,u),Uw(y),r(y)}):null}}function Uw(s){if(s.uniforms){kn&&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 WM=x("debugextensions");let ou;const GM=Promise.resolve().then(()=>require("./vendor-Csj7XHEr.umd.cjs")).then(s=>s.index$2).then(async s=>(ou=s.GLTFAnimationPointerExtension,ou)).catch(s=>{console.warn("Failed to import GLTFLoaderAnimationPointer. Please use @needle-tools/three-animationpointer for full KHR_animation support",s)}),mr=new Array;function HM(s){mr.includes(s)||mr.push(s)}function qM(s){const e=mr.indexOf(s);e>=0&&mr.splice(e,1)}function zg(s){if(s instanceof X.GLTFLoader){const e=new Bw;return s.register(t=>(e.parser=t,e)),e}return null}class XM{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 ru(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 FM(o)),s.register(o=>new KC(o)),s.register(o=>new f1(o,e.lightmaps,i)),s.register(o=>new UM(o,i,e)),s.register(o=>new $M(o,i)),s.register(o=>new to(o,i)),s.register(o=>new re.NEEDLE_progressive(o)),s.register(o=>new LM(o)),s.register(o=>new vu(o)),s.register(o=>new NM(e,s,t,o)),W0()&&s.register(o=>new wa(o)),await GM.catch(o=>{}),s.register(o=>{if(ou){const r=new ou(o);return r.setAnimationPointerResolver.bind(r)(new XM),r}else return(WM||A())&&console.error("Missing KHR_animation_pointer extension..."),{name:"KHR_animation_pointer_NOT_AVAILABLE"}});for(const o of mr)o.onImport&&o.onImport(s,t,e)}function Ng(s,e){for(const t of mr)t.onExport&&t.onExport(s,e)}function zw(s,e,t){for(const i of mr)i.onLoaded&&i.onLoaded(s,e,t)}const kt=x("debuginstancing");class gr{static instance=new gr;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(u=>re.NEEDLE_progressive.assignTextureLOD(u,0)):re.NEEDLE_progressive.assignTextureLOD(l,0);const h=a.object,d=h.geometry;re.NEEDLE_progressive.assignMeshLOD(h,0).then(u=>{u&&d!=u&&a.setGeometry(u)})}else if(r<=0&&t.type!=="Mesh"){const l=r+1;for(const h of t.children)n=this.setup(e,h,i,n,o,l)}return r===0&&o.useMatrixWorldAutoUpdate&&n&&n.length>=0&&this.autoUpdateInstanceMatrix(t),n}tryCreateOrAddInstance(e,t,i){if(e.type==="Mesh"){const n=i.foundMeshes;if(i.foundMeshes+=1,!i.rend.enableInstancing)return null;if(i.rend.enableInstancing!==!0){if(n>=i.rend.enableInstancing.length)return kt&&console.error("Something is wrong with instance setup",e,i.rend.enableInstancing,n),null;if(!i.rend.enableInstancing[n])return null}const o=e,r=o.material;for(const u of this.objs){if(!u.canAdd(o.geometry,r))continue;return u.addInstance(o)}let a=gr.getStartInstanceCount(e);(!a||a<0)&&(a=4);let l=e.name;l?.length||(l=pv());const h=new QM(l,o.geometry,r,a,t);return this.objs.push(h),h.addInstance(o)}return null}autoUpdateInstanceMatrix(e){const t=e.matrixWorld.multiplyMatrices.bind(e.matrixWorld),i=e.matrixWorld.clone(),n=(o,r)=>{const a=t(o,r);return(e[Sc]||i.equals(a)===!1)&&(i.copy(a),e[Sc]=!0),a};e.matrixWorld.multiplyMatrices=n}}class cr{static all=[];get name(){return this.object.name}get isActive(){return this.__instanceIndex>=0}get vertexCount(){return this.object.geometry.attributes.position.count}get maxVertexCount(){return Math.max(this.meshInformation.vertexCount,this.vertexCount)}get reservedVertexCount(){return this.__reservedVertexRange}get indexCount(){return this.object.geometry.index?this.object.geometry.index.count:0}get maxIndexCount(){return Math.max(this.meshInformation.indexCount,this.indexCount)}get reservedIndexCount(){return this.__reservedIndexRange}object;renderer;__instanceIndex=-1;__reservedVertexRange=0;__reservedIndexRange=0;__geometryIndex=-1;meshInformation;constructor(e,t){this.__instanceIndex=-1,this.object=e,this.renderer=t,e[Q0]=t,this.meshInformation=qo(e.geometry),cr.all.push(this)}updateMeshInformation(){const e=qo(this.object.geometry),t=this.meshInformation.vertexCount,i=this.meshInformation.indexCount;return Object.assign(this.meshInformation,e),t!==this.meshInformation.vertexCount||i!==this.meshInformation.indexCount}updateInstanceMatrix(e=!1,t=!0){this.__instanceIndex<0||(t&&this.object.updateWorldMatrix(!0,e),this.renderer.updateInstance(this.object.matrixWorld,this.__instanceIndex))}setMatrix(e){this.__instanceIndex<0||this.renderer.updateInstance(e,this.__instanceIndex)}setGeometry(e){if(this.__geometryIndex<0)return!1;const t=this;if(this.vertexCount>this.__reservedVertexRange)return i(`Instancing: Can not update geometry (${this.name}), reserved vertex range is too small: ${this.__reservedVertexRange.toLocaleString()} < ${this.vertexCount.toLocaleString()} vertices for ${this.name}`);if(this.indexCount>this.__reservedIndexRange)return i(`Instancing: Can not update geometry (${this.name}), reserved index range is too small: ${this.__reservedIndexRange.toLocaleString()} < ${this.indexCount.toLocaleString()} indices for ${this.name}`);return this.renderer.updateGeometry(e,this.__geometryIndex);function i(n){return t.updateMeshInformation()&&(t.renderer.remove(t,!0),t.renderer.add(t))?!0:((A()||kt)&&console.error(n),!1)}}add(){this.__instanceIndex>=0||(this.renderer.add(this),S.markAsInstancedRendered(this.object,!0))}remove(e){if(!(this.__instanceIndex<0)&&(this.renderer.remove(this,e),S.markAsInstancedRendered(this.object,!1),e)){const t=cr.all.indexOf(this);t>=0&&cr.all.splice(t,1)}}}class QM{get batchedMesh(){return this._batchedMesh}get visible(){return this._batchedMesh.visible}set visible(e){this._batchedMesh.visible=e}get castShadow(){return this._batchedMesh.castShadow}set castShadow(e){this._batchedMesh.castShadow=e}set receiveShadow(e){this._batchedMesh.receiveShadow=e}allowResize=!0;name="";geometry;material;get count(){return this._currentInstanceCount}updateBounds(e=!0,t=!0){if(this._needUpdateBounds=!1,e&&this._batchedMesh.computeBoundingBox(),t&&this._batchedMesh.computeBoundingSphere(),kt&&this._batchedMesh.boundingSphere){const i=this._batchedMesh.boundingSphere;B.DrawWireSphere(i.center,i.radius,65280)}}_context;_batchedMesh;_handles=[];_geometryIds=new WeakMap;_maxInstanceCount;_currentInstanceCount=0;_currentVertexCount=0;_currentIndexCount=0;_maxVertexCount;_maxIndexCount;static nullMatrix=new c.Matrix4;canAdd(e,t){return this._maxVertexCount>1e7||t!==this.material||!this.validateGeometry(e)?!1:!!(!this.mustGrow(e)||this.allowResize)}_needUpdateBounds=!1;_debugMaterial=null;getBatchedMeshName(){return this.name?`${this.name} (BatchedMesh)`:"BatchedMesh"}constructor(e,t,i,n,o){this.name=e,this.geometry=t,this.material=i,this._context=o,this._maxInstanceCount=Math.max(2,n),kt&&(this._debugMaterial=vb());const r=this.tryEstimateVertexCountSize(this._maxInstanceCount,[t],n);this._maxVertexCount=r.vertexCount,this._maxIndexCount=r.indexCount,this._batchedMesh=new c.BatchedMesh(this._maxInstanceCount,this._maxVertexCount,this._maxIndexCount,this._debugMaterial??this.material),this._batchedMesh.name=this.getBatchedMeshName(),this._batchedMesh[Nl]=!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),kt&&console.log(`Instanced renderer (${this.name}) created with ${this._maxInstanceCount} instances, ${this._maxVertexCount} max vertices and ${this._maxIndexCount} max indices for "${e}"`)}dispose(){kt&&console.warn("Dispose instanced renderer",this.name),this._context.scene.remove(this._batchedMesh),this._batchedMesh.dispose(),this._batchedMesh=null,this._handles=[]}addInstance(e){const t=new cr(e,this);e.castShadow===!0&&this._batchedMesh.castShadow===!1&&(this._batchedMesh.castShadow=!0),e.receiveShadow===!0&&this._batchedMesh.receiveShadow===!1&&(this._batchedMesh.receiveShadow=!0);try{this.add(t)}catch(i){if(console.error(`Failed adding mesh to instancing (object name: "${e.name}", instances: ${this._currentInstanceCount.toLocaleString()}/${this._maxInstanceCount.toLocaleString()}, vertices: ${this._currentVertexCount.toLocaleString()}/${this._maxVertexCount.toLocaleString()}, indices: ${this._currentIndexCount.toLocaleString()}/${this._maxIndexCount.toLocaleString()})
|
|
1001
1001
|
`,i),A()){Vc("Failed instancing mesh. See the browser console for details.");debugger}return null}return t}add(e){const t=e.object.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._batchedMesh.setMatrixAt(t,e),this.markNeedsUpdate()}updateGeometry(e,t){return this.validateGeometry(e)?(this.mustGrow()&&this.grow(e),kt&&console.debug("[Instancing] UPDATE GEOMETRY at "+t,this._batchedMesh._geometryCount,e.name,qo(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._batchedMesh.layers.enableAll(),this._needUpdateBounds&&this._batchedMesh[Nl]===!0&&(kt==="verbose"&&console.log("Update instancing bounds",this.name,this._batchedMesh.matrixWorldNeedsUpdate),this.updateBounds())};onAfterRender=()=>{this._batchedMesh.layers.disableAll()};validateGeometry(e){const t=this.geometry;for(const i in t.attributes)if(i!=="batchId"&&!e.hasAttribute(i))return A()&&console.warn(`BatchedMesh: Added geometry missing "${i}". All geometries must have consistent attributes.`),!1;return!0}markNeedsUpdate(){kt==="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=qo(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(kt){const p=qo(e);console.warn(`[Instancing] Growing Buffer
|
|
1002
1002
|
Mesh: "${this.name}${e.name?.length?"/"+e.name:""}" (${p.vertexCount.toLocaleString()} vertices, ${p.indexCount.toLocaleString()} indices)
|
|
1003
1003
|
Max count ${this._maxInstanceCount.toLocaleString()} → ${o.toLocaleString()}
|
|
@@ -1651,4 +1651,4 @@ Error:`,r),null}}updateColliderCollisionGroups(e){const t=e[gt],i=e.membership;l
|
|
|
1651
1651
|
justify-content: center;
|
|
1652
1652
|
gap: .5rem;
|
|
1653
1653
|
}
|
|
1654
|
-
`),this.#n.innerHTML=this.#e.innerHTML,this.#n.style.cssText="display: flex; align-items: center; justify-content: center;",this.#e.innerHTML=this.#n.outerHTML,this.#t.innerHTML=this.#e.outerHTML,this.#t.prepend(this.#s),vc(Kp,{element:this.#t}),this.#o?.disconnect(),this.#o??=new MutationObserver(()=>this.#c()),this.#o.observe(this.#e,{attributes:!0}),Rp&&console.log("Needle Button updated",this)}#c(){this.#e&&(this.#e.style.display==="none"?this.style.display="none":this.style.display==="none"&&(this.style.display=""))}#a=e=>{Rp&&console.log("Needle Button clicked",{defaultPrevented:e.defaultPrevented,hasButton:!!this.#e}),!e.defaultPrevented&&this.#e&&this.#e.click()}}typeof window<"u"&&!window.customElements.get(hv)&&window.customElements.define(hv,Xx);const Bl=x("debugavatar");class qy{root;head;leftHand;rigthHand;get isValid(){return this.head!==null&&this.head!==void 0}constructor(e,t,i,n){this.root=e,this.head=t,this.leftHand=i,this.rigthHand=n,this.root?.traverse(o=>o.layers.set(2))}}class Qx{avatarRegistryUrl=null;async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let i=null;if(typeof t=="string"){if(i=await this.loadAvatar(e,t),!i){const o=new gn;i=S.instantiate(Oa(t,e.scene),o)}}else i=t;if(!i)return null;const n=this.findAvatar(i);return n.isValid?(Bl&&console.log("[Custom Avatar] valid config",t,Bl?n:""),n):(console.warn("[Custom Avatar] config isn't valid",t,Bl?n:""),null)}async loadAvatar(e,t){if(console.assert(t!=null&&typeof t=="string","Avatar id must not be null"),t.length<=0||!t)return null;if(Bl&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){const n=await fetch("./"+t);let o=null;if(n.ok){const a=await n.blob();a&&(o=await a.arrayBuffer())}return o?(await un().parseSync(e,o,null,0))?.scene??null:null}const i=new X.GLTFLoader;return ay(i,e),new Promise((n,o)=>{const r=this.avatarRegistryUrl+"/"+t;i.load(r,async a=>{await un().createBuiltinComponents(e,r,a,null,void 0),n(a.scene)},a=>{Bl&&console.log("[Custom Avatar] "+a.loaded/a.total*100+"% loaded of "+a.total/1024+"kB")},a=>{console.error("[Custom Avatar] Error when loading: "+a),n(null)})})}cacheModel(e,t){}findAvatar(e){const t=e;let i=t;i.children.length==1&&(i=e.children[0]);let n=this.findAvatarPart(i,["head"]);const o=this.findAvatarPart(i,["left","hand"]),r=this.findAvatarPart(i,["right","hand"]);if(!n){n=t;const l=new c.Vector3;new c.Box3().setFromObject(n).getSize(l);const h=Math.max(l.x,l.y,l.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+h+" meters! Should be < 0.3m"),h>.3&&n.scale.multiplyScalar(1/h*.3)}return new qy(t,n,o,r)}findAvatarPart(e,t){const i=e.name.toLowerCase();let n=!0;for(const o of t){if(!n)break;i.indexOf(o)===-1&&(n=!1)}if(n)return e;if(e.children)for(const o of e.children){const r=this.findAvatarPart(o,t);if(r)return r}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}}class Yx{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(e){}}class Kx{}const OA=Object.freeze(Object.defineProperty({__proto__:null,ActionBuilder:ue,ActionCollection:rx,ActionModel:Jt,AlignmentConstraint:th,Animation:Tt,AnimationCurve:gh,AnimationExtension:qu,AnimationTrackHandler:Ec,Animator:lt,AnimatorController:Vi,Antialiasing:_h,Attractor:al,AudioExtension:Or,AudioListener:ds,AudioSource:vi,AudioTrackHandler:us,Avatar:fo,AvatarBlink_Simple:xr,AvatarEyeLook_Rotation:Ag,AvatarLoader:Qx,AvatarMarker:Oe,AvatarModel:qy,Avatar_Brain_LookAt:Tc,Avatar_MouthShapes:nh,Avatar_MustacheShake:Rg,Avatar_POI:lr,AxesHelper:Ha,BaseUIComponent:Wi,BasicIKConstraint:Lg,BehaviorExtension:ly,BehaviorModel:St,BloomEffect:cf,BoxCollider:Nu,BoxGizmo:Rr,BoxHelperComponent:bt,Button:Ds,CallInfo:ls,Camera:si,CameraTargetReachedEvent:kc,Canvas:Ba,CanvasGroup:po,CapsuleCollider:bs,ChangeMaterialOnClick:ey,ChangeTransformOnClick:Mr,CharacterController:Sr,CharacterControllerInput:Cs,ChromaticAberration:bh,ClickThrough:vf,ColorAdjustments:ko,ColorBySpeedModule:rl,ColorOverLifetimeModule:rf,ContactShadows:sh,ControlTrackHandler:ju,CursorFollow:Nr,CustomBranding:Er,Deletable:Fg,DeleteBox:ro,DepthOfField:bn,DeviceFlag:Vu,DocumentExtension:Yx,DragControls:Ko,DropListener:Os,Duplicatable:Gg,EffectWrapper:Ic,EmissionModule:Rs,EmphasizeOnClick:Ya,EnvironmentScene:Bu,EventList:ne,EventListEvent:Ru,EventSystem:Gt,EventTrigger:Gu,FieldWithDefault:Nw,FixedJoint:xy,Fog:tl,GltfExport:Yg,GltfExportBox:Xg,Gradient:Ar,Graphic:fh,GraphicRaycaster:Au,GridHelper:il,GridLayoutGroup:py,GroundProjectedEnv:Xn,GroupActionModel:Zo,HideOnStart:Ii,HingeJoint:mh,HorizontalLayoutGroup:fy,get HoverAnimation(){return exports.HoverAnimation},Image:dl,InheritVelocityModule:ky,InputField:Uy,InstanceHandle:cr,InstancingHandler:gr,Interactable:Bg,Keyframe:oi,LODGroup:nf,LODModel:nl,Light:Ot,LimitVelocityOverLifetimeModule:nt,LogStats:jg,LookAt:zy,LookAtConstraint:sl,MainModule:Lt,MarkerTrackHandler:Iu,MaskableGraphic:ph,MeshCollider:wo,MeshRenderer:ah,MinMaxCurve:H,MinMaxGradient:Dr,NeedleMenu:Yn,NestedGltf:ol,Networking:Oy,NoiseModule:me,ObjectRaycaster:$i,OffsetConstraint:Tr,OpenURL:ul,OrbitControls:de,Outline:el,Padding:kr,ParticleBurst:hu,ParticleSubEmitter:Ey,ParticleSystem:Lc,ParticleSystemRenderer:Yi,PhysicsExtension:cy,PixelationEffect:vh,PlayAnimationOnClick:Ac,PlayAudioOnClick:uo,PlayableDirector:Ia,PlayerColor:Fa,PointerEventData:Kc,PostProcessingHandler:Ua,PreliminaryAction:Ka,PreliminaryTrigger:ch,RawImage:yf,Rect:ux,RectTransform:mn,ReflectionProbe:os,RegisteredAnimationInfo:so,RemoteSkybox:Fu,Renderer:Ht,RendererLightmap:Vg,Rigidbody:$e,RotationBySpeedModule:Qi,RotationOverLifetimeModule:_n,SceneSwitcher:We,ScreenCapture:Eo,ScreenSpaceAmbientOcclusion:Ts,ScreenSpaceAmbientOcclusionN8:vn,ScrollFollow:Ls,SeeThrough:As,SetActiveOnClick:ty,ShadowCatcher:Ch,ShapeModule:My,SharpeningEffect:xh,SignalAsset:Lu,SignalReceiver:Jc,SignalReceiverEvent:Zc,SignalTrackHandler:Rc,Size:dx,SizeBySpeedModule:di,SizeOverLifetimeModule:Lr,SkinnedMeshRenderer:$g,SmoothFollow:uf,SpatialGrabRaycaster:fr,SpatialHtml:kh,SpatialTrigger:ff,SpatialTriggerReceiver:Gn,SpectatorCamera:pf,SphereCollider:qa,SplineContainer:Ur,SplineData:qn,SplineWalker:Zi,Sprite:Ms,SpriteData:Ca,SpriteRenderer:ci,SpriteSheet:ja,SubEmitterSystem:du,SyncedCamera:Iy,SyncedRoom:wn,SyncedTransform:pn,TapGestureTrigger:ny,TeleportTarget:Zu,TestRunner:jy,TestSimulateUserData:By,Text:Dt,TextBuilder:dy,TextExtension:ef,TextureSheetAnimationModule:It,TiltShiftEffect:Zn,ToneMappingEffect:mo,TrailModule:Le,TransformData:Ae,TransformGizmo:zr,TriggerBuilder:Rt,TriggerModel:ao,UIRaycastUtils:wg,UIRootComponent:dh,USDZExporter:Wn,USDZText:pa,USDZUIExtension:gy,UsageMarker:oh,VariantAction:Jg,VelocityOverLifetimeModule:Fe,VerticalLayoutGroup:uy,VideoPlayer:tt,get ViewBox(){return exports.ViewBox},Vignette:Br,VisibilityAction:hh,Voip:vo,Volume:Fr,VolumeParameter:z,VolumeProfile:af,WebARCameraBackground:Rh,WebARSessionRoot:Ui,WebXR:Ju,WebXRImageTracking:Th,WebXRImageTrackingModel:js,WebXRPlaneTracking:Bs,WebXRTrackedImage:za,XRControllerFollow:Is,XRControllerModel:vs,XRControllerMovement:xi,XRFlag:ji,XRRig:Sf,XRState:Wt,__Ignore:Kx},Symbol.toStringTag,{value:"Module"}));exports.SplineUtils=void 0;(s=>{function e(t,i=!1,n=.75){const o=new Ur,r=1-I.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 qn;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 MA extends ce.WorkerBase{constructor(){super(new Worker(new URL("/generateMeshBVH.worker-DiCnZlf3.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:ga&&ga.tagName.toUpperCase()==="SCRIPT"&&ga.src||new URL("needle-engine.bundle-BVgcWaGl.umd.cjs",document.baseURI).href),{type:"module"})),this.name="GenerateMeshBVHWorker"}runTask(e,t,i={}){return new Promise((n,o)=>{if(t.getAttribute("position").isInterleavedBufferAttribute||t.index&&t.index.isInterleavedBufferAttribute)throw new Error("GenerateMeshBVHWorker: InterleavedBufferAttribute are not supported for the geometry attributes.");e.onerror=h=>{o(new Error(`[GenerateMeshBVHWorker] ${h.message||"Unknown error. Please check the server console. If you're using vite try adding 'three-mesh-bvh' to 'optimizeDeps.exclude' in your vite.config.js"}`))},e.onmessage=h=>{const{data:d}=h;if(d.error)o(new Error(d.error)),e.onmessage=null;else if(d.serialized){const{serialized:u,position:p}=d,m=ce.MeshBVH.deserialize(u,t,{setIndex:!1}),y=Object.assign({setBoundingBox:!0},i);if(t.attributes.position.array=p,u.index)if(t.index)t.index.array=u.index;else{const _=new c.BufferAttribute(u.index,1,!1);t.setIndex(_)}y.setBoundingBox&&(t.boundingBox=m.getBoundingBox(new c.Box3)),i.onProgress&&i.onProgress(d.progress),n(m),e.onmessage=null}else i.onProgress&&i.onProgress(d.progress)};const r=t.index?t.index.array:null,a=t.attributes.position.array,l=[a];r&&l.push(r),e.postMessage({index:r,position:a,options:{...i,onProgress:null,includedProgressCallback:!!i.onProgress,groups:[...t.groups]}},l.map(h=>h.buffer).filter(h=>typeof SharedArrayBuffer>"u"||!(h instanceof SharedArrayBuffer)))})}}const kA=Object.freeze(Object.defineProperty({__proto__:null,GenerateMeshBVHWorker:MA},Symbol.toStringTag,{value:"Module"}));exports.$componentName=Gv;exports.$physicsKey=AC;exports.ActionBuilder=ue;exports.ActionCollection=rx;exports.ActionModel=Jt;exports.Addressables=f0;exports.AlignmentConstraint=th;exports.AmbientMode=ba;exports.Animation=Tt;exports.AnimationCurve=gh;exports.AnimationExtension=qu;exports.AnimationTrackHandler=Ec;exports.AnimationUtils=Hn;exports.Animator=lt;exports.AnimatorConditionMode=Zs;exports.AnimatorController=Vi;exports.AnimatorControllerParameterType=vg;exports.AnimatorStateInfo=Vl;exports.Antialiasing=_h;exports.Application=fn;exports.AssetDatabase=V0;exports.AssetReference=Z;exports.Attractor=al;exports.AudioExtension=Or;exports.AudioListener=ds;exports.AudioSource=vi;exports.AudioTrackHandler=us;exports.Avatar=fo;exports.AvatarBlink_Simple=xr;exports.AvatarEyeLook_Rotation=Ag;exports.AvatarLoader=Qx;exports.AvatarMarker=Oe;exports.AvatarModel=qy;exports.Avatar_Brain_LookAt=Tc;exports.Avatar_MouthShapes=nh;exports.Avatar_MustacheShake=Rg;exports.Avatar_POI=lr;exports.Axes=ua;exports.AxesHelper=Ha;exports.BUILD_TIME=_c;exports.BaseUIComponent=Wi;exports.BasicIKConstraint=Lg;exports.BehaviorExtension=ly;exports.BehaviorModel=St;exports.BloomEffect=cf;exports.BoxCollider=Nu;exports.BoxGizmo=Rr;exports.BoxHelperComponent=bt;exports.Button=Ds;exports.ButtonsFactory=Fi;exports.CallDirection=Cw;exports.CallInfo=ls;exports.Camera=si;exports.CameraTargetReachedEvent=kc;exports.Canvas=Ba;exports.CanvasGroup=po;exports.CapsuleCollider=bs;exports.ChangeMaterialOnClick=ey;exports.ChangeTransformOnClick=Mr;exports.CharacterController=Sr;exports.CharacterControllerInput=Cs;exports.ChromaticAberration=bh;exports.CircularBuffer=_i;exports.ClearFlags=ar;exports.ClickThrough=vf;exports.ClipExtrapolation=Mn;exports.Collider=Xi;exports.Collision=qv;exports.CollisionDetectionMode=Tu;exports.ColorAdjustments=ko;exports.ColorBySpeedModule=rl;exports.ColorOverLifetimeModule=rf;exports.Component=FP;exports.Component$1=E;exports.ComponentLifecycleEvents=mu;exports.Components=OA;exports.ConnectionEvents=x0;exports.ContactPoint=Hv;exports.ContactShadows=sh;exports.Context=U;exports.ContextArgs=Y1;exports.ContextEvent=ae;exports.ContextRegistry=le;exports.ControlTrackHandler=ju;exports.CursorFollow=Nr;exports.CustomBranding=Er;exports.CustomShader=ve;exports.DefaultReflectionMode=Qd;exports.Deletable=Fg;exports.DeleteBox=ro;exports.DepthOfField=bn;exports.DeviceFlag=Vu;exports.DocumentExtension=Yx;exports.DragControls=Ko;exports.DragMode=Ug;exports.DropListener=Os;exports.Duplicatable=Gg;exports.EffectWrapper=Ic;exports.EmissionModule=Rs;exports.EmphasizeOnClick=Ya;exports.EngineLoadingView=jc;exports.EnvironmentScene=Bu;exports.EventList=ne;exports.EventListEvent=Ru;exports.EventSystem=Gt;exports.EventTrigger=Gu;exports.FieldWithDefault=Nw;exports.FileReference=ir;exports.FileReferenceSerializer=m0;exports.FileSpawnModel=xM;exports.File_Event=Aw;exports.FixedJoint=xy;exports.Fog=tl;exports.FrameEvent=ge;exports.GENERATOR=ka;exports.GameObject=S;exports.Gizmos=B;exports.GltfExport=Yg;exports.GltfExportBox=Xg;exports.Gradient=Ar;exports.Graphic=fh;exports.GraphicRaycaster=Au;exports.Graphics=co;exports.GridHelper=il;exports.GridLayoutGroup=py;exports.GroundProjectedEnv=Xn;exports.GroupActionModel=Zo;exports.HideFlags=yu;exports.HideOnStart=Ii;exports.HingeJoint=mh;exports.HorizontalLayoutGroup=fy;exports.HostData=WC;exports.Image=dl;exports.ImageReference=tr;exports.ImageReferenceSerializer=p0;exports.InheritVelocityModule=ky;exports.Input=y0;exports.InputEventQueue=ti;exports.InputEvents=Pe;exports.InputField=Uy;exports.InstanceHandle=cr;exports.InstancingHandler=gr;exports.InstancingUtil=Ni;exports.InstantiateEvent=t0;exports.InstantiateIdProvider=xt;exports.InstantiateOptions=gn;exports.Interactable=Bg;exports.JoinedRoomResponse=v1;exports.KeyEventArgs=u1;exports.Keyframe=oi;exports.LODGroup=nf;exports.LODModel=nl;exports.LeftRoomResponse=w1;exports.Light=Ot;exports.LightData=k0;exports.LimitVelocityOverLifetimeModule=nt;exports.LoadingElementOptions=fA;exports.LogStats=jg;exports.LogType=gi;exports.LookAt=zy;exports.LookAtConstraint=sl;exports.MODULES=T;exports.MainModule=Lt;exports.MarkerTrackHandler=Iu;exports.MarkerType=Sg;exports.MaskableGraphic=ph;exports.MaterialPropertyBlock=ys;exports.Mathf=I;exports.MeshCollider=wo;exports.MeshRenderer=ah;exports.MinMaxCurve=H;exports.MinMaxGradient=Dr;exports.NEEDLE_ENGINE_FEATURE_FLAGS=qm;exports.NEKeyboardEvent=Fl;exports.NEPointerEvent=ss;exports.NeedleButtonElement=Xx;exports.NeedleEngineWebComponent=Hy;exports.NeedleMenu=Yn;exports.NeedlePatchesKey=gd;exports.NeedleXRController=dg;exports.NeedleXRSession=q;exports.NeedleXRSync=U0;exports.NeedleXRUtils=N0;exports.NestedGltf=ol;exports.NetworkConnection=C0;exports.NetworkedStreamEvents=Un;exports.NetworkedStreams=ih;exports.Networking=Oy;exports.NewInstanceModel=n0;exports.NoiseModule=me;exports.ObjectRaycaster=$i;exports.ObjectUtils=_o;exports.OffsetConstraint=Tr;exports.OneEuroFilter=pd;exports.OneEuroFilterXYZ=Fm;exports.OpenURL=ul;exports.OrbitControls=de;exports.Outline=el;exports.OwnershipEvent=S0;exports.OwnershipModel=ag;exports.PUBLIC_KEY=no;exports.Padding=kr;exports.ParticleBurst=hu;exports.ParticleSubEmitter=Ey;exports.ParticleSystem=Lc;exports.ParticleSystemBaseBehaviour=Mo;exports.ParticleSystemRenderer=Yi;exports.ParticleSystemShapeType=cu;exports.PeerHandle=fs;exports.PeerNetworking=w0;exports.Physics=La;exports.PhysicsExtension=cy;exports.PhysicsMaterialCombine=st;exports.PixelationEffect=vh;exports.PlayAnimationOnClick=Ac;exports.PlayAudioOnClick=uo;exports.PlayableDirector=Ia;exports.PlayerColor=Fa;exports.PlayerState=zi;exports.PlayerStateEvent=cx;exports.PlayerSync=oy;exports.PlayerView=P0;exports.PlayerViewManager=O0;exports.PointerEventData=Kc;exports.PointerType=bu;exports.PostProcessingEffect=Xe;exports.PostProcessingEffectOrder=et;exports.PostProcessingHandler=Ua;exports.PreliminaryAction=Ka;exports.PreliminaryTrigger=ch;exports.PrimitiveType=Na;exports.Progress=oe;exports.PromiseAllWithErrors=jm;exports.PromiseErrorResult=Dp;exports.RGBAColor=te;exports.RapierPhysics=Pa;exports.RawImage=yf;exports.RaycastOptions=bo;exports.Rect=ux;exports.RectTransform=mn;exports.ReflectionProbe=os;exports.RegisteredAnimationInfo=so;exports.RemoteSkybox=Fu;exports.RenderTexture=Bn;exports.RenderTextureSerializer=mw;exports.Renderer=Ht;exports.RendererData=M0;exports.RendererLightmap=Vg;exports.Rigidbody=$e;exports.RigidbodyConstraints=Ve;exports.RoomEvents=K;exports.RotationBySpeedModule=Qi;exports.RotationOverLifetimeModule=_n;exports.SceneLightSettings=su;exports.SceneSwitcher=We;exports.ScreenCapture=Eo;exports.ScreenSpaceAmbientOcclusion=Ts;exports.ScreenSpaceAmbientOcclusionN8=vn;exports.ScrollFollow=Ls;exports.SeeThrough=As;exports.SendQueue=ln;exports.SerializationContext=ig;exports.SetActiveOnClick=ty;exports.ShadowCatcher=Ch;exports.ShapeModule=My;exports.ShapeOverlapResult=Xv;exports.SharpeningEffect=xh;exports.SignalAsset=Lu;exports.SignalReceiver=Jc;exports.SignalReceiverEvent=Zc;exports.SignalTrackHandler=Rc;exports.Size=dx;exports.SizeBySpeedModule=di;exports.SizeOverLifetimeModule=Lr;exports.SkinnedMeshRenderer=$g;exports.SmoothFollow=uf;exports.SpatialGrabRaycaster=fr;exports.SpatialHtml=kh;exports.SpatialTrigger=ff;exports.SpatialTriggerReceiver=Gn;exports.SpectatorCamera=pf;exports.SphereCollider=qa;exports.SphereIntersection=pg;exports.SplineContainer=Ur;exports.SplineData=qn;exports.SplineWalker=Zi;exports.Sprite=Ms;exports.SpriteData=Ca;exports.SpriteRenderer=ci;exports.SpriteSheet=ja;exports.StateMachineBehaviour=$P;exports.StreamEndedEvent=kg;exports.StreamReceivedEvent=Sw;exports.SubEmitterSystem=du;exports.SyncedCamera=Iy;exports.SyncedRoom=wn;exports.SyncedTransform=pn;exports.TapGestureTrigger=ny;exports.TeleportTarget=Zu;exports.TestRunner=jy;exports.TestSimulateUserData=By;exports.Text=Dt;exports.TextBuilder=dy;exports.TextExtension=ef;exports.TextureSheetAnimationModule=It;exports.TiltShiftEffect=Zn;exports.Time=E0;exports.ToneMappingEffect=mo;exports.TrackHandler=Ga;exports.TrackType=fi;exports.TrailModule=Le;exports.TransformData=Ae;exports.TransformGizmo=zr;exports.TriggerBuilder=Rt;exports.TriggerModel=ao;exports.TypeStore=P;exports.UIRaycastUtils=wg;exports.UIRootComponent=dh;exports.USDDocument=Kg;exports.USDObject=qe;exports.USDWriter=Kw;exports.USDZExporter=Zw;exports.USDZExporter$1=Wn;exports.USDZText=pa;exports.USDZUIExtension=gy;exports.UriSerializer=gw;exports.UsageMarker=oh;exports.UserJoinedOrLeftRoomModel=x1;exports.VERSION=ii;exports.VariantAction=Jg;exports.VelocityOverLifetimeModule=Fe;exports.VerticalLayoutGroup=uy;exports.VideoPlayer=tt;exports.ViewDevice=gs;exports.Vignette=Br;exports.VisibilityAction=hh;exports.Voip=vo;exports.Volume=Fr;exports.VolumeParameter=z;exports.VolumeProfile=af;exports.WaitForFrames=l1;exports.WaitForPromise=g0;exports.WaitForSeconds=ng;exports.Watch=ms;exports.WebARCameraBackground=Rh;exports.WebARSessionRoot=Ui;exports.WebXR=Ju;exports.WebXRButtonFactory=lo;exports.WebXRImageTracking=Th;exports.WebXRImageTrackingModel=js;exports.WebXRPlaneTracking=Bs;exports.WebXRTrackedImage=za;exports.XRControllerFollow=Is;exports.XRControllerModel=vs;exports.XRControllerMovement=xi;exports.XRFlag=ji;exports.XRRig=Sf;exports.XRState=Wt;exports.XRStateFlag=Ln;exports.__Ignore=Kx;exports.__internalNotifyObjectDestroyed=yP;exports.activeInHierarchyFieldName=jn;exports.addAttributeChangeCallback=Lm;exports.addComponent=hn;exports.addCustomExtensionPlugin=HM;exports.addNewComponent=or;exports.addPatch=gu;exports.apply=Pu;exports.applyHMRChanges=BP;exports.applyPrototypeExtensions=K0;exports.beginListenDestroy=i0;exports.beginListenInstantiate=o0;exports.binaryIdentifierCasts=sg;exports.build_scene_functions=Q1;exports.builtinComponentKeyName=Ho;exports.calculateProgress01=Gy;exports.clearMessages=OS;exports.colorSerializer=YP;exports.compareAssociation=c0;exports.componentSerializer=Pd;exports.copyTexture=Tv;exports.createMotion=fw;exports.debugNet=Yt;exports.debugOwner=Ul;exports.decompressGpuTexture=ix;exports.deepClone=Fc;exports.delay=_s;exports.delayForFrames=Uc;exports.deserializeObject=qd;exports.destroy=bi;exports.destroyComponentInstance=aw;exports.determineMimeTypeFromExtension=Dw;exports.disposeObjectResources=we;exports.disposeStream=zn;exports.editorGuidKeyName=ec;exports.enableSpatialConsole=ya;exports.euler=ZP;exports.eventListSerializer=iO;exports.exportAsGLTF=SA;exports.findByGuid=yg;exports.findObjectOfType=Wa;exports.findObjectsOfType=cw;exports.findResourceUsers=mg;exports.fitCamera=yw;exports.fitObjectIntoVolume=Dv;exports.foreachComponent=ur;exports.foreachComponentEnumerator=Mu;exports.forward=GS;exports.generateQRCode=L0;exports.generateSeed=s0;exports.getBoundingBox=ri;exports.getCameraController=Sv;exports.getComponent=vr;exports.getComponentInChildren=Qc;exports.getComponentInParent=Cc;exports.getComponents=Xc;exports.getComponentsInChildren=$a;exports.getComponentsInParent=ku;exports.getFormattedDate=qw;exports.getIconElement=wt;exports.getIconTexture=Yp;exports.getLoader=un;exports.getOrAddComponent=qc;exports.getParam=x;exports.getParentHierarchyPath=XS;exports.getPath=sS;exports.getPeerOptions=g1;exports.getPeerjsInstance=v0;exports.getResourceUserCount=bP;exports.getTempColor=Mv;exports.getTempQuaternion=ei;exports.getTempVector=F;exports.getUrlParams=Bc;exports.getVisibleInCustomShadowRendering=Av;exports.getWorldDirection=kv;exports.getWorldEuler=Nm;exports.getWorldPosition=Y;exports.getWorldQuaternion=pe;exports.getWorldRotation=pu;exports.getWorldScale=je;exports.hasCommercialLicense=$n;exports.hasIndieLicense=$c;exports.hasPointerEventComponent=tu;exports.hasProLicense=Vn;exports.hideDebugConsole=Bv;exports.imageToCanvas=nx;exports.initEngine=hA;exports.instantiate=ho;exports.invokeLoadedImportPluginHooks=zw;exports.invokeXRSessionEnd=D0;exports.invokeXRSessionStart=A0;exports.isActiveInHierarchy=Z0;exports.isActiveSelf=Va;exports.isAndroidDevice=hS;exports.isAnimationAction=Rv;exports.isComponent=Qm;exports.isDebugMode=eS;exports.isDesktop=rS;exports.isDestroyed=dr;exports.isDevEnvironment=A;exports.isDisposed=gP;exports.isExporting=wA;exports.isGLTFModel=Wv;exports.isHostedOnGlitch=dv;exports.isHotReloadEnabled=am;exports.isHotReloading=IP;exports.isIPad=lS;exports.isIconElement=I0;exports.isLocalNetwork=yi;exports.isMacOS=uS;exports.isMobileDevice=aS;exports.isMozillaXR=dS;exports.isQuest=mS;exports.isResourceTrackingEnabled=W0;exports.isSafari=pS;exports.isUsingInstancing=Ou;exports.isiOS=fS;exports.isiPad=cS;exports.loadAsset=sA;exports.loadPMREM=Mg;exports.loadSync=Wy;exports.logHierarchy=Nd;exports.lookAtInverse=BS;exports.lookAtObject=zc;exports.lookAtScreenPoint=FS;exports.makeId=iS;exports.makeIdFromRandomWords=pv;exports.makeNameSafe=wi;exports.markAsInstancedRendered=J0;exports.microphonePermissionsGranted=gS;exports.nameof=Jx;exports.nameofFactory=uv;exports.objectSerializer=pw;exports.offXRSessionEnd=D1;exports.offXRSessionStart=A1;exports.onAfterRender=jC;exports.onBeforeRender=IC;exports.onClear=DC;exports.onDestroy=LC;exports.onInitialized=Ym;exports.onStart=_u;exports.onUpdate=Zv;exports.onXRSessionEnd=cg;exports.onXRSessionStart=wu;exports.parseSync=$x;exports.placeOnSurface=Lv;exports.postprocessFBXMaterials=Wm;exports.prefix=cO;exports.pushState=fv;exports.randomNumber=nS;exports.registerBinaryType=og;exports.registerComponent=Su;exports.registerComponentExtension=zg;exports.registerCustomEffectType=Ki;exports.registerExportExtensions=Ng;exports.registerExtensions=ru;exports.registerHotReloadType=hw;exports.registerLoader=Yv;exports.registerPrefabProvider=a0;exports.registerPrototypeExtensions=gg;exports.registerType=Hm;exports.relativePathPrefix=gv;exports.removeAttributeChangeCallback=Im;exports.removeComponent=bg;exports.removeCustomImportExtensionType=qM;exports.removePatch=EC;exports.resolveUrl=ws;exports.sanitizeString=mv;exports.saveImage=zx;exports.screenshot=BT;exports.screenshot2=$y;exports.sendDestroyed=Zm;exports.serializable=f;exports.serializeObject=d0;exports.serializeable=Be;exports.setActive=sc;exports.setAllowBalloonMessages=vv;exports.setAllowOverlayMessages=xS;exports.setAutoFitEnabled=Ud;exports.setCameraController=jp;exports.setDestroyed=tw;exports.setDevEnvironment=TS;exports.setDisposable=H0;exports.setDontDestroy=ta;exports.setOrAddParamsToUrl=Ap;exports.setParam=tS;exports.setParamWithoutReload=yc;exports.setPeerOptions=y1;exports.setResourceTrackingEnabled=mP;exports.setState=Am;exports.setVisibleInCustomShadowRendering=$m;exports.setWorldEuler=Vm;exports.setWorldPosition=at;exports.setWorldPositionXYZ=hr;exports.setWorldQuaternion=dn;exports.setWorldQuaternionXYZW=zm;exports.setWorldRotation=Ev;exports.setWorldRotationXYZ=Nc;exports.setWorldScale=Ma;exports.showBalloonError=Vc;exports.showBalloonMessage=Se;exports.showBalloonWarning=fe;exports.showDebugConsole=Gm;exports.slerp=Pv;exports.syncDestroy=Wc;exports.syncField=Og;exports.syncInstantiate=Jm;exports.textureToCanvas=QS;exports.toSourceId=yv;exports.tryCastBinary=_0;exports.tryDetermineMimetypeFromBinary=Iw;exports.tryDetermineMimetypeFromURL=Lw;exports.tryFindObject=Oa;exports.tryGetGuid=b0;exports.unregisterHotReloadType=dw;exports.unwatchWrite=Dm;exports.useForAutoFit=Cv;exports.validate=Ct;exports.watchWrite=fu;
|
|
1654
|
+
`),this.#n.innerHTML=this.#e.innerHTML,this.#n.style.cssText="display: flex; align-items: center; justify-content: center;",this.#e.innerHTML=this.#n.outerHTML,this.#t.innerHTML=this.#e.outerHTML,this.#t.prepend(this.#s),vc(Kp,{element:this.#t}),this.#o?.disconnect(),this.#o??=new MutationObserver(()=>this.#c()),this.#o.observe(this.#e,{attributes:!0}),Rp&&console.log("Needle Button updated",this)}#c(){this.#e&&(this.#e.style.display==="none"?this.style.display="none":this.style.display==="none"&&(this.style.display=""))}#a=e=>{Rp&&console.log("Needle Button clicked",{defaultPrevented:e.defaultPrevented,hasButton:!!this.#e}),!e.defaultPrevented&&this.#e&&this.#e.click()}}typeof window<"u"&&!window.customElements.get(hv)&&window.customElements.define(hv,Xx);const Bl=x("debugavatar");class qy{root;head;leftHand;rigthHand;get isValid(){return this.head!==null&&this.head!==void 0}constructor(e,t,i,n){this.root=e,this.head=t,this.leftHand=i,this.rigthHand=n,this.root?.traverse(o=>o.layers.set(2))}}class Qx{avatarRegistryUrl=null;async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let i=null;if(typeof t=="string"){if(i=await this.loadAvatar(e,t),!i){const o=new gn;i=S.instantiate(Oa(t,e.scene),o)}}else i=t;if(!i)return null;const n=this.findAvatar(i);return n.isValid?(Bl&&console.log("[Custom Avatar] valid config",t,Bl?n:""),n):(console.warn("[Custom Avatar] config isn't valid",t,Bl?n:""),null)}async loadAvatar(e,t){if(console.assert(t!=null&&typeof t=="string","Avatar id must not be null"),t.length<=0||!t)return null;if(Bl&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){const n=await fetch("./"+t);let o=null;if(n.ok){const a=await n.blob();a&&(o=await a.arrayBuffer())}return o?(await un().parseSync(e,o,null,0))?.scene??null:null}const i=new X.GLTFLoader;return ay(i,e),new Promise((n,o)=>{const r=this.avatarRegistryUrl+"/"+t;i.load(r,async a=>{await un().createBuiltinComponents(e,r,a,null,void 0),n(a.scene)},a=>{Bl&&console.log("[Custom Avatar] "+a.loaded/a.total*100+"% loaded of "+a.total/1024+"kB")},a=>{console.error("[Custom Avatar] Error when loading: "+a),n(null)})})}cacheModel(e,t){}findAvatar(e){const t=e;let i=t;i.children.length==1&&(i=e.children[0]);let n=this.findAvatarPart(i,["head"]);const o=this.findAvatarPart(i,["left","hand"]),r=this.findAvatarPart(i,["right","hand"]);if(!n){n=t;const l=new c.Vector3;new c.Box3().setFromObject(n).getSize(l);const h=Math.max(l.x,l.y,l.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+h+" meters! Should be < 0.3m"),h>.3&&n.scale.multiplyScalar(1/h*.3)}return new qy(t,n,o,r)}findAvatarPart(e,t){const i=e.name.toLowerCase();let n=!0;for(const o of t){if(!n)break;i.indexOf(o)===-1&&(n=!1)}if(n)return e;if(e.children)for(const o of e.children){const r=this.findAvatarPart(o,t);if(r)return r}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}}class Yx{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(e){}}class Kx{}const OA=Object.freeze(Object.defineProperty({__proto__:null,ActionBuilder:ue,ActionCollection:rx,ActionModel:Jt,AlignmentConstraint:th,Animation:Tt,AnimationCurve:gh,AnimationExtension:qu,AnimationTrackHandler:Ec,Animator:lt,AnimatorController:Vi,Antialiasing:_h,Attractor:al,AudioExtension:Or,AudioListener:ds,AudioSource:vi,AudioTrackHandler:us,Avatar:fo,AvatarBlink_Simple:xr,AvatarEyeLook_Rotation:Ag,AvatarLoader:Qx,AvatarMarker:Oe,AvatarModel:qy,Avatar_Brain_LookAt:Tc,Avatar_MouthShapes:nh,Avatar_MustacheShake:Rg,Avatar_POI:lr,AxesHelper:Ha,BaseUIComponent:Wi,BasicIKConstraint:Lg,BehaviorExtension:ly,BehaviorModel:St,BloomEffect:cf,BoxCollider:Nu,BoxGizmo:Rr,BoxHelperComponent:bt,Button:Ds,CallInfo:ls,Camera:si,CameraTargetReachedEvent:kc,Canvas:Ba,CanvasGroup:po,CapsuleCollider:bs,ChangeMaterialOnClick:ey,ChangeTransformOnClick:Mr,CharacterController:Sr,CharacterControllerInput:Cs,ChromaticAberration:bh,ClickThrough:vf,ColorAdjustments:ko,ColorBySpeedModule:rl,ColorOverLifetimeModule:rf,ContactShadows:sh,ControlTrackHandler:ju,CursorFollow:Nr,CustomBranding:Er,Deletable:Fg,DeleteBox:ro,DepthOfField:bn,DeviceFlag:Vu,DocumentExtension:Yx,DragControls:Ko,DropListener:Os,Duplicatable:Gg,EffectWrapper:Ic,EmissionModule:Rs,EmphasizeOnClick:Ya,EnvironmentScene:Bu,EventList:ne,EventListEvent:Ru,EventSystem:Gt,EventTrigger:Gu,FieldWithDefault:Nw,FixedJoint:xy,Fog:tl,GltfExport:Yg,GltfExportBox:Xg,Gradient:Ar,Graphic:fh,GraphicRaycaster:Au,GridHelper:il,GridLayoutGroup:py,GroundProjectedEnv:Xn,GroupActionModel:Zo,HideOnStart:Ii,HingeJoint:mh,HorizontalLayoutGroup:fy,get HoverAnimation(){return exports.HoverAnimation},Image:dl,InheritVelocityModule:ky,InputField:Uy,InstanceHandle:cr,InstancingHandler:gr,Interactable:Bg,Keyframe:oi,LODGroup:nf,LODModel:nl,Light:Ot,LimitVelocityOverLifetimeModule:nt,LogStats:jg,LookAt:zy,LookAtConstraint:sl,MainModule:Lt,MarkerTrackHandler:Iu,MaskableGraphic:ph,MeshCollider:wo,MeshRenderer:ah,MinMaxCurve:H,MinMaxGradient:Dr,NeedleMenu:Yn,NestedGltf:ol,Networking:Oy,NoiseModule:me,ObjectRaycaster:$i,OffsetConstraint:Tr,OpenURL:ul,OrbitControls:de,Outline:el,Padding:kr,ParticleBurst:hu,ParticleSubEmitter:Ey,ParticleSystem:Lc,ParticleSystemRenderer:Yi,PhysicsExtension:cy,PixelationEffect:vh,PlayAnimationOnClick:Ac,PlayAudioOnClick:uo,PlayableDirector:Ia,PlayerColor:Fa,PointerEventData:Kc,PostProcessingHandler:Ua,PreliminaryAction:Ka,PreliminaryTrigger:ch,RawImage:yf,Rect:ux,RectTransform:mn,ReflectionProbe:os,RegisteredAnimationInfo:so,RemoteSkybox:Fu,Renderer:Ht,RendererLightmap:Vg,Rigidbody:$e,RotationBySpeedModule:Qi,RotationOverLifetimeModule:_n,SceneSwitcher:We,ScreenCapture:Eo,ScreenSpaceAmbientOcclusion:Ts,ScreenSpaceAmbientOcclusionN8:vn,ScrollFollow:Ls,SeeThrough:As,SetActiveOnClick:ty,ShadowCatcher:Ch,ShapeModule:My,SharpeningEffect:xh,SignalAsset:Lu,SignalReceiver:Jc,SignalReceiverEvent:Zc,SignalTrackHandler:Rc,Size:dx,SizeBySpeedModule:di,SizeOverLifetimeModule:Lr,SkinnedMeshRenderer:$g,SmoothFollow:uf,SpatialGrabRaycaster:fr,SpatialHtml:kh,SpatialTrigger:ff,SpatialTriggerReceiver:Gn,SpectatorCamera:pf,SphereCollider:qa,SplineContainer:Ur,SplineData:qn,SplineWalker:Zi,Sprite:Ms,SpriteData:Ca,SpriteRenderer:ci,SpriteSheet:ja,SubEmitterSystem:du,SyncedCamera:Iy,SyncedRoom:wn,SyncedTransform:pn,TapGestureTrigger:ny,TeleportTarget:Zu,TestRunner:jy,TestSimulateUserData:By,Text:Dt,TextBuilder:dy,TextExtension:ef,TextureSheetAnimationModule:It,TiltShiftEffect:Zn,ToneMappingEffect:mo,TrailModule:Le,TransformData:Ae,TransformGizmo:zr,TriggerBuilder:Rt,TriggerModel:ao,UIRaycastUtils:wg,UIRootComponent:dh,USDZExporter:Wn,USDZText:pa,USDZUIExtension:gy,UsageMarker:oh,VariantAction:Jg,VelocityOverLifetimeModule:Fe,VerticalLayoutGroup:uy,VideoPlayer:tt,get ViewBox(){return exports.ViewBox},Vignette:Br,VisibilityAction:hh,Voip:vo,Volume:Fr,VolumeParameter:z,VolumeProfile:af,WebARCameraBackground:Rh,WebARSessionRoot:Ui,WebXR:Ju,WebXRImageTracking:Th,WebXRImageTrackingModel:js,WebXRPlaneTracking:Bs,WebXRTrackedImage:za,XRControllerFollow:Is,XRControllerModel:vs,XRControllerMovement:xi,XRFlag:ji,XRRig:Sf,XRState:Wt,__Ignore:Kx},Symbol.toStringTag,{value:"Module"}));exports.SplineUtils=void 0;(s=>{function e(t,i=!1,n=.75){const o=new Ur,r=1-I.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 qn;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 MA extends ce.WorkerBase{constructor(){super(new Worker(new URL("/generateMeshBVH.worker-DiCnZlf3.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:ga&&ga.tagName.toUpperCase()==="SCRIPT"&&ga.src||new URL("needle-engine.bundle-DDZfnvgI.umd.cjs",document.baseURI).href),{type:"module"})),this.name="GenerateMeshBVHWorker"}runTask(e,t,i={}){return new Promise((n,o)=>{if(t.getAttribute("position").isInterleavedBufferAttribute||t.index&&t.index.isInterleavedBufferAttribute)throw new Error("GenerateMeshBVHWorker: InterleavedBufferAttribute are not supported for the geometry attributes.");e.onerror=h=>{o(new Error(`[GenerateMeshBVHWorker] ${h.message||"Unknown error. Please check the server console. If you're using vite try adding 'three-mesh-bvh' to 'optimizeDeps.exclude' in your vite.config.js"}`))},e.onmessage=h=>{const{data:d}=h;if(d.error)o(new Error(d.error)),e.onmessage=null;else if(d.serialized){const{serialized:u,position:p}=d,m=ce.MeshBVH.deserialize(u,t,{setIndex:!1}),y=Object.assign({setBoundingBox:!0},i);if(t.attributes.position.array=p,u.index)if(t.index)t.index.array=u.index;else{const _=new c.BufferAttribute(u.index,1,!1);t.setIndex(_)}y.setBoundingBox&&(t.boundingBox=m.getBoundingBox(new c.Box3)),i.onProgress&&i.onProgress(d.progress),n(m),e.onmessage=null}else i.onProgress&&i.onProgress(d.progress)};const r=t.index?t.index.array:null,a=t.attributes.position.array,l=[a];r&&l.push(r),e.postMessage({index:r,position:a,options:{...i,onProgress:null,includedProgressCallback:!!i.onProgress,groups:[...t.groups]}},l.map(h=>h.buffer).filter(h=>typeof SharedArrayBuffer>"u"||!(h instanceof SharedArrayBuffer)))})}}const kA=Object.freeze(Object.defineProperty({__proto__:null,GenerateMeshBVHWorker:MA},Symbol.toStringTag,{value:"Module"}));exports.$componentName=Gv;exports.$physicsKey=AC;exports.ActionBuilder=ue;exports.ActionCollection=rx;exports.ActionModel=Jt;exports.Addressables=f0;exports.AlignmentConstraint=th;exports.AmbientMode=ba;exports.Animation=Tt;exports.AnimationCurve=gh;exports.AnimationExtension=qu;exports.AnimationTrackHandler=Ec;exports.AnimationUtils=Hn;exports.Animator=lt;exports.AnimatorConditionMode=Zs;exports.AnimatorController=Vi;exports.AnimatorControllerParameterType=vg;exports.AnimatorStateInfo=Vl;exports.Antialiasing=_h;exports.Application=fn;exports.AssetDatabase=V0;exports.AssetReference=Z;exports.Attractor=al;exports.AudioExtension=Or;exports.AudioListener=ds;exports.AudioSource=vi;exports.AudioTrackHandler=us;exports.Avatar=fo;exports.AvatarBlink_Simple=xr;exports.AvatarEyeLook_Rotation=Ag;exports.AvatarLoader=Qx;exports.AvatarMarker=Oe;exports.AvatarModel=qy;exports.Avatar_Brain_LookAt=Tc;exports.Avatar_MouthShapes=nh;exports.Avatar_MustacheShake=Rg;exports.Avatar_POI=lr;exports.Axes=ua;exports.AxesHelper=Ha;exports.BUILD_TIME=_c;exports.BaseUIComponent=Wi;exports.BasicIKConstraint=Lg;exports.BehaviorExtension=ly;exports.BehaviorModel=St;exports.BloomEffect=cf;exports.BoxCollider=Nu;exports.BoxGizmo=Rr;exports.BoxHelperComponent=bt;exports.Button=Ds;exports.ButtonsFactory=Fi;exports.CallDirection=Cw;exports.CallInfo=ls;exports.Camera=si;exports.CameraTargetReachedEvent=kc;exports.Canvas=Ba;exports.CanvasGroup=po;exports.CapsuleCollider=bs;exports.ChangeMaterialOnClick=ey;exports.ChangeTransformOnClick=Mr;exports.CharacterController=Sr;exports.CharacterControllerInput=Cs;exports.ChromaticAberration=bh;exports.CircularBuffer=_i;exports.ClearFlags=ar;exports.ClickThrough=vf;exports.ClipExtrapolation=Mn;exports.Collider=Xi;exports.Collision=qv;exports.CollisionDetectionMode=Tu;exports.ColorAdjustments=ko;exports.ColorBySpeedModule=rl;exports.ColorOverLifetimeModule=rf;exports.Component=FP;exports.Component$1=E;exports.ComponentLifecycleEvents=mu;exports.Components=OA;exports.ConnectionEvents=x0;exports.ContactPoint=Hv;exports.ContactShadows=sh;exports.Context=U;exports.ContextArgs=Y1;exports.ContextEvent=ae;exports.ContextRegistry=le;exports.ControlTrackHandler=ju;exports.CursorFollow=Nr;exports.CustomBranding=Er;exports.CustomShader=ve;exports.DefaultReflectionMode=Qd;exports.Deletable=Fg;exports.DeleteBox=ro;exports.DepthOfField=bn;exports.DeviceFlag=Vu;exports.DocumentExtension=Yx;exports.DragControls=Ko;exports.DragMode=Ug;exports.DropListener=Os;exports.Duplicatable=Gg;exports.EffectWrapper=Ic;exports.EmissionModule=Rs;exports.EmphasizeOnClick=Ya;exports.EngineLoadingView=jc;exports.EnvironmentScene=Bu;exports.EventList=ne;exports.EventListEvent=Ru;exports.EventSystem=Gt;exports.EventTrigger=Gu;exports.FieldWithDefault=Nw;exports.FileReference=ir;exports.FileReferenceSerializer=m0;exports.FileSpawnModel=xM;exports.File_Event=Aw;exports.FixedJoint=xy;exports.Fog=tl;exports.FrameEvent=ge;exports.GENERATOR=ka;exports.GameObject=S;exports.Gizmos=B;exports.GltfExport=Yg;exports.GltfExportBox=Xg;exports.Gradient=Ar;exports.Graphic=fh;exports.GraphicRaycaster=Au;exports.Graphics=co;exports.GridHelper=il;exports.GridLayoutGroup=py;exports.GroundProjectedEnv=Xn;exports.GroupActionModel=Zo;exports.HideFlags=yu;exports.HideOnStart=Ii;exports.HingeJoint=mh;exports.HorizontalLayoutGroup=fy;exports.HostData=WC;exports.Image=dl;exports.ImageReference=tr;exports.ImageReferenceSerializer=p0;exports.InheritVelocityModule=ky;exports.Input=y0;exports.InputEventQueue=ti;exports.InputEvents=Pe;exports.InputField=Uy;exports.InstanceHandle=cr;exports.InstancingHandler=gr;exports.InstancingUtil=Ni;exports.InstantiateEvent=t0;exports.InstantiateIdProvider=xt;exports.InstantiateOptions=gn;exports.Interactable=Bg;exports.JoinedRoomResponse=v1;exports.KeyEventArgs=u1;exports.Keyframe=oi;exports.LODGroup=nf;exports.LODModel=nl;exports.LeftRoomResponse=w1;exports.Light=Ot;exports.LightData=k0;exports.LimitVelocityOverLifetimeModule=nt;exports.LoadingElementOptions=fA;exports.LogStats=jg;exports.LogType=gi;exports.LookAt=zy;exports.LookAtConstraint=sl;exports.MODULES=T;exports.MainModule=Lt;exports.MarkerTrackHandler=Iu;exports.MarkerType=Sg;exports.MaskableGraphic=ph;exports.MaterialPropertyBlock=ys;exports.Mathf=I;exports.MeshCollider=wo;exports.MeshRenderer=ah;exports.MinMaxCurve=H;exports.MinMaxGradient=Dr;exports.NEEDLE_ENGINE_FEATURE_FLAGS=qm;exports.NEKeyboardEvent=Fl;exports.NEPointerEvent=ss;exports.NeedleButtonElement=Xx;exports.NeedleEngineWebComponent=Hy;exports.NeedleMenu=Yn;exports.NeedlePatchesKey=gd;exports.NeedleXRController=dg;exports.NeedleXRSession=q;exports.NeedleXRSync=U0;exports.NeedleXRUtils=N0;exports.NestedGltf=ol;exports.NetworkConnection=C0;exports.NetworkedStreamEvents=Un;exports.NetworkedStreams=ih;exports.Networking=Oy;exports.NewInstanceModel=n0;exports.NoiseModule=me;exports.ObjectRaycaster=$i;exports.ObjectUtils=_o;exports.OffsetConstraint=Tr;exports.OneEuroFilter=pd;exports.OneEuroFilterXYZ=Fm;exports.OpenURL=ul;exports.OrbitControls=de;exports.Outline=el;exports.OwnershipEvent=S0;exports.OwnershipModel=ag;exports.PUBLIC_KEY=no;exports.Padding=kr;exports.ParticleBurst=hu;exports.ParticleSubEmitter=Ey;exports.ParticleSystem=Lc;exports.ParticleSystemBaseBehaviour=Mo;exports.ParticleSystemRenderer=Yi;exports.ParticleSystemShapeType=cu;exports.PeerHandle=fs;exports.PeerNetworking=w0;exports.Physics=La;exports.PhysicsExtension=cy;exports.PhysicsMaterialCombine=st;exports.PixelationEffect=vh;exports.PlayAnimationOnClick=Ac;exports.PlayAudioOnClick=uo;exports.PlayableDirector=Ia;exports.PlayerColor=Fa;exports.PlayerState=zi;exports.PlayerStateEvent=cx;exports.PlayerSync=oy;exports.PlayerView=P0;exports.PlayerViewManager=O0;exports.PointerEventData=Kc;exports.PointerType=bu;exports.PostProcessingEffect=Xe;exports.PostProcessingEffectOrder=et;exports.PostProcessingHandler=Ua;exports.PreliminaryAction=Ka;exports.PreliminaryTrigger=ch;exports.PrimitiveType=Na;exports.Progress=oe;exports.PromiseAllWithErrors=jm;exports.PromiseErrorResult=Dp;exports.RGBAColor=te;exports.RapierPhysics=Pa;exports.RawImage=yf;exports.RaycastOptions=bo;exports.Rect=ux;exports.RectTransform=mn;exports.ReflectionProbe=os;exports.RegisteredAnimationInfo=so;exports.RemoteSkybox=Fu;exports.RenderTexture=Bn;exports.RenderTextureSerializer=mw;exports.Renderer=Ht;exports.RendererData=M0;exports.RendererLightmap=Vg;exports.Rigidbody=$e;exports.RigidbodyConstraints=Ve;exports.RoomEvents=K;exports.RotationBySpeedModule=Qi;exports.RotationOverLifetimeModule=_n;exports.SceneLightSettings=su;exports.SceneSwitcher=We;exports.ScreenCapture=Eo;exports.ScreenSpaceAmbientOcclusion=Ts;exports.ScreenSpaceAmbientOcclusionN8=vn;exports.ScrollFollow=Ls;exports.SeeThrough=As;exports.SendQueue=ln;exports.SerializationContext=ig;exports.SetActiveOnClick=ty;exports.ShadowCatcher=Ch;exports.ShapeModule=My;exports.ShapeOverlapResult=Xv;exports.SharpeningEffect=xh;exports.SignalAsset=Lu;exports.SignalReceiver=Jc;exports.SignalReceiverEvent=Zc;exports.SignalTrackHandler=Rc;exports.Size=dx;exports.SizeBySpeedModule=di;exports.SizeOverLifetimeModule=Lr;exports.SkinnedMeshRenderer=$g;exports.SmoothFollow=uf;exports.SpatialGrabRaycaster=fr;exports.SpatialHtml=kh;exports.SpatialTrigger=ff;exports.SpatialTriggerReceiver=Gn;exports.SpectatorCamera=pf;exports.SphereCollider=qa;exports.SphereIntersection=pg;exports.SplineContainer=Ur;exports.SplineData=qn;exports.SplineWalker=Zi;exports.Sprite=Ms;exports.SpriteData=Ca;exports.SpriteRenderer=ci;exports.SpriteSheet=ja;exports.StateMachineBehaviour=$P;exports.StreamEndedEvent=kg;exports.StreamReceivedEvent=Sw;exports.SubEmitterSystem=du;exports.SyncedCamera=Iy;exports.SyncedRoom=wn;exports.SyncedTransform=pn;exports.TapGestureTrigger=ny;exports.TeleportTarget=Zu;exports.TestRunner=jy;exports.TestSimulateUserData=By;exports.Text=Dt;exports.TextBuilder=dy;exports.TextExtension=ef;exports.TextureSheetAnimationModule=It;exports.TiltShiftEffect=Zn;exports.Time=E0;exports.ToneMappingEffect=mo;exports.TrackHandler=Ga;exports.TrackType=fi;exports.TrailModule=Le;exports.TransformData=Ae;exports.TransformGizmo=zr;exports.TriggerBuilder=Rt;exports.TriggerModel=ao;exports.TypeStore=P;exports.UIRaycastUtils=wg;exports.UIRootComponent=dh;exports.USDDocument=Kg;exports.USDObject=qe;exports.USDWriter=Kw;exports.USDZExporter=Zw;exports.USDZExporter$1=Wn;exports.USDZText=pa;exports.USDZUIExtension=gy;exports.UriSerializer=gw;exports.UsageMarker=oh;exports.UserJoinedOrLeftRoomModel=x1;exports.VERSION=ii;exports.VariantAction=Jg;exports.VelocityOverLifetimeModule=Fe;exports.VerticalLayoutGroup=uy;exports.VideoPlayer=tt;exports.ViewDevice=gs;exports.Vignette=Br;exports.VisibilityAction=hh;exports.Voip=vo;exports.Volume=Fr;exports.VolumeParameter=z;exports.VolumeProfile=af;exports.WaitForFrames=l1;exports.WaitForPromise=g0;exports.WaitForSeconds=ng;exports.Watch=ms;exports.WebARCameraBackground=Rh;exports.WebARSessionRoot=Ui;exports.WebXR=Ju;exports.WebXRButtonFactory=lo;exports.WebXRImageTracking=Th;exports.WebXRImageTrackingModel=js;exports.WebXRPlaneTracking=Bs;exports.WebXRTrackedImage=za;exports.XRControllerFollow=Is;exports.XRControllerModel=vs;exports.XRControllerMovement=xi;exports.XRFlag=ji;exports.XRRig=Sf;exports.XRState=Wt;exports.XRStateFlag=Ln;exports.__Ignore=Kx;exports.__internalNotifyObjectDestroyed=yP;exports.activeInHierarchyFieldName=jn;exports.addAttributeChangeCallback=Lm;exports.addComponent=hn;exports.addCustomExtensionPlugin=HM;exports.addNewComponent=or;exports.addPatch=gu;exports.apply=Pu;exports.applyHMRChanges=BP;exports.applyPrototypeExtensions=K0;exports.beginListenDestroy=i0;exports.beginListenInstantiate=o0;exports.binaryIdentifierCasts=sg;exports.build_scene_functions=Q1;exports.builtinComponentKeyName=Ho;exports.calculateProgress01=Gy;exports.clearMessages=OS;exports.colorSerializer=YP;exports.compareAssociation=c0;exports.componentSerializer=Pd;exports.copyTexture=Tv;exports.createMotion=fw;exports.debugNet=Yt;exports.debugOwner=Ul;exports.decompressGpuTexture=ix;exports.deepClone=Fc;exports.delay=_s;exports.delayForFrames=Uc;exports.deserializeObject=qd;exports.destroy=bi;exports.destroyComponentInstance=aw;exports.determineMimeTypeFromExtension=Dw;exports.disposeObjectResources=we;exports.disposeStream=zn;exports.editorGuidKeyName=ec;exports.enableSpatialConsole=ya;exports.euler=ZP;exports.eventListSerializer=iO;exports.exportAsGLTF=SA;exports.findByGuid=yg;exports.findObjectOfType=Wa;exports.findObjectsOfType=cw;exports.findResourceUsers=mg;exports.fitCamera=yw;exports.fitObjectIntoVolume=Dv;exports.foreachComponent=ur;exports.foreachComponentEnumerator=Mu;exports.forward=GS;exports.generateQRCode=L0;exports.generateSeed=s0;exports.getBoundingBox=ri;exports.getCameraController=Sv;exports.getComponent=vr;exports.getComponentInChildren=Qc;exports.getComponentInParent=Cc;exports.getComponents=Xc;exports.getComponentsInChildren=$a;exports.getComponentsInParent=ku;exports.getFormattedDate=qw;exports.getIconElement=wt;exports.getIconTexture=Yp;exports.getLoader=un;exports.getOrAddComponent=qc;exports.getParam=x;exports.getParentHierarchyPath=XS;exports.getPath=sS;exports.getPeerOptions=g1;exports.getPeerjsInstance=v0;exports.getResourceUserCount=bP;exports.getTempColor=Mv;exports.getTempQuaternion=ei;exports.getTempVector=F;exports.getUrlParams=Bc;exports.getVisibleInCustomShadowRendering=Av;exports.getWorldDirection=kv;exports.getWorldEuler=Nm;exports.getWorldPosition=Y;exports.getWorldQuaternion=pe;exports.getWorldRotation=pu;exports.getWorldScale=je;exports.hasCommercialLicense=$n;exports.hasIndieLicense=$c;exports.hasPointerEventComponent=tu;exports.hasProLicense=Vn;exports.hideDebugConsole=Bv;exports.imageToCanvas=nx;exports.initEngine=hA;exports.instantiate=ho;exports.invokeLoadedImportPluginHooks=zw;exports.invokeXRSessionEnd=D0;exports.invokeXRSessionStart=A0;exports.isActiveInHierarchy=Z0;exports.isActiveSelf=Va;exports.isAndroidDevice=hS;exports.isAnimationAction=Rv;exports.isComponent=Qm;exports.isDebugMode=eS;exports.isDesktop=rS;exports.isDestroyed=dr;exports.isDevEnvironment=A;exports.isDisposed=gP;exports.isExporting=wA;exports.isGLTFModel=Wv;exports.isHostedOnGlitch=dv;exports.isHotReloadEnabled=am;exports.isHotReloading=IP;exports.isIPad=lS;exports.isIconElement=I0;exports.isLocalNetwork=yi;exports.isMacOS=uS;exports.isMobileDevice=aS;exports.isMozillaXR=dS;exports.isQuest=mS;exports.isResourceTrackingEnabled=W0;exports.isSafari=pS;exports.isUsingInstancing=Ou;exports.isiOS=fS;exports.isiPad=cS;exports.loadAsset=sA;exports.loadPMREM=Mg;exports.loadSync=Wy;exports.logHierarchy=Nd;exports.lookAtInverse=BS;exports.lookAtObject=zc;exports.lookAtScreenPoint=FS;exports.makeId=iS;exports.makeIdFromRandomWords=pv;exports.makeNameSafe=wi;exports.markAsInstancedRendered=J0;exports.microphonePermissionsGranted=gS;exports.nameof=Jx;exports.nameofFactory=uv;exports.objectSerializer=pw;exports.offXRSessionEnd=D1;exports.offXRSessionStart=A1;exports.onAfterRender=jC;exports.onBeforeRender=IC;exports.onClear=DC;exports.onDestroy=LC;exports.onInitialized=Ym;exports.onStart=_u;exports.onUpdate=Zv;exports.onXRSessionEnd=cg;exports.onXRSessionStart=wu;exports.parseSync=$x;exports.placeOnSurface=Lv;exports.postprocessFBXMaterials=Wm;exports.prefix=cO;exports.pushState=fv;exports.randomNumber=nS;exports.registerBinaryType=og;exports.registerComponent=Su;exports.registerComponentExtension=zg;exports.registerCustomEffectType=Ki;exports.registerExportExtensions=Ng;exports.registerExtensions=ru;exports.registerHotReloadType=hw;exports.registerLoader=Yv;exports.registerPrefabProvider=a0;exports.registerPrototypeExtensions=gg;exports.registerType=Hm;exports.relativePathPrefix=gv;exports.removeAttributeChangeCallback=Im;exports.removeComponent=bg;exports.removeCustomImportExtensionType=qM;exports.removePatch=EC;exports.resolveUrl=ws;exports.sanitizeString=mv;exports.saveImage=zx;exports.screenshot=BT;exports.screenshot2=$y;exports.sendDestroyed=Zm;exports.serializable=f;exports.serializeObject=d0;exports.serializeable=Be;exports.setActive=sc;exports.setAllowBalloonMessages=vv;exports.setAllowOverlayMessages=xS;exports.setAutoFitEnabled=Ud;exports.setCameraController=jp;exports.setDestroyed=tw;exports.setDevEnvironment=TS;exports.setDisposable=H0;exports.setDontDestroy=ta;exports.setOrAddParamsToUrl=Ap;exports.setParam=tS;exports.setParamWithoutReload=yc;exports.setPeerOptions=y1;exports.setResourceTrackingEnabled=mP;exports.setState=Am;exports.setVisibleInCustomShadowRendering=$m;exports.setWorldEuler=Vm;exports.setWorldPosition=at;exports.setWorldPositionXYZ=hr;exports.setWorldQuaternion=dn;exports.setWorldQuaternionXYZW=zm;exports.setWorldRotation=Ev;exports.setWorldRotationXYZ=Nc;exports.setWorldScale=Ma;exports.showBalloonError=Vc;exports.showBalloonMessage=Se;exports.showBalloonWarning=fe;exports.showDebugConsole=Gm;exports.slerp=Pv;exports.syncDestroy=Wc;exports.syncField=Og;exports.syncInstantiate=Jm;exports.textureToCanvas=QS;exports.toSourceId=yv;exports.tryCastBinary=_0;exports.tryDetermineMimetypeFromBinary=Iw;exports.tryDetermineMimetypeFromURL=Lw;exports.tryFindObject=Oa;exports.tryGetGuid=b0;exports.unregisterHotReloadType=dw;exports.unwatchWrite=Dm;exports.useForAutoFit=Cv;exports.validate=Ct;exports.watchWrite=fu;
|