@needle-tools/engine 4.12.0-next.f546e2b → 4.12.0-next.fb75c78

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.
@@ -141,7 +141,7 @@ void main(){
141
141
  #__vconsole .vc-mask {
142
142
  overflow: hidden;
143
143
  }
144
- `,br?.prepend(i),o===!0&&$b()<=0&&f_(),console.log("\u{1F335} Debug console has loaded")}},e.onerror=()=>{console.warn("\u{1F335} Debug console failed to load."+(window.crossOriginIsolated?"This page is using cross-origin isolation, so external scripts can't be loaded.":"")),dc=!1,li=null},e.src="https://cdn.jsdelivr.net/npm/vconsole@3.15.1/dist/vconsole.min.js",document.body.appendChild(e)}function BO(){if(!globalThis.VConsole)return;const o=new VConsole.VConsolePlugin("needle-console","\u{1F335} Inspect glTF"),e=()=>document.querySelector("#__vc_plug_"+o._id+" iframe");return o.on("renderTab",function(t){const i=globalThis["needle:codegen_files"];if(!i||i.length===0)return;let n=globalThis["needle:codegen_files"][0];const s=n.indexOf("?");s>-1&&(n=n.substring(0,s));const r=location.protocol+"//"+location.host+location.pathname+"/"+n,a=encodeURIComponent(r);o.fullUrl="https://viewer.needle.tools?inspect&file="+a;var l='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';t(l)}),o.on("show",function(){const t=e();t&&t.src!==o.fullUrl&&(t.src=o.fullUrl)}),o.on("hide",function(){const t=e();t&&(t.src="")}),o.on("addTopBar",function(t){var i=new Array;i.push({name:"Open in new window \u2197",onClick:function(n){window.open(o.fullUrl,"_blank"),li?.hide()}}),i.push({name:"Reload",onClick:function(n){const s=e();s&&(s.src=o.fullUrl)}}),i.push({name:"Fullscreen",onClick:function(n){const s=e();s.requestFullscreen?s.requestFullscreen():s.webkitRequestFullscreen instanceof Function&&s.webkitRequestFullscreen()}}),t(i)}),o}const ag="padding: 10px; font-family: monospace;",b_="margin-bottom: 10px;",_r="margin-bottom: 10px; margin-top: 15px;",FO="width: 100%; border-collapse: collapse; border: 1px solid rgba(0,0,0,0.1); table-layout: fixed;",__="border: 1px solid rgba(0,0,0,0.1); padding: 5px;",UO=__,zO=__+" word-break: break-all;";function $n(o,e=!1){e&&o.sort((i,n)=>(n.value?1:0)-(i.value?1:0));let t=`<table style='${FO}'>`;t+="<tbody>";for(const i of o){const n=typeof i.value=="boolean"?i.value?"\u2705":"\u274C":i.value;t+=`<tr><td style='${UO}'>${i.label}</td><td style='${zO}'>${n}</td></tr>`}return t+="</tbody></table>",t}function v_(){try{if(document.createElement("canvas").getContext("webgl2"))return"\u2705"}catch{}return"\u274C"}function NO(){if(!globalThis.VConsole)return;const o=new VConsole.VConsolePlugin("device-utilities","\u{1F4F1} Device Info");return o.on("renderTab",function(e){let t=`<div style='${ag}'>`;const i=ZO();t+=`<h3 style='${b_}'>Device: ${i}</h3>`,t+=$n([{label:"\u{1F4BB} Desktop",value:L.isDesktop()},{label:"\u{1F4F1} Mobile Device",value:L.isMobileDevice()},{label:"\u{1F34E} iOS",value:L.isiOS()},{label:"\u{1F4F1} iPad",value:L.isiPad()},{label:"\u{1F916} Android",value:L.isAndroidDevice()},{label:"\u{1F98A} Mozilla XR",value:L.isMozillaXR()},{label:"\u{1F335} Needle App Clip",value:L.isNeedleAppClip()},{label:"\u{1F34F} macOS",value:L.isMacOS()},{label:"\u{1F453} VisionOS",value:L.isVisionOS()},{label:"\u{1F9ED} Safari",value:L.isSafari()},{label:"\u{1F576}\uFE0F Meta Quest",value:L.isQuest()},{label:"\u{1F517} QuickLook AR Support",value:L.supportsQuickLookAR()}],!0);const n=[],s=L.getiOSVersion();s&&n.push({label:"\u{1F34E} iOS Version",value:s});const r=L.getChromeVersion();r&&n.push({label:"\u{1F310} Chrome Version",value:r});const a=L.getSafariVersion();a&&n.push({label:"\u{1F9ED} Safari Version",value:a}),n.length>0&&(t+=$n(n,!1)),t+="</div>",t+=`<div style='${ag} margin-top: 20px;'>`,t+=`<h3 style='${b_}'>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?"\u2705":"\u274C"},{label:"WebGPU",value:"gpu"in navigator?"\u2705":"\u274C"},{label:"WebGL 2",value:v_()}];t+=$n(l,!1),t+="</div>",e(t)}),o}function WO(){if(!globalThis.VConsole)return;const o=new VConsole.VConsolePlugin("graphics-info","\u{1F3A8} Graphics Info");return o.on("renderTab",async function(e){let t=`<div style='${ag}'>`;const i=VO();i.length>0&&(t+=`<h3 style='${_r}'>General GPU Info</h3>`,t+=$n(i,!1));const n=HO();n.length>0&&(t+=`<h3 style='${_r}'>WebGL</h3>`,t+=$n(n,!1));const s=GO();s.length>0&&(t+=`<h3 style='${_r}'>WebGL 2 Features</h3>`,t+=$n(s,!1));const r=qO();r.length>0&&(t+=`<h3 style='${_r}'>WebGL Limits</h3>`,t+=$n(r,!1));const a=XO();a.length>0&&(t+=`<h3 style='${_r}'>Texture Formats</h3>`,t+=$n(a,!1));const l=await QO();if(l.length>0&&(t+=`<h3 style='${_r}'>WebGPU</h3>`,t+=$n(l,!1)),L.isSafari()){const c=YO();c.length>0&&(t+=`<h3 style='${_r}'>Safari GPU Info</h3>`,t+=$n(c,!1))}t+="</div>",e(t)}),o}function VO(){const o=[],e=window.devicePixelRatio;o.push({label:"Device Pixel Ratio",value:e.toString()}),o.push({label:"Width (px)",value:(window.innerWidth*e).toString()}),o.push({label:"Height (px)",value:(window.innerHeight*e).toString()});const t=L.isMobileDevice()?150:96,i=screen.width/t,n=screen.height/t,s=i*2.54,r=n*2.54;o.push({label:"Estimated Width (cm)",value:s.toFixed(1)}),o.push({label:"Estimated Height (cm)",value:r.toFixed(1)});const a=w_();if(a){o.push({label:"GPU",value:a.renderer}),o.push({label:"Driver",value:a.vendor}),o.push({label:"ANGLE",value:a.angle||"Not detected"});const l=$O(a.renderer);l&&(l.manufacturer&&o.push({label:"Manufacturer",value:l.manufacturer}),l.cardVersion&&o.push({label:"Card Version",value:l.cardVersion}),l.brand&&o.push({label:"Brand",value:l.brand}),o.push({label:"Integrated",value:l.integrated?"Yes":"No"}),l.layer&&o.push({label:"WebGL Layer",value:l.layer}))}return o}function $O(o){if(!o)return null;const e=(l,c)=>{const h=c.match(l);return h&&h[0]},t=e(/(ANGLE)/g,o)||void 0,i=e(/((NVIDIA|AMD|Intel)[^\d]*[^\s]+)/,o)||o,n=i.split(" ");n.shift();const s=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:s,cardVersion:r,brand:a,integrated:s==="Intel",layer:t,card:i}}function HO(){const o=[],e=w_();return e&&(o.push({label:"\u{1F4CA} WebGL Version",value:e.version}),o.push({label:"\u{1F3AE} WebGL 2 Available",value:v_()})),o}function GO(){const o=[];try{const e=document.createElement("canvas").getContext("webgl2");if(!e)return o;o.push({label:"Float Color Buffer",value:e.getExtension("EXT_color_buffer_float")?"\u2705":"\u274C"}),o.push({label:"Anisotropic Filtering",value:e.getExtension("EXT_texture_filter_anisotropic")?"\u2705":"\u274C"}),o.push({label:"Float Texture Linear",value:e.getExtension("OES_texture_float_linear")?"\u2705":"\u274C"}),o.push({label:"S3TC Compression",value:e.getExtension("WEBGL_compressed_texture_s3tc")?"\u2705":"\u274C"}),o.push({label:"ETC Compression",value:e.getExtension("WEBGL_compressed_texture_etc")?"\u2705":"\u274C"}),o.push({label:"PVRTC Compression",value:e.getExtension("WEBGL_compressed_texture_pvrtc")?"\u2705":"\u274C"}),o.push({label:"ASTC Compression",value:e.getExtension("WEBGL_compressed_texture_astc")?"\u2705":"\u274C"})}catch{}return o}function qO(){const o=[];try{const e=document.createElement("canvas"),t=e.getContext("webgl2")||e.getContext("webgl");if(!t)return o;const i=t instanceof WebGL2RenderingContext;o.push({label:"\u{1F4CF} Max Texture Size",value:t.getParameter(t.MAX_TEXTURE_SIZE).toString()}),o.push({label:"\u{1F3A8} Max Renderbuffer Size",value:t.getParameter(t.MAX_RENDERBUFFER_SIZE).toString()}),o.push({label:"\u{1F517} Max Vertex Attribs",value:t.getParameter(t.MAX_VERTEX_ATTRIBS).toString()}),o.push({label:"\u{1F3AF} Max Texture Units",value:t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS).toString()}),i&&(o.push({label:"\u26A1 Max Samples",value:t.getParameter(t.MAX_SAMPLES).toString()}),o.push({label:"\u{1F504} Max Uniform Buffer Bindings",value:t.getParameter(t.MAX_UNIFORM_BUFFER_BINDINGS).toString()}),o.push({label:"\u{1F4D0} Max 3D Texture Size",value:t.getParameter(t.MAX_3D_TEXTURE_SIZE).toString()}))}catch{}return o}function XO(){const o=[];try{document.createElement("canvas").getContext("webgl")&&(o.push({label:"WebGL 1 RGBA",value:"\u2705"}),o.push({label:"WebGL 1 RGB",value:"\u2705"}));const e=document.createElement("canvas").getContext("webgl2");e&&(o.push({label:"WebGL 2 RGBA32F",value:e.getExtension("EXT_color_buffer_float")?"\u2705":"\u274C"}),o.push({label:"WebGL 2 RGB32F",value:e.getExtension("EXT_color_buffer_float")?"\u2705":"\u274C"}),o.push({label:"WebGL 2 R11F_G11F_B10F",value:"\u2705"}),o.push({label:"WebGL 2 RGB565",value:"\u2705"}),o.push({label:"WebGL 2 RGB5_A1",value:"\u2705"}),o.push({label:"WebGL 2 RGBA4444",value:"\u2705"}))}catch{}return o}async function QO(){const o=[];if(!("gpu"in navigator))return o.push({label:"\u{1F680} WebGPU Support",value:"\u274C Not supported"}),o;o.push({label:"\u{1F680} WebGPU Support",value:"\u2705 Supported"});try{const e=await navigator.gpu.requestAdapter();if(!e)return o.push({label:"\u{1F3AF} Adapter",value:"No adapter available"}),o;o.push({label:"\u{1F3AF} Adapter",value:e.name||"Unknown Adapter"});const t=await e.requestDevice();o.push({label:"\u{1F527} Device",value:t.label||"WebGPU Device"}),o.push({label:"\u{1F4CF} Max Texture 2D",value:t.limits.maxTextureDimension2D.toString()}),o.push({label:"\u{1F4D0} Max Texture 3D",value:t.limits.maxTextureDimension3D.toString()}),o.push({label:"\u{1F4CA} Max Texture Array Layers",value:t.limits.maxTextureArrayLayers.toString()}),o.push({label:"\u{1F4BE} Max Buffer Size",value:`${(t.limits.maxBufferSize/1024/1024).toFixed(1)}MB`}),o.push({label:"\u{1F517} Max Bind Groups",value:t.limits.maxBindGroups.toString()})}catch(e){o.push({label:"\u274C Error",value:e.message})}return o}function w_(){try{const o=document.createElement("canvas"),e=o.getContext("webgl2")||o.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),s=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:s,angle:r}}catch{return null}}function YO(){const o=[];try{const e=document.createElement("canvas").getContext("webgl");if(e){const t=e.getExtension("WEBGL_debug_renderer_info");if(t){const i=e.getParameter(t.UNMASKED_RENDERER_WEBGL);i&&i.includes("Apple")&&o.push({label:"\u{1F34E} Apple GPU",value:i})}}}catch{}try{const e=document.createElement("canvas").getContext("webgl");e&&(e.getSupportedExtensions()||[]).includes("WEBGL_compressed_texture_pvrtc")&&o.push({label:"\u{1F5DC}\uFE0F PVRTC Support",value:"\u2705"})}catch{}return o}function ZO(){return L.isQuest()?"Meta Quest":L.isVisionOS()?"Vision Pro":L.isiOS()?L.isiPad()?"iPad":"iPhone/iPod":L.isAndroidDevice()?"Android Device":L.isMozillaXR()?"Mozilla XR Browser":L.isNeedleAppClip()?"Needle App Clip":L.isMacOS()?"Mac":L.isDesktop()?"Desktop PC":"Unknown Device"}function KO(){return document.querySelector("#__vconsole .vc-switch")||null}function JO(){return document.querySelector("#__vconsole")||null}const x_=v("debugdefines");bs('if(!globalThis["NEEDLE_ENGINE_VERSION"]) globalThis["NEEDLE_ENGINE_VERSION"] = "0.0.0";'),bs('if(!globalThis["NEEDLE_ENGINE_GENERATOR"]) globalThis["NEEDLE_ENGINE_GENERATOR"] = "unknown";'),bs('if(!globalThis["NEEDLE_PROJECT_BUILD_TIME"]) globalThis["NEEDLE_PROJECT_BUILD_TIME"] = "unknown";'),bs('if(!globalThis["NEEDLE_PUBLIC_KEY"]) globalThis["NEEDLE_PUBLIC_KEY"] = "unknown";'),bs('globalThis["__NEEDLE_ENGINE_VERSION__"] = "4.12.0-beta.1";'),bs('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";'),bs('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Tue Jan 20 2026 14:41:38 GMT+0000 (Coordinated Universal Time)";'),bs('globalThis["__NEEDLE_PUBLIC_KEY__"] = "'+NEEDLE_PUBLIC_KEY+'";');const _n="4.12.0-beta.1",zd="undefined",lg="Tue Jan 20 2026 14:41:38 GMT+0000 (Coordinated Universal Time)";x_&&console.log(`Engine version: ${_n} (generator: ${zd})
144
+ `,br?.prepend(i),o===!0&&$b()<=0&&f_(),console.log("\u{1F335} Debug console has loaded")}},e.onerror=()=>{console.warn("\u{1F335} Debug console failed to load."+(window.crossOriginIsolated?"This page is using cross-origin isolation, so external scripts can't be loaded.":"")),dc=!1,li=null},e.src="https://cdn.jsdelivr.net/npm/vconsole@3.15.1/dist/vconsole.min.js",document.body.appendChild(e)}function BO(){if(!globalThis.VConsole)return;const o=new VConsole.VConsolePlugin("needle-console","\u{1F335} Inspect glTF"),e=()=>document.querySelector("#__vc_plug_"+o._id+" iframe");return o.on("renderTab",function(t){const i=globalThis["needle:codegen_files"];if(!i||i.length===0)return;let n=globalThis["needle:codegen_files"][0];const s=n.indexOf("?");s>-1&&(n=n.substring(0,s));const r=location.protocol+"//"+location.host+location.pathname+"/"+n,a=encodeURIComponent(r);o.fullUrl="https://viewer.needle.tools?inspect&file="+a;var l='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';t(l)}),o.on("show",function(){const t=e();t&&t.src!==o.fullUrl&&(t.src=o.fullUrl)}),o.on("hide",function(){const t=e();t&&(t.src="")}),o.on("addTopBar",function(t){var i=new Array;i.push({name:"Open in new window \u2197",onClick:function(n){window.open(o.fullUrl,"_blank"),li?.hide()}}),i.push({name:"Reload",onClick:function(n){const s=e();s&&(s.src=o.fullUrl)}}),i.push({name:"Fullscreen",onClick:function(n){const s=e();s.requestFullscreen?s.requestFullscreen():s.webkitRequestFullscreen instanceof Function&&s.webkitRequestFullscreen()}}),t(i)}),o}const ag="padding: 10px; font-family: monospace;",b_="margin-bottom: 10px;",_r="margin-bottom: 10px; margin-top: 15px;",FO="width: 100%; border-collapse: collapse; border: 1px solid rgba(0,0,0,0.1); table-layout: fixed;",__="border: 1px solid rgba(0,0,0,0.1); padding: 5px;",UO=__,zO=__+" word-break: break-all;";function $n(o,e=!1){e&&o.sort((i,n)=>(n.value?1:0)-(i.value?1:0));let t=`<table style='${FO}'>`;t+="<tbody>";for(const i of o){const n=typeof i.value=="boolean"?i.value?"\u2705":"\u274C":i.value;t+=`<tr><td style='${UO}'>${i.label}</td><td style='${zO}'>${n}</td></tr>`}return t+="</tbody></table>",t}function v_(){try{if(document.createElement("canvas").getContext("webgl2"))return"\u2705"}catch{}return"\u274C"}function NO(){if(!globalThis.VConsole)return;const o=new VConsole.VConsolePlugin("device-utilities","\u{1F4F1} Device Info");return o.on("renderTab",function(e){let t=`<div style='${ag}'>`;const i=ZO();t+=`<h3 style='${b_}'>Device: ${i}</h3>`,t+=$n([{label:"\u{1F4BB} Desktop",value:L.isDesktop()},{label:"\u{1F4F1} Mobile Device",value:L.isMobileDevice()},{label:"\u{1F34E} iOS",value:L.isiOS()},{label:"\u{1F4F1} iPad",value:L.isiPad()},{label:"\u{1F916} Android",value:L.isAndroidDevice()},{label:"\u{1F98A} Mozilla XR",value:L.isMozillaXR()},{label:"\u{1F335} Needle App Clip",value:L.isNeedleAppClip()},{label:"\u{1F34F} macOS",value:L.isMacOS()},{label:"\u{1F453} VisionOS",value:L.isVisionOS()},{label:"\u{1F9ED} Safari",value:L.isSafari()},{label:"\u{1F576}\uFE0F Meta Quest",value:L.isQuest()},{label:"\u{1F517} QuickLook AR Support",value:L.supportsQuickLookAR()}],!0);const n=[],s=L.getiOSVersion();s&&n.push({label:"\u{1F34E} iOS Version",value:s});const r=L.getChromeVersion();r&&n.push({label:"\u{1F310} Chrome Version",value:r});const a=L.getSafariVersion();a&&n.push({label:"\u{1F9ED} Safari Version",value:a}),n.length>0&&(t+=$n(n,!1)),t+="</div>",t+=`<div style='${ag} margin-top: 20px;'>`,t+=`<h3 style='${b_}'>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?"\u2705":"\u274C"},{label:"WebGPU",value:"gpu"in navigator?"\u2705":"\u274C"},{label:"WebGL 2",value:v_()}];t+=$n(l,!1),t+="</div>",e(t)}),o}function WO(){if(!globalThis.VConsole)return;const o=new VConsole.VConsolePlugin("graphics-info","\u{1F3A8} Graphics Info");return o.on("renderTab",async function(e){let t=`<div style='${ag}'>`;const i=VO();i.length>0&&(t+=`<h3 style='${_r}'>General GPU Info</h3>`,t+=$n(i,!1));const n=HO();n.length>0&&(t+=`<h3 style='${_r}'>WebGL</h3>`,t+=$n(n,!1));const s=GO();s.length>0&&(t+=`<h3 style='${_r}'>WebGL 2 Features</h3>`,t+=$n(s,!1));const r=qO();r.length>0&&(t+=`<h3 style='${_r}'>WebGL Limits</h3>`,t+=$n(r,!1));const a=XO();a.length>0&&(t+=`<h3 style='${_r}'>Texture Formats</h3>`,t+=$n(a,!1));const l=await QO();if(l.length>0&&(t+=`<h3 style='${_r}'>WebGPU</h3>`,t+=$n(l,!1)),L.isSafari()){const c=YO();c.length>0&&(t+=`<h3 style='${_r}'>Safari GPU Info</h3>`,t+=$n(c,!1))}t+="</div>",e(t)}),o}function VO(){const o=[],e=window.devicePixelRatio;o.push({label:"Device Pixel Ratio",value:e.toString()}),o.push({label:"Width (px)",value:(window.innerWidth*e).toString()}),o.push({label:"Height (px)",value:(window.innerHeight*e).toString()});const t=L.isMobileDevice()?150:96,i=screen.width/t,n=screen.height/t,s=i*2.54,r=n*2.54;o.push({label:"Estimated Width (cm)",value:s.toFixed(1)}),o.push({label:"Estimated Height (cm)",value:r.toFixed(1)});const a=w_();if(a){o.push({label:"GPU",value:a.renderer}),o.push({label:"Driver",value:a.vendor}),o.push({label:"ANGLE",value:a.angle||"Not detected"});const l=$O(a.renderer);l&&(l.manufacturer&&o.push({label:"Manufacturer",value:l.manufacturer}),l.cardVersion&&o.push({label:"Card Version",value:l.cardVersion}),l.brand&&o.push({label:"Brand",value:l.brand}),o.push({label:"Integrated",value:l.integrated?"Yes":"No"}),l.layer&&o.push({label:"WebGL Layer",value:l.layer}))}return o}function $O(o){if(!o)return null;const e=(l,c)=>{const h=c.match(l);return h&&h[0]},t=e(/(ANGLE)/g,o)||void 0,i=e(/((NVIDIA|AMD|Intel)[^\d]*[^\s]+)/,o)||o,n=i.split(" ");n.shift();const s=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:s,cardVersion:r,brand:a,integrated:s==="Intel",layer:t,card:i}}function HO(){const o=[],e=w_();return e&&(o.push({label:"\u{1F4CA} WebGL Version",value:e.version}),o.push({label:"\u{1F3AE} WebGL 2 Available",value:v_()})),o}function GO(){const o=[];try{const e=document.createElement("canvas").getContext("webgl2");if(!e)return o;o.push({label:"Float Color Buffer",value:e.getExtension("EXT_color_buffer_float")?"\u2705":"\u274C"}),o.push({label:"Anisotropic Filtering",value:e.getExtension("EXT_texture_filter_anisotropic")?"\u2705":"\u274C"}),o.push({label:"Float Texture Linear",value:e.getExtension("OES_texture_float_linear")?"\u2705":"\u274C"}),o.push({label:"S3TC Compression",value:e.getExtension("WEBGL_compressed_texture_s3tc")?"\u2705":"\u274C"}),o.push({label:"ETC Compression",value:e.getExtension("WEBGL_compressed_texture_etc")?"\u2705":"\u274C"}),o.push({label:"PVRTC Compression",value:e.getExtension("WEBGL_compressed_texture_pvrtc")?"\u2705":"\u274C"}),o.push({label:"ASTC Compression",value:e.getExtension("WEBGL_compressed_texture_astc")?"\u2705":"\u274C"})}catch{}return o}function qO(){const o=[];try{const e=document.createElement("canvas"),t=e.getContext("webgl2")||e.getContext("webgl");if(!t)return o;const i=t instanceof WebGL2RenderingContext;o.push({label:"\u{1F4CF} Max Texture Size",value:t.getParameter(t.MAX_TEXTURE_SIZE).toString()}),o.push({label:"\u{1F3A8} Max Renderbuffer Size",value:t.getParameter(t.MAX_RENDERBUFFER_SIZE).toString()}),o.push({label:"\u{1F517} Max Vertex Attribs",value:t.getParameter(t.MAX_VERTEX_ATTRIBS).toString()}),o.push({label:"\u{1F3AF} Max Texture Units",value:t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS).toString()}),i&&(o.push({label:"\u26A1 Max Samples",value:t.getParameter(t.MAX_SAMPLES).toString()}),o.push({label:"\u{1F504} Max Uniform Buffer Bindings",value:t.getParameter(t.MAX_UNIFORM_BUFFER_BINDINGS).toString()}),o.push({label:"\u{1F4D0} Max 3D Texture Size",value:t.getParameter(t.MAX_3D_TEXTURE_SIZE).toString()}))}catch{}return o}function XO(){const o=[];try{document.createElement("canvas").getContext("webgl")&&(o.push({label:"WebGL 1 RGBA",value:"\u2705"}),o.push({label:"WebGL 1 RGB",value:"\u2705"}));const e=document.createElement("canvas").getContext("webgl2");e&&(o.push({label:"WebGL 2 RGBA32F",value:e.getExtension("EXT_color_buffer_float")?"\u2705":"\u274C"}),o.push({label:"WebGL 2 RGB32F",value:e.getExtension("EXT_color_buffer_float")?"\u2705":"\u274C"}),o.push({label:"WebGL 2 R11F_G11F_B10F",value:"\u2705"}),o.push({label:"WebGL 2 RGB565",value:"\u2705"}),o.push({label:"WebGL 2 RGB5_A1",value:"\u2705"}),o.push({label:"WebGL 2 RGBA4444",value:"\u2705"}))}catch{}return o}async function QO(){const o=[];if(!("gpu"in navigator))return o.push({label:"\u{1F680} WebGPU Support",value:"\u274C Not supported"}),o;o.push({label:"\u{1F680} WebGPU Support",value:"\u2705 Supported"});try{const e=await navigator.gpu.requestAdapter();if(!e)return o.push({label:"\u{1F3AF} Adapter",value:"No adapter available"}),o;o.push({label:"\u{1F3AF} Adapter",value:e.name||"Unknown Adapter"});const t=await e.requestDevice();o.push({label:"\u{1F527} Device",value:t.label||"WebGPU Device"}),o.push({label:"\u{1F4CF} Max Texture 2D",value:t.limits.maxTextureDimension2D.toString()}),o.push({label:"\u{1F4D0} Max Texture 3D",value:t.limits.maxTextureDimension3D.toString()}),o.push({label:"\u{1F4CA} Max Texture Array Layers",value:t.limits.maxTextureArrayLayers.toString()}),o.push({label:"\u{1F4BE} Max Buffer Size",value:`${(t.limits.maxBufferSize/1024/1024).toFixed(1)}MB`}),o.push({label:"\u{1F517} Max Bind Groups",value:t.limits.maxBindGroups.toString()})}catch(e){o.push({label:"\u274C Error",value:e.message})}return o}function w_(){try{const o=document.createElement("canvas"),e=o.getContext("webgl2")||o.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),s=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:s,angle:r}}catch{return null}}function YO(){const o=[];try{const e=document.createElement("canvas").getContext("webgl");if(e){const t=e.getExtension("WEBGL_debug_renderer_info");if(t){const i=e.getParameter(t.UNMASKED_RENDERER_WEBGL);i&&i.includes("Apple")&&o.push({label:"\u{1F34E} Apple GPU",value:i})}}}catch{}try{const e=document.createElement("canvas").getContext("webgl");e&&(e.getSupportedExtensions()||[]).includes("WEBGL_compressed_texture_pvrtc")&&o.push({label:"\u{1F5DC}\uFE0F PVRTC Support",value:"\u2705"})}catch{}return o}function ZO(){return L.isQuest()?"Meta Quest":L.isVisionOS()?"Vision Pro":L.isiOS()?L.isiPad()?"iPad":"iPhone/iPod":L.isAndroidDevice()?"Android Device":L.isMozillaXR()?"Mozilla XR Browser":L.isNeedleAppClip()?"Needle App Clip":L.isMacOS()?"Mac":L.isDesktop()?"Desktop PC":"Unknown Device"}function KO(){return document.querySelector("#__vconsole .vc-switch")||null}function JO(){return document.querySelector("#__vconsole")||null}const x_=v("debugdefines");bs('if(!globalThis["NEEDLE_ENGINE_VERSION"]) globalThis["NEEDLE_ENGINE_VERSION"] = "0.0.0";'),bs('if(!globalThis["NEEDLE_ENGINE_GENERATOR"]) globalThis["NEEDLE_ENGINE_GENERATOR"] = "unknown";'),bs('if(!globalThis["NEEDLE_PROJECT_BUILD_TIME"]) globalThis["NEEDLE_PROJECT_BUILD_TIME"] = "unknown";'),bs('if(!globalThis["NEEDLE_PUBLIC_KEY"]) globalThis["NEEDLE_PUBLIC_KEY"] = "unknown";'),bs('globalThis["__NEEDLE_ENGINE_VERSION__"] = "4.12.0-beta.2";'),bs('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";'),bs('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Thu Jan 22 2026 12:52:21 GMT+0000 (Coordinated Universal Time)";'),bs('globalThis["__NEEDLE_PUBLIC_KEY__"] = "'+NEEDLE_PUBLIC_KEY+'";');const _n="4.12.0-beta.2",zd="undefined",lg="Thu Jan 22 2026 12:52:21 GMT+0000 (Coordinated Universal Time)";x_&&console.log(`Engine version: ${_n} (generator: ${zd})
145
145
  Project built at ${lg}`);const Da=NEEDLE_PUBLIC_KEY,Mo="needle_isActiveInHierarchy",vr="builtin_components",uc="needle_editor_guid";function bs(o){try{(0,eval)(o)}catch(e){x_&&console.error(e)}}let S_,C_=null;function vn(){return S_}function cg(o){if(o==null){console.warn("Oh no: someone tried registering a non-existend gltf-loader. When you see this log it might mean that needle-engine is being imported multiple times. Please check your project setup.");return}C_!==o&&(C_=o,S_=new o)}function ek(o,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>o.time.frame)return window.requestAnimationFrame(()=>i());const r=s.captureCanvas(e);r&&r instanceof Promise?r.then(()=>s.displayUI()):s.displayUI()};const n=Number.parseInt(t.get("spector")||"0")||0;console.log("Scheduled Spector capture at frame #"+n);const s=new window.SPECTOR.Spector;s.spyCanvases=!0,i();return}else A()&&console.debug("Spector available: Add '?spector=<frame>' to the URL to enable it and capture a frame.")}}const Ri=Symbol("shadowDomOwner"),tk=v("debugpatch");function Nd(o,e,t,i){const n=tk===e;if(!t&&!i)return;const s=e+"___needle";nk(o,e,t,i);const r=Object.getOwnPropertyDescriptor(o,e),a=o[e];n&&console.log("Patch",o.constructor.name,e,r,a),r?(n&&console.log("Apply patch with existing descriptor",o.constructor.name,e,r),typeof r.value=="function"&&(o[e]=O_(r.value,o,e))):(n&&console.log("Create patch with new property",o.constructor.name,e,r),Object.defineProperty(o,e,{set:function(l){if(typeof l=="function")this[s]=O_(l,o,e);else{const c=this[s];k_(o,e,this,c,l),this[s]=l,M_(o,e,this,c,l)}},get:function(){const l=this[s];return typeof l=="function"&&l[s]?l[s]:l}}))}function ik(o,e,t){const i=dg(o,e);if(i)for(let n=i.length-1;n>=0;n--){const s=i[n];s.prefix===t&&(s.prefix=null),s.postfix===t&&(s.postfix=null),!s.prefix&&!s.postfix&&i.splice(n,1)}}const P_=Symbol("Needle:Patches:WrappedFunction");function O_(o,e,t){if(o[P_])return o;const i=function(...n){k_(e,t,this,...n);const s=o.apply(this,n);return M_(e,t,this,s,...n),s};return i[P_]=!0,i}const Wd="Needle:Patches";function hg(){return globalThis[Wd]||(globalThis[Wd]=new WeakMap),globalThis[Wd]}function dg(o,e){const t=hg().get(o);return t?t.get(e):null}function nk(o,e,t,i){let n=hg().get(o);n||(n=new Map,hg().set(o,n));let s=n.get(e);s||(s=[],n.set(e,s)),s.push({prefix:t,postfix:i})}function k_(o,e,t,...i){if(!t)return;const n=dg(o,e);if(n)for(const s of n)s.prefix?.call(t,...i)}function M_(o,e,t,i,...n){if(!t)return;const s=dg(o,e);if(s)for(const r of s)r.postfix?.call(t,i,...n)}const ja=[];function Vd(o){ja.indexOf(o)===-1&&ja.push(o)}function ok(o){const e=ja.indexOf(o);e!==-1&&ja.splice(e,1)}const Ba=[];function ug(o){Ba.indexOf(o)===-1&&Ba.push(o)}function sk(o){const e=Ba.indexOf(o);e!==-1&&Ba.splice(e,1)}function R_(o){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-start",{detail:o}));for(let e=0;e<ja.length;e++)ja[e](o)}function E_(o){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-end",{detail:o}));for(let e=0;e<Ba.length;e++)Ba[e](o)}const rt=v("debuginput");var $d=(o=>(o.Mouse="mouse",o.Touch="touch",o.Controller="controller",o.Hand="hand",o))($d||{}),Te=(o=>(o.PointerDown="pointerdown",o.PointerUp="pointerup",o.PointerMove="pointermove",o.KeyDown="keydown",o.KeyUp="keyup",o.KeyPressed="keypress",o))(Te||{});class Ro extends PointerEvent{clientZ;deviceIndex;origin;source;mode;get isSpatial(){return this.mode!="screen"}get ray(){return this._ray||(this._ray=new vo(this.space.worldPosition.clone(),this.space.worldForward.clone())),this._ray}set ray(e){this._ray=e}get hasRay(){return this._ray!==void 0}_ray;space;isClick=!1;isDoubleClick=!1;get used(){return this._used}_used=!1;use(){this._used=!0}get pointerId(){return this._pointerid}_pointerid;get pointerType(){return this._pointerType}_pointerType;buttonName=void 0;get type(){return this._type}_type;metadata={};intersections=new Array;constructor(e,t,i){super(e,i),this.clientZ=i.clientZ,this._pointerid=i.pointerId,this._pointerType=i.pointerType,this._type=e,this.deviceIndex=i.deviceIndex,this.origin=i.origin,this.source=t,this.mode=i.mode,this._ray=i.ray,this.space=i.device,this.buttonName=i.buttonName}_immediatePropagationStopped=!1;get immediatePropagationStopped(){return this._immediatePropagationStopped}_propagationStopped=!1;get propagationStopped(){return this._immediatePropagationStopped||this._propagationStopped}stopImmediatePropagation(){this._immediatePropagationStopped=!0,super.stopImmediatePropagation(),this.source?.stopImmediatePropagation()}stopPropagation(){this._propagationStopped=!0,super.stopPropagation(),this.source?.stopPropagation(),rt&&console.warn("Stop propagation...",this.pointerId,this.pointerType)}}class pc extends KeyboardEvent{source;constructor(e,t,i){super(e,i),this.source=t}stopImmediatePropagation(){super.stopImmediatePropagation(),this.source?.stopImmediatePropagation()}}class rk{key;keyType;source;constructor(e){this.key=e.key,this.keyType=e.type,this.source=e}}var ci=(o=>(o[o.Early=-100]="Early",o[o.Default=0]="Default",o[o.Late=100]="Late",o))(ci||{});class T_{_eventListeners={};addEventListener(e,t,i){if(this._eventListeners[e]||(this._eventListeners[e]=[]),!t||typeof t!="function"){console.error("Invalid call to addEventListener: callback is required and must be a function!");return}i?i={...i}:i={};let n=0;i?.queue!=null&&(n=i.queue);const s=this._eventListeners[e],r=s.find(a=>a.priority===n);r?r.listeners.push({callback:t,options:i}):(s.push({priority:n,listeners:[{callback:t,options:i}]}),s.sort((a,l)=>a.priority-l.priority))}removeEventListener(e,t,i){if(!this._eventListeners[e]||!t)return;const n=this._eventListeners[e];if(i?.queue!=null){const s=n.find(a=>a.priority===i.queue);if(!s)return;const r=s.listeners.findIndex(a=>a.callback===t);r>=0&&s.listeners.splice(r,1)}else for(const s of n){const r=s.listeners.findIndex(a=>a.callback===t);r>=0&&s.listeners.splice(r,1)}}dispatchEvent(e){let t=!1;if(e instanceof pc){const i=this._eventListeners[e.type];if(i)for(const n of i)for(let s=0;s<n.listeners.length;s++){const r=n.listeners[s];if(r.options?.signal?.aborted){n.listeners.splice(s,1),s--;continue}r.options.once&&(n.listeners.splice(s,1),s--),r.callback(e)}}if(e instanceof Ro){const i=this._eventListeners[e.type];if(i)for(const n of i){if(t)break;for(let s=0;s<n.listeners.length;s++){const r=n.listeners[s];if(r.options?.signal?.aborted){n.listeners.splice(s,1),s--;continue}if(e.immediatePropagationStopped){t=!0,rt&&console.log("immediatePropagationStopped",e.type);break}else e.propagationStopped&&(t=!0,rt&&console.log("propagationStopped",e.type));r.options.once&&(n.listeners.splice(s,1),s--),r.callback(e)}}}}_doubleClickTimeThreshold=.2;_longPressTimeThreshold=1;get mousePosition(){return this._pointerPositions[0]}get mousePositionRC(){return this._pointerPositionsRC[0]}get mouseDown(){return this._pointerDown[0]}get mouseUp(){return this._pointerUp[0]}get mouseClick(){return this._pointerClick[0]}get mouseDoubleClick(){return this._pointerDoubleClick[0]}get mousePressed(){return this._pointerPressed[0]}get mouseWheelChanged(){return this.getMouseWheelChanged(0)}get click(){return this._pointerClick[0]}get doubleClick(){return this._pointerDoubleClick[0]}getGamepad(e=0){return typeof navigator<"u"&&"getGamepads"in navigator&&navigator.getGamepads()[e]||null}_setCursorTypes=[];setCursorPointer(){this.setCursor("pointer")}setCursorNormal(){this.unsetCursor("pointer")}setCursor(e){this._setCursorTypes.push(e),this._setCursorTypes.length>10&&this._setCursorTypes.shift(),this.updateCursor()}unsetCursor(e){for(let t=this._setCursorTypes.length-1;t>=0;t--)if(this._setCursorTypes[t]===e){this._setCursorTypes.splice(t,1),this.updateCursor();break}}updateCursor(){this._setCursorTypes?.length==0?this.context.domElement.style.cursor="default":this.context.domElement.style.cursor=this._setCursorTypes[this._setCursorTypes.length-1]}getIsPointerIdInUse(e){for(const t of this._pointerEventsPressed)if(t.pointerId===e&&t.used)return!0;return!1}getPointerPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&e++;return e}getPointerPosition(e){return e>=this._pointerPositions.length?null:this._pointerPositions[e]}getPointerPositionLastFrame(e){return e>=this._pointerPositionsLastFrame.length?null:this._pointerPositionsLastFrame[e]}getPointerPositionDelta(e){return e>=this._pointerPositionsDelta.length?null:this._pointerPositionsDelta[e]}getPointerPositionRC(e){return e>=this._pointerPositionsRC.length?null:this._pointerPositionsRC[e]}getPointerDown(e){return e>=this._pointerDown.length?!1:this._pointerDown[e]}getPointerUp(e){return e>=this._pointerUp.length?!1:this._pointerUp[e]}getPointerPressed(e){return e>=this._pointerPressed.length?!1:this._pointerPressed[e]}getPointerClicked(e){return e>=this._pointerClick.length?!1:this._pointerClick[e]}getPointerDoubleClicked(e){return e>=this._pointerDoubleClick.length?!1:this._pointerDoubleClick[e]}getPointerDownTime(e){return e>=this._pointerDownTime.length?-1:this._pointerDownTime[e]}getPointerUpTime(e){return e>=this._pointerUpTime.length?-1:this._pointerUpTime[e]}getPointerLongPress(e){return e>=this._pointerDownTime.length?!1:this.getPointerPressed(e)&&this.context.time.time-this._pointerDownTime[e]>this._longPressTimeThreshold}getIsMouse(e){return e<0||e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="mouse"}getIsTouch(e){return e<0||e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="touch"}getTouchesPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&this.getIsTouch(t)&&e++;return e}getMouseWheelChanged(e=0){return e>=this._mouseWheelChanged.length?!1:this._mouseWheelChanged[e]}getMouseWheelDeltaY(e=0){return e>=this._mouseWheelDeltaY.length?0:this._mouseWheelDeltaY[e]}getPointerEvent(e){if(!(e>=this._pointerEvent.length))return this._pointerEvent[e]??void 0}*foreachPointerId(e){for(let t=0;t<this._pointerTypes.length;t++)if(this._pointerIsActive(t)){if(e!==void 0){const i=this._pointerTypes[t];if(Array.isArray(e)){let n=!1;for(const s of e)if(i===s){n=!0;break}if(!n)continue}else if(e!==i)continue}yield t}}*foreachTouchId(){for(let e=0;e<this._pointerTypes.length;e++)this._pointerTypes[e]==="touch"&&this._pointerIsActive[e]&&(yield e)}_pointerIsActive(e){return e<0?!1:this._pointerPressed[e]||this._pointerDown[e]||this._pointerUp[e]}context;_pointerDown=[!1];_pointerUp=[!1];_pointerClick=[!1];_pointerDoubleClick=[!1];_pointerPressed=[!1];_pointerPositions=[new ee];_pointerPositionsLastFrame=[new ee];_pointerPositionsDelta=[new ee];_pointerPositionsRC=[new ee];_pointerPositionDown=[new b];_pointerDownTime=[];_pointerUpTime=[];_pointerUpTimestamp=[];_pointerIds=[];_pointerTypes=[""];_mouseWheelChanged=[!1];_mouseWheelDeltaY=[0];_pointerEvent=[];_pointerEventsPressed=[];_pointerSpace=[];_pressedStack=new Map;onDownButton(e,t){let i=this._pressedStack.get(e);i||(i=[],this._pressedStack.set(e,i)),i.push(t)}onReleaseButton(e,t){const i=this._pressedStack.get(e);if(!i)return;const n=i.indexOf(t);n>=0&&i.splice(n,1)}getFirstPressedButtonForPointer(e){const t=this._pressedStack.get(e);if(t)return t[0]}getLatestPressedButtonForPointer(e){const t=this._pressedStack.get(e);if(t)return t[t.length-1]}getKeyDown(e){if(e!==void 0)return this.isKeyDown(e);for(const t in this.keysPressed){const i=this.keysPressed[t];if(i.startFrame===this.context.time.frameCount)return i.key}return null}getKeyPressed(e){if(e!==void 0)return this.isKeyPressed(e);for(const t in this.keysPressed){const i=this.keysPressed[t];if(i.pressed)return i.key}return null}getKeyUp(e){if(e!==void 0)return this.isKeyUp(e);for(const t in this.keysPressed){const i=this.keysPressed[t];return i.pressed===!1&&i.frame===this.context.time.frameCount}return null}isKeyDown(e){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const t=this.getCodeForCommonKeyName(e);if(t!==null){for(const n of t)if(this.isKeyDown(n))return!0;return!1}const i=this.keysPressed[e];return i?i.startFrame===this.context.time.frameCount&&i.pressed:!1}isKeyUp(e){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const t=this.getCodeForCommonKeyName(e);if(t!==null){for(const n of t)if(this.isKeyUp(n))return!0;return!1}const i=this.keysPressed[e];return i?i.frame===this.context.time.frameCount&&i.pressed===!1:!1}isKeyPressed(e){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const t=this.getCodeForCommonKeyName(e);if(t!==null){for(const n of t)if(this.isKeyPressed(n))return!0;return!1}const i=this.keysPressed[e];return i&&i.pressed||!1}getCodeForCommonKeyName(e){if(e.length===1){if(e>="0"&&e<="9")return["Digit"+e];if(e>="a"&&e<="z")return["Key"+e.toUpperCase()];if(e==" ")return["Space"]}switch(e){case"shift":case"Shift":return["ShiftLeft","ShiftRight"];case"control":case"Control":return["ControlLeft","ControlRight"];case"alt":case"Alt":return["AltLeft","AltRight"]}return null}createInputEvent(e){switch(e.type){case"pointerdown":rt&&Ee("Create Pointer down"),this.onDownButton(e.deviceIndex,e.button),this.onDown(e);break;case"pointermove":rt&&Ee("Create Pointer move"),this.onMove(e);break;case"pointerup":rt&&Ee("Create Pointer up"),this.onUp(e),this.onReleaseButton(e.deviceIndex,e.button);break}}convertScreenspaceToRaycastSpace(e){return e.x=(e.x-this.context.domX)/this.context.domWidth*2-1,e.y=-((e.y-this.context.domY)/this.context.domHeight)*2+1,e}constructor(e){this.context=e,this.context.post_render_callbacks.push(this.onEndOfFrame)}_htmlEventSource;bindEvents(){this.unbindEvents(),this._htmlEventSource=this.context.renderer.domElement,window.addEventListener("contextmenu",this.onContextMenu),this._htmlEventSource.addEventListener("pointerdown",this.onPointerDown,{passive:!0}),window.addEventListener("pointermove",this.onPointerMove,{passive:!0,capture:!0}),window.addEventListener("pointerup",this.onPointerUp,{passive:!0}),window.addEventListener("pointercancel",this.onPointerCancel,{passive:!0}),window.addEventListener("touchstart",this.onTouchStart,{passive:!0}),window.addEventListener("touchmove",this.onTouchMove,{passive:!0}),window.addEventListener("touchend",this.onTouchEnd,{passive:!0}),this._htmlEventSource.addEventListener("wheel",this.onMouseWheel,{passive:!0}),window.addEventListener("wheel",this.onWheelWindow,{passive:!0}),window.addEventListener("keydown",this.onKeyDown,!1),window.addEventListener("keypress",this.onKeyPressed,!1),window.addEventListener("keyup",this.onKeyUp,!1),window.addEventListener("blur",this.onLostFocus)}unbindEvents(){for(const e in this._eventListeners)this._eventListeners[e].length=0;window.removeEventListener("contextmenu",this.onContextMenu),this._htmlEventSource?.removeEventListener("pointerdown",this.onPointerDown),window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),window.removeEventListener("pointercancel",this.onPointerCancel),window.removeEventListener("touchstart",this.onTouchStart),window.removeEventListener("touchmove",this.onTouchMove),window.removeEventListener("touchend",this.onTouchEnd),this._htmlEventSource?.removeEventListener("wheel",this.onMouseWheel,!1),window.removeEventListener("wheel",this.onWheelWindow,!1),window.removeEventListener("keydown",this.onKeyDown,!1),window.removeEventListener("keypress",this.onKeyPressed,!1),window.removeEventListener("keyup",this.onKeyUp,!1),window.removeEventListener("blur",this.onLostFocus)}dispose(){const e=this.context.post_render_callbacks.indexOf(this.onEndOfFrame);e>=0&&this.context.post_render_callbacks.splice(e,1),this.unbindEvents()}onLostFocus=()=>{for(const e in this.keysPressed)this.keysPressed[e].pressed=!1};_receivedPointerMoveEventsThisFrame=new Array;onEndOfFrame=()=>{this._receivedPointerMoveEventsThisFrame.length=0;for(let e=0;e<this._pointerUp.length;e++)this._pointerUp[e]=!1;for(let e=0;e<this._pointerDown.length;e++)this._pointerDown[e]=!1;for(let e=0;e<this._pointerClick.length;e++)this._pointerClick[e]=!1;for(let e=0;e<this._pointerDoubleClick.length;e++)this._pointerDoubleClick[e]=!1;for(const e of this._pointerPositionsDelta)e.set(0,0);for(let e=0;e<this._mouseWheelChanged.length;e++)this._mouseWheelChanged[e]=!1;for(let e=0;e<this._mouseWheelDeltaY.length;e++)this._mouseWheelDeltaY[e]=0};canReceiveInput(e){return e.target===this.context.renderer?.domElement||e.target===this.context.domElement||this.context.isInAR||this.context.isInAR&&e.target===document.body&&L.isMozillaXR()?!0:(rt&&console.warn("CanReceiveInput:False for",e.target),!1)}onContextMenu=e=>{this.canReceiveInput(e)!==!1&&e instanceof PointerEvent&&e.pointerType};keysPressed={};onKeyDown=e=>{if(rt&&console.log(`key down ${e.code}, ${this.context.application.hasFocus}`,e),!this.context.application.hasFocus)return;const t=this.keysPressed[e.code];if(t&&t.pressed)return;this.keysPressed[e.code]={pressed:!0,frame:this.context.time.frameCount+1,startFrame:this.context.time.frameCount+1,key:e.key,code:e.code};const i=new pc("keydown",e,e);this.onDispatchEvent(i)};onKeyPressed=e=>{if(!this.context.application.hasFocus)return;const t=this.keysPressed[e.code];if(!t)return;t.pressed=!0,t.frame=this.context.time.frameCount+1;const i=new pc("keypress",e,e);this.onDispatchEvent(i)};onKeyUp=e=>{if(!this.context.application.hasFocus)return;const t=this.keysPressed[e.code];if(!t)return;t.pressed=!1,t.frame=this.context.time.frameCount+1;const i=new pc("keyup",e,e);this.onDispatchEvent(i)};onWheelWindow=e=>{document.pointerLockElement&&this.onMouseWheel(e)};onMouseWheel=e=>{if(this.canReceiveInput(e)===!1)return;this._mouseWheelDeltaY.length<=0&&this._mouseWheelDeltaY.push(0),this._mouseWheelChanged.length<=0&&this._mouseWheelChanged.push(!1),this._mouseWheelChanged[0]=!0;const t=this._mouseWheelDeltaY[0];this._mouseWheelDeltaY[0]=t+e.deltaY};onPointerDown=e=>{if(this.context.isInAR||this.canReceiveInput(e)===!1)return;e.target instanceof HTMLElement&&e.target.setPointerCapture(e.pointerId);const t=this.getPointerId(e);rt&&Ee(`pointer down #${t}, identifier:${e.pointerId}`);const i=this.getAndUpdateSpatialObjectForScreenPosition(t,e.clientX,e.clientY),n=new Ro("pointerdown",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:t,button:e.button,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,buttonName:this.getButtonName(e),device:i,pressure:e.pressure});this.onDown(n)};onPointerMove=e=>{if(this.context.isInAR||this._receivedPointerMoveEventsThisFrame.includes(e.pointerId))return;this._receivedPointerMoveEventsThisFrame.push(e.pointerId);let t=e.button;e.pointerType==="mouse"&&(t=this.getFirstPressedButtonForPointer(0)??0);const i=this.getPointerId(e,t);t===-1&&(t=i);const n=this.getAndUpdateSpatialObjectForScreenPosition(i,e.clientX,e.clientY),s=new Ro("pointermove",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:i,button:t,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,buttonName:this.getButtonName(e),device:n,pressure:e.pressure});this.onMove(s)};onPointerCancel=e=>{this.context.isInAR||(rt&&console.log("Pointer cancel",e),this.onPointerUp(e))};onPointerUp=e=>{if(this.context.isInAR)return;e.target instanceof HTMLElement&&e.target.releasePointerCapture(e.pointerId);const t=this.getPointerId(e),i=new Ro("pointerup",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:t,button:e.button,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,buttonName:this.getButtonName(e),device:this.getAndUpdateSpatialObjectForScreenPosition(t,e.clientX,e.clientY),pressure:e.pressure});this.onUp(i),this._pointerIds[t]=-1,rt&&console.log("ID="+t,"PointerId="+e.pointerId,"ALL:",[...this._pointerIds])};getPointerId(e,t){return e.pointerType==="mouse"?0+(t??e.button):this.getPointerIndex(e.pointerId)}getButtonName(e){const t=e.button;if(e.pointerType==="mouse")switch(t){case 0:return"left";case 1:return"middle";case 2:return"right"}return"unknown"}onTouchStart=e=>{if(this.context.isInAR)for(let t=0;t<e.changedTouches.length;t++){const i=e.changedTouches[t],n=this.getPointerIndex(i.identifier),s=this.getAndUpdateSpatialObjectForScreenPosition(n,i.clientX,i.clientY),r=new Ro("pointerdown",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:0,clientX:i.clientX,clientY:i.clientY,pointerType:"touch",buttonName:"unknown",device:s,pressure:i.force});this.onDown(r)}};onTouchMove=e=>{if(this.context.isInAR)for(let t=0;t<e.changedTouches.length;t++){const i=e.changedTouches[t],n=this.getPointerIndex(i.identifier),s=this.getAndUpdateSpatialObjectForScreenPosition(n,i.clientX,i.clientY),r=new Ro("pointermove",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:0,clientX:i.clientX,clientY:i.clientY,pointerType:"touch",buttonName:"unknown",device:s,pressure:i.force});this.onMove(r)}};onTouchEnd=e=>{if(this.context.isInAR)for(let t=0;t<e.changedTouches.length;t++){const i=e.changedTouches[t],n=this.getPointerIndex(i.identifier),s=new Ro("pointerup",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:0,clientX:i.clientX,clientY:i.clientY,pointerType:"touch",buttonName:"unknown",device:this.getAndUpdateSpatialObjectForScreenPosition(n,i.clientX,i.clientY),pressure:i.force});this.onUp(s),this._pointerIds[n]=-1}};tempNearPlaneVector=new b;tempFarPlaneVector=new b;tempLookMatrix=new K;getAndUpdateSpatialObjectForScreenPosition(e,t,i){let n=this._pointerSpace[e];n||(n=new k,this._pointerSpace[e]=n),this._pointerSpace[e]=n;const s=this.context.mainCamera;if(s){const r=this.tempNearPlaneVector.set(t,i,-1);this.convertScreenspaceToRaycastSpace(r);const a=this.tempFarPlaneVector.set(r.x,r.y,1);r.unproject(s),a.unproject(s);const l=s.worldUp||B(0,1,0).applyQuaternion(_e(s));this.tempLookMatrix.lookAt(a,r,l),n.position.set(r.x,r.y,r.z),n.quaternion.setFromRotationMatrix(this.tempLookMatrix)}return n}isInRect(e){if(this.context.isInXR)return!0;const t=this.context.domElement.getBoundingClientRect(),i=e.clientX,n=e.clientY,s=i>=t.x&&i<=t.right&&n>=t.y&&n<=t.bottom;return rt&&!s&&console.log("Not in rect",t,i,n),s}onDown(e){const t=e.pointerId;if(this.getPointerPressed(t)&&console.warn(`Received pointerDown for pointerId that is already pressed: ${t}`,rt?e:""),rt&&console.log(e.pointerType,"DOWN",t),!!this.isInRect(e)){for(this.setPointerState(t,this._pointerPressed,!0),this.setPointerState(t,this._pointerDown,!0),this.setPointerStateT(t,this._pointerEvent,e.source);t>=this._pointerTypes.length;)this._pointerTypes.push(e.pointerType);for(this._pointerTypes[t]=e.pointerType;t>=this._pointerPositionDown.length;)this._pointerPositionDown.push(new b);for(this._pointerPositionDown[t].set(e.clientX,e.clientY,e.clientZ??0);t>=this._pointerPositions.length;)this._pointerPositions.push(new ee);this._pointerPositions[t].set(e.clientX,e.clientY),t>=this._pointerDownTime.length&&this._pointerDownTime.push(0),this._pointerDownTime[t]=this.context.time.realtimeSinceStartup,this.updatePointerPosition(e),this._pointerEventsPressed.push(e),this.onDispatchEvent(e)}}onMove(e){const t=e.pointerId,i=this.getPointerPressed(t);i===!1&&!this.isInRect(e)||e.pointerType==="touch"&&!i||(this.updatePointerPosition(e),this.setPointerStateT(t,this._pointerEvent,e.source),this.onDispatchEvent(e))}onUp(e){const t=e.pointerId;if(!this.getPointerPressed(t)){rt&&console.log(e.pointerType,"UP",t,"was not down");return}rt&&console.log(e.pointerType,"UP",t),this.setPointerState(t,this._pointerPressed,!1),this.setPointerStateT(t,this._pointerEvent,e.source),this.setPointerState(t,this._pointerUp,!0),this.updatePointerPosition(e);for(let a=this._pointerEventsPressed.length-1;a>=0;a--)if(this._pointerEventsPressed[a].pointerId===t){this._pointerEventsPressed.splice(a,1);break}if(!this._pointerPositionDown[t]){rt&&be("Received pointer up event without matching down event for button: "+t),console.warn("Received pointer up event without matching down event for button: "+t);return}const i=this._pointerUpTime[t],n=this._pointerDownTime[t],s=this.context.time.realtimeSinceStartup,r=s-n;if(t>=this._pointerUpTime.length&&this._pointerUpTime.push(-99),this._pointerUpTime[t]=s,r<1){let a=e.clientX-this._pointerPositionDown[t].x,l=e.clientY-this._pointerPositionDown[t].y,c=0;if(e.isSpatial&&e.clientZ!=null&&(c=e.clientZ-this._pointerPositionDown[t].z,a*=200,l*=200,c*=200),Math.abs(a)<5&&Math.abs(l)<5&&Math.abs(c)<5){this.setPointerState(t,this._pointerClick,!0),e.isClick=!0;const h=s-i;rt&&console.log("CLICK",t,a,l,c,h),h<this._doubleClickTimeThreshold&&h>0&&(this.setPointerState(t,this._pointerDoubleClick,!0),e.isDoubleClick=!0)}}this.onDispatchEvent(e)}updatePointerPosition(e){const t=e.pointerId;for(;t>=this._pointerPositions.length;)this._pointerPositions.push(new ee);for(;t>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new ee);for(;t>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new ee);const i=this._pointerPositionsLastFrame[t];i.copy(this._pointerPositions[t]);const n=this._pointerPositionsDelta[t];let s=e.clientX-i.x,r=e.clientY-i.y;if(e.source instanceof MouseEvent||e.source instanceof TouchEvent){const h=e.source;s===0&&h.movementX!==0&&(s=h.movementX||0),r===0&&h.movementY!==0&&(r=h.movementY||0)}n.x+=s,n.y+=r,this._pointerPositions[t].x=e.clientX,this._pointerPositions[t].y=e.clientY;const a=e.clientX,l=e.clientY;for(;t>=this._pointerPositionsRC.length;)this._pointerPositionsRC.push(new ee);const c=this._pointerPositionsRC[t];c.set(a,l),this.convertScreenspaceToRaycastSpace(c)}getPointerIndex(e){let t=-1;for(let i=0;i<this._pointerIds.length;i++){if(this._pointerIds[i]===e)return i;t===-1&&this._pointerIds[i]===-1&&(t=i)}return t!==-1?(this._pointerIds[t]=e,t):(rt&&console.log("PUSH pointerId:",e),this._pointerIds.push(e),this._pointerIds.length-1)}setPointerState(e,t,i){t[e]=i}setPointerStateT(e,t,i){return t[e]=i,i}onDispatchEvent(e){const t=W.Current;try{W.Current=this.context,this.dispatchEvent(e)}finally{W.Current=t}}}const Fa=new K().makeRotationY(Math.PI),$i=new z().setFromAxisAngle(new b(0,1,0),Math.PI),ak=v("debugwebxr");class lk{priority=-1e5;gameObject;isXRRig(){return!0}get isActive(){return this.gameObject.visible}constructor(){if(this.gameObject=new k,this.gameObject.name="Implicit XR Rig",ak){const e=kg(16733661);e.position.y+=.5,this.gameObject.add(e)}}}const Eo=v("debugwebxr"),Hd=v("debugcustomgesture"),ck="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",hk="generic-trigger",dk=new z().setFromEuler(new st(wo.degToRad(0),wo.degToRad(-90),wo.degToRad(-90))),uk=new b(.04,-.04,0);class pg{xr;get context(){return this.xr.context}inputSource;index=0;emitEvents=!0;get connected(){return this._connected}_connected=!0;get isTracking(){return this._isTracking}_isTracking=!1;get gamepad(){return this.__gamepad??=this.inputSource.gamepad}__gamepad;get isHand(){return this.hand!=null}get hand(){return this.__hand??=this.inputSource.hand}__hand;get handObject(){return this.context.renderer.xr.getHand(this.index)}get profiles(){return this.inputSource.profiles}get layout(){return this._layout}get targetRayMode(){return this.inputSource.targetRayMode}get targetRaySpace(){return this.inputSource.targetRaySpace}get gripSpace(){return this.inputSource.gripSpace}get side(){return this.__side??=this.inputSource.handedness}__side=void 0;get isRight(){return this.side==="right"}get isLeft(){return this.side==="left"}get isStylus(){return this._isMxInk}getHitTestSource(){return this._hitTestSource||this._requestHitTestSource(),this._hitTestSource}get hasHitTestSource(){return this._hitTestSource}cancelHitTestSource(){this._hitTestSource&&(this._hitTestSource.cancel(),this._hitTestSource=void 0)}_hitTestSource=void 0;_hasSelectEvent=!1;get hasSelectEvent(){return this._hasSelectEvent}_isMxInk=!1;_isMetaQuestTouchController=!1;getHitTest(){return this.xr.getHitTest(this)}_handJointPoses=new Map;getHandJointPose(e,t){if(t=t||this.xr.frame,!this.hand||!t?.getJointPose||!this.xr.referenceSpace)return null;let i=this._handJointPoses?.get(e);return i||(i=t.getJointPose(e,this.xr.referenceSpace),i&&this._handJointPoses.set(e,i),i)}_gripMatrix=new K;_gripPosition=new b;_gripQuaternion=new z;_linearVelocity=new b;_rayPositionRaw=new b;_rayRotationRaw=new z;_rayMatrix=new K;_rayPosition=new b;_rayQuaternion=new z;get gripPosition(){return B(this._gripPosition)}get gripQuaternion(){return ai(this._gripQuaternion)}get gripMatrix(){return this._gripMatrix}get gripLinearVelocity(){return B(this._linearVelocity).applyQuaternion($i)}get rayPosition(){return B(this._rayPosition)}get rayQuaternion(){return ai(this._rayQuaternion)}get gripWorldPosition(){return B(this._gripWorldPosition)}_gripWorldPosition=new b;get gripWorldQuaternion(){return ai(this._gripWorldQuaternion)}_gripWorldQuaternion=new z;get rayWorldPosition(){return B(this._rayWorldPosition)}_rayWorldPosition=new b;updateRayWorldPosition(){const e=this.xr.context.mainCamera?.parent;this._rayWorldPosition.copy(this._rayPositionRaw),e&&this._rayWorldPosition.applyMatrix4(e.matrixWorld)}get rayWorldQuaternion(){return ai(this._rayWorldQuaternion)}_rayWorldQuaternion=new z;get pinchPosition(){return B(this._pinchPosition)}_pinchPosition=new b;updateRayWorldQuaternion(){const e=this.xr.context.mainCamera?.parent,t=e?_e(e):void 0;this._rayWorldQuaternion.copy(this._rayRotationRaw).multiply($i),t&&this._rayWorldQuaternion.premultiply(t)}get ray(){return this._ray.origin.copy(this.rayWorldPosition),this._ray.direction.copy(B(0,0,1).applyQuaternion(this.rayWorldQuaternion)),this._ray}_ray;_hand_wristDotUp=void 0;get handWristDotUp(){if(this._hand_wristDotUp!==void 0)return this._hand_wristDotUp;const e=this.handObject?.joints.wrist;if(e){const t=B(0,1,0).applyQuaternion(e.quaternion),i=B(0,1,0).dot(t);return this._hand_wristDotUp=i}}get isHandUpsideDown(){return this.handWristDotUp!==void 0?this.handWristDotUp<-.7:!1}get isTeleportGesture(){return this.isHandUpsideDown&&this.getGesture("pinch")?.isDown}get object(){return this._object}_object;_gripSpaceObject;_raySpaceObject;model=null;_debugAxesHelper=new Ci(.15);_debugGripAxesHelper=new Ci(.07);_debugRayAxesHelper=new Ci(.07);async getModelUrl(){return this.getMotionController?.then(e=>e?.assetUrl||null)}constructor(e,t,i){this.xr=e,this.inputSource=t,this.index=i,this._object=new k,this._object.name=`NeedleXRController_${i}`,Eo&&(this._object.add(this._debugAxesHelper),this._gripSpaceObject=new k,this._raySpaceObject=new k,this._gripSpaceObject.name=`NeedleXRController_${i}_gripSpace`,this._raySpaceObject.name=`NeedleXRController_${i}_raySpace`,this._gripSpaceObject.add(this._debugGripAxesHelper),this._raySpaceObject.add(this._debugRayAxesHelper),this.xr.context.scene.add(this._gripSpaceObject),this.xr.context.scene.add(this._raySpaceObject)),this.xr.context.scene.add(this._object),this._ray=new vo,this.pointerInit={origin:this,pointerType:this.hand?"hand":"controller",deviceIndex:this.index,pointerId:-1,mode:this.inputSource.targetRayMode,ray:this._ray,device:this._object,buttonName:"none"},this.initialize(),this.subscribeEvents()}_hitTestSourcePromise=null;_requestHitTestSource(){return this._hitTestSourcePromise?this._hitTestSourcePromise:this.xr.mode==="immersive-ar"&&this.inputSource.targetRayMode==="tracked-pointer"&&this.xr.session.requestHitTestSourceForTransientInput?this._hitTestSourcePromise=this.xr.session.requestHitTestSourceForTransientInput({profile:this.inputSource.profiles[0],offsetRay:new XRRay})?.then(e=>(this._hitTestSourcePromise=null,this.connected?this._hitTestSource=e:(e.cancel(),null)))??null:null}onPointerHits=e=>{};onUpdate(e){this.onUpdateFrame(e),this.updateInputEvents(),this.onUpdateMove()}onRenderDebug(){F.DrawSphere(this.rayWorldPosition,.003),F.DrawDirection(this.rayWorldPosition,B(0,0,10).applyQuaternion(this.rayWorldQuaternion));const e=(this.inputSource.gripSpace?this.gripWorldPosition:this.object.worldPosition).sub(this.object.worldForward.multiplyScalar(.1)),t=this.inputSource.profiles.join(`
146
146
  `);let i=`Controller[${this.index}] (${this.inputSource.targetRayMode}, ${this.side})
147
147
  C:${this.connected?"x":"-"} T:${this.isTracking?"x":"-"} Hand:${this.inputSource.hand?"x":"-"} Pen: ${this._isMxInk?"x":"-"}`;if(this.inputSource.hand&&(i+=`
@@ -163,7 +163,7 @@ or by using the once option like onStart(()=>{}, { once:true }).
163
163
  See https://engine.needle.tools/docs/scripting.html#special-lifecycle-hooks for more information.`))}}function _s(o,e){const t=za.get(e);if(t){for(let n=0;n<t.length;n++)if(t[n].method===o){t.splice(n,1);return}}const i=Ua.get(e);if(i){for(let n=0;n<i.length;n++)if(i[n].method===o){i.splice(n,1);return}}}function Hn(o,e){e===ue.ContextCreated&&gg.delete(o),D_(o,e)}function D_(o,e){e===xe.Start&&Ua.get(ue.ContextCreated)&&D_(o,ue.ContextCreated);const t=e===xe.Start||e===ue.ContextCreated,i=za.get(e);i&&i.length>0&&B_(o,i,t);const n=Ua.get(e);if(n&&n.length>0){const s=[...n];n.length=0,B_(o,s,t),s.length>0&&(za.has(e)||za.set(e,new Array),za.get(e).push(...s))}}const Gd=new Array,j_={context:null};function B_(o,e,t){Gd.length=0;for(let n=0;n<e.length;n++)Gd.push(e[n]);let i=gg.get(o);for(let n=0;n<Gd.length;n++){const s=Gd[n];let r=!0;if(i&&i.has(s)&&(r=!1),r)try{j_.context=o,s.method?.call(j_,o)}catch(a){console.error("Error in lifecycle method",a)}if(s.options?.once){for(let a=0;a<e.length;a++)if(e[a]===s){e.splice(a,1);break}}else t&&(i||(i=new Set,gg.set(o,i)),i.add(s))}}const gg=new WeakMap,fg={};function yg(o,e){fg[o]=e}function F_(o){const e=o.getBufferIdentifier(),t=fg[e];return t(o)}function U_(o){return typeof o.guid=="function"?o.guid():null}let bg;function pk(){return bg}function mk(o){bg=o}function z_(o,e){return e||(e={}),e={...bg,...e},o?new Pb(o,e):new Pb(e)}async function N_(){const o=await import("./vendor-sURMCFSI.min.js").then(e=>e.bundler);return console.log(o),o.default===void 0?o:o.default}class W_{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 N_(),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 fk(i)})}async trySetupClient(e){const t=await N_();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 gk{_peer;constructor(e){this._peer=e}}class fk extends gk{get isHost(){return!0}_connections=[];constructor(e){super(e),console.log("I AM THE HOST"),this._peer?.on("connection",this.onConnection.bind(this)),this._peer.on("close",()=>{this.broadcast("BYE")}),setInterval(()=>{this.broadcast("HELLO")},2e3)}onConnection(e){console.log("host connection",e),e.on("open",()=>{this._connections.push(e),this.broadcastConnection(e)})}broadcastConnection(e){const t=this._connections.map(i=>i.metadata?.id).filter(i=>i!==void 0);this.broadcast({type:"connection-list",connections:t})}broadcast(e){if(e!=null){console.log(">>",e);for(const t in this._peer.connections){const i=this._peer.connections[t];if(i)if(Array.isArray(i))for(const n of i)n&&n.send(e);else console.warn(i)}}}}var wn=(o=>(o[o.OnConnection=0]="OnConnection",o[o.OnRoomJoin=1]="OnRoomJoin",o[o.Queued=2]="Queued",o[o.Immediate=3]="Immediate",o))(wn||{});const V_="https://urls.needle.tools/default-networking-backend/index";let Hi="wss://networking.needle.tools/socket";const hi=!!v("debugnet"),gc=!!(hi||v("debugowner")),qd=v("debugnetbin");var $_=(o=>(o.ConnectionInfo="connection-start-info",o))($_||{}),ie=(o=>(o.Join="join-room",o.Leave="leave-room",o.JoinedRoom="joined-room",o.LeftRoom="left-room",o.UserJoinedRoom="user-joined-room",o.UserLeftRoom="user-left-room",o.RoomStateSent="room-state-sent",o))(ie||{});class yk{room;viewId;allowEditing;inRoom}class bk{room}class _k{userId}var H_=(o=>(o.RequestHasOwner="request-has-owner",o.ResponseHasOwner="response-has-owner",o.RequestIsOwner="request-is-owner",o.ResponseIsOwner="response-is-owner",o.RequestOwnership="request-ownership",o.GainedOwnership="gained-ownership",o.RemoveOwnership="remove-ownership",o.LostOwnership="lost-ownership",o.GainedOwnershipBroadcast="gained-ownership-broadcast",o.LostOwnershipBroadcast="lost-ownership-broadcast",o))(H_||{});class _g{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||(gc&&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 gc&&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?(gc&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(gc&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}}class G_{context;_peer=null;constructor(e){this.context=e}get peer(){return this._peer||(this._peer=new W_),this._peer}tryGetState(e){return e==="invalid"?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return hi}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(),hi&&console.log("join: "+e),this.send("join-room",{room:e,viewOnly:t},wn.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=wn.Queued){if(t===null&&(t={}),i===wn.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){qd&&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,wn.Immediate);break}const s=this.toMessage(n.key,n.value);this._defaultMessagesBufferArray.push(s)}if(this._defaultMessagesBuffer.length=0,this._defaultMessagesBufferArray.length>0&&hi&&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!==Hi)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?Hi=t:Lb()&&(Hi="wss://"+window.location.host+"/socket"),this.connectWebsocket()}disconnect(){this._ws?.close(),this._ws=void 0,Hi=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=c=>{i||(i=!0,e(c))};if(Hi===void 0&&(console.log("Fetch default backend url: "+V_),Hi=await(await fetch(V_)).text()),Hi===void 0){n(!1);return}console.debug(`Connecting to networking backend on
164
164
  `+Hi);const s=await import("./vendor-sURMCFSI.min.js").then(c=>c.index),r=s.default?.WebsocketBuilder??s.WebsocketBuilder,a=s.default?.ExponentialBackoff??s.ExponentialBackoff,l=new r(Hi).withMaxRetries(10).withBackoff(new a(2e3,4)).onOpen(()=>{this._connectingToWebsocketPromise=null,this._ws=l,this.connected=!0,A()||hi?console.log(`Connected to networking backend
165
165
  `+Hi):console.debug("Connected to networking backend",Hi),n(!0),this.onSendQueued(wn.OnConnection)}).onClose(c=>{this._connectingToWebsocketPromise=null,this.connected=!1,this._isInRoom=!1,n(!1);let h="Websocket connection closed...";Hi?.includes("/socket")||(h+=' Do you perhaps mean to connect to "/socket"?'),console.error(h)}).onError(c=>{console.error("Websocket connection failed..."),n(!1)}).onRetry(()=>{console.log("Retry connecting to networking websocket")}).build();l.addEventListener(s.WebsocketEvent.message,(c,h)=>{this.onMessage(c,h)})})}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 s of n)this.handleIncomingStringMessage(s);else this.handleIncomingStringMessage(n);return}catch(n){hi&&i==="pong"?console.log("<<",i):A()&&console.error("Failed to parse message",n)}}async handleIncomingBinaryMessage(e){qd&&console.log("<< bin",this.context.time.frame);const t=await e.arrayBuffer();var i=new Uint8Array(t);const n=new gP(i),s=n.getBufferIdentifier(),r=this._listenersBinary[s],a=F_(n),l=U_(a);if(l&&typeof l=="string"&&(this._state[l]=a),!r)return;const c=a??n;for(const h of r)h(c)}handleIncomingStringMessage(e){if(hi&&console.log("<<",e.key??e),e.key)switch(e.key){case"connection-start-info":if(e.data){const r=e.data;r&&(console.assert(r.id!==void 0&&r.id!==null&&r.id.length>0,"server did not send connection id",r.id),console.debug("Your id is: "+r.id,this.context.alias??""),this._connectionId=r.id)}else console.warn("Expected connection id in "+e.key);break;case"joined-room":if(hi&&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),(qd||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}
166
- ${a.href}`)}this.onSendQueued(wn.OnRoomJoin);break;case"left-room":const n=e;n.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentRoomAllowEditing=!0,this._currentInRoom.length=0,(qd||A())&&console.debug("Left Needle Engine Room: "+n.room));break;case"user-joined-room":if(e.data){const r=e.data;this._currentInRoom.push(r.userId),hi&&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&&(hi&&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":hi&&console.log("RECEIVED all-room-state-deleted"),this._state={};break;case"ping":case"pong":const s=e.data?.time;s&&(this._currentDelay=this.context.time.time-s),hi&&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(s){console.error('Error invoking callback for "'+e.key+'"',s)}}}toMessage(e,t){return{key:e,data:t}}sendWithWebsocket(e,t,i=wn.OnRoomJoin){if(!this._ws){const s=this._waitingForSocket[i]||[];s.push(()=>this.sendWithWebsocket(e,t,i)),this._waitingForSocket[i]=s;return}const n=JSON.stringify(this.toMessage(e,t));hi&&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 fc=v("debugwebxr");class vg{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=>{fc&&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 s=0;s<e.controllers.length;s++)e.controllers[s].index===i.index&&(n=!0);n||(fc&&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),fc&&console.log(`XRSync: ${i.type} ${i.handedness} added`,i.index)}}}class q_{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(n=>n.handedness===t)?.isTracking||!1:void 0}getDeviceType(e,t){if(!e)return;const i=this._states.get(e);return i?i.controllerStates.find(n=>n.handedness===t)?.type||"unknown":void 0}context;constructor(e){this.context=e,this.context.connection.beginListen(ie.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(ie.LeftRoom,this.onLeftRoom),this.context.connection.beginListen(ie.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.beginListen(ie.UserLeftRoom,this.onOtherUserLeftRoom)}destroy(){this.context.connection.stopListen(ie.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(ie.LeftRoom,this.onLeftRoom),this.context.connection.stopListen(ie.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.stopListen(ie.UserLeftRoom,this.onOtherUserLeftRoom)}onJoinedRoom=()=>{if(this.context.connection.connectionId){this._states.has(this.context.connection.connectionId)||(fc&&console.log("XRSync: Local user joined room",this.context.connection.connectionId),this._states.set(this.context.connection.connectionId,new vg(this.context.connection.connectionId,this.context)));for(const e of this.context.connection.usersInRoom())this._states.has(e)||this._states.set(e,new vg(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)||(fc&&console.log("XRSync: Remote user joined room",t),this._states.set(t,new vg(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 X_{_fadeToColorQuad;_fadeToColorMaterial;constructor(){this._fadeToColorMaterial=new Se({color:0,transparent:!0,depthTest:!1,fog:!1,side:Pi}),this._fadeToColorQuad=new H(new Un(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 s=this._requestedFadeValue;n.opacity=D.lerp(n.opacity,s,t/.03),Math.abs(n.opacity-s)<=.01&&this._transitionResolve&&(this._transitionResolve(),this._transitionResolve=null,this._transitionPromise=null,this._requestedFadeValue=0)}remove(){this._fadeToColorQuad.removeFromParent()}fadeTransition(){if(this._transitionPromise)return this._transitionPromise;this._requestedFadeValue=1;const e=new Promise(t=>{this._transitionResolve=t});return this._transitionPromise=e,e}_requestedFadeValue=0;_transitionPromise=null;_transitionResolve=null}var Sr=(o=>(o[o.Quad=0]="Quad",o[o.Cube=1]="Cube",o[o.Sphere=2]="Sphere",o[o.Cylinder=3]="Cylinder",o[o.RoundedCube=10]="RoundedCube",o))(Sr||{});class Cr{static createText(e,t){let i=null;const n=t?.font||wk(t?.familyFamily||null);n instanceof QC?i=this.#t(e,n,t):i==null&&(i=new fn);const s=t?.color||16777215,r=new H(i,t?.material??new mt({color:s}));return this.applyDefaultObjectOptions(r,t),n instanceof Promise?n.then(a=>{r.geometry=this.#t(e,a,t),t?.onGeometry&&t.onGeometry(r)}):t?.onGeometry&&t.onGeometry(r),r}static#t(e,t,i){const n=i?.depth||.1;return new YC(e,{font:t,size:1,depth:n,height:n,bevelEnabled:i?.bevel||!1,bevelThickness:.01,bevelOffset:.01,bevelSize:.01})}static createOccluder(e){const t=new Se({colorWrite:!1,depthWrite:!0,side:Pi});return this.createPrimitive(e,{material:t})}static createPrimitive(e,t){let i;const n=t?.color||16777215;switch(e){case"Quad":case 0:{const s=new Un(1,1,1,1),r=t?.material??new mt({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new H(s,r),i.name="Quad"}break;case"Cube":case 1:{const s=new Oa(1,1,1),r=t?.material??new mt({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new H(s,r),i.name="Cube"}break;case 10:case"RoundedCube":{const s=vk(1,1,1,.1,2),r=t?.material??new mt({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new H(s,r),i.name="RoundedCube"}break;case"Sphere":case 2:{const s=new _d(.5,16,16),r=t?.material??new mt({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new H(s,r),i.name="Sphere"}break;case"Cylinder":case 3:{const s=new nb(.5,.5,1,32),r=t?.material??new mt({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new H(s,r),i.name="Cylinder"}break;case"ShaderBall":i=new xo,i.name="ShaderBall",xk(i,t);break}return this.applyDefaultObjectOptions(i,t),i}static createSprite(e){const t=new TS({color:16777215});e?.texture&&"map"in t&&(t.map=e.texture);const i=new AS(t);return this.applyDefaultObjectOptions(i,e),i}static applyDefaultObjectOptions(e,t){e.receiveShadow=!0,e.castShadow=!0,t?.name&&(e.name=t.name),t?.position&&(Array.isArray(t.position)?e.position.set(t.position[0],t.position[1],t.position[2]):e.position.set(t.position.x||0,t.position.y||0,t.position.z||0)),t?.rotation&&(Array.isArray(t.rotation)?e.rotation.set(t.rotation[0],t.rotation[1],t.rotation[2]):e.rotation.set(t.rotation.x||0,t.rotation.y||0,t.rotation.z||0)),t?.scale&&(typeof t.scale=="number"?e.scale.set(t.scale,t.scale,t.scale):Array.isArray(t.scale)?e.scale.set(t.scale[0],t.scale[1],t.scale[2]):e.scale.set(t.scale.x||1,t.scale.y||1,t.scale.z||1)),t?.receiveShadow!=null&&(e.receiveShadow=t.receiveShadow),t?.castShadow!=null&&(e.castShadow=t.castShadow),t?.parent&&t.parent.add(e)}}function vk(o,e,t,i,n){const s=new IS,r=1e-5,a=i-r;s.absarc(r,r,r,-Math.PI/2,-Math.PI,!0),s.absarc(r,e-a*2,r,Math.PI,Math.PI/2,!0),s.absarc(o-a*2,e-a*2,r,Math.PI/2,0,!0),s.absarc(o-a*2,r,r,0,-Math.PI/2,!0);const l=new LS(s,{bevelEnabled:!0,bevelSegments:n*2,steps:1,bevelSize:a,bevelThickness:i,curveSegments:n,UVGenerator:{generateTopUV:(c,h)=>{const d=[];for(let p=0;p<h.length;p+=3)d.push(new ee(h[p]/o,h[p+1]/e));return d},generateSideWallUV:(c,h,d,p,m,f)=>{const g=[];return g.push(new ee(h[d]/o,h[d+1]/e)),g.push(new ee(h[p]/o,h[p+1]/e)),g.push(new ee(h[m]/o,h[m+1]/e)),g.push(new ee(h[f]/o,h[f+1]/e)),g}}});return l.scale(1,1,1-i),l.center(),l.index||l.setIndex(Array.from({length:l.attributes.position.count},(c,h)=>h)),l.computeVertexNormals(),l}const Xd=new Map;function wk(o){let e="";switch(o){default:case"OpenSans":e="https://cdn.needle.tools/static/fonts/facetype/Open Sans_Regular_ascii.json";break;case"Helvetiker":e="https://raw.githubusercontent.com/mrdoob/three.js/master/examples/fonts/helvetiker_regular.typeface.json";break}if(Xd.has(e)){const n=Xd.get(e);if(n)return n}const t=new ZC,i=new Promise((n,s)=>{t.load(e,r=>{Xd.set(e,r),n(r)},void 0,s)});return Xd.set(e,i),i}let wg=!1,xg=null;function xk(o,e){if(xg===null){const t="https://cdn.needle.tools/static/models/shaderball.glb",i=new Po,n=Mm(null);i.setDRACOLoader(n.dracoLoader),i.setKTX2Loader(n.ktx2Loader),wg=!0,xg=i.loadAsync(t).then(s=>{const r=s.scene;return r.position.y-=.5,r}).catch(s=>(console.warn("Failed to load shaderball mesh: "+s.message),Y_())).finally(()=>{wg=!1})}if(wg){const t=Y_();t.name="ShaderBall-Placeholder";const i=t.children[0];i?.type==="Mesh"&&Q_(i,e),o.add(t)}xg.then(t=>{o.children.forEach(s=>{s.name==="ShaderBall-Placeholder"&&o.remove(s)});const i=t.clone(),n=i.children[0];n?.type==="Mesh"&&(n.geometry.attributes.tangent||n.geometry.computeTangents(),Q_(n,e)),o.add(i)})}function Q_(o,e){if(e?.color||e?.material||e?.texture){const t=e?.material??o.material?.clone()??new mt;e.color&&"color"in t&&t.color instanceof oe&&t.color.set(e.color),e?.texture&&"map"in t&&(t.map=e.texture),o.material=t}}function Y_(){return new xo().add(Cr.createPrimitive("Sphere",{material:new Se({transparent:!0,opacity:.1})}))}class Gl{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 Gl(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 ko(100)),this._active=null}_session;_mode;_init;get isAR(){return this._mode==="immersive-ar"}_renderer;_camera;_scene;constructor(e,t,i){this._mode=e,this._init=t,this._session=i,this._session.addEventListener("end",this.onEnd),this._renderer=new hr({alpha:!0,antialias:!0}),this._renderer.outputColorSpace="srgb",this._renderer.setAnimationLoop(this.onFrame),this._renderer.xr.setSession(i),this._renderer.xr.enabled=!0,this._renderer.setPixelRatio(Math.min(2,window.devicePixelRatio)),this._renderer.setSize(window.innerWidth,window.innerHeight),this._camera=new ae,this._scene=new xi,this._scene.fog=new ob(4473924,10,250),this._scene.add(this._camera),this.setupScene()}end(){return this._session?this._session.end():Promise.resolve()}async handoff(){if(!this._session)throw new Error("Cannot handoff a session that has already ended");const e={session:this._session,mode:this._mode,init:this._init};return await this.onBeforeHandoff(),this.onEnd(),this._session=null,e}onEnd=()=>{this._session?.removeEventListener("end",this.onEnd),this._renderer.setAnimationLoop(null),this._renderer.dispose(),this._scene.clear()};_lastTime=0;onFrame=(e,t)=>{const i=e-this._lastTime;this.update(e,i),this._camera.parent!==this._scene&&this._scene.add(this._camera),this._renderer.render(this._scene,this._camera)};async onBeforeHandoff(){await ko(1e3),this._scene.clear()}_objects=[];setupScene(){this._scene.background=new oe(0),this._scene.add(new mm(5,10,1118481,1118481));const e=new gm(16777215,1);e.position.set(0,20,0),e.castShadow=!1,this._scene.add(e);const t=new gm(16777215,1);t.position.set(0,-1,0),t.castShadow=!1,this._scene.add(t);const i=new fm(16777215,1,100,1);i.position.set(0,2,0),i.castShadow=!1,i.distance=200,this._scene.add(i);const n=50;for(let s=0;s<100;s++){const r=new mt({color:2236962,metalness:1,roughness:.8});this.isAR&&(r.emissive=new oe(Math.random(),Math.random(),Math.random()),r.emissiveIntensity=Math.random());const a=D.random(0,1)>.5?Sr.Sphere:Sr.Cube,l=Cr.createPrimitive(a,{material:r});l.position.x=D.random(-n,n),l.position.y=D.random(-2,n),l.position.z=D.random(-n,n),l.rotation.x=D.random(0,Math.PI*2),l.rotation.y=D.random(0,Math.PI*2),l.rotation.z=D.random(0,Math.PI*2),l.scale.multiplyScalar(.5+Math.random()*10);const c=l.position.distanceTo(this._camera.position)-l.scale.x;c<1&&l.position.multiplyScalar(1+1/c),this._objects.push(l),this._scene.add(l)}}update(e,t){const i=e*4e-4;for(let n=0;n<this._objects.length;n++){const s=this._objects[n];s.position.y+=Math.sin(i+n*.5)*.005,s.rotateY(.002)}}}var yc;(o=>{const e=[];function t(){e?.length||A()&&console.warn("No USDZ exporters found \u2013 cannot export USDZ for QuickLook.");for(const s of e)s.exportAndOpen();return!0}o.exportAndOpen=t;function i(s){e.push(s)}o.registerExporter=i;function n(s){if(!e)return;const r=e.indexOf(s);r>=0&&e.splice(r,1)}o.unregisterExporter=n})(yc||(yc={}));const qe=v("debugwebxr"),Z_=v("stats");let Sg=0;function Sk(o){let e=null;const t=o;return t.getAROverlayContainer?e=t.getAROverlayContainer():e=o,e}Ck();async function Ck(){let o="immersive-vr";try{if(L.isNeedleAppClip()?o="immersive-ar":await navigator.xr?.isSessionSupported("immersive-vr")||(o="immersive-ar"),!await navigator.xr?.isSessionSupported("immersive-ar")&&o==="immersive-ar"){console.warn("[NeedleXRSession:granted] Neither VR nor AR supported, aborting session start.");return}}catch(e){console.error("[NeedleXRSession:granted] Error while checking XR support:",e);return}if(v("debugasap")){let e=globalThis["needle:XRSession"];if(e instanceof Promise){delete globalThis["needle:XRSession"],pe.addContextCreatedCallback(async t=>{if(!e)return;La(!0);const i=await e;if(i){const n=Z.getDefaultSessionInit(o);Z.setSession(o,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(K_()&&(await Gl.start(e||o,i||Z.getDefaultSessionInit(o)).catch(s=>console.warn("[NeedleXRSession:granted] TemporaryXRContext start failed:",s)),await kk(),n=await Gl.handoff()),n)Z.setSession(n.mode,n.session,n.init,W.Current);else if(e&&t){console.log("[NeedleXRSession:granted] Restore last session");const s=JSON.parse(t);Z.start(e,s).catch(r=>console.warn(r))}else Z.start(o).catch(s=>console.warn("[NeedleXRSession:granted] failed:",s))},{once:!0})}}function Pk(o,e){sessionStorage.setItem("needle_xr_session_mode",o),sessionStorage.setItem("needle_xr_session_init",JSON.stringify(e))}function Ok(){sessionStorage.removeItem("needle_xr_session_mode"),sessionStorage.removeItem("needle_xr_session_init")}const Cg=new Set;pe.registerCallback(ue.ContextCreationStart,async o=>{Cg.add(o.context)}),pe.registerCallback(ue.ContextCreated,async o=>{Cg.delete(o.context);const e=o.context?.domElement.getAttribute("autostart")||null;Mk(e)});function K_(){return Cg.size>0}function kk(){return new Promise(o=>{const e=Date.now(),t=setInterval(()=>{(!K_()||Date.now()-e>6e4)&&(clearInterval(t),o())},100)})}L.isDesktop()&&A()&&window.addEventListener("keydown",o=>{(o.key==="x"||o.key==="Escape")&&Z.active&&Z.stop()});function Mk(o){o&&o?.toLowerCase()==="ar"&&jn.registerWaitForInteraction(()=>{Z.start("ar")})}const Qd=Symbol("initial-fov");class Z{static _sync=null;static getXRSync(e){return this._sync||(this._sync=new q_(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=>(qe&&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=>Z.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 L.isVisionOS()||t.push("hand-tracking"),{optionalFeatures:t};case"immersive-vr":const i=["local-floor","bounded-floor","high-fixed-foveation-level","layers"];return L.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(L.isiOS()){const r=await this.isARSupported().catch(()=>!1);if(L.isVisionOS()&&!r&&(e==="ar"||e==="immersive-ar")&&(e="quicklook"),e==="quicklook")return yc.exportAndOpen(),null;if(!r&&(e==="immersive-ar"||e==="ar")){const a=`https://appclip.needle.tools/ar?url=${encodeURIComponent(location.href)}`;return console.debug("iOS device detected - opening Needle App Clip for AR experience",a,{mode:e,init:t}),window.location.href=a,null}}if(e==="quicklook")return console.warn("QuickLook mode is only supported on iOS devices"),null;if(e=="ar"&&(e="immersive-ar"),A()&&v("debugxrpreroom"))return console.warn("Debug: Starting temporary XR session"),await Gl.start(e,t||Z.getDefaultSessionInit(e)),null;if(this._currentSessionRequest)return console.warn("A XRSession is already being requested"),(qe||A())&&be("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=W.Current),i||(i=pe.All[0]),!i)throw new Error("No Needle Engine Context found");switch(t||(t={}),e){case"immersive-ar":{if(await this.xrSystem?.isSessionSupported("immersive-ar")!==!0)return console.error(e+" is not supported by this browser."),null;const r=this.getDefaultSessionInit(e),a=Sk(i.domElement);a&&!L.isQuest()&&(r.domOverlay={root:a},r.optionalFeatures.push("dom-overlay")),t={...r,...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 Gl.stop();const n=e=="immersive-ar"?i.scripts_immersive_ar:i.scripts_immersive_vr;qe?console.log(`%cRequesting ${e} session`,"font-weight:bold;",t,n):console.log(`%cRequesting ${e} session`,"font-weight:bold;");for(const r of n)r.onBeforeXR&&r.activeAndEnabled&&!r.destroyed&&r.onBeforeXR(e,t);for(const r of this._sessionRequestStartListeners)r({mode:e,init:t});qe&&Ee("Requesting "+e+" session ("+Date.now()+")"),this._currentSessionRequest=navigator?.xr?.requestSession(e,t),this._currentSessionRequestMode=e;const s=await this._currentSessionRequest?.catch(r=>{console.error(r,"Code: "+r?.code),r?.code===9&&be("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:"&&be("XR requires a secure connection (HTTPS)")});this._currentSessionRequest=void 0,this._currentSessionRequestMode=null;for(const r of this._sessionRequestEndListeners)r({mode:e,init:t,newSession:s||null});return s?this.setSession(e,s,t,i):(console.warn("XR Session request was rejected"),null)}static setSession(e,t,i,n){if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;const s=e=="immersive-ar"?n.scripts_immersive_ar:n.scripts_immersive_vr;return this._activeSession=new Z(e,t,n,{scripts:s,controller_added:this._controllerAddedListeners,controller_removed:this._controllerRemovedListeners,init:i}),t.addEventListener("end",this.onEnd),qe?console.log(`%cStarted ${e} session`,"font-weight:bold;",s):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?(qe&&console.log("[NeedleXRSession] Stopping XR Session... (new)"),e[this.$_stop_request]=setTimeout(()=>{e.end()})):qe&&console.warn("[NeedleXRSession] XR Session stop already requested"))}static onEnd=()=>{qe&&console.log("XR Session ended"),this._activeSession=null};context;get sync(){return Z._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()&&L.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&&Tr(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 B(0,0,0);const t=B(e);return t.x*=-1,t.z*=-1,t.applyQuaternion(ai(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(Tr(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)}qe&&(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 s of n.results)return this.convertHitTestResult(s);return null}convertHitTestResult(e){const t=this.context.renderer.xr.getReferenceSpace(),i=t&&e.getPose(t);if(i){const n=B(i.transform.position),s=ai(i.transform.orientation),r=this.context.mainCamera;if(r?.parent!==this._cameraRenderParent&&n.applyMatrix4(Fa),r?.parent){n.applyMatrix4(r.parent.matrixWorld),s.multiply($i);const a=_e(r.parent);a.premultiply($i),s.premultiply(a)}return{hit:e,position:n,quaternion:s}}return null}convertSpace(e){const t=B(e.position);t.applyMatrix4(Fa);const i=ai(e.orientation);return i.premultiply($i),{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){Pk(e,n.init),this.session=t,this.mode=e,this.context=i,(qe||v("console"))&&La(!0),this._xr_scripts=[...n.scripts],this._xr_update_scripts=this._xr_scripts.filter(s=>typeof s.onUpdateXR=="function"),this._controllerAdded=n.controller_added,this._controllerRemoved=n.controller_removed,To(this.onBefore,xe.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(s=>t.requestHitTestSource?.call(t,{space:s})?.then(r=>this._viewerHitTestSource=r).catch(r=>console.error(r))).catch(s=>console.error(s)),this.context.mainCamera&&(this._originalCameraWorldPosition=J(this.context.mainCamera,new b),this._originalCameraWorldRotation=_e(this.context.mainCamera,new z),this._originalCameraWorldScale=Ge(this.context.mainCamera,new b),this._originalCameraParent=this.context.mainCamera.parent,this.context.mainCamera instanceof ae&&(this.context.mainCamera[Qd]=this.context.mainCamera.fov)),this._defaultRig=new lk,this.context.scene.add(this._defaultRig.gameObject),this.addRig(this._defaultRig);for(let s=0;s<t.inputSources.length;s++){const r=t.inputSources[s];if(!r.handedness){console.warn("Input source in xr session has no handedness - ignoring",s);continue}this.onInputSourceAdded(r)}this.session.addEventListener("end",this.onEnd),this.session.addEventListener("inputsourceschange",s=>{for(const r of s.removed)this.disconnectInputSource(r);for(const r of s.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):qe&&console.warn("controllerAutoUpdate is not available in three.js - cannot disable it")}onRendererSessionSet=()=>{this.running&&(this.context.renderer.xr.enabled=!0,this.context.renderer.xr.updateCamera(this.context.mainCamera),this.context.mainCameraComponent?.applyClearFlags())};onInputSourceAdded=e=>{if(e.targetRayMode==="screen")return;let t=0;for(let n=0;n<this.session.inputSources.length;n++)if(this.session.inputSources[n]===e){t=n;break}if(this.controllers.find(n=>n.inputSource===e)){console.debug("Controller already exists for input source",t);return}else if(this._newControllers.find(n=>n.inputSource===e)){console.debug("Controller already registered for input source",t);return}const i=new pg(this,e,t);this._newControllers.push(i)};disconnectInputSource(e){const t=(s,r)=>{if(s.inputSource===e){qe&&console.log("Disconnecting controller",s.index);const a=r.indexOf(s);a>=0&&r.splice(a,1),this.invokeControllerEvent(s,this._controllerRemoved,"removed");const l={xr:this,controller:s,change:"removed"};for(const c of this._xr_scripts)c.onXRControllerRemoved&&c.onXRControllerRemoved(l);s.onDisconnected()}},i=[...this.controllers];for(let s=i.length-1;s>=0;s--){const r=i[s];t(r,this.controllers)}const n=[...this._newControllers];for(let s=n.length-1;s>=0;s--){const r=n[s];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"),Ok(),this.onAfterRender(),this.revertCustomForward(),this._didStart=!1,this._previousCameraParent=null,this.requestedCameraNearPlane=null,_s(this.onBefore,xe.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()}),E_({session:this});for(const s of Z._xrEndListeners)s({xr:this});const n=[...this.controllers];for(let s=0;s<n.length;s++)this.disconnectInputSource(n[s].inputSource);this.controllers.length=0,this._newControllers.length=0;for(const s of this._xr_scripts)s?.onLeaveXR?.({xr:this});this.sync?.onExitXR(this),this.context.mainCamera&&(this._originalCameraParent?.add(this.context.mainCamera),this._originalCameraWorldPosition&&ft(this.context.mainCamera,this._originalCameraWorldPosition),this._originalCameraWorldRotation&&bn(this.context.mainCamera,this._originalCameraWorldRotation),this._originalCameraWorldScale&&Ia(this.context.mainCamera,this._originalCameraWorldScale),this.context.mainCamera instanceof ae&&this.context.mainCamera[Qd]&&(this.context.mainCamera.fov=this.context.mainCamera[Qd],this.context.mainCamera[Qd]=0)),this.context.requestSizeUpdate(),this._defaultRig.gameObject.removeFromParent(),La(!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&&(qe&&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 s=0;s<n.length;s++){const r=this.context.new_scripts_xr[s];if(!r||r.destroyed||r.supportsXR?.(this.mode)==!1){this.context.new_scripts_xr.splice(s,1);continue}if(!r.activeAndEnabled){this.context.new_scripts_xr.splice(s,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 s=Xt(this.context.scene.children);if(s){const r=s.getSize(B());if(r.length()>0){const a=this._defaultRig.gameObject;a.position.set(s.min.x+r.x*.5,s.min.y,s.max.z+r.z*.5+1.5);const l=s.getCenter(B());l.y=a.position.y,a.lookAt(l)}}}R_({session:this}),xr();for(const s of Z._xrStartListeners)s(i);const n=[...this._xr_scripts];qe&&console.log("NeedleXRSession start, handle scripts:",n);for(const s of n){if(s.destroyed){this._script_to_remove.push(s);continue}if(!s.activeAndEnabled){this.markInactive(s);continue}this.invokeCallback_EnterXR(s);for(const r of this.controllers)this.invokeCallback_ControllerAdded(s,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 s of n){if(!s.connected){console.warn("New controller is not connected",s);continue}this.controllers.push(s);for(const r of this._xr_scripts){if(r.destroyed){this._script_to_remove.push(r);continue}r.activeAndEnabled!==!1&&this.invokeCallback_ControllerAdded(r,s)}}this.controllers.sort((s,r)=>s.index-r.index)}qe&&this.context.time.frame%30===0&&this.controllers.length<=0&&this.session.inputSources.length>0&&(La(!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 s of n)!s.destroyed&&this.running&&s.onLeaveXR?.(i),this.removeScript(s)}this.sync?.onUpdate(this),this.onRenderDebug()};onRenderDebug(){if(qe)for(const e of this.controllers)e.onRenderDebug();if((qe||Z_)&&this.rig&&(Sg++,Sg>=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()}`,qe||Z_)for(const s of this.controllers)n+=`
166
+ ${a.href}`)}this.onSendQueued(wn.OnRoomJoin);break;case"left-room":const n=e;n.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentRoomAllowEditing=!0,this._currentInRoom.length=0,(qd||A())&&console.debug("Left Needle Engine Room: "+n.room));break;case"user-joined-room":if(e.data){const r=e.data;this._currentInRoom.push(r.userId),hi&&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&&(hi&&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":hi&&console.log("RECEIVED all-room-state-deleted"),this._state={};break;case"ping":case"pong":const s=e.data?.time;s&&(this._currentDelay=this.context.time.time-s),hi&&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(s){console.error('Error invoking callback for "'+e.key+'"',s)}}}toMessage(e,t){return{key:e,data:t}}sendWithWebsocket(e,t,i=wn.OnRoomJoin){if(!this._ws){const s=this._waitingForSocket[i]||[];s.push(()=>this.sendWithWebsocket(e,t,i)),this._waitingForSocket[i]=s;return}const n=JSON.stringify(this.toMessage(e,t));hi&&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 fc=v("debugwebxr");class vg{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=>{fc&&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 s=0;s<e.controllers.length;s++)e.controllers[s].index===i.index&&(n=!0);n||(fc&&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),fc&&console.log(`XRSync: ${i.type} ${i.handedness} added`,i.index)}}}class q_{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(n=>n.handedness===t)?.isTracking||!1:void 0}getDeviceType(e,t){if(!e)return;const i=this._states.get(e);return i?i.controllerStates.find(n=>n.handedness===t)?.type||"unknown":void 0}context;constructor(e){this.context=e,this.context.connection.beginListen(ie.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(ie.LeftRoom,this.onLeftRoom),this.context.connection.beginListen(ie.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.beginListen(ie.UserLeftRoom,this.onOtherUserLeftRoom)}destroy(){this.context.connection.stopListen(ie.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(ie.LeftRoom,this.onLeftRoom),this.context.connection.stopListen(ie.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.stopListen(ie.UserLeftRoom,this.onOtherUserLeftRoom)}onJoinedRoom=()=>{if(this.context.connection.connectionId){this._states.has(this.context.connection.connectionId)||(fc&&console.log("XRSync: Local user joined room",this.context.connection.connectionId),this._states.set(this.context.connection.connectionId,new vg(this.context.connection.connectionId,this.context)));for(const e of this.context.connection.usersInRoom())this._states.has(e)||this._states.set(e,new vg(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)||(fc&&console.log("XRSync: Remote user joined room",t),this._states.set(t,new vg(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 X_{_fadeToColorQuad;_fadeToColorMaterial;constructor(){this._fadeToColorMaterial=new Se({color:0,transparent:!0,depthTest:!1,fog:!1,side:Pi}),this._fadeToColorQuad=new H(new Un(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 s=this._requestedFadeValue;n.opacity=D.lerp(n.opacity,s,t/.03),Math.abs(n.opacity-s)<=.01&&this._transitionResolve&&(this._transitionResolve(),this._transitionResolve=null,this._transitionPromise=null,this._requestedFadeValue=0)}remove(){this._fadeToColorQuad.removeFromParent()}fadeTransition(){if(this._transitionPromise)return this._transitionPromise;this._requestedFadeValue=1;const e=new Promise(t=>{this._transitionResolve=t});return this._transitionPromise=e,e}_requestedFadeValue=0;_transitionPromise=null;_transitionResolve=null}var Sr=(o=>(o[o.Quad=0]="Quad",o[o.Cube=1]="Cube",o[o.Sphere=2]="Sphere",o[o.Cylinder=3]="Cylinder",o[o.RoundedCube=10]="RoundedCube",o))(Sr||{});class Cr{static createText(e,t){let i=null;const n=t?.font||wk(t?.familyFamily||null);n instanceof QC?i=this.#t(e,n,t):i==null&&(i=new fn);const s=t?.color||16777215,r=new H(i,t?.material??new mt({color:s}));return this.applyDefaultObjectOptions(r,t),n instanceof Promise?n.then(a=>{r.geometry=this.#t(e,a,t),t?.onGeometry&&t.onGeometry(r)}):t?.onGeometry&&t.onGeometry(r),r}static#t(e,t,i){const n=i?.depth||.1;return new YC(e,{font:t,size:1,depth:n,height:n,bevelEnabled:i?.bevel||!1,bevelThickness:.01,bevelOffset:.01,bevelSize:.01})}static createOccluder(e){const t=new Se({colorWrite:!1,depthWrite:!0,side:Pi});return this.createPrimitive(e,{material:t})}static createPrimitive(e,t){let i;const n=t?.color||16777215;switch(e){case"Quad":case 0:{const s=new Un(1,1,1,1),r=t?.material??new mt({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new H(s,r),i.name="Quad"}break;case"Cube":case 1:{const s=new Oa(1,1,1),r=t?.material??new mt({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new H(s,r),i.name="Cube"}break;case 10:case"RoundedCube":{const s=vk(1,1,1,.1,2),r=t?.material??new mt({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new H(s,r),i.name="RoundedCube"}break;case"Sphere":case 2:{const s=new _d(.5,16,16),r=t?.material??new mt({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new H(s,r),i.name="Sphere"}break;case"Cylinder":case 3:{const s=new nb(.5,.5,1,32),r=t?.material??new mt({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new H(s,r),i.name="Cylinder"}break;case"ShaderBall":i=new xo,i.name="ShaderBall",xk(i,t);break}return this.applyDefaultObjectOptions(i,t),i}static createSprite(e){const t=new TS({color:16777215});e?.texture&&"map"in t&&(t.map=e.texture);const i=new AS(t);return this.applyDefaultObjectOptions(i,e),i}static applyDefaultObjectOptions(e,t){e.receiveShadow=!0,e.castShadow=!0,t?.name&&(e.name=t.name),t?.position&&(Array.isArray(t.position)?e.position.set(t.position[0],t.position[1],t.position[2]):e.position.set(t.position.x||0,t.position.y||0,t.position.z||0)),t?.rotation&&(Array.isArray(t.rotation)?e.rotation.set(t.rotation[0],t.rotation[1],t.rotation[2]):e.rotation.set(t.rotation.x||0,t.rotation.y||0,t.rotation.z||0)),t?.scale&&(typeof t.scale=="number"?e.scale.set(t.scale,t.scale,t.scale):Array.isArray(t.scale)?e.scale.set(t.scale[0],t.scale[1],t.scale[2]):e.scale.set(t.scale.x||1,t.scale.y||1,t.scale.z||1)),t?.receiveShadow!=null&&(e.receiveShadow=t.receiveShadow),t?.castShadow!=null&&(e.castShadow=t.castShadow),t?.parent&&t.parent.add(e)}}function vk(o,e,t,i,n){const s=new IS,r=1e-5,a=i-r;s.absarc(r,r,r,-Math.PI/2,-Math.PI,!0),s.absarc(r,e-a*2,r,Math.PI,Math.PI/2,!0),s.absarc(o-a*2,e-a*2,r,Math.PI/2,0,!0),s.absarc(o-a*2,r,r,0,-Math.PI/2,!0);const l=new LS(s,{bevelEnabled:!0,bevelSegments:n*2,steps:1,bevelSize:a,bevelThickness:i,curveSegments:n,UVGenerator:{generateTopUV:(c,h)=>{const d=[];for(let p=0;p<h.length;p+=3)d.push(new ee(h[p]/o,h[p+1]/e));return d},generateSideWallUV:(c,h,d,p,m,f)=>{const g=[];return g.push(new ee(h[d]/o,h[d+1]/e)),g.push(new ee(h[p]/o,h[p+1]/e)),g.push(new ee(h[m]/o,h[m+1]/e)),g.push(new ee(h[f]/o,h[f+1]/e)),g}}});return l.scale(1,1,1-i),l.center(),l.index||l.setIndex(Array.from({length:l.attributes.position.count},(c,h)=>h)),l.computeVertexNormals(),l}const Xd=new Map;function wk(o){let e="";switch(o){default:case"OpenSans":e="https://cdn.needle.tools/static/fonts/facetype/Open Sans_Regular_ascii.json";break;case"Helvetiker":e="https://raw.githubusercontent.com/mrdoob/three.js/master/examples/fonts/helvetiker_regular.typeface.json";break}if(Xd.has(e)){const n=Xd.get(e);if(n)return n}const t=new ZC,i=new Promise((n,s)=>{t.load(e,r=>{Xd.set(e,r),n(r)},void 0,s)});return Xd.set(e,i),i}let wg=!1,xg=null;function xk(o,e){if(xg===null){const t="https://cdn.needle.tools/static/models/shaderball.glb",i=new Po,n=Mm(null);i.setDRACOLoader(n.dracoLoader),i.setKTX2Loader(n.ktx2Loader),wg=!0,xg=i.loadAsync(t).then(s=>{const r=s.scene;return r.position.y-=.5,r}).catch(s=>(console.warn("Failed to load shaderball mesh: "+s.message),Y_())).finally(()=>{wg=!1})}if(wg){const t=Y_();t.name="ShaderBall-Placeholder";const i=t.children[0];i?.type==="Mesh"&&Q_(i,e),o.add(t)}xg.then(t=>{o.children.forEach(s=>{s.name==="ShaderBall-Placeholder"&&o.remove(s)});const i=t.clone(),n=i.children[0];n?.type==="Mesh"&&(n.geometry.attributes.tangent||n.geometry.computeTangents(),Q_(n,e)),o.add(i)})}function Q_(o,e){if(e?.color||e?.material||e?.texture){const t=e?.material??o.material?.clone()??new mt;e.color&&"color"in t&&t.color instanceof oe&&t.color.set(e.color),e?.texture&&"map"in t&&(t.map=e.texture),o.material=t}}function Y_(){return new xo().add(Cr.createPrimitive("Sphere",{material:new Se({transparent:!0,opacity:.1})}))}class Gl{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 Gl(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 ko(100)),this._active=null}_session;_mode;_init;get isAR(){return this._mode==="immersive-ar"}_renderer;_camera;_scene;constructor(e,t,i){this._mode=e,this._init=t,this._session=i,this._session.addEventListener("end",this.onEnd),this._renderer=new hr({alpha:!0,antialias:!0}),this._renderer.outputColorSpace="srgb",this._renderer.setAnimationLoop(this.onFrame),this._renderer.xr.setSession(i),this._renderer.xr.enabled=!0,this._renderer.setPixelRatio(Math.min(2,window.devicePixelRatio)),this._renderer.setSize(window.innerWidth,window.innerHeight),this._camera=new ae,this._scene=new xi,this._scene.fog=new ob(4473924,10,250),this._scene.add(this._camera),this.setupScene()}end(){return this._session?this._session.end():Promise.resolve()}async handoff(){if(!this._session)throw new Error("Cannot handoff a session that has already ended");const e={session:this._session,mode:this._mode,init:this._init};return await this.onBeforeHandoff(),this.onEnd(),this._session=null,e}onEnd=()=>{this._session?.removeEventListener("end",this.onEnd),this._renderer.setAnimationLoop(null),this._renderer.dispose(),this._scene.clear()};_lastTime=0;onFrame=(e,t)=>{const i=e-this._lastTime;this.update(e,i),this._camera.parent!==this._scene&&this._scene.add(this._camera),this._renderer.render(this._scene,this._camera)};async onBeforeHandoff(){await ko(1e3),this._scene.clear()}_objects=[];setupScene(){this._scene.background=new oe(0),this._scene.add(new mm(5,10,1118481,1118481));const e=new gm(16777215,1);e.position.set(0,20,0),e.castShadow=!1,this._scene.add(e);const t=new gm(16777215,1);t.position.set(0,-1,0),t.castShadow=!1,this._scene.add(t);const i=new fm(16777215,1,100,1);i.position.set(0,2,0),i.castShadow=!1,i.distance=200,this._scene.add(i);const n=50;for(let s=0;s<100;s++){const r=new mt({color:2236962,metalness:1,roughness:.8});this.isAR&&(r.emissive=new oe(Math.random(),Math.random(),Math.random()),r.emissiveIntensity=Math.random());const a=D.random(0,1)>.5?Sr.Sphere:Sr.Cube,l=Cr.createPrimitive(a,{material:r});l.position.x=D.random(-n,n),l.position.y=D.random(-2,n),l.position.z=D.random(-n,n),l.rotation.x=D.random(0,Math.PI*2),l.rotation.y=D.random(0,Math.PI*2),l.rotation.z=D.random(0,Math.PI*2),l.scale.multiplyScalar(.5+Math.random()*10);const c=l.position.distanceTo(this._camera.position)-l.scale.x;c<1&&l.position.multiplyScalar(1+1/c),this._objects.push(l),this._scene.add(l)}}update(e,t){const i=e*4e-4;for(let n=0;n<this._objects.length;n++){const s=this._objects[n];s.position.y+=Math.sin(i+n*.5)*.005,s.rotateY(.002)}}}var yc;(o=>{const e=[];function t(){e?.length||A()&&console.warn("No USDZ exporters found \u2013 cannot export USDZ for QuickLook.");for(const s of e)s.exportAndOpen();return!0}o.exportAndOpen=t;function i(s){e.push(s)}o.registerExporter=i;function n(s){if(!e)return;const r=e.indexOf(s);r>=0&&e.splice(r,1)}o.unregisterExporter=n})(yc||(yc={}));const qe=v("debugwebxr"),Z_=v("stats");let Sg=0;function Sk(o){let e=null;const t=o;return t.getAROverlayContainer?e=t.getAROverlayContainer():e=o,e}Ck();async function Ck(){let o="immersive-vr";try{if(L.isNeedleAppClip()?o="immersive-ar":await navigator.xr?.isSessionSupported("immersive-vr")||(o="immersive-ar"),!await navigator.xr?.isSessionSupported("immersive-ar")&&o==="immersive-ar"){console.warn("[NeedleXRSession:granted] Neither VR nor AR supported, aborting session start.");return}}catch(e){console.error("[NeedleXRSession:granted] Error while checking XR support:",e);return}if(v("debugasap")){let e=globalThis["needle:XRSession"];if(e instanceof Promise){delete globalThis["needle:XRSession"],pe.addContextCreatedCallback(async t=>{if(!e)return;La(!0);const i=await e;if(i){const n=Z.getDefaultSessionInit(o);Z.setSession(o,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(K_()&&(await Gl.start(e||o,i||Z.getDefaultSessionInit(o)).catch(s=>console.warn("[NeedleXRSession:granted] TemporaryXRContext start failed:",s)),await kk(),n=await Gl.handoff()),n)Z.setSession(n.mode,n.session,n.init,W.Current);else if(e&&t){console.log("[NeedleXRSession:granted] Restore last session");const s=JSON.parse(t);Z.start(e,s).catch(r=>console.warn(r))}else Z.start(o).catch(s=>console.warn("[NeedleXRSession:granted] failed:",s))},{once:!0})}}function Pk(o,e){sessionStorage.setItem("needle_xr_session_mode",o),sessionStorage.setItem("needle_xr_session_init",JSON.stringify(e))}function Ok(){sessionStorage.removeItem("needle_xr_session_mode"),sessionStorage.removeItem("needle_xr_session_init")}const Cg=new Set;pe.registerCallback(ue.ContextCreationStart,async o=>{Cg.add(o.context)}),pe.registerCallback(ue.ContextCreated,async o=>{Cg.delete(o.context);const e=o.context?.domElement.getAttribute("autostart")||null;Mk(e)});function K_(){return Cg.size>0}function kk(){return new Promise(o=>{const e=Date.now(),t=setInterval(()=>{(!K_()||Date.now()-e>6e4)&&(clearInterval(t),o())},100)})}L.isDesktop()&&A()&&window.addEventListener("keydown",o=>{(o.key==="x"||o.key==="Escape")&&Z.active&&Z.stop()});function Mk(o){o&&o?.toLowerCase()==="ar"&&jn.registerWaitForInteraction(()=>{Z.start("ar")})}const Qd=Symbol("initial-fov");class Z{static _sync=null;static getXRSync(e){return this._sync||(this._sync=new q_(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=>(qe&&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=>Z.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 L.isVisionOS()||t.push("hand-tracking"),{optionalFeatures:t};case"immersive-vr":const i=["local-floor","bounded-floor","high-fixed-foveation-level","layers"];return L.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(L.isiOS()){const r=await this.isARSupported().catch(()=>!1);if(L.isVisionOS()&&!r&&(e==="ar"||e==="immersive-ar")&&(e="quicklook"),e==="quicklook")return yc.exportAndOpen(),null;if(!r&&(e==="immersive-ar"||e==="ar")){const a=new URL("https://appclip.apple.com/id?p=tools.needle.launch-app.Clip");return a.searchParams.set("url",location.href),console.debug("iOS device detected - opening Needle App Clip for AR experience",{mode:e,init:t,url:a}),window.location.href=encodeURI(a.toString()),null}}if(e==="quicklook")return console.warn("QuickLook mode is only supported on iOS devices"),null;if(e=="ar"&&(e="immersive-ar"),A()&&v("debugxrpreroom"))return console.warn("Debug: Starting temporary XR session"),await Gl.start(e,t||Z.getDefaultSessionInit(e)),null;if(this._currentSessionRequest)return console.warn("A XRSession is already being requested"),(qe||A())&&be("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=W.Current),i||(i=pe.All[0]),!i)throw new Error("No Needle Engine Context found");switch(t||(t={}),e){case"immersive-ar":{if(await this.xrSystem?.isSessionSupported("immersive-ar")!==!0)return console.error(e+" is not supported by this browser."),null;const r=this.getDefaultSessionInit(e),a=Sk(i.domElement);a&&!L.isQuest()&&(r.domOverlay={root:a},r.optionalFeatures.push("dom-overlay")),t={...r,...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 Gl.stop();const n=e=="immersive-ar"?i.scripts_immersive_ar:i.scripts_immersive_vr;qe?console.log(`%cRequesting ${e} session`,"font-weight:bold;",t,n):console.log(`%cRequesting ${e} session`,"font-weight:bold;");for(const r of n)r.onBeforeXR&&r.activeAndEnabled&&!r.destroyed&&r.onBeforeXR(e,t);for(const r of this._sessionRequestStartListeners)r({mode:e,init:t});qe&&Ee("Requesting "+e+" session ("+Date.now()+")"),this._currentSessionRequest=navigator?.xr?.requestSession(e,t),this._currentSessionRequestMode=e;const s=await this._currentSessionRequest?.catch(r=>{console.error(r,"Code: "+r?.code),r?.code===9&&be("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:"&&be("XR requires a secure connection (HTTPS)")});this._currentSessionRequest=void 0,this._currentSessionRequestMode=null;for(const r of this._sessionRequestEndListeners)r({mode:e,init:t,newSession:s||null});return s?this.setSession(e,s,t,i):(console.warn("XR Session request was rejected"),null)}static setSession(e,t,i,n){if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;const s=e=="immersive-ar"?n.scripts_immersive_ar:n.scripts_immersive_vr;return this._activeSession=new Z(e,t,n,{scripts:s,controller_added:this._controllerAddedListeners,controller_removed:this._controllerRemovedListeners,init:i}),t.addEventListener("end",this.onEnd),qe?console.log(`%cStarted ${e} session`,"font-weight:bold;",s):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?(qe&&console.log("[NeedleXRSession] Stopping XR Session... (new)"),e[this.$_stop_request]=setTimeout(()=>{e.end()})):qe&&console.warn("[NeedleXRSession] XR Session stop already requested"))}static onEnd=()=>{qe&&console.log("XR Session ended"),this._activeSession=null};context;get sync(){return Z._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()&&L.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&&Tr(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 B(0,0,0);const t=B(e);return t.x*=-1,t.z*=-1,t.applyQuaternion(ai(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(Tr(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)}qe&&(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 s of n.results)return this.convertHitTestResult(s);return null}convertHitTestResult(e){const t=this.context.renderer.xr.getReferenceSpace(),i=t&&e.getPose(t);if(i){const n=B(i.transform.position),s=ai(i.transform.orientation),r=this.context.mainCamera;if(r?.parent!==this._cameraRenderParent&&n.applyMatrix4(Fa),r?.parent){n.applyMatrix4(r.parent.matrixWorld),s.multiply($i);const a=_e(r.parent);a.premultiply($i),s.premultiply(a)}return{hit:e,position:n,quaternion:s}}return null}convertSpace(e){const t=B(e.position);t.applyMatrix4(Fa);const i=ai(e.orientation);return i.premultiply($i),{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){Pk(e,n.init),this.session=t,this.mode=e,this.context=i,(qe||v("console"))&&La(!0),this._xr_scripts=[...n.scripts],this._xr_update_scripts=this._xr_scripts.filter(s=>typeof s.onUpdateXR=="function"),this._controllerAdded=n.controller_added,this._controllerRemoved=n.controller_removed,To(this.onBefore,xe.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(s=>t.requestHitTestSource?.call(t,{space:s})?.then(r=>this._viewerHitTestSource=r).catch(r=>console.error(r))).catch(s=>console.error(s)),this.context.mainCamera&&(this._originalCameraWorldPosition=J(this.context.mainCamera,new b),this._originalCameraWorldRotation=_e(this.context.mainCamera,new z),this._originalCameraWorldScale=Ge(this.context.mainCamera,new b),this._originalCameraParent=this.context.mainCamera.parent,this.context.mainCamera instanceof ae&&(this.context.mainCamera[Qd]=this.context.mainCamera.fov)),this._defaultRig=new lk,this.context.scene.add(this._defaultRig.gameObject),this.addRig(this._defaultRig);for(let s=0;s<t.inputSources.length;s++){const r=t.inputSources[s];if(!r.handedness){console.warn("Input source in xr session has no handedness - ignoring",s);continue}this.onInputSourceAdded(r)}this.session.addEventListener("end",this.onEnd),this.session.addEventListener("inputsourceschange",s=>{for(const r of s.removed)this.disconnectInputSource(r);for(const r of s.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):qe&&console.warn("controllerAutoUpdate is not available in three.js - cannot disable it")}onRendererSessionSet=()=>{this.running&&(this.context.renderer.xr.enabled=!0,this.context.renderer.xr.updateCamera(this.context.mainCamera),this.context.mainCameraComponent?.applyClearFlags())};onInputSourceAdded=e=>{if(e.targetRayMode==="screen")return;let t=0;for(let n=0;n<this.session.inputSources.length;n++)if(this.session.inputSources[n]===e){t=n;break}if(this.controllers.find(n=>n.inputSource===e)){console.debug("Controller already exists for input source",t);return}else if(this._newControllers.find(n=>n.inputSource===e)){console.debug("Controller already registered for input source",t);return}const i=new pg(this,e,t);this._newControllers.push(i)};disconnectInputSource(e){const t=(s,r)=>{if(s.inputSource===e){qe&&console.log("Disconnecting controller",s.index);const a=r.indexOf(s);a>=0&&r.splice(a,1),this.invokeControllerEvent(s,this._controllerRemoved,"removed");const l={xr:this,controller:s,change:"removed"};for(const c of this._xr_scripts)c.onXRControllerRemoved&&c.onXRControllerRemoved(l);s.onDisconnected()}},i=[...this.controllers];for(let s=i.length-1;s>=0;s--){const r=i[s];t(r,this.controllers)}const n=[...this._newControllers];for(let s=n.length-1;s>=0;s--){const r=n[s];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"),Ok(),this.onAfterRender(),this.revertCustomForward(),this._didStart=!1,this._previousCameraParent=null,this.requestedCameraNearPlane=null,_s(this.onBefore,xe.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()}),E_({session:this});for(const s of Z._xrEndListeners)s({xr:this});const n=[...this.controllers];for(let s=0;s<n.length;s++)this.disconnectInputSource(n[s].inputSource);this.controllers.length=0,this._newControllers.length=0;for(const s of this._xr_scripts)s?.onLeaveXR?.({xr:this});this.sync?.onExitXR(this),this.context.mainCamera&&(this._originalCameraParent?.add(this.context.mainCamera),this._originalCameraWorldPosition&&ft(this.context.mainCamera,this._originalCameraWorldPosition),this._originalCameraWorldRotation&&bn(this.context.mainCamera,this._originalCameraWorldRotation),this._originalCameraWorldScale&&Ia(this.context.mainCamera,this._originalCameraWorldScale),this.context.mainCamera instanceof ae&&this.context.mainCamera[Qd]&&(this.context.mainCamera.fov=this.context.mainCamera[Qd],this.context.mainCamera[Qd]=0)),this.context.requestSizeUpdate(),this._defaultRig.gameObject.removeFromParent(),La(!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&&(qe&&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 s=0;s<n.length;s++){const r=this.context.new_scripts_xr[s];if(!r||r.destroyed||r.supportsXR?.(this.mode)==!1){this.context.new_scripts_xr.splice(s,1);continue}if(!r.activeAndEnabled){this.context.new_scripts_xr.splice(s,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 s=Xt(this.context.scene.children);if(s){const r=s.getSize(B());if(r.length()>0){const a=this._defaultRig.gameObject;a.position.set(s.min.x+r.x*.5,s.min.y,s.max.z+r.z*.5+1.5);const l=s.getCenter(B());l.y=a.position.y,a.lookAt(l)}}}R_({session:this}),xr();for(const s of Z._xrStartListeners)s(i);const n=[...this._xr_scripts];qe&&console.log("NeedleXRSession start, handle scripts:",n);for(const s of n){if(s.destroyed){this._script_to_remove.push(s);continue}if(!s.activeAndEnabled){this.markInactive(s);continue}this.invokeCallback_EnterXR(s);for(const r of this.controllers)this.invokeCallback_ControllerAdded(s,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 s of n){if(!s.connected){console.warn("New controller is not connected",s);continue}this.controllers.push(s);for(const r of this._xr_scripts){if(r.destroyed){this._script_to_remove.push(r);continue}r.activeAndEnabled!==!1&&this.invokeCallback_ControllerAdded(r,s)}}this.controllers.sort((s,r)=>s.index-r.index)}qe&&this.context.time.frame%30===0&&this.controllers.length<=0&&this.session.inputSources.length>0&&(La(!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 s of n)!s.destroyed&&this.running&&s.onLeaveXR?.(i),this.removeScript(s)}this.sync?.onUpdate(this),this.onRenderDebug()};onRenderDebug(){if(qe)for(const e of this.controllers)e.onRenderDebug();if((qe||Z_)&&this.rig&&(Sg++,Sg>=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()}`,qe||Z_)for(const s of this.controllers)n+=`
167
167
  ${s.hand?"hand":"ctrl"} ${s.inputSource.handedness}[${s.index}] con:${s.connected} tr:${s.isTracking} hts:${s.hasHitTestSource?"yes":"no"}`;Sg=0,F.DrawLabel(e,n,void 0,1/60*20)}}onBeforeRender=()=>{this.context.mainCamera&&(this.updateFade(this.context.mainCamera),this.requestedCameraNearPlane!==null&&this.context.mainCamera instanceof ae&&(this.context.mainCamera.near=this.requestedCameraNearPlane,this.requestedCameraNearPlane=null))};onAfterRender=()=>{if(this.onUpdateFade_PostRender(),L.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:(qe&&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){qe&&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 s=this._inactive_scripts.indexOf(e);s>=0&&this._inactive_scripts.splice(s,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 s=t[n];if(s)try{s({xr:this,controller:e,change:i})}catch(r){console.error(r)}}}_camera;_cameraRenderParent=new k().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=Ge(this.rig.gameObject);e*=i.x}this._camera instanceof ae&&Math.abs(this._camera.near-e)>t&&(this.isAR?this.originalCameraNearPlane=this._camera.near:this._camera.near=e,qe&&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 ae&&this.originalCameraNearPlane!=null&&(this._camera.near=this.originalCameraNearPlane,this.originalCameraNearPlane=void 0)}_viewerPose;_transformOrientation=new z;_transformPosition=new b;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 X_),this._transition}fadeTransition(){return this._transition||(this._transition=new X_),this._transition.fadeTransition()}updateFade(e){this._transition&&e instanceof ae&&this._transition.update(e,this.context.time.deltaTime)}onUpdateFade_PostRender(){this._transition?.remove()}}const Pg=v("debugwebxr");class J_{static tryFindAvatarObjects(e,t,i){if(i.head&&i.leftHand&&i.rightHand)return;const n=e.name.toLocaleLowerCase();!i.head&&n.includes("head")&&(Pg&&console.log("FOUND AVATAR HEAD",e.name),i.head=new ne("",t,e)),n.includes("hand")&&(!i.leftHand&&n.includes("left")&&(Pg&&console.log("FOUND AVATAR LEFT HAND",e.name),i.leftHand=new ne("",t,e)),!i.rightHand&&n.includes("right")&&(Pg&&console.log("FOUND AVATAR RIGHT HAND",e.name),i.rightHand=new ne("",t,e)));for(let s=0;s<e.children.length;s++){if(i.head&&i.leftHand&&i.rightHand)return;const r=e.children[s];this.tryFindAvatarObjects(r,t,i)}}}class se extends oe{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=D.lerp(this.alpha,i.alpha,t)),super.lerp(e,t)}lerpColors(e,t,i){const n=e,s=t;return n.alpha!=null&&s.alpha!=null&&(this.alpha=D.lerp(n.alpha,s.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 se(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,s=t>>8&255,r=t>>0&255;return new se(i/255,n/255,s/255,r/255)}else if(e.startsWith("#")){const t=parseInt(e.slice(1),16),i=t>>16&255,n=t>>8&255,s=t>>0&255;return new se(i/255,n/255,s/255,1)}else if(e.startsWith("rgba")){const t=e.slice(5,-1).split(",").map(Number);return new se(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 se(t[0]/255,t[1]/255,t[2]/255,1)}}else if(Array.isArray(e)){if(e.length===4)return new se(e[0],e[1],e[2],e[3]);if(e.length===3)return new se(e[0],e[1],e[2],1);console.error("Invalid color array length. Expected 3 or 4, got "+e.length)}return new se(e)}}const jt=new b,ev=new b,tv=new z,Rk=v("debuggizmos"),xn=8947848,Og=32;class F{constructor(){}static enabled=!0;static isGizmo(e){return e[Mg]!==void 0}static setVisible(e){for(const t of Gi.timedObjectsBuffer)t.visible=e}static DrawLabel(e,t,i=.05,n=0,s,r,a){if(!F.enabled)return null;s||(s=xn);const l=Z.active?.rigScale??1,c=Gi.getTextLabel(n,t,i*l,s,r);return a instanceof k&&a.add(c),c.position.x=e.x,c.position.y=e.y,c.position.z=e.z,c}static DrawRay(e,t,i=xn,n=0,s=!0){if(!F.enabled)return;const r=Gi.getLine(n),a=r.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),jt.set(t.x,t.y,t.z).multiplyScalar(999999999),a.setXYZ(1,e.x+jt.x,e.y+jt.y,e.z+jt.z),a.needsUpdate=!0,r.material.depthTest=s,r.material.depthWrite=!1,r.material.fog=!1,Sn(r.material,i)}static DrawDirection(e,t,i=xn,n=0,s=!0,r=1){if(!F.enabled)return;const a=Gi.getLine(n),l=a.geometry.getAttribute("position");l.setXYZ(0,e.x,e.y,e.z),t.w!==void 0?(jt.set(0,0,-r),tv.set(t.x,t.y,t.z,t.w),jt.applyQuaternion(tv)):(jt.set(t.x,t.y,t.z),jt.multiplyScalar(r)),l.setXYZ(1,e.x+jt.x,e.y+jt.y,e.z+jt.z),l.needsUpdate=!0,a.material.depthTest=s,a.material.depthWrite=!1,Sn(a.material,i)}static DrawLine(e,t,i=xn,n=0,s=!0){if(!F.enabled)return;const r=Gi.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=s,r.material.depthWrite=!1,r.material.fog=!1,Sn(r.material,i)}static DrawCircle(e,t,i,n=xn,s=0,r=!0){if(!F.enabled)return;const a=Gi.getCircle(s);a.position.set(e.x,e.y,e.z),a.scale.set(i,i,i),a.quaternion.setFromUnitVectors(this._up,jt.set(t.x,t.y,t.z).normalize()),a.material.depthTest=r,a.material.depthWrite=!1,a.material.fog=!1,Sn(a.material,n)}static DrawWireSphere(e,t,i=xn,n=0,s=!0){if(!F.enabled)return;const r=Gi.getSphere(t,n,!0);gr(r,e.x,e.y,e.z),r.material.depthTest=s,r.material.depthWrite=!1,r.material.fog=!1,Sn(r.material,i)}static DrawSphere(e,t,i=xn,n=0,s=!0){if(!F.enabled)return;const r=Gi.getSphere(t,n,!1);gr(r,e.x,e.y,e.z),r.material.depthTest=s,r.material.depthWrite=!1,Sn(r.material,i)}static DrawWireBox(e,t,i=xn,n=0,s=!0,r=void 0){if(!F.enabled)return;const a=Gi.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=s,a.material.wireframe=!0,a.material.depthWrite=!1,a.material.fog=!1,Sn(a.material,i)}static DrawWireBox3(e,t=xn,i=0,n=!0){if(!F.enabled)return;const s=Gi.getBox(i);s.position.copy(e.getCenter(jt)),s.scale.copy(e.getSize(jt)),s.material.depthTest=n,s.material.wireframe=!0,s.material.depthWrite=!1,s.material.fog=!1,Sn(s.material,t)}static _up=new b(0,1,0);static DrawArrow(e,t,i=xn,n=0,s=!0,r=!1){if(!F.enabled)return;const a=Gi.getArrowHead(n);a.position.set(t.x,t.y,t.z),a.quaternion.setFromUnitVectors(this._up.set(0,1,0),jt.set(t.x,t.y,t.z).sub(ev.set(e.x,e.y,e.z)).normalize());const l=jt.set(t.x,t.y,t.z).sub(ev.set(e.x,e.y,e.z)).length()*.1;a.scale.set(l,l,l),a.material.depthTest=s,a.material.wireframe=r,Sn(a.material,i),this.DrawLine(e,t,i,n,s)}static DrawWireMesh(e){const t=Gi.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,Sn(t.material,e.color??xn)}}const Ek=new Oa(1,1,1);function kg(o=null){const e=new oe(o??14540253),t=new DS(Ek);return new sb(t,new ym({color:e}))}function Sn(o,e){if(Array.isArray(o)){for(const i of o)Sn(i,e);return}const t=e instanceof se?e.a:1;o.color.set(e),o.opacity=t,o.transparent=t<1}const Mg=Symbol("GizmoCache");class Gi{static familyName="needle-gizmos";static ensureFont(){let e=Ce.FontLibrary.getFontFamily(this.familyName);e||(e=Ce.FontLibrary.addFontFamily(this.familyName),e.addVariant("normal","normal","https://uploads.needle.tools/include/font-msdf.json","https://uploads.needle.tools/include/font.png")?.addEventListener("ready",()=>{Ce.update()}))}static getTextLabel(e,t,i,n,s){this.ensureFont();let r=this.textLabelCache.pop(),a=1;s&&typeof s=="string"&&s?.length>=8&&s.startsWith("#")?(a=parseInt(s.substring(7),16)/255,s=s.substring(0,7),Rk&&console.log(s,a)):typeof s=="object"&&s.a!==void 0&&(a=s.a);const l={boxSizing:"border-box",fontFamily:this.familyName,width:"auto",fontSize:i,color:n,lineHeight:1,backgroundColor:s??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 Eb(l);const c=this,h=r;h.setText=function(d){this.set({textContent:d}),c.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(W.Current,r,e,this.textLabelCache),r}static getBox(e){let t=this.boxesCache.pop();if(!t){const i=new Oa(1,1,1);t=new H(i)}return this.registerTimedObject(W.Current,t,e,this.boxesCache),t}static getLine(e){let t=this.linesCache.pop();if(!t){t=new ka;let i=t.geometry.getAttribute("position");i||(i=new gt(new Float32Array(6),3),t.geometry.setAttribute("position",i))}return t.frustumCulled=!1,this.registerTimedObject(W.Current,t,e,this.linesCache),t}static getCircle(e){let t=this.circlesCache.pop();if(!t){t=new ka;let i=t.geometry.getAttribute("position");if(!i){i=new gt(new Float32Array(Og*3),3),t.geometry.setAttribute("position",i);const n=B(0,1,0),s=B(0,0,1),r=B(s);r.cross(n).normalize();const a=B(r),l=Math.PI*2/(Og-1);for(let c=0;c<Og+1;c++){const h=l*c;n.copy(a).multiplyScalar(Math.cos(h)*1),r.copy(s).multiplyScalar(Math.sin(h)*1);const d=n.add(r);i.setXYZ(c,d.x,d.y,d.z)}}}return t.frustumCulled=!1,this.registerTimedObject(W.Current,t,e,this.circlesCache),t}static getSphere(e,t,i){let n=this.spheresCache.pop();return n||(n=new H(new _d(1,8,8))),n.scale.set(e,e,e),n.material.wireframe=i,this.registerTimedObject(W.Current,n,t,this.spheresCache),n}static getArrowHead(e){let t=this.arrowHeadsCache.pop();return t||(t=new H(new nb(0,.5,1,8))),this.registerTimedObject(W.Current,t,e,this.arrowHeadsCache),t}static getMesh(e){let t=this.mesh.pop();return t||(t=new H,t.material=new Se),this.registerTimedObject(W.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 s=this.contextBeforeRenderCallbacks.get(e),r=this.contextPostRenderCallbacks.get(e);if(s){if(e.pre_render_callbacks[e.pre_render_callbacks.length-1]!==s){const a=e.pre_render_callbacks.indexOf(s);a>=0&&e.pre_render_callbacks.splice(a,1),e.pre_render_callbacks.push(s)}}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[Mg]=n,t.castShadow=!1,t.receiveShadow=!1,t.isGizmo=!0,this.timedObjectsBuffer.push(t),this.timesBuffer.push(W.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,Ce.update());for(let i=0;i<t.length;i++){const n=t[i];if(e.mainCamera&&n instanceof Ce.MeshUIBaseElement){if(Tr(n))continue;const s=e.isInVR,r=!1,a=!s;rc(n,e.mainCamera,r,a)}}}static onPostRender(e,t,i){const n=e.time.realtimeSinceStartup;for(let s=t.length-1;s>=0;s--){const r=t[s];n>=i[s]-1e-6&&(t.splice(s,1),i.splice(s,1),r.removeFromParent(),Tr(r)!=!0&&r[Mg].push(r))}}}const Qt=v("debugphysics"),Tk=v("debugworker"),iv=new ps;class vs{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 ee),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setLayer(e){iv.set(e),this.layerMask=iv}setMask(e){this.layerMask||(this.layerMask=new ps);const t=this.layerMask;t?t.mask=e:this.layerMask=e}}class Rg{distance;point;object;constructor(e,t,i){this.object=e,this.distance=t,this.point=i}}class ql{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 vd;defaultRaycastOptions=new vs;targetBuffer=new Array(1);defaultThresholds={Mesh:{},Line:{threshold:-1},LOD:{},Points:{threshold:0},Sprite:{}};sphereResults=new Array;sphereMask=new ps;sphere=new wd;sphereOverlap(e,t,i=!0,n=!1,s=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,s);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){Qt&&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 Qt&&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 jS&&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 s=e.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),s||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),s=this.defaultRaycastOptions.results),e.layerMask!==void 0?e.layerMask instanceof ps?i.layers.mask=e.layerMask.mask:i.layers.mask=e.layerMask:(i.layers.enableAll(),i.layers.disable(2)),Qt&&console.time("raycast"),s.length=0,ql._raycasting++,this.intersect(this.raycaster,n,s,e),s.sort((a,l)=>a.distance-l.distance);const r=e.ignore;return r!==void 0&&r.length>0&&(s=s.filter(a=>!r.includes(a.object))),ql._raycasting--,Qt&&(console.timeEnd("raycast"),console.warn("#"+this.context.time.frame+", hits:",s?.length?[...s]:"nothing"),performance.mark("raycast.end"),performance.measure("raycast","raycast.start","raycast.end")),s}intersect(e,t,i,n){for(const s of t){if(!s||s.visible===!1||F.isGizmo(s)||n.lineThreshold!==void 0&&n.lineThreshold<0&&s instanceof ka)continue;let r=!0;const a=s,l=a.geometry;if(s.raycastAllowed===!1&&(r=!1),r&&n.testObject){const c=n.testObject?.(s);if(c===!1)continue;c==="continue in children"&&(r=!1)}else r&&(l&&nv(l)||(r=!1));if(r){const c=i.length,h=s.raycastPreference||"lod";let d=h!=="bounds";if(n.precise===!1&&(d=!1),l&&(d||=l.getAttribute("position")?.array?.length<64),a instanceof Ea&&(d=!1),h==="lod"){const p=yb(s);p&&(a.geometry=p)}if(!d&&Ik(a,e,i)||(n.useAcceleratedRaycast!==!1?Zd.runMeshBVHRaycast(e,a,i,this.context,n):e.intersectObject(a,!1,i)),a.geometry=l,Qt&&i.length!=c){const p=i[i.length-1];F.DrawWireSphere(p.point,.1,7798784,1,!1),F.DrawWireMesh({mesh:s,depthTest:!1,duration:.2,color:7798784})}}n.recursive!==!1&&this.intersect(e,s.children,i,n)}return i}tempBoundingBox=new Si;intersectSphere(e,t,i,n,s,r,a,l){let c=e&&e.isMesh&&e.layers.test(n)&&!F.isGizmo(e);c&&=e.visible,c&&=!(e instanceof ka),c&&=!(e instanceof Ea);const h=e,d=h.geometry;if(c&&l){const p=l(e);if(p===!1)return;p==="continue in children"&&(c=!1)}if(d&&nv(d)||(c=!1),c){if(a){const p=this.sphere;p.center.copy(t),p.radius=i;const m=s.length;if(Zd.runMeshBVHRaycast(this.sphere,h,s,this.context,{}),m!=s.length&&!r)return}else if(d.boundingBox||d.computeBoundingBox(),d.boundingBox){h.matrixWorldNeedsUpdate&&h.updateWorldMatrix(!1,!1);const p=this.tempBoundingBox.copy(d.boundingBox).applyMatrix4(h.matrixWorld),m=this.sphere;if(m.center.copy(t),m.radius=i,m.intersectsBox(p)){const f=J(e),g=f.distanceTo(m.center),y=new Rg(e,g,f);if(s.push(y),!r)return}}}if(e.children)for(const p of e.children){const m=s.length;if(this.intersectSphere(p,t,i,n,s,r,a,l),m!=s.length&&!r)return}}}function nv(o){return!(o.index&&o.index.array.length<3)}const Pr=new wd,Yd=new dr,Ak=new ib;function Ik(o,e,t){const i=o._computeIntersections;if(!i)return!1;let n=o["_computeIntersections:Needle"];return n||(n=o["_computeIntersections:Needle"]=function(s,r,a){const l=this,c=l.geometry.boundingSphere;if(c){if(l instanceof Ea){Yd.setFromNormalAndCoplanarPoint(B(0,1,0),B(0,-l.position.y,0)),Yd.applyMatrix4(l.matrixWorld,Ak);const d=s.ray.intersectPlane(Yd,B());if(d){Pr.copy(c),Pr.applyMatrix4(l.matrixWorld);const p=B(d).sub(s.ray.origin).length(),m=Pr.radius*.5;p<m&&r.push({distance:p,point:d,object:l,normal:Yd.normal.clone()})}return}Pr.copy(c),Pr.applyMatrix4(l.matrixWorld);const h=s.ray.intersectSphere(Pr,B());if(h){const d=B(h).sub(s.ray.origin),p=d.length();if(p>Pr.radius){const m=d.clone().normalize();r.push({distance:p,point:h,object:l,normal:m})}}}}),o._computeIntersections=n,e.intersectObject(o,!1,t),o._computeIntersections=i,!0}var Zd;(o=>{let e=0;function t(w,P,M,O,j){if(!P.geometry||!P.geometry.hasAttribute("position"))return!1;const I=P.geometry;if(P?.isSkinnedMesh){const V=P,N=V.bvhNeedsUpdate;if(!V.staticGenerator)l(),r&&(V.staticGenerator=new r(P),V.staticGenerator.applyWorldTransforms=!1,V.staticGeometry=V.staticGenerator.generate(),I.boundsTree=a?.call(V.staticGeometry),V.staticGeometryLastUpdate=performance.now()+Math.random()*200,V.bvhNeedsUpdate=!0);else if(I.boundsTree&&(V.autoUpdateMeshBvhInterval!==void 0&&V.autoUpdateMeshBvhInterval>=0||N===!0)){const G=performance.now(),X=G-V.staticGeometryLastUpdate,E=V.autoUpdateMeshBvhInterval??100;(N||X>E)&&(Qt&&console.warn(`Physics: updating skinned mesh bvh for ${P.name} after ${X.toFixed(2)}ms`),V.bvhNeedsUpdate=!1,V.staticGeometryLastUpdate=G,V.staticGenerator?.generate(V.staticGeometry),I.boundsTree.refit())}}else if(!I.boundsTree){h||_();let V=!0;if((O.xr||I[f]===!1||I.getAttribute("position")?.isInterleavedBufferAttribute||I.index&&I.index?.isInterleavedBufferAttribute||e>10)&&(V=!1),V&&p){if(I[m]===void 0){let N=null;if(y.length>0){const G=y.shift();G&&!G.running&&(N=G)}if(!N&&g.length<3)try{Tk&&console.warn("[GenerateMeshBVHWorker] Creating worker with import.meta.url:",import.meta.url),N=new p,g.push(N)}catch(G){G instanceof DOMException&&G.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(G),e+=10):(console.error("Failed to create MeshBVH worker. Please see below for more details:"),console.log(G)),e++}if(N!=null&&!N.running){const G=P.name;Qt&&console.log("<<<< worker start",G,N),I[m]="queued",performance.mark("bvh.create.start");const X=I.clone();try{N.generate(X).then(E=>{I[m]="done",I.boundsTree=E}).catch(E=>{I[m]="failed - "+E?.message,I[f]=!1,Qt&&console.error("Failed to generate mesh bvh on worker",E)}).finally(()=>{Qt&&console.log(">>>>> worker done",G,{hasBoundsTre:I.boundsTree!=null}),y.push(N),X.dispose(),performance.mark("bvh.create.end"),performance.measure("bvh.create (worker)","bvh.create.start","bvh.create.end")})}catch(E){console.error("Failed to generate mesh bvh on worker",E)}}else Qt&&console.warn("No worker available")}}else(!d||!V)&&(l(),s&&(performance.mark("bvh.create.start"),I.boundsTree=new s(I),performance.mark("bvh.create.end"),performance.measure("bvh.create","bvh.create.start","bvh.create.end")))}if(w instanceof vd){const V=w,N=P.raycast;if(I.boundsTree)l(),n&&(P.acceleratedRaycast||(P.acceleratedRaycast=n.bind(P),Qt&&console.debug(`Physics: bind acceleratedRaycast fn to "${P.name}"`)),P.raycast=P.acceleratedRaycast);else if(Qt&&console.warn("No bounds tree found for mesh",P.name,{workerTask:I[m],hasAcceleratedRaycast:n!=null}),j.allowSlowRaycastFallback===!1&&(I.getAttribute("position")?.array?.length??0)>2e3)return Qt&&console.warn("Skipping raycast because no bounds tree is available and allowSlowRaycastFallback is false"),!1;const G=V.firstHitOnly;return V.firstHitOnly=!1,V.intersectObject(P,!1,M),V.firstHitOnly=G,P.raycast=N,!0}else if(w instanceof wd){const V=I.boundsTree;if(V){const N=w;if(c.copy(P.matrixWorld).invert(),N.applyMatrix4(c),V.intersectsSphere(N)){const G=J(P),X=G.distanceTo(N.center),E=new Rg(P,X,G);M.push(E)}}return!0}return!1}o.runMeshBVHRaycast=t;let i=!1,n=null,s=null,r=null,a=null;function l(){i||(i=!0,import("./vendor-sURMCFSI.min.js").then(w=>w.index$1).then(w=>{n=w.acceleratedRaycast,s=w.MeshBVH,r=w.StaticGeometryGenerator,a=w.computeBoundsTree}).catch(w=>{(Qt||A())&&console.error("Failed to load BVH library...",w.message)}))}const c=new K;let h=!1,d=!1,p=null;const m=Symbol("Needle:MeshBVH-Worker"),f=Symbol("Needle:MeshBVH-CanUseWorker"),g=[],y=[];function _(){h=!0,d=!0,Promise.resolve().then(()=>BL).then(w=>{p=w.GenerateMeshBVHWorker}).catch(w=>{Qt||A()?console.warn("Failed to setup mesh bvh worker"):console.debug("Failed to setup mesh bvh worker",w)}).finally(()=>{d=!1})}})(Zd||(Zd={}));const ov=Symbol("gltf-loader-internal-usage-tracker"),Lk=v("debugusers");class Xl{get name(){return"NEEDLE_internal_usage_tracker"}static isLoading(e){return Xl._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(){Xl._loadingProcesses++;const e=this,t=this._getDependency;return this.parser.getDependency=function(i,n){const s=t.call(this,i,n);return s.then(r=>(r&&(e._loadedObjects.add(r),r[ov]=e._loadingId),r)),s},null}afterRoot(e){Xl._loadingProcesses--,this.parser.getDependency=this._getDependency;for(const t of this._loadedObjects)delete t[ov],t instanceof k&&(t.parent||t instanceof H&&setTimeout(()=>{Lk&&console.warn("> GLTF LOADER: Mesh not used in scene!",t),t.material=null,t.geometry=null},1e3));return null}}class sv{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:
168
168
  `+i.src),e.preventDefault())}})}}const Kd=v("trackresources");function rv(){return Kd==="dispose"}let Or=!0;Kd===0&&(Or=!1);function Dk(o){Or=o}function av(){return Or}const lv=Symbol("disposable");function cv(o,e){o&&(o[lv]=e,kr&&console.warn("Set disposable",e,o))}const hv=Symbol("disposed");function jk(o){return o[hv]===!0}function Pe(o){if(o){if(o[lv]===!1){kr&&console.warn("Object is marked as not disposable",o);return}if(typeof o=="object"&&(o[hv]=!0),o instanceof xi)Pe(o.environment),Pe(o.background),Pe(o.customDepthMaterial),Pe(o.customDistanceMaterial);else if(o instanceof ms)Pe(o.geometry),Pe(o.material),Pe(o.skeleton),Pe(o.bindMatrix),Pe(o.bindMatrixInverse),Pe(o.customDepthMaterial),Pe(o.customDistanceMaterial),o.visible=!1;else if(o instanceof H)Pe(o.geometry),Pe(o.material),Pe(o.customDepthMaterial),Pe(o.customDistanceMaterial),o.visible=!1;else if(o instanceof k)o.visible=!1;else if(o instanceof fn){Na(o);for(const e of Object.keys(o.attributes)){const t=o.attributes[e];Pe(t)}}else if(o instanceof gt||o instanceof rb)kr&&console.warn("BufferAttribute dispose not supported",o.count);else if(o instanceof Array)for(const e of o)e instanceof we&&Pe(e);else if(o instanceof we){Na(o);for(const t of Object.keys(o)){const i=o[t];i instanceof Le&&Pe(i)}const e=o.uniforms;if(e)for(const t of Object.keys(e)){const i=e[t];i instanceof Le?Pe(i):i instanceof Wi&&Pe(i.value)}}else o instanceof Le?(Na(o),Na(o.source),o.source?.data instanceof ImageBitmap&&Na(o.source.data)):o instanceof BS?(Na(o.boneTexture),o.boneTexture=null):o instanceof FS||!(o instanceof k)&&kr&&console.warn("Unknown object type",o)}}function Na(o){o&&((kr||rv()||Kd)&&console.warn("\u{1F9E8} FREE",o),o instanceof ImageBitmap||"dispose"in o&&typeof o.dispose=="function"&&o.dispose())}function Bk(o){}const Fk=new Set;function Eg(o,e,t=null,i){if(i||(i=Fk,i.clear()),!o)return i;const n=o[bc];if(n)for(const s of n)i.has(s)||t?.call(null,s)!==!1&&(i.add(s),e&&Eg(s,!0,t,i));return i}function Uk(o){return o[_c]}const kr=v("debugresourceusers")||v("debugmemory"),bc=Symbol("needle-resource-users"),_c=Symbol("needle-resource-users-count");function Yt(o,e){Nd(o,e,function(t,i){Or&&!ql.raycasting&&(Jd(bc,this,t,!1),Jd(bc,this,i,!0))})}Or&&(Yt(H.prototype,"material"),Yt(H.prototype,"geometry"),Yt(we.prototype,"map"),Yt(we.prototype,"bumpMap"),Yt(we.prototype,"alphaMap"),Yt(we.prototype,"normalMap"),Yt(we.prototype,"displacementMap"),Yt(we.prototype,"roughnessMap"),Yt(we.prototype,"metalnessMap"),Yt(we.prototype,"emissiveMap"),Yt(we.prototype,"specularMap"),Yt(we.prototype,"envMap"),Yt(we.prototype,"lightMap"),Yt(we.prototype,"aoMap"),Yt(we.prototype,"gradientMap"));function zk(o){if(Or===!1)return;const e=o[bc];if(e)for(const t of e)Jd(bc,t,o,!1)}Or&&Nd(we.prototype,"dispose",function(){zk(this)});let Tg=0;function Jd(o,e,t,i){if(Tg>0)return;if(Array.isArray(t)){for(const s of t)Jd(o,e,s,i);return}if(!t)return;let n=t[o];if(n||(n=new Set),i){if(e&&!n.has(e)){n.add(e);let s=t[_c]||0;s+=1,t[_c]=s,kr&&console.warn(`\u{1F7E2} Added user of "${t.type}"`,e,t,s,"users:",n)}}else if(e&&n.has(e)){n.delete(e);let s=t[_c]||0;s>0&&(s-=1,t[_c]=s),kr&&console.warn(`\u{1F534} Removed user of "${t.type}"`,e,t,s,"users:",n),s<=0&&(Xl.isLoading(t)||(Kd&&console.warn(`\u{1F534} Removed all user of "${t.type}"`,t),rv()&&Pe(t)))}t[o]=n}try{Nd(hr.prototype,"render",function(){Tg++},function(){Tg--})}catch(o){console.warn("Could not wrap WebGLRenderer.render",o)}const dv=v("debugcomponentevents");class eu{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),dv&&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(dv&&console.log("Dispatching event "+e,i),!!i)for(const n of i)n(t)}}const vc=Symbol("NEEDLE_NEED_UPDATE_INSTANCE"),uv=Symbol("isUsingInstancing"),pv=Symbol("instancingRenderer"),wc=Symbol("instancingAutoUpdateBounds");class dn{static isUsingInstancing(e){return e[uv]===!0}static getRenderer(e){return e[pv]||null}setAutoUpdateBounds(e,t){const i=dn.getRenderer(e);i&&(i[wc]=t)}static markDirty(e,t=!0){if(e&&(this.isUsingInstancing(e)&&(e[vc]=!0,e.matrixWorldNeedsUpdate=!0),t))for(const i of e.children)dn.markDirty(i,!0)}}var xc;(o=>{o.experimentalSmartHierarchyUpdate=!1})(xc||(xc={}));function Wa(o,e){try{e||o()}catch(t){return console.error(t),!1}return!0}const Ag=v("debugnewscripts"),Nk=v("debughierarchy"),Ae=[];function Wk(){return Ae.length>0}function tu(o){if(Ag&&console.log("Register new components",o.new_scripts.length,[...o.new_scripts],o.alias?"element: "+o.alias:o.hash,o),o.new_scripts_pre_setup_callbacks.length>0){for(const e of o.new_scripts_pre_setup_callbacks)e&&e();o.new_scripts_pre_setup_callbacks.length=0}if(!(o.new_scripts.length<=0)){Ae.length=0,o.new_scripts.length>0&&Ae.push(...o.new_scripts),o.new_scripts.length=0;for(let e=0;e<Ae.length;e++)try{const t=Ae[e];if(t.isComponent!==!0){(A()||Ag)&&console.error(`Registered script is not a Needle Engine component.
169
169
  The script will be ignored. Please make sure your component extends "Behaviour" imported from "@needle-tools/engine"
@@ -959,7 +959,7 @@ ${t.path}! : AssetReference;
959
959
  Could not find method ${r.method} on object ${l.name}. Please rename ${r.method} to ${d}?
960
960
  `,l[d],`
961
961
  in script: `,l),be("EventList methods must start with lowercase letter, see console for details");return}else console.warn(`EventList method:
962
- Could not find method ${r.method} on object ${l.name}`,l,typeof l[r.method])};if(typeof l[r.method]!="function"){let d=!1,p=l;for(;p;){const m=Object.getOwnPropertyDescriptor(p,r.method);if(m&&(m.writable===!0||m.set)){d=!0;break}p=Object.getPrototypeOf(p)}!d&&(A()||yt)&&h()}}if(l){let h=r.argument;if(h!==void 0?h=a(h):r.arguments!==void 0&&(h=r.arguments.map(a)),!l[r.method])console.warn(`EventList method not found: "${r.method}" on ${l?.name}`);else{h!==void 0&&!Array.isArray(h)&&(h=[h]);const d=new Bo(l,r.method,h,r.enabled);i.push(d)}}else A()&&console.warn(`[Dev] EventList: Could not find event listener in scene (${t.object?.name})`,r)}const n=new de(i);yt&&console.log(n);const s=t.target;return s!==void 0&&t.path!==void 0&&n.setEventTarget(t.path,s),n}}}const GR=new HR,Du=new WeakMap,qR=Le.prototype.clone;Le.prototype.clone=function(){const o=qR.call(this);return Du.has(o)||Du.set(o,this),o};class Hw extends Xi{constructor(){super([_o,Wn])}onSerialize(e,t){}onDeserialize(e,t){if(e instanceof Le&&t.type===_o){let i=e;Du.has(i)&&(i=Du.get(i)),i.isRenderTargetTexture=!0,i.flipY=!0,i.offset.y=1,i.repeat.y=-1,i.needsUpdate=!0,i.mipmaps=[],i instanceof qS&&(i.isCompressedTexture=!1,i.format=xd);const n=new _o(i.image.width,i.image.height,{colorSpace:So});return n.texture=i,n}}}new Hw;class Gw extends Xi{constructor(){super([URL])}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"&&e.length>0)return fs(t.gltfId,e)}}new Gw;var XR=Object.defineProperty,QR=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&XR(e,t,n),n};class el extends R{awake(){si.createIfNoneExists(this.context)}onEnable(){si.get(this.context)?.register(this)}onDisable(){si.get(this.context)?.unregister(this)}}class Ti extends el{targets=null;raycastHits=[];ignoreSkinnedMeshes=!1;start(){this.targets=[this.gameObject]}performRaycast(e=null){if(!this.targets)return null;e??=new vs,e.targets=this.targets,e.results=this.raycastHits,e.useAcceleratedRaycast=!0;const t=e.testObject;this.ignoreSkinnedMeshes&&(e.testObject=n=>n instanceof ms?"continue in children":t?t(n):!0);const i=this.context.physics.raycast(e);return e.testObject=t,i}}QR([u()],Ti.prototype,"ignoreSkinnedMeshes");class ju extends Ti{constructor(){super(),this.ignoreSkinnedMeshes=!0}}class ba extends el{static allow=!0;performRaycast(e){if(!Z.active||!ba.allow||!e?.ray)return null;const t=e.ray.origin;return this.context.physics.sphereOverlap(t,.015,!1,!0)}}class wf{static getObject(e){const t=e[Ri];return t&&(t.isComponent===!0?e=t.gameObject:e=t),e}static isInteractable(e,t){if(t&&(t.canvasGroup=void 0,t.graphic=void 0),e==null||!e.visible||(e=this.getObject(e),!e.visible))return!1;const i=this.tryFindCanvasGroup(e);if(i?.isCanvasGroup===!0&&(t&&(t.canvasGroup=i),i.blocksRaycasts===!1||i.interactable===!1))return!1;const n=Ar(e,s=>{if(s.isGraphic===!0)return s},!1);return t&&n?.isGraphic===!0&&(t.graphic=n),!(n?.raycastTarget===!1||n?.layer===2)}static tryFindCanvasGroup(e){if(!e)return null;const t=Ar(e,i=>{if(i.activeAndEnabled){const n=i;if(n.blocksRaycasts!==void 0&&n.interactable!==void 0)return n}},!1);return t!==void 0?t:this.tryFindCanvasGroup(e.parent)}}function xf(o){return o[Ri]||(o.parent?xf(o.parent):null)}function YR(o){return o.isUI===!0||typeof o[Ri]=="object"}function Bu(o,e){if(!o)return;const t=o.material;if(t?.isMaterial===!0){const i=o.parent;i&&i.isText,t.side=e.doubleSided??!0?Pi:gs,t.shadowSide=e.doubleSided?Pi:gs,o.castShadow=e.castShadows?e.castShadows:!1,o.receiveShadow=e.receiveShadows?e.receiveShadows:!1}for(const i of o.children)Bu(i,e)}function tl(o,e,t){o[e]===void 0&&console.warn("Field",e,"is undefined on",o);const i=Proxy.revocable(o[e],{set(r,a,l,c){const h=r[a],d=Reflect.set(r,a,l,c);return t(l,h),d}}),n=i.revoke,s=o[e];return i.revoke=()=>{o[e]=s,n()},o[e]=i.proxy,i}const qw=Symbol("Scheduled action");function ZR(o,e,t=xe.OnBeforeRender){let i=o[qw];i||(i=o[qw]={});const n=e.name;i[t]||(i[t]={});const s=i[t];if(s[n])return;function*r(){e?.call(o),s[n]=null}const a=o.startCoroutine(r(),t);s[n]=a}const ks=v("debugeventsystem");var Sf=(o=>(o.BeforeHandleInput="BeforeHandleInput",o.AfterHandleInput="AfterHandleInput",o))(Sf||{});Pw(o=>{si.createIfNoneExists(o)});class si extends R{static ensureUpdateMeshUI(e,t,i=!1){Wc.update(e,t,i)}static markUIDirty(e){Wc.markDirty()}static createIfNoneExists(e){e.scene.getComponent(si)||e.scene.addComponent(si)}static get(e){return this.createIfNoneExists(e),e.scene.getComponent(si)}static get instance(){return this.get(W.Current)}raycaster=[];register(e){e&&this.raycaster&&!this.raycaster.includes(e)&&this.raycaster?.push(e)}unregister(e){const t=this.raycaster?.indexOf(e);t!==void 0&&t!==-1&&this.raycaster?.splice(t,1)}get hasActiveUI(){return this.currentActiveMeshUIComponents.length>0}get isHoveringObjects(){return this.hoveredByID.size>0}awake(){this.gameObject!==this.context.scene&&(console.debug(`[Needle Engine] EventSystem is only allowed on the scene root. Disabling EventSystem on '${this.gameObject.name}'`),this.enabled=!1)}start(){this.context.scene.getComponent(el)||this.context.scene.addComponent(Ti)}onEnable(){this.context.input.addEventListener(Te.PointerDown,this.onPointerEvent),this.context.input.addEventListener(Te.PointerUp,this.onPointerEvent),this.context.input.addEventListener(Te.PointerMove,this.onPointerEvent)}onDisable(){this.context.input.removeEventListener(Te.PointerDown,this.onPointerEvent),this.context.input.removeEventListener(Te.PointerUp,this.onPointerEvent),this.context.input.removeEventListener(Te.PointerMove,this.onPointerEvent)}pressedByID=new Map;hoveredByID=new Map;onBeforeRender(){this.resetMeshUIStates()}onPointerEvent=e=>{if(e===void 0||e.propagationStopped||e.defaultPrevented||e.used)return;const t=new md(this.context.input,e);this._currentPointerEventName=e.type,t.inputSource=this.context.input,t.isClick=e.isClick,t.isDoubleClick=e.isDoubleClick,t.isDown=e.type==Te.PointerDown,t.isUp=e.type==Te.PointerUp,t.isPressed=this.context.input.getPointerPressed(e.pointerId);const i=new vs;e.hasRay?i.ray=e.ray:i.screenPoint=this.context.input.getPointerPositionRC(e.pointerId),i.allowSlowRaycastFallback=e.isClick||e.isDoubleClick;const n=this.performRaycast(i);if(ks&&(t.isDown?console.log("DOWN",{id:t.pointerId,hits:n.length}):t.isUp&&console.log("UP",{id:t.pointerId,hits:n.length}),t.isClick&&console.log("CLICK",{id:t.pointerId,hits:n.length})),n){for(const r of n)r.event=e,e.intersections.push(r);e.origin.onPointerHits&&e.origin.onPointerHits({sender:this,event:e,hits:n})}ks&&t.isClick&&Ee("EventSystem: "+t.pointerId+" - "+this.context.time.frame+" - Up:"+t.isUp+", Down:"+t.isDown);const s={sender:this,args:t,hasActiveUI:this.currentActiveMeshUIComponents.length>0};this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:s})),this.handleIntersections(n,t),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:s}))};_sortedHits=[];_testObjectsCache=new Map;_currentlyActiveRaycaster=null;_currentPointerEventName=null;shouldRaycastObject=e=>{const t=e&&"getComponent"in e?e.getComponent(el):null;if(t&&t!=this._currentlyActiveRaycaster)return!1;let i=null;if(YR(e)&&(i=e[Ri]?.gameObject),this._testObjectsCache.has(e)||i&&this._testObjectsCache.has(i))return this._testObjectsCache.get(e)===!1?"continue in children":!0;{let n=Au(e,this._currentPointerEventName);if(!n&&i&&(n=Au(i,this._currentPointerEventName)),n){this._testObjectsCache.set(e,!0);for(const s of e.children)this.shouldRaycastObject_AddToYesCache(s);return!0}return this._testObjectsCache.set(e,!1),"continue in children"}};shouldRaycastObject_AddToYesCache(e){this._testObjectsCache.set(e,!0);for(const t of e.children)this.shouldRaycastObject_AddToYesCache(t)}performRaycast(e){if(!this.raycaster)return null;this._testObjectsCache.clear(),this._sortedHits.length=0,e.testObject=this.shouldRaycastObject;for(const t of this.raycaster){if(!t.activeAndEnabled)continue;this._currentlyActiveRaycaster=t;const i=t.performRaycast(e);this._currentlyActiveRaycaster=null,i&&i.length>0&&this._sortedHits.push(...i)}return this._sortedHits.sort((t,i)=>t.distance-i.distance),this._sortedHits}assignHitInformation(e,t){t?(e.intersection=t,e.point=t.point,e.normal=t.normal,e.face=t.face,e.distance=t.distance,e.instanceId=t.instanceId):(e.intersection=void 0,e.point=void 0,e.normal=void 0,e.face=void 0,e.distance=void 0,e.instanceId=void 0)}handleIntersections(e,t){if(e?.length){e=this.sortCandidates(e);for(const n of e){if(t.event.immediatePropagationStopped)return!1;if(this.assignHitInformation(t,n),this.handleEventOnObject(n.object,t))return!0}}this.assignHitInformation(t,e?.[0]),this.invokePointerCapture(t);const i=this.hoveredByID.get(t.pointerId);return i&&this.propagatePointerExit(i.obj,i.data,null),this.hoveredByID.delete(t.pointerId),t.isUp&&(this.pressedByID.get(t.pointerId)?.handlers.forEach(n=>this.invokeOnPointerUp(t,n)),this.pressedByID.delete(t.pointerId)),!1}_sortingBuffer=[];_noDepthTestingResults=[];sortCandidates(e){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let t=0;t<e.length;t++){const i=e[t],n=i.object;if(n.material&&n.material.depthTest===!1){this._noDepthTestingResults.push(i);continue}this._sortingBuffer.push(i)}for(const t of this._sortingBuffer)this._noDepthTestingResults.push(t);return this._noDepthTestingResults}out={};handleEventOnObject(e,t){if(!this.testIsVisible(e))return t.isClick&&ks&&console.log("not allowed",e),!1;if(t.pointerId===void 0)return ks&&console.error("Event without pointer can't be handled",t),!1;t.object=e;const i=e.parent,n=t.isClick??!1;let s=null;if(i&&i.isUI){const c=(t.isPressed||t.isClick)??!1;if(i[Ri]){const h=i[Ri].gameObject;if(h){if(!wf.isInteractable(h,this.out))return!1;s=this.out.canvasGroup??null,this.handleMeshUIIntersection(e,c),e=h}}}n&&ks&&console.log(this.context.time.frame,e);const r=this.hoveredByID.get(t.pointerId),a=r?.obj;a!==e&&a&&this.propagatePointerExit(a,r.data,e);const l=this.hoveredByID.get(t.pointerId);if(l?(l.obj=e,l.data=t):this.hoveredByID.set(t.pointerId,{obj:e,data:t}),t.isDown){const c=this.pressedByID.get(t.pointerId);c?(c.obj=e,c.data=t):this.pressedByID.set(t.pointerId,{obj:e,data:t,handlers:new Set})}return(s===null||s.interactable)&&this.handleMainInteraction(e,t,a??null),!0}propagate(e,t){for(;e;)x.foreachComponent(e,i=>{t(i)},!1),e=e.parent}handleMainInteraction(e,t,i){const n=this.pressedByID.get(t.pointerId),s=i!==e;let r=!0;switch(t.event.pointerType){case"mouse":case"touch":const a=this.context.input.getPointerPositionLastFrame(t.pointerId),l=this.context.input.getPointerPosition(t.pointerId);r=a&&!D.approximately(a,l);break}this.propagate(e,a=>{const l=a;l.interactable!==!1&&(!l.activeAndEnabled||!l.enabled||(l.onPointerEnter&&s&&this.handlePointerEnter(l,t),t.isDown&&l.onPointerDown&&(l.onPointerDown(t),n?.handlers.add(l),this.handlePointerCapture(t,l)),l.onPointerMove&&(r&&l.onPointerMove(t),this.handlePointerCapture(t,l)),t.isUp&&(l.onPointerUp&&(this.invokeOnPointerUp(t,l),n?.handlers.delete(l)),l.onPointerExit&&t.event?.pointerType===$d.Touch&&(this.handlePointerExit(l,t),this.hoveredByID.delete(t.pointerId))),t.isClick&&l.onPointerClick&&l.onPointerClick(t)))}),t.isUp&&(n?.handlers.forEach(a=>{this.invokeOnPointerUp(t,a)}),this.pressedByID.delete(t.pointerId))}propagatePointerExit(e,t,i){this.propagate(e,n=>{if(!n.gameObject||n.destroyed)return;const s=n;if(s.onPointerExit||s.onPointerEnter){if(i&&this.isChild(i,n.gameObject))return;this.handlePointerExit(s,t)}})}invokeOnPointerUp(e,t){t.onPointerUp?.call(t,e),this.releasePointerCapture(e,t)}handlePointerEnter(e,t){e.onPointerEnter&&this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!0)&&e.onPointerEnter(t),this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!1)}handlePointerExit(e,t){e.onPointerExit&&this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!0)&&e.onPointerExit(t),this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!1)}updatePointerState(e,t,i,n){let s=e[i];if(n)return s&&s.includes(t)?!1:(s=s||[],s.push(t),e[i]=s,!0);{if(!s||!s.includes(t))return!1;const r=s.indexOf(t);return r!==-1&&s.splice(r,1),!0}}_capturedPointer={};handlePointerCapture(e,t){if(e.z__pointer_ctured){e.z__pointer_ctured=!1;const i=e.pointerId;if(t.onPointerMove){const n=this._capturedPointer[i]||[];n.push(t),this._capturedPointer[i]=n}else A()&&!t.z__warned_no_pointermove&&(t.z__warned_no_pointermove=!0,console.warn("PointerCapture was requested but the component doesn't implement onPointerMove. It will not receive any pointer events"))}else e.z__pointer_cture_rleased&&(e.z__pointer_cture_rleased=!1,this.releasePointerCapture(e,t))}releasePointerCapture(e,t){const i=e.pointerId;if(this._capturedPointer[i]){const n=this._capturedPointer[i].indexOf(t);n!==-1&&(this._capturedPointer[i].splice(n,1),ks&&console.log("released pointer capture",i,t,this._capturedPointer))}}invokePointerCapture(e){if(e.event.type===Te.PointerMove){const t=e.pointerId,i=this._capturedPointer[t];if(i){ks&&console.log("Captured",t,i);for(let n=0;n<i.length;n++){const s=i[n];if(s.destroyed){i.splice(n,1),n--;continue}s.onPointerMove?.call(s,e)}}}}pointerEnterSymbol=Symbol("pointerEnter");pointerExitSymbol=Symbol("pointerExit");isChild(e,t){return!e||!t?!1:e===t?!0:e.parent?this.isChild(e.parent,t):!1}handleMeshUiObjectWithoutShadowDom(e,t){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,t)}currentActiveMeshUIComponents=[];handleMeshUIIntersection(e,t){const i=Wc.updateState(e,t);return i&&this.currentActiveMeshUIComponents.push(i),i!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&Wc.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){const t=this.currentActiveMeshUIComponents[e];Wc.resetState(t)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?x.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}}class Wc{static lastSelected=null;static lastUpdateFrame=[];static needsUpdate=!1;static markDirty(){this.needsUpdate=!0}static update(e,t,i=!1){if(i){e.update();return}const n=t.time.frameCount;for(const s of this.lastUpdateFrame)if(s.context===t){if(n===s.frame)return;s.frame=n;let r=this.needsUpdate||n<1;s.nextUpdate<=n&&(r=!0),r&&(ks&&console.log("Update threemeshui"),this.needsUpdate=!1,s.nextUpdate=n+60,e.update());return}this.lastUpdateFrame=[{context:t,frame:n,nextUpdate:n+60}],e.update(),this.needsUpdate=!1}static updateState(e,t){let i=null;if(e&&(i=this.findBlockOrTextInParent(e),i&&i!==this.lastSelected)){if(i.interactable===!1)return null;this.needsUpdate=!0}return i}static resetLastSelected(){const e=this.lastSelected;e&&(this.lastSelected=null,this.resetState(e))}static resetState(e){e&&(this.needsUpdate=!0)}static findBlockOrTextInParent(e){return e?e.isBlock||e.isText?e:this.findBlockOrTextInParent(e.parent):null}}var KR=Object.defineProperty,JR=Object.getOwnPropertyDescriptor,Oe=(o,e,t,i)=>{for(var n=i>1?void 0:i?JR(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&KR(e,t,n),n};const Ft=v("debugorbit"),Cf=v("freecam"),eE=v("debugcamerafit"),Fu=v("smoothcam"),tE={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let Pf;class Vc extends CustomEvent{constructor(e,t){super("target-reached",{detail:{controls:e,type:t}})}}class fe extends R{get isCameraController(){return!0}get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(e){this.controls?.addEventListener("start",e)}autoTarget=!0;autoFit=!1;enableRotate=!0;autoRotate=!1;autoRotateSpeed=1;minAzimuthAngle=1/0;maxAzimuthAngle=1/0;minPolarAngle=0;maxPolarAngle=Math.PI;enableKeys=!1;enableDamping=!0;dampingFactor=.1;enableZoom=!0;minZoom=0;maxZoom=1/0;zoomSpeed=1;zoomToCursor=!1;enablePan=!0;lookAtConstraint=null;lookAtConstraint01=1;allowInterrupt=!0;middleClickToFocus=!0;doubleClickToFocus=!0;clickBackgroundToFitScene=2;get targetElement(){return this._controls?.domElement??this._targetElement}set targetElement(e){this._targetElement=e,this._controls&&this._controls.domElement!==e&&(this._controls.disconnect(),this._controls.domElement=e,this._controls.connect())}_targetElement=null;debugLog=!1;get targetLerpSpeed(){return 5}set targetLerpSpeed(e){this.targetLerpDuration=1/e}get targetLerpDuration(){return this._lookTargetLerpDuration}set targetLerpDuration(e){this._lookTargetLerpDuration=e}_lookTargetLerpDuration=1;targetBounds=null;rotateLeft(e){this._controls?._rotateLeft(e)}rotateUp(e){this._controls?._rotateUp(e)}pan(e,t){this._controls?._pan(e,t)}zoomIn(e){e>0?this._controls?._dollyIn(1-e):e<0&&this._controls?._dollyOut(1+e)}_controls=null;_cameraObject=null;_lookTargetLerpActive=!1;_lookTargetStartPosition=new b;_lookTargetEndPosition=new b;_lookTargetLerp01=0;_cameraLerpActive=!1;_cameraStartPosition=new b;_cameraEndPosition=new b;_cameraLerp01=0;_cameraLerpDuration=0;_fovLerpActive=!1;_fovLerpStartValue=0;_fovLerpEndValue=0;_fovLerp01=0;_fovLerpDuration=0;_inputs=0;_enableTime=0;_startedListeningToKeyEvents=!1;_eventSystem;_afterHandleInputFn;_camera=null;_syncedTransform;_didSetTarget=0;awake(){Ft&&console.debug("OrbitControls",this),this._didSetTarget=0,this._startedListeningToKeyEvents=!1,this.context.domElement.cameraControls===!1&&(this.enabled=!1)}start(){this._eventSystem=si.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(Sf.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){this._controls?.dispose(),this._eventSystem?.removeEventListener(Sf.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._didSetTarget=0,this._enableTime=this.context.time.time;const e=x.getComponent(this.gameObject,ui);this._camera=e;let t=e?.threeCamera;if(!t&&this.gameObject instanceof ae&&(t=this.gameObject),t&&Xm(t,this,!0),!this._controls&&t instanceof k){this._cameraObject=t;const i=this.targetElement??this.context.renderer.domElement,n=t?.quaternion.clone();this._controls=new wb(t,i),t?.quaternion.copy(n),Pf===void 0&&(Pf={...this._controls.keys});const s=J(t),r=this.gameObject.worldForward,a=s.clone().sub(r.multiplyScalar(2.5));this._controls.target.copy(a)}if(this._controls)if(Cf&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,L.isMobileDevice()&&(this.doubleClickToFocus=!0)),this._controls.addEventListener("start",this.onControlsChangeStarted),this._controls.addEventListener("endMovement",this.onControlsChangeEnded),!this._startedListeningToKeyEvents&&this.enableKeys)this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(this.context.domElement);else try{this._controls.stopListenToKeyEvents()}catch{}this._syncedTransform=x.getComponent(this.gameObject,On)??void 0,this.context.pre_render_callbacks.push(this.__onPreRender),this._activePointerEvents=[],this.context.input.addEventListener("pointerdown",this._onPointerDown,{queue:ci.Early}),this.context.input.addEventListener("pointerdown",this._onPointerDownLate,{queue:ci.Late}),this.context.input.addEventListener("pointerup",this._onPointerUp,{queue:ci.Early}),this.context.input.addEventListener("pointerup",this._onPointerUpLate,{queue:ci.Late})}onDisable(){if(this._camera?.threeCamera&&Xm(this._camera.threeCamera,this,!1),this._controls){this._controls.enabled=!1,this._controls.autoRotate=!1,this._controls.removeEventListener("start",this.onControlsChangeStarted),this._controls.removeEventListener("endMovement",this.onControlsChangeEnded);try{this._controls.stopListenToKeyEvents()}catch{}this._startedListeningToKeyEvents=!1}this._activePointerEvents.length=0,this.context.input.removeEventListener("pointerdown",this._onPointerDown),this.context.input.removeEventListener("pointerdown",this._onPointerDownLate),this.context.input.removeEventListener("pointerup",this._onPointerUp),this.context.input.removeEventListener("pointerup",this._onPointerUpLate)}_activePointerEvents;_lastTimeClickOnBackground=-1;_clickOnBackgroundCount=0;_onPointerDown=e=>{this._activePointerEvents.push(e)};_onPointerDownLate=e=>{e.used&&this._controls&&(this._controls.enabled=!1)};_onPointerUp=e=>{for(let t=this._activePointerEvents.length-1;t>=0;t--){const i=this._activePointerEvents[t];if(i.pointerId===e.pointerId&&i.button===e.button){this._activePointerEvents.splice(t,1);break}}if(this.clickBackgroundToFitScene>0&&e.isClick&&e.button===0){if(e.hasRay||e.intersections.push(...this.context.physics.raycast()),e.intersections.length<=0){const t=this.context.time.time-this._lastTimeClickOnBackground;this._lastTimeClickOnBackground=this.context.time.time,this.clickBackgroundToFitScene<=1||t<this.clickBackgroundToFitScene*.15?(this._clickOnBackgroundCount+=1,this._clickOnBackgroundCount>=this.clickBackgroundToFitScene-1&&(this.autoRotate=!1,this.fitCamera({objects:this.context.scene,immediate:!1}))):this._clickOnBackgroundCount=0}Ft&&console.log(this.clickBackgroundToFitScene,e.intersections.length,this._clickOnBackgroundCount)}};_onPointerUpLate=e=>{this.doubleClickToFocus&&e.isDoubleClick&&!e.used&&this.setTargetFromRaycast()};updateTargetNow(e){const t=new vo(this._cameraObject?.worldPosition,this._cameraObject?.worldForward.multiplyScalar(-1)),i=this.context.physics.raycastFromRay(t,e),n=i.length>0?i[0]:void 0;n&&n.distance>this.minZoom&&n.distance<this.maxZoom?(Ft&&F.DrawWireSphere(n.point,.1,16711680,2),this._controls?.target.copy(i[0].point)):Ft&&console.log("OrbitControls: No hit found when updating target",{hits:[...i]})}_orbitStartAngle=0;_zoomStartDistance=0;onControlsChangeStarted=()=>{Ft&&console.debug("OrbitControls: Change started"),this._controls&&(this._orbitStartAngle=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle(),this._zoomStartDistance=this._controls.getDistance()),this._syncedTransform&&this._syncedTransform.requestOwnership()};onControlsChangeEnded=()=>{if(Ft&&console.debug("OrbitControls: Change ended",{autoTarget:this.autoTarget}),this._controls&&this.autoTarget){const e=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle()-this._orbitStartAngle;Math.abs(e)<.01?(Ft&&console.debug("OrbitControls: Update target",{deltaAngle:e}),this.updateTargetNow({allowSlowRaycastFallback:!1})):Ft&&console.debug("OrbitControls: No target update",{deltaAngle:e})}};_shouldDisable=!1;afterHandleInput(e){e.detail.args.pointerId===0&&(e.detail.args.isDown?this._controls&&this._eventSystem&&(this._shouldDisable=this._eventSystem.hasActiveUI):(!e.detail.args.isPressed||e.detail.args.isUp)&&(this._shouldDisable=!1))}onPausedChanged(e){this._controls&&e&&(this._controls.enabled=!1)}onBeforeRender(){if(!!this._controls){if(this._cameraObject!==this.context.mainCamera){this._controls.enabled=!1;return}if(this._controls.enabled=!0,(this.context.input.getPointerDown(1)||this.context.input.getPointerDown(2)||this.context.input.mouseWheelChanged||this.context.input.getPointerPressed(0)&&this.context.input.getPointerPositionDelta(0)?.length())&&(this._inputs+=1),this._inputs>0&&this.allowInterrupt&&(this.enableRotate&&(this.autoRotate=!1),this._cameraLerpActive=!1,this._lookTargetLerpActive=!1),this._inputs=0,this.autoTarget&&this._didSetTarget++===0){const e=x.getComponent(this.gameObject,ui);if(e&&!this.setLookTargetFromConstraint()){this.debugLog&&console.log("NO TARGET");const t=J(e.threeCamera),i=Math.max(.01,t.length()),n=new b(0,0,-i).applyMatrix4(e.threeCamera.matrixWorld);Ft&&F.DrawLine(t,n,5592575,10),this.setLookTargetPosition(n,!0)}if(!this.setLookTargetFromConstraint()){const t=new vs;t.screenPoint=new ee(0,0),t.lineThreshold=.1;const i=this.context.physics.raycast(t);i.length>0&&this.setLookTargetPosition(i[0].point,!0),eE&&console.log("OrbitControls hits",...i)}}if(this.middleClickToFocus&&this.context.input.getPointerClicked(1)&&this.setTargetFromRaycast(),this._lookTargetLerpActive||this._cameraLerpActive||this._fovLerpActive){if(this._cameraLerpActive&&this._cameraObject)if(this._cameraLerp01+=this.context.time.deltaTime/this._cameraLerpDuration,this._cameraLerp01>=1)this._cameraObject.position.copy(this._cameraEndPosition),this._cameraLerpActive=!1,this.dispatchEvent(new Vc(this,"camera"));else{const e=D.easeInOutCubic(this._cameraLerp01);this._cameraObject.position.lerpVectors(this._cameraStartPosition,this._cameraEndPosition,e)}if(this._lookTargetLerpActive)if(this._lookTargetLerp01+=this.context.time.deltaTime/this._lookTargetLerpDuration,this._lookTargetLerp01>=1)this.lerpLookTarget(this._lookTargetEndPosition,this._lookTargetEndPosition,1),this._lookTargetLerpActive=!1,this.dispatchEvent(new Vc(this,"lookat"));else{const e=D.easeInOutCubic(this._lookTargetLerp01);this.lerpLookTarget(this._lookTargetStartPosition,this._lookTargetEndPosition,e)}if(this._fovLerpActive&&this._cameraObject){const e=this._cameraObject;if(this._fovLerp01+=this.context.time.deltaTime/this._fovLerpDuration,this._fovLerp01>=1)e.fov=this._fovLerpEndValue,this._fovLerpActive=!1;else{const t=D.easeInOutCubic(this._fovLerp01);e.fov=D.lerp(this._fovLerpStartValue,this._fovLerpEndValue,t)}e.updateProjectionMatrix()}}if(this.targetBounds){const e=this._controls.target,t=this.targetBounds.worldPosition,i=B(this.targetBounds.worldScale).multiplyScalar(.5),n=B(t).sub(i),s=B(t).add(i),r=B(this._controls.target).clamp(n,s),a=.1;e.lerp(r,this.context.time.deltaTime/a),this._lookTargetLerpActive&&this._lookTargetEndPosition.lerp(r,this.context.time.deltaTime/(a*5)),Ft&&F.DrawWireBox(t,i.multiplyScalar(2),16755200)}if(this._controls){this.debugLog&&(this._controls.domElement=this.context.renderer.domElement);const e=1/(this.context.focusRectSettings?.zoom||1);if(this._controls.enabled=!this._shouldDisable&&this._camera===this.context.mainCameraComponent&&!this.context.isInXR&&!this._activePointerEvents.some(t=>t.used),this._controls.keys=this.enableKeys?Pf:tE,this._controls.autoRotate=this.autoRotate,this._controls.autoRotateSpeed=this.autoRotateSpeed,this._controls.enableZoom=this.enableZoom,this._controls.zoomSpeed=this.zoomSpeed,this._controls.zoomToCursor=this.zoomToCursor,this._controls.enableDamping=this.enableDamping,this._controls.dampingFactor=this.dampingFactor,this._controls.enablePan=this.enablePan,this._controls.panSpeed=e,this._controls.enableRotate=this.enableRotate,this._controls.minAzimuthAngle=this.minAzimuthAngle,this._controls.maxAzimuthAngle=this.maxAzimuthAngle,this._controls.minPolarAngle=this.minPolarAngle,this._controls.maxPolarAngle=this.maxPolarAngle,Cf||(this._camera?.threeCamera?.type==="PerspectiveCamera"?(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom,this._controls.minZoom=0,this._controls.maxZoom=1/0):(this._controls.minDistance=0,this._controls.maxDistance=1/0,this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom)),typeof Fu=="number"||Fu===!0){this._controls.enableDamping=!0;const t=typeof Fu=="number"?Fu:.99;this._controls.dampingFactor=Math.max(.001,1-Math.min(1,t))}this.allowInterrupt||(this._lookTargetLerpActive&&(this._controls.enablePan=!1),this._cameraLerpActive&&(this._controls.enableRotate=!1,this._controls.autoRotate=!1),(this._lookTargetLerpActive||this._cameraLerpActive)&&(this._controls.enableZoom=!1)),this.context.isInXR||(!Cf&&this.lookAtConstraint?.locked&&!this._lookTargetLerpActive&&this.setLookTargetFromConstraint(0,this.lookAtConstraint01),this._controls.update(this.context.time.deltaTime),Ft&&F.DrawWireSphere(this._controls.target,.1,65280))}}}__onPreRender=()=>{const e=this.context.pre_render_callbacks.indexOf(this.__onPreRender);e>=0&&this.context.pre_render_callbacks.splice(e,1),this.autoFit&&(this.autoFit=!1,this.fitCamera({centerCamera:"y",immediate:!0,objects:this.scene.children}))};setCameraAndLookTarget(e,t=!1){if(!e)return(A()||Ft)&&console.warn("[OrbitControls] setCameraAndLookTarget target is null"),!1;if(!(e instanceof k)&&!(e instanceof ui))return(A()||Ft)&&console.warn("[OrbitControls] setCameraAndLookTarget target is not an Object3D or Camera"),!1;e instanceof ui&&(e=e.gameObject);const i=e.worldPosition,n=e.worldForward;e instanceof XS&&(Ft&&console.debug("[OrbitControls] setCameraAndLookTarget flip forward direction for camera"),n.multiplyScalar(-1));const s=new vo(i,n);return Ft&&F.DrawRay(s.origin,s.direction,16711680,10),this.setTargetFromRaycast(s,t)||this.setLookTargetPosition(s.at(2,B()),t),this.setCameraTargetPosition(i,t),!0}setCameraTargetPosition(e,t=!1){e&&(e instanceof k&&(e=J(e)),this._cameraEndPosition||(this._cameraEndPosition=new b),this._cameraEndPosition.copy(e),t===!0?(this._cameraLerpActive=!1,this._cameraObject&&this._cameraObject.position.copy(this._cameraEndPosition)):this._cameraObject&&(this._cameraLerpActive=!0,this._cameraLerp01=0,this._cameraStartPosition.copy(this._cameraObject?.position),typeof t=="number"?this._cameraLerpDuration=t:this._cameraLerpDuration=this.targetLerpDuration))}get cameraLerpActive(){return this._cameraLerpActive}stopCameraLerp(){this._cameraLerpActive=!1}setFieldOfView(e,t=!1){if(!this._controls||typeof e!="number")return;const i=this._camera?.threeCamera;i&&(t===!0?i.fov=e:(this._fovLerpActive=!0,this._fovLerp01=0,this._fovLerpStartValue=i.fov,this._fovLerpEndValue=e,typeof t=="number"?this._fovLerpDuration=t:this._fovLerpDuration=this.targetLerpDuration))}setLookTargetPosition(e=null,t=!1){this._controls&&e&&(e instanceof k&&(e=J(e)),this._lookTargetEndPosition.copy(e),this._didSetTarget++,Ft&&(console.warn("OrbitControls: setLookTargetPosition",e,t),F.DrawWireSphere(this._lookTargetEndPosition,.2,16711680,2)),t===!0?this.lerpLookTarget(this._lookTargetEndPosition,this._lookTargetEndPosition,1):(this._lookTargetLerpActive=!0,this._lookTargetLerp01=0,this._lookTargetStartPosition.copy(this._controls.target),typeof t=="number"?this._lookTargetLerpDuration=t:this._lookTargetLerpDuration=this.targetLerpDuration))}get lookTargetLerpActive(){return this._lookTargetLerpActive}stopLookTargetLerp(){this._lookTargetLerpActive=!1}setLookTargetFromConstraint(e=0,t=1){if(!this._controls||this.lookAtConstraint?.enabled===!1)return!1;const i=this.lookAtConstraint?.sources;if(i&&i.length>0){const n=i[e];if(n)return n.getWorldPosition(this._lookTargetEndPosition),this.lerpLookTarget(this._controls.target,this._lookTargetEndPosition,t),!0}return!1}lerpLookTarget(e,t,i){this._controls&&(i>=1?this._controls.target.copy(t):this._controls.target.lerpVectors(e,t,i),this.lookAtConstraint&&this.lookAtConstraint.setConstraintPosition(this._controls.target))}setTargetFromRaycast(e,t=!1){if(!this.controls)return!1;const i=e?this.context.physics.raycastFromRay(e):this.context.physics.raycast();for(const n of i)if(n.distance>0&&x.isActiveInHierarchy(n.object)){const s=xf(n.object);if(s&&s.canvas?.screenspace)break;return this.setLookTargetPosition(n.point,t),!0}return!1}fitCamera(e,t){let i;if(Array.isArray(e)||e&&"type"in e?i=e:e&&typeof e=="object"&&!(e instanceof k)&&!Array.isArray(e)&&(t=e,i=t.objects),i&&!Array.isArray(i)&&(i=[i]),(!Array.isArray(i)||i&&i.length<=0)&&(i=this.context.scene.children),!Array.isArray(i)||i.length<=0){console.warn("No objects to fit camera to...");return}const n=Nw({objects:[...i],...t,autoApply:!1,context:this.context,camera:this._cameraObject,currentZoom:this._controls?.getDistance()||void 0,minZoom:this.minZoom,maxZoom:this.maxZoom});n&&(this.setLookTargetPosition(n.lookAt,t?.immediate||!1),this.setCameraTargetPosition(n.position,t?.immediate||!1),this.setFieldOfView(t?.fov,t?.immediate||!1),this.onBeforeRender())}_haveAttachedKeyboardEvents=!1}Oe([u()],fe.prototype,"autoTarget",2),Oe([u()],fe.prototype,"autoFit",2),Oe([u()],fe.prototype,"enableRotate",2),Oe([u()],fe.prototype,"autoRotate",2),Oe([u()],fe.prototype,"autoRotateSpeed",2),Oe([u()],fe.prototype,"minAzimuthAngle",2),Oe([u()],fe.prototype,"maxAzimuthAngle",2),Oe([u()],fe.prototype,"minPolarAngle",2),Oe([u()],fe.prototype,"maxPolarAngle",2),Oe([u()],fe.prototype,"enableKeys",2),Oe([u()],fe.prototype,"enableDamping",2),Oe([u()],fe.prototype,"dampingFactor",2),Oe([u()],fe.prototype,"enableZoom",2),Oe([u()],fe.prototype,"minZoom",2),Oe([u()],fe.prototype,"maxZoom",2),Oe([u()],fe.prototype,"zoomSpeed",2),Oe([u()],fe.prototype,"enablePan",2),Oe([u(jr)],fe.prototype,"lookAtConstraint",2),Oe([u()],fe.prototype,"lookAtConstraint01",2),Oe([u()],fe.prototype,"allowInterrupt",2),Oe([u()],fe.prototype,"middleClickToFocus",2),Oe([u()],fe.prototype,"doubleClickToFocus",2),Oe([u()],fe.prototype,"clickBackgroundToFitScene",2),Oe([u()],fe.prototype,"targetLerpDuration",1),Oe([u(k)],fe.prototype,"targetBounds",2);var iE=Object.defineProperty,nE=Object.getOwnPropertyDescriptor,Zt=(o,e,t,i)=>{for(var n=i>1?void 0:i?nE(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&iE(e,t,n),n},Fr=(o=>(o[o.None=0]="None",o[o.Skybox=1]="Skybox",o[o.SolidColor=2]="SolidColor",o[o.Uninitialized=4]="Uninitialized",o))(Fr||{});const Ms=v("debugcam"),Xw=v("debugscreenpointtoray"),Ut=class ld extends R{get isCamera(){return!0}get aspect(){return this._cam instanceof ae?this._cam.aspect:this.context.domWidth/this.context.domHeight}set aspect(e){this._cam instanceof ae&&this._cam.aspect!==e&&(this._cam.aspect=e,this._cam.updateProjectionMatrix())}get fieldOfView(){return this._cam instanceof ae?this._cam.fov:this._fov}set fieldOfView(e){const t=this.fieldOfView!=e;if(this._fov=e,t&&this._cam&&this._cam instanceof ae){if(this._fov===void 0){console.warn("Can not set undefined fov on PerspectiveCamera");return}this._cam.fov=this._fov,this._cam.updateProjectionMatrix()}}get nearClipPlane(){return this._nearClipPlane}set nearClipPlane(e){const t=this._nearClipPlane!=e;this._nearClipPlane=e,this._cam&&(t||this._cam.near!=e)&&(this._cam.near=e,this._cam.updateProjectionMatrix())}_nearClipPlane=.1;get farClipPlane(){return this._farClipPlane}set farClipPlane(e){const t=this._farClipPlane!=e;this._farClipPlane=e,this._cam&&(t||this._cam.far!=e)&&(this._cam.far=e,this._cam.updateProjectionMatrix())}_farClipPlane=1e3;applyClippingPlane(){this._cam&&(this._cam.near=this._nearClipPlane,this._cam.far=this._farClipPlane,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(e){if(typeof e=="string")switch(e){case"skybox":e=1;break;case"solidcolor":e=2;break;default:e=0;break}e!==this._clearFlags&&(this._clearFlags=e,this.applyClearFlagsIfIsActiveCamera())}orthographic=!1;orthographicSize=5;ARBackgroundAlpha=0;set cullingMask(e){this._cullingMask=e,this._cam&&(this._cam.layers.mask=e)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}_cullingMask=4294967295;set cullingLayer(e){this.cullingMask=(1<<e|0)>>>0}set backgroundBlurriness(e){e!==this._backgroundBlurriness&&(e===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(e,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}_backgroundBlurriness=void 0;set backgroundIntensity(e){e!==this._backgroundIntensity&&(e===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(e,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}_backgroundIntensity=void 0;set backgroundRotation(e){e!==this._backgroundRotation&&(e===void 0?this._backgroundRotation=void 0:this._backgroundRotation=e,this.applyClearFlagsIfIsActiveCamera())}get backgroundRotation(){return this._backgroundRotation}_backgroundRotation=void 0;set environmentIntensity(e){this._environmentIntensity=e}get environmentIntensity(){return this._environmentIntensity}_environmentIntensity=void 0;get backgroundColor(){return this._backgroundColor??null}set backgroundColor(e){e&&(this._backgroundColor||(this._backgroundColor=new se(1,1,1,1)),this._backgroundColor.copy(e),(!("alpha"in e)||e.alpha===void 0)&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera())}set targetTexture(e){this._targetTexture=e}get targetTexture(){return this._targetTexture}_targetTexture=null;_backgroundColor;_fov;_cam=null;_clearFlags=2;_skybox;get cam(){return this.threeCamera}get threeCamera(){return this.activeAndEnabled&&this.buildCamera(),this._cam}static _origin=new b;static _direction=new b;screenPointToRay(e,t,i){const n=this.threeCamera,s=ld._origin;s.set(e,t,-1),this.context.input.convertScreenspaceToRaycastSpace(s),Xw&&console.log("screenPointToRay",e.toFixed(2),t.toFixed(2),"now:",s.x.toFixed(2),s.y.toFixed(2),"isInXR:"+this.context.isInXR),s.z=-1,s.unproject(n);const r=ld._direction.set(s.x,s.y,s.z),a=J(n);return r.sub(a),r.normalize(),i?(i.set(a,r),i):new vo(a.clone(),r.clone())}_frustum;getFrustum(){return this._frustum||(this._frustum=new lb,this.updateFrustum()),this._frustum}updateFrustum(){this._frustum||(this._frustum=new lb),this._frustum.setFromProjectionMatrix(this.getProjectionScreenMatrix(this._projScreenMatrix,!0),this.context.renderer.coordinateSystem)}getProjectionScreenMatrix(e,t){return t&&this._projScreenMatrix.multiplyMatrices(this.threeCamera.projectionMatrix,this.threeCamera.matrixWorldInverse),e===this._projScreenMatrix?e:e.copy(this._projScreenMatrix)}_projScreenMatrix=new K;awake(){Xw&&window.addEventListener("pointerdown",e=>{const t=e.clientX,i=e.clientY;console.log("touch",t.toFixed(2),i.toFixed(2));const n=this.screenPointToRay(t,i),s="#"+Math.floor(Math.random()*16777215).toString(16);F.DrawRay(n.origin,n.direction,s,10)})}onEnable(){Ms&&console.log(`Camera enabled: "${this.name}". ClearFlags=${Fr[this._clearFlags]}`,this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),sE(this)),this.applyClearFlagsIfIsActiveCamera({applySkybox:!0})}onDisable(){this.context.removeCamera(this)}onLeaveXR(e){this.fieldOfView=this._fov}onBeforeRender(){if(this._cam&&(this._frustum&&this.updateFrustum(),this._clearFlags===2&&this.applyClearFlagsIfIsActiveCamera(),this._targetTexture)){this.context.isManagedExternally&&(this._warnedAboutExternalRenderer||(this._warnedAboutExternalRenderer=!0,console.warn("Rendering with external renderer is not supported yet. This may not work or throw errors. Please remove the the target texture from your camera: "+this.name,this.targetTexture))),this.context.composer;const e=this.context.renderer;if(e){const t=this.context.mainCameraComponent;this.applyClearFlags(),this._targetTexture.render(this.context.scene,this._cam,e),t?.applyClearFlags()}}}buildCamera(){if(this._cam)return;const e=this.gameObject.isCamera;let t=null;if(e?(t=this.gameObject,t?.layers.enableAll(),t instanceof ae&&(this._fov=t.fov)):t=this.gameObject.children[0],t&&t.isCamera)t instanceof ae&&(this._fov&&(t.fov=this._fov),t.near=this._nearClipPlane,t.far=this._farClipPlane,t.updateProjectionMatrix());else if(!this.orthographic)t=new ae(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),this.fieldOfView&&(t.fov=this.fieldOfView),this.gameObject.add(t);else{const i=this.orthographicSize*100;t=new bd(window.innerWidth/-i,window.innerWidth/i,window.innerHeight/i,window.innerHeight/-i,this._nearClipPlane,this._farClipPlane),this.gameObject.add(t)}this._cam=t,this._cam.layers.mask=this._cullingMask,this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(e){this.context.mainCameraComponent===this&&this.applyClearFlags(e)}applyClearFlags(e){if(!this._cam){Ms&&console.log("Camera does not exist (apply clear flags)");return}if(this.fieldOfView=this.fieldOfView,Ms){const i=`[Camera] Apply ClearFlags: ${Fr[this._clearFlags]} - "${this.name}"`;console.debug(i)}const t=this.context.domElement.getAttribute("background-image")||this.context.domElement.getAttribute("background-color");switch(this._clearFlags){case 0:return;case 1:if(ld.backgroundShouldBeTransparent(this.context)&&(!this.ARBackgroundAlpha||this.ARBackgroundAlpha<.001)){this.context.scene.background=null,this.context.renderer.setClearColor(0,0);return}(!this.scene.background||!this._skybox||e?.applySkybox===!0)&&this.applySceneSkybox(),this._backgroundBlurriness!==void 0&&!this.context.domElement.getAttribute("background-blurriness")?this.context.scene.backgroundBlurriness=this._backgroundBlurriness:Ms&&console.warn(`Camera "${this.name}" has no background blurriness`),this._backgroundIntensity!==void 0&&!this.context.domElement.getAttribute("background-intensity")&&(this.context.scene.backgroundIntensity=this._backgroundIntensity),this._backgroundRotation!==void 0&&!this.context.domElement.getAttribute("background-rotation")?this.context.scene.backgroundRotation=this._backgroundRotation:Ms&&console.warn(`Camera "${this.name}" has no background intensity`);break;case 2:if(this._backgroundColor&&!t){let i=this._backgroundColor.alpha;ld.backgroundShouldBeTransparent(this.context)&&(i=this.ARBackgroundAlpha??0),this.context.scene.background=null,this.context.xr?.isVR?this.context.renderer.setClearColor(e_(this._backgroundColor).convertLinearToSRGB()):this.context.renderer.setClearColor(this._backgroundColor,i)}else this._backgroundColor||Ms&&console.warn(`[Camera] has no background color "${this.name}" `);break;case 4:t||(this.context.scene.background=null,this.context.renderer.setClearColor(0,0));break}}applySceneSkybox(){this._skybox||(this._skybox=new oE(this)),this._skybox.apply()}static backgroundShouldBeTransparent(e){const t=e.renderer.xr?.getSession();if(!t)return!1;if(typeof t._transparent=="boolean")return t._transparent;const i=t.environmentBlendMode;Ms&&Ee("Environment blend mode: "+i+" on "+navigator.userAgent);let n=i==="additive"||i==="alpha-blend";return e.isInAR&&i==="opaque"&&(navigator.userAgent?.includes("OculusBrowser")||navigator.userAgent?.includes("Mozilla")&&navigator.userAgent?.includes("Mobile WebXRViewer/v2"))&&(n=!0),t._transparent=n,n}};Zt([u()],Ut.prototype,"aspect",1),Zt([u()],Ut.prototype,"fieldOfView",1),Zt([u()],Ut.prototype,"nearClipPlane",1),Zt([u()],Ut.prototype,"farClipPlane",1),Zt([u()],Ut.prototype,"clearFlags",1),Zt([u()],Ut.prototype,"orthographic",2),Zt([u()],Ut.prototype,"orthographicSize",2),Zt([u()],Ut.prototype,"ARBackgroundAlpha",2),Zt([u()],Ut.prototype,"cullingMask",1),Zt([u()],Ut.prototype,"backgroundBlurriness",1),Zt([u()],Ut.prototype,"backgroundIntensity",1),Zt([u(st)],Ut.prototype,"backgroundRotation",1),Zt([u()],Ut.prototype,"environmentIntensity",1),Zt([u(se)],Ut.prototype,"backgroundColor",1),Zt([u(_o)],Ut.prototype,"targetTexture",1);let ui=Ut;class oE{_camera;_skybox;get context(){return this._camera?.context}constructor(e){this._camera=e}apply(){if(this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),!this._skybox)this._did_log_failed_to_find_skybox||(this._did_log_failed_to_find_skybox=!0,console.warn(`Camera "${this._camera.name}" has no skybox texture. ${this._camera.sourceId}`));else if(this.context.scene.background!==this._skybox){const e=this.context.domElement.getAttribute("background-image")||this.context.domElement.getAttribute("background-color");Ms&&console.debug(`[Camera] Apply Skybox ${this._skybox?.name} ${e} - "${this._camera.name}"`),e?.length||(this._skybox.mapping=Nn,this.context.scene.background=this._skybox)}}}function sE(o){v("freecam")&&o.context.mainCameraComponent===o&&x.getOrAddComponent(o.gameObject,fe)}class Fo extends R{get listener(){return this._listener==null&&(this._listener=new QS),this._listener}_listener=null;onEnable(){jn.registerWaitForInteraction(this.onInteraction),this.addListenerIfItExists()}onDisable(){jn.unregisterWaitForInteraction(this.onInteraction),this.removeListenerIfItExists()}onInteraction=()=>{this.destroyed||this.listener==null||this.addListenerIfItExists()};addListenerIfItExists(){const e=this._listener;if(!e||e?.parent)return;const t=this.context.mainCameraComponent||x.getComponentInParent(this.gameObject,ui);t?.threeCamera?t.threeCamera.add(e):this.gameObject.add(e),e.filter?(e.gain.connect(e.filter),e.filter.connect(e.context.destination)):e.gain.connect(e.context.destination)}removeListenerIfItExists(){const e=this._listener;e&&(e.removeFromParent(),e.filter&&e.filter.disconnect(),e.gain&&e.gain.disconnect())}}var rE=Object.defineProperty,aE=Object.getOwnPropertyDescriptor,kn=(o,e,t,i)=>{for(var n=i>1?void 0:i?aE(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&rE(e,t,n),n};const Mt=v("debugaudio"),Ki=class nr extends R{static get userInteractionRegistered(){return jn.userInteractionRegistered}static registerWaitForAllowAudio(e){jn.registerWaitForInteraction(e)}clip="";playOnAwake=!1;preload=!0;playInBackground=!0;get isPlaying(){return this.sound?.isPlaying??!1}get duration(){return this.sound?.buffer?.duration}get time01(){const e=this.duration;return e&&this.sound?this.sound?.context.currentTime/e:0}set time01(e){const t=this.duration;t&&this.sound&&(this.time=e*t)}get time(){return this.sound?.source?this.sound.source?.context.currentTime-this._lastContextTime+this.sound.offset:0}set time(e){if(this.sound){if(e===this.sound.offset)return;const t=this.isPlaying;this.stop(),this.sound.offset=e,t&&this.play()}}get loop(){return this.sound&&(this._loop=this.sound.getLoop()),this._loop}set loop(e){this._loop=e,this.sound&&this.sound.setLoop(e)}get spatialBlend(){return this._spatialBlend}set spatialBlend(e){e!==this._spatialBlend&&(this._spatialBlend=e,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(e){this._minDistance!==e&&(this._minDistance=e,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(e){this._maxDistance!==e&&(this._maxDistance=e,this._needUpdateSpatialDistanceSettings=!0)}_spatialBlend=0;_minDistance=1;_maxDistance=100;get volume(){return this._volume}set volume(e){this._volume=e,this.sound&&!this.context.application.muted&&(Mt&&console.log(this.name,"audio set volume",e),this.sound.setVolume(e))}_volume=1;set pitch(e){this.sound&&this.sound.setPlaybackRate(e)}get pitch(){return this.sound?this.sound.getPlaybackRate():1}rollOffMode=0;_loop=!1;sound=null;helper=null;wasPlaying=!1;audioLoader=null;shouldPlay=!1;_lastClipStartedLoading=null;_audioElement=null;get Sound(){if(!this.sound&&nr.userInteractionRegistered){let e=this.gameObject.getComponent(Fo)??this.context.mainCamera.getComponent(Fo)??Ga(Fo,this.context,!1);!e&&this.context.mainCamera&&(e=this.context.mainCamera.addComponent(Fo)),e?.listener?(this.sound=new YS(e.listener),this.gameObject?.add(this.sound)):Mt&&console.warn("No audio listener found in scene - can not play audio")}return this.sound}get ShouldPlay(){return this.shouldPlay}get audioContext(){return this.sound?.context}awake(){Mt&&console.log("[AudioSource]",this),this.audioLoader=new xm,this.playOnAwake&&(this.shouldPlay=!0),this.preload&&typeof this.clip=="string"&&this.audioLoader.load(this.clip,this.createAudio,()=>{},console.error)}onEnable(){this.sound&&this.gameObject.add(this.sound),nr.userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():nr.registerWaitForAllowAudio(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.onNewClip(this.clip)}),globalThis.addEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.addEventListener(mg.MuteChanged,this.onApplicationMuteChanged)}onDisable(){globalThis.removeEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.removeEventListener(mg.MuteChanged,this.onApplicationMuteChanged),this.pause()}onVisibilityChanged=()=>{switch(document.visibilityState){case"hidden":(this.playInBackground===!1||L.isMobileDevice())&&(this.wasPlaying=this.isPlaying,this.isPlaying&&this.pause());break;case"visible":Mt&&console.log("visible",this.enabled,this.playOnAwake,!this.isPlaying,nr.userInteractionRegistered,this.wasPlaying),this.enabled&&this.playOnAwake&&!this.isPlaying&&nr.userInteractionRegistered&&this.wasPlaying&&this.play();break}};onApplicationMuteChanged=()=>{this.context.application.muted?this.sound?.setVolume(0):this.sound?.setVolume(this.volume)};createAudio=e=>{if(this.destroyed){Mt&&console.warn("AudioSource destroyed, not creating audio",this.name);return}Mt&&console.log("AudioBuffer finished loading",e);const t=this.Sound;if(!t){Mt&&console.warn("Failed getting sound?",this.name);return}t.isPlaying&&t.stop(),e&&t.setBuffer(e),t.loop=this._loop,this.context.application.muted?t.setVolume(0):t.setVolume(this.volume),t.autoplay=this.shouldPlay&&nr.userInteractionRegistered,this.applySpatialDistanceSettings(),t.isPlaying&&t.stop(),nr.registerWaitForAllowAudio(this.__onAllowAudioCallback)};__onAllowAudioCallback=()=>{this.shouldPlay&&this.play()};applySpatialDistanceSettings(){const e=this.sound;if(!e)return;this._needUpdateSpatialDistanceSettings=!1;const t=D.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(Mt&&console.log(this.name,this._minDistance,this._maxDistance,this.spatialBlend,"Ref distance="+t),e.setRefDistance(t),e.setMaxDistance(Math.max(.01,this._maxDistance)),this.rollOffMode){case 0:e.setDistanceModel("exponential");break;case 1:e.setDistanceModel("linear");break;case 2:console.warn("Custom rolloff for AudioSource is not supported: "+this.name);break}this.spatialBlend>0?Mt&&!this.helper&&(this.helper=new JC(e,e.getRefDistance()),e.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}async onNewClip(e){if(e&&(this.clip=e),typeof e=="string")if(Mt&&console.log(e),e.endsWith(".mp3")||e.endsWith(".wav")){if(this.audioLoader||(this.audioLoader=new xm),this.shouldPlay=!0,this._lastClipStartedLoading===e){Mt&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=e,Mt&&console.log("load audio",e);const t=await this.audioLoader.loadAsync(e).catch(console.error);if(this.destroyed)return;this._lastClipStartedLoading===e&&(this._lastClipStartedLoading=null),t&&this.createAudio(t)}else console.warn("Unsupported audio clip type",e);else this.shouldPlay=!0,this.createAudio()}play(e=void 0){!e&&this.clip&&(e=this.clip),e!==void 0&&typeof e!="string"&&!(e instanceof MediaStream)&&(A()&&console.warn("Called play on AudioSource with unknown argument type:",e+`
962
+ Could not find method ${r.method} on object ${l.name}`,l,typeof l[r.method])};if(typeof l[r.method]!="function"){let d=!1,p=l;for(;p;){const m=Object.getOwnPropertyDescriptor(p,r.method);if(m&&(m.writable===!0||m.set)){d=!0;break}p=Object.getPrototypeOf(p)}!d&&(A()||yt)&&h()}}if(l){let h=r.argument;if(h!==void 0?h=a(h):r.arguments!==void 0&&(h=r.arguments.map(a)),!l[r.method])console.warn(`EventList method not found: "${r.method}" on ${l?.name}`);else{h!==void 0&&!Array.isArray(h)&&(h=[h]);const d=new Bo(l,r.method,h,r.enabled);i.push(d)}}else A()&&console.warn(`[Dev] EventList: Could not find event listener in scene (${t.object?.name})`,r)}const n=new de(i);yt&&console.log(n);const s=t.target;return s!==void 0&&t.path!==void 0&&n.setEventTarget(t.path,s),n}}}const GR=new HR,Du=new WeakMap,qR=Le.prototype.clone;Le.prototype.clone=function(){const o=qR.call(this);return Du.has(o)||Du.set(o,this),o};class Hw extends Xi{constructor(){super([_o,Wn])}onSerialize(e,t){}onDeserialize(e,t){if(e instanceof Le&&t.type===_o){let i=e;Du.has(i)&&(i=Du.get(i)),i.isRenderTargetTexture=!0,i.flipY=!0,i.offset.y=1,i.repeat.y=-1,i.needsUpdate=!0,i.mipmaps=[],i instanceof qS&&(i.isCompressedTexture=!1,i.format=xd);const n=new _o(i.image.width,i.image.height,{colorSpace:So});return n.texture=i,n}}}new Hw;class Gw extends Xi{constructor(){super([URL])}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"&&e.length>0)return fs(t.gltfId,e)}}new Gw;var XR=Object.defineProperty,QR=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&XR(e,t,n),n};class el extends R{awake(){si.createIfNoneExists(this.context)}onEnable(){si.get(this.context)?.register(this)}onDisable(){si.get(this.context)?.unregister(this)}}class Ti extends el{targets=null;raycastHits=[];ignoreSkinnedMeshes=!1;start(){this.targets=[this.gameObject]}performRaycast(e=null){if(!this.targets)return null;e??=new vs,e.targets=this.targets,e.results=this.raycastHits,e.useAcceleratedRaycast=!0;const t=e.testObject;this.ignoreSkinnedMeshes&&(e.testObject=n=>n instanceof ms?"continue in children":t?t(n):!0);const i=this.context.physics.raycast(e);return e.testObject=t,i}}QR([u()],Ti.prototype,"ignoreSkinnedMeshes");class ju extends Ti{constructor(){super(),this.ignoreSkinnedMeshes=!0}}class ba extends el{static allow=!0;performRaycast(e){if(!Z.active||!ba.allow||!e?.ray)return null;const t=e.ray.origin;return this.context.physics.sphereOverlap(t,.015,!1,!0)}}class wf{static getObject(e){const t=e[Ri];return t&&(t.isComponent===!0?e=t.gameObject:e=t),e}static isInteractable(e,t){if(t&&(t.canvasGroup=void 0,t.graphic=void 0),e==null||!e.visible||(e=this.getObject(e),!e.visible))return!1;const i=this.tryFindCanvasGroup(e);if(i?.isCanvasGroup===!0&&(t&&(t.canvasGroup=i),i.blocksRaycasts===!1||i.interactable===!1))return!1;const n=Ar(e,s=>{if(s.isGraphic===!0)return s},!1);return t&&n?.isGraphic===!0&&(t.graphic=n),!(n?.raycastTarget===!1||n?.layer===2)}static tryFindCanvasGroup(e){if(!e)return null;const t=Ar(e,i=>{if(i.activeAndEnabled){const n=i;if(n.blocksRaycasts!==void 0&&n.interactable!==void 0)return n}},!1);return t!==void 0?t:this.tryFindCanvasGroup(e.parent)}}function xf(o){return o[Ri]||(o.parent?xf(o.parent):null)}function YR(o){return o.isUI===!0||typeof o[Ri]=="object"}function Bu(o,e){if(!o)return;const t=o.material;if(t?.isMaterial===!0){const i=o.parent;i&&i.isText,t.side=e.doubleSided??!0?Pi:gs,t.shadowSide=e.doubleSided?Pi:gs,o.castShadow=e.castShadows?e.castShadows:!1,o.receiveShadow=e.receiveShadows?e.receiveShadows:!1}for(const i of o.children)Bu(i,e)}function tl(o,e,t){o[e]===void 0&&console.warn("Field",e,"is undefined on",o);const i=Proxy.revocable(o[e],{set(r,a,l,c){const h=r[a],d=Reflect.set(r,a,l,c);return t(l,h),d}}),n=i.revoke,s=o[e];return i.revoke=()=>{o[e]=s,n()},o[e]=i.proxy,i}const qw=Symbol("Scheduled action");function ZR(o,e,t=xe.OnBeforeRender){let i=o[qw];i||(i=o[qw]={});const n=e.name;i[t]||(i[t]={});const s=i[t];if(s[n])return;function*r(){e?.call(o),s[n]=null}const a=o.startCoroutine(r(),t);s[n]=a}const ks=v("debugeventsystem");var Sf=(o=>(o.BeforeHandleInput="BeforeHandleInput",o.AfterHandleInput="AfterHandleInput",o))(Sf||{});Pw(o=>{si.createIfNoneExists(o)});class si extends R{static ensureUpdateMeshUI(e,t,i=!1){Wc.update(e,t,i)}static markUIDirty(e){Wc.markDirty()}static createIfNoneExists(e){e.scene.getComponent(si)||e.scene.addComponent(si)}static get(e){return this.createIfNoneExists(e),e.scene.getComponent(si)}static get instance(){return this.get(W.Current)}raycaster=[];register(e){e&&this.raycaster&&!this.raycaster.includes(e)&&this.raycaster?.push(e)}unregister(e){const t=this.raycaster?.indexOf(e);t!==void 0&&t!==-1&&this.raycaster?.splice(t,1)}get hasActiveUI(){return this.currentActiveMeshUIComponents.length>0}get isHoveringObjects(){return this.hoveredByID.size>0}awake(){this.gameObject!==this.context.scene&&(console.debug(`[Needle Engine] EventSystem is only allowed on the scene root. Disabling EventSystem on '${this.gameObject.name}'`),this.enabled=!1)}start(){this.context.scene.getComponent(el)||this.context.scene.addComponent(Ti)}onEnable(){this.context.input.addEventListener(Te.PointerDown,this.onPointerEvent),this.context.input.addEventListener(Te.PointerUp,this.onPointerEvent),this.context.input.addEventListener(Te.PointerMove,this.onPointerEvent)}onDisable(){this.context.input.removeEventListener(Te.PointerDown,this.onPointerEvent),this.context.input.removeEventListener(Te.PointerUp,this.onPointerEvent),this.context.input.removeEventListener(Te.PointerMove,this.onPointerEvent)}pressedByID=new Map;hoveredByID=new Map;onBeforeRender(){this.resetMeshUIStates()}onPointerEvent=e=>{if(e===void 0||e.propagationStopped||e.defaultPrevented||e.used)return;const t=new md(this.context.input,e);this._currentPointerEventName=e.type,t.inputSource=this.context.input,t.isClick=e.isClick,t.isDoubleClick=e.isDoubleClick,t.isDown=e.type==Te.PointerDown,t.isUp=e.type==Te.PointerUp,t.isPressed=this.context.input.getPointerPressed(e.pointerId);const i=new vs;e.hasRay?i.ray=e.ray:i.screenPoint=this.context.input.getPointerPositionRC(e.pointerId),i.allowSlowRaycastFallback=e.isClick||e.isDoubleClick;const n=this.performRaycast(i);if(ks&&(t.isDown?console.log("DOWN",{id:t.pointerId,hits:n.length}):t.isUp&&console.log("UP",{id:t.pointerId,hits:n.length}),t.isClick&&console.log("CLICK",{id:t.pointerId,hits:n.length})),n){for(const r of n)r.event=e,e.intersections.push(r);e.origin.onPointerHits&&e.origin.onPointerHits({sender:this,event:e,hits:n})}ks&&t.isClick&&Ee("EventSystem: "+t.pointerId+" - "+this.context.time.frame+" - Up:"+t.isUp+", Down:"+t.isDown);const s={sender:this,args:t,hasActiveUI:this.currentActiveMeshUIComponents.length>0};this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:s})),this.handleIntersections(n,t),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:s}))};_sortedHits=[];_testObjectsCache=new Map;_currentlyActiveRaycaster=null;_currentPointerEventName=null;shouldRaycastObject=e=>{const t=e&&"getComponent"in e?e.getComponent(el):null;if(t&&t!=this._currentlyActiveRaycaster)return!1;let i=null;if(YR(e)&&(i=e[Ri]?.gameObject),this._testObjectsCache.has(e)||i&&this._testObjectsCache.has(i))return this._testObjectsCache.get(e)===!1?"continue in children":!0;{let n=Au(e,this._currentPointerEventName);if(!n&&i&&(n=Au(i,this._currentPointerEventName)),n){this._testObjectsCache.set(e,!0);for(const s of e.children)this.shouldRaycastObject_AddToYesCache(s);return!0}return this._testObjectsCache.set(e,!1),"continue in children"}};shouldRaycastObject_AddToYesCache(e){this._testObjectsCache.set(e,!0);for(const t of e.children)this.shouldRaycastObject_AddToYesCache(t)}performRaycast(e){if(!this.raycaster)return null;this._testObjectsCache.clear(),this._sortedHits.length=0,e.testObject=this.shouldRaycastObject;for(const t of this.raycaster){if(!t.activeAndEnabled)continue;this._currentlyActiveRaycaster=t;const i=t.performRaycast(e);this._currentlyActiveRaycaster=null,i&&i.length>0&&this._sortedHits.push(...i)}return this._sortedHits.sort((t,i)=>t.distance-i.distance),this._sortedHits}assignHitInformation(e,t){t?(e.intersection=t,e.point=t.point,e.normal=t.normal,e.face=t.face,e.distance=t.distance,e.instanceId=t.instanceId):(e.intersection=void 0,e.point=void 0,e.normal=void 0,e.face=void 0,e.distance=void 0,e.instanceId=void 0)}handleIntersections(e,t){if(e?.length){e=this.sortCandidates(e);for(const n of e){if(t.event.immediatePropagationStopped)return!1;if(this.assignHitInformation(t,n),this.handleEventOnObject(n.object,t))return!0}}this.assignHitInformation(t,e?.[0]),this.invokePointerCapture(t);const i=this.hoveredByID.get(t.pointerId);return i&&this.propagatePointerExit(i.obj,i.data,null),this.hoveredByID.delete(t.pointerId),t.isUp&&(this.pressedByID.get(t.pointerId)?.handlers.forEach(n=>this.invokeOnPointerUp(t,n)),this.pressedByID.delete(t.pointerId)),!1}_sortingBuffer=[];_noDepthTestingResults=[];sortCandidates(e){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let t=0;t<e.length;t++){const i=e[t],n=i.object;if(n.material&&n.material.depthTest===!1){this._noDepthTestingResults.push(i);continue}this._sortingBuffer.push(i)}for(const t of this._sortingBuffer)this._noDepthTestingResults.push(t);return this._noDepthTestingResults}out={};handleEventOnObject(e,t){if(!this.testIsVisible(e))return t.isClick&&ks&&console.log("not allowed",e),!1;if(t.pointerId===void 0)return ks&&console.error("Event without pointer can't be handled",t),!1;t.object=e;const i=e.parent,n=t.isClick??!1;let s=null;if(i&&i.isUI){const c=(t.isPressed||t.isClick)??!1;if(i[Ri]){const h=i[Ri].gameObject;if(h){if(!wf.isInteractable(h,this.out))return!1;s=this.out.canvasGroup??null,this.handleMeshUIIntersection(e,c),e=h}}}n&&ks&&console.log(this.context.time.frame,e);const r=this.hoveredByID.get(t.pointerId),a=r?.obj;a!==e&&a&&this.propagatePointerExit(a,r.data,e);const l=this.hoveredByID.get(t.pointerId);if(l?(l.obj=e,l.data=t):this.hoveredByID.set(t.pointerId,{obj:e,data:t}),t.isDown){const c=this.pressedByID.get(t.pointerId);c?(c.obj=e,c.data=t):this.pressedByID.set(t.pointerId,{obj:e,data:t,handlers:new Set})}return(s===null||s.interactable)&&this.handleMainInteraction(e,t,a??null),!0}propagate(e,t){for(;e;)x.foreachComponent(e,i=>{t(i)},!1),e=e.parent}handleMainInteraction(e,t,i){const n=this.pressedByID.get(t.pointerId),s=i!==e;let r=!0;switch(t.event.pointerType){case"mouse":case"touch":const a=this.context.input.getPointerPositionLastFrame(t.pointerId),l=this.context.input.getPointerPosition(t.pointerId);r=a&&!D.approximately(a,l);break}this.propagate(e,a=>{const l=a;l.interactable!==!1&&(!l.activeAndEnabled||!l.enabled||(l.onPointerEnter&&s&&this.handlePointerEnter(l,t),t.isDown&&l.onPointerDown&&(l.onPointerDown(t),n?.handlers.add(l),this.handlePointerCapture(t,l)),l.onPointerMove&&(r&&l.onPointerMove(t),this.handlePointerCapture(t,l)),t.isUp&&(l.onPointerUp&&(this.invokeOnPointerUp(t,l),n?.handlers.delete(l)),l.onPointerExit&&t.event?.pointerType===$d.Touch&&(this.handlePointerExit(l,t),this.hoveredByID.delete(t.pointerId))),t.isClick&&l.onPointerClick&&l.onPointerClick(t)))}),t.isUp&&(n?.handlers.forEach(a=>{this.invokeOnPointerUp(t,a)}),this.pressedByID.delete(t.pointerId))}propagatePointerExit(e,t,i){this.propagate(e,n=>{if(!n.gameObject||n.destroyed)return;const s=n;if(s.onPointerExit||s.onPointerEnter){if(i&&this.isChild(i,n.gameObject))return;this.handlePointerExit(s,t)}})}invokeOnPointerUp(e,t){t.onPointerUp?.call(t,e),this.releasePointerCapture(e,t)}handlePointerEnter(e,t){e.onPointerEnter&&this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!0)&&e.onPointerEnter(t),this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!1)}handlePointerExit(e,t){e.onPointerExit&&this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!0)&&e.onPointerExit(t),this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!1)}updatePointerState(e,t,i,n){let s=e[i];if(n)return s&&s.includes(t)?!1:(s=s||[],s.push(t),e[i]=s,!0);{if(!s||!s.includes(t))return!1;const r=s.indexOf(t);return r!==-1&&s.splice(r,1),!0}}_capturedPointer={};handlePointerCapture(e,t){if(e.z__pointer_ctured){e.z__pointer_ctured=!1;const i=e.pointerId;if(t.onPointerMove){const n=this._capturedPointer[i]||[];n.push(t),this._capturedPointer[i]=n}else A()&&!t.z__warned_no_pointermove&&(t.z__warned_no_pointermove=!0,console.warn("PointerCapture was requested but the component doesn't implement onPointerMove. It will not receive any pointer events"))}else e.z__pointer_cture_rleased&&(e.z__pointer_cture_rleased=!1,this.releasePointerCapture(e,t))}releasePointerCapture(e,t){const i=e.pointerId;if(this._capturedPointer[i]){const n=this._capturedPointer[i].indexOf(t);n!==-1&&(this._capturedPointer[i].splice(n,1),ks&&console.log("released pointer capture",i,t,this._capturedPointer))}}invokePointerCapture(e){if(e.event.type===Te.PointerMove){const t=e.pointerId,i=this._capturedPointer[t];if(i){ks&&console.log("Captured",t,i);for(let n=0;n<i.length;n++){const s=i[n];if(s.destroyed){i.splice(n,1),n--;continue}s.onPointerMove?.call(s,e)}}}}pointerEnterSymbol=Symbol("pointerEnter");pointerExitSymbol=Symbol("pointerExit");isChild(e,t){return!e||!t?!1:e===t?!0:e.parent?this.isChild(e.parent,t):!1}handleMeshUiObjectWithoutShadowDom(e,t){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,t)}currentActiveMeshUIComponents=[];handleMeshUIIntersection(e,t){const i=Wc.updateState(e,t);return i&&this.currentActiveMeshUIComponents.push(i),i!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&Wc.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){const t=this.currentActiveMeshUIComponents[e];Wc.resetState(t)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?x.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}}class Wc{static lastSelected=null;static lastUpdateFrame=[];static needsUpdate=!1;static markDirty(){this.needsUpdate=!0}static update(e,t,i=!1){if(i){e.update();return}const n=t.time.frameCount;for(const s of this.lastUpdateFrame)if(s.context===t){if(n===s.frame)return;s.frame=n;let r=this.needsUpdate||n<1;s.nextUpdate<=n&&(r=!0),r&&(ks&&console.log("Update threemeshui"),this.needsUpdate=!1,s.nextUpdate=n+60,e.update());return}this.lastUpdateFrame=[{context:t,frame:n,nextUpdate:n+60}],e.update(),this.needsUpdate=!1}static updateState(e,t){let i=null;if(e&&(i=this.findBlockOrTextInParent(e),i&&i!==this.lastSelected)){if(i.interactable===!1)return null;this.needsUpdate=!0}return i}static resetLastSelected(){const e=this.lastSelected;e&&(this.lastSelected=null,this.resetState(e))}static resetState(e){e&&(this.needsUpdate=!0)}static findBlockOrTextInParent(e){return e?e.isBlock||e.isText?e:this.findBlockOrTextInParent(e.parent):null}}var KR=Object.defineProperty,JR=Object.getOwnPropertyDescriptor,Oe=(o,e,t,i)=>{for(var n=i>1?void 0:i?JR(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&KR(e,t,n),n};const Ft=v("debugorbit"),Cf=v("freecam"),eE=v("debugcamerafit"),Fu=v("smoothcam"),tE={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let Pf;class Vc extends CustomEvent{constructor(e,t){super("target-reached",{detail:{controls:e,type:t}})}}class fe extends R{get isCameraController(){return!0}get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(e){this.controls?.addEventListener("start",e)}autoTarget=!0;autoFit=!1;enableRotate=!0;autoRotate=!1;autoRotateSpeed=1;minAzimuthAngle=1/0;maxAzimuthAngle=1/0;minPolarAngle=0;maxPolarAngle=Math.PI;enableKeys=!1;enableDamping=!0;dampingFactor=.1;enableZoom=!0;minZoom=0;maxZoom=1/0;zoomSpeed=1;zoomToCursor=!1;enablePan=!0;lookAtConstraint=null;lookAtConstraint01=1;allowInterrupt=!0;middleClickToFocus=!0;doubleClickToFocus=!0;clickBackgroundToFitScene=2;get targetElement(){return this._controls?.domElement??this._targetElement}set targetElement(e){this._targetElement=e,this._controls&&this._controls.domElement!==e&&(this._controls.disconnect(),this._controls.domElement=e,this._controls.connect())}_targetElement=null;debugLog=!1;get targetLerpSpeed(){return 5}set targetLerpSpeed(e){this.targetLerpDuration=1/e}get targetLerpDuration(){return this._lookTargetLerpDuration}set targetLerpDuration(e){this._lookTargetLerpDuration=e}_lookTargetLerpDuration=1;targetBounds=null;rotateLeft(e){this._controls?._rotateLeft(e)}rotateUp(e){this._controls?._rotateUp(e)}pan(e,t){this._controls?._pan(e,t)}zoomIn(e){e>0?this._controls?._dollyIn(1-e):e<0&&this._controls?._dollyOut(1+e)}_controls=null;_cameraObject=null;_lookTargetLerpActive=!1;_lookTargetStartPosition=new b;_lookTargetEndPosition=new b;_lookTargetLerp01=0;_cameraLerpActive=!1;_cameraStartPosition=new b;_cameraEndPosition=new b;_cameraLerp01=0;_cameraLerpDuration=0;_fovLerpActive=!1;_fovLerpStartValue=0;_fovLerpEndValue=0;_fovLerp01=0;_fovLerpDuration=0;_inputs=0;_enableTime=0;_startedListeningToKeyEvents=!1;_eventSystem;_afterHandleInputFn;_camera=null;_syncedTransform;_didSetTarget=0;awake(){Ft&&console.debug("OrbitControls",this),this._didSetTarget=0,this._startedListeningToKeyEvents=!1,this.context.domElement.cameraControls===!1&&(this.enabled=!1)}start(){this._eventSystem=si.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(Sf.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){this._controls?.dispose(),this._eventSystem?.removeEventListener(Sf.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._didSetTarget=0,this._enableTime=this.context.time.time;const e=x.getComponent(this.gameObject,ui);this._camera=e;let t=e?.threeCamera;if(!t&&this.gameObject instanceof ae&&(t=this.gameObject),t&&Xm(t,this,!0),!this._controls&&t instanceof k){this._cameraObject=t;const i=this.targetElement??this.context.renderer.domElement,n=t?.quaternion.clone();this._controls=new wb(t,i),t?.quaternion.copy(n),Pf===void 0&&(Pf={...this._controls.keys});const s=J(t),r=this.gameObject.worldForward,a=s.clone().sub(r.multiplyScalar(2.5));this._controls.target.copy(a)}if(this._controls)if(Cf&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,L.isMobileDevice()&&(this.doubleClickToFocus=!0)),this._controls.addEventListener("start",this.onControlsChangeStarted),this._controls.addEventListener("endMovement",this.onControlsChangeEnded),!this._startedListeningToKeyEvents&&this.enableKeys)this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(this.context.domElement);else try{this._controls.stopListenToKeyEvents()}catch{}this._syncedTransform=x.getComponent(this.gameObject,On)??void 0,this.context.pre_render_callbacks.push(this.__onPreRender),this._activePointerEvents=[],this.context.input.addEventListener("pointerdown",this._onPointerDown,{queue:ci.Early}),this.context.input.addEventListener("pointerdown",this._onPointerDownLate,{queue:ci.Late}),this.context.input.addEventListener("pointerup",this._onPointerUp,{queue:ci.Early}),this.context.input.addEventListener("pointerup",this._onPointerUpLate,{queue:ci.Late})}onDisable(){if(this._camera?.threeCamera&&Xm(this._camera.threeCamera,this,!1),this._controls){this._controls.enabled=!1,this._controls.autoRotate=!1,this._controls.removeEventListener("start",this.onControlsChangeStarted),this._controls.removeEventListener("endMovement",this.onControlsChangeEnded);try{this._controls.stopListenToKeyEvents()}catch{}this._startedListeningToKeyEvents=!1}this._activePointerEvents.length=0,this.context.input.removeEventListener("pointerdown",this._onPointerDown),this.context.input.removeEventListener("pointerdown",this._onPointerDownLate),this.context.input.removeEventListener("pointerup",this._onPointerUp),this.context.input.removeEventListener("pointerup",this._onPointerUpLate)}_activePointerEvents;_lastTimeClickOnBackground=-1;_clickOnBackgroundCount=0;_onPointerDown=e=>{this._activePointerEvents.push(e)};_onPointerDownLate=e=>{e.used&&this._controls&&(this._controls.enabled=!1)};_onPointerUp=e=>{for(let t=this._activePointerEvents.length-1;t>=0;t--){const i=this._activePointerEvents[t];if(i.pointerId===e.pointerId&&i.button===e.button){this._activePointerEvents.splice(t,1);break}}if(this.clickBackgroundToFitScene>0&&e.isClick&&e.button===0){if(e.hasRay||e.intersections.push(...this.context.physics.raycast()),e.intersections.length<=0){const t=this.context.time.time-this._lastTimeClickOnBackground;this._lastTimeClickOnBackground=this.context.time.time,this.clickBackgroundToFitScene<=1||t<this.clickBackgroundToFitScene*.15?(this._clickOnBackgroundCount+=1,this._clickOnBackgroundCount>=this.clickBackgroundToFitScene-1&&(this.autoRotate=!1,this.fitCamera({objects:this.context.scene,immediate:!1}))):this._clickOnBackgroundCount=0}Ft&&console.log(this.clickBackgroundToFitScene,e.intersections.length,this._clickOnBackgroundCount)}};_onPointerUpLate=e=>{this.doubleClickToFocus&&e.isDoubleClick&&!e.used&&this.setTargetFromRaycast()};updateTargetNow(e){const t=new vo(this._cameraObject?.worldPosition,this._cameraObject?.worldForward.multiplyScalar(-1)),i=this.context.physics.raycastFromRay(t,e),n=i.length>0?i[0]:void 0;n&&n.distance>this.minZoom&&n.distance<this.maxZoom?(Ft&&F.DrawWireSphere(n.point,.1,16711680,2),this._controls?.target.copy(i[0].point)):Ft&&console.log("OrbitControls: No hit found when updating target",{hits:[...i]})}_orbitStartAngle=0;_zoomStartDistance=0;onControlsChangeStarted=()=>{Ft&&console.debug("OrbitControls: Change started"),this._controls&&(this._orbitStartAngle=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle(),this._zoomStartDistance=this._controls.getDistance()),this._syncedTransform&&this._syncedTransform.requestOwnership()};onControlsChangeEnded=()=>{if(Ft&&console.debug("OrbitControls: Change ended",{autoTarget:this.autoTarget}),this._controls&&this.autoTarget){const e=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle()-this._orbitStartAngle;Math.abs(e)<.01?(Ft&&console.debug("OrbitControls: Update target",{deltaAngle:e}),this.updateTargetNow({allowSlowRaycastFallback:!1})):Ft&&console.debug("OrbitControls: No target update",{deltaAngle:e})}};_shouldDisable=!1;afterHandleInput(e){e.detail.args.pointerId===0&&(e.detail.args.isDown?this._controls&&this._eventSystem&&(this._shouldDisable=this._eventSystem.hasActiveUI):(!e.detail.args.isPressed||e.detail.args.isUp)&&(this._shouldDisable=!1))}onPausedChanged(e){this._controls&&e&&(this._controls.enabled=!1)}onBeforeRender(){if(!!this._controls){if(this._cameraObject!==this.context.mainCamera){this._controls.enabled=!1;return}if(this._controls.enabled=!0,(this.context.input.getPointerDown(1)||this.context.input.getPointerDown(2)||this.context.input.mouseWheelChanged||this.context.input.getPointerPressed(0)&&this.context.input.getPointerPositionDelta(0)?.length())&&(this._inputs+=1),this._inputs>0&&this.allowInterrupt&&(this.enableRotate&&(this.autoRotate=!1),this._cameraLerpActive=!1,this._lookTargetLerpActive=!1),this._inputs=0,this.autoTarget&&this._didSetTarget++===0){const e=x.getComponent(this.gameObject,ui);if(e&&!this.setLookTargetFromConstraint()){this.debugLog&&console.log("NO TARGET");const t=J(e.threeCamera),i=Math.max(.01,t.length()),n=new b(0,0,-i).applyMatrix4(e.threeCamera.matrixWorld);Ft&&F.DrawLine(t,n,5592575,10),this.setLookTargetPosition(n,!0)}if(!this.setLookTargetFromConstraint()){const t=new vs;t.screenPoint=new ee(0,0),t.lineThreshold=.1;const i=this.context.physics.raycast(t);i.length>0&&this.setLookTargetPosition(i[0].point,!0),eE&&console.log("OrbitControls hits",...i)}}if(this.middleClickToFocus&&this.context.input.getPointerClicked(1)&&this.setTargetFromRaycast(),this._lookTargetLerpActive||this._cameraLerpActive||this._fovLerpActive){if(this._cameraLerpActive&&this._cameraObject)if(this._cameraLerp01+=this.context.time.deltaTime/this._cameraLerpDuration,this._cameraLerp01>=1)this._cameraObject.position.copy(this._cameraEndPosition),this._cameraLerpActive=!1,this.dispatchEvent(new Vc(this,"camera"));else{const e=D.easeInOutCubic(this._cameraLerp01);this._cameraObject.position.lerpVectors(this._cameraStartPosition,this._cameraEndPosition,e)}if(this._lookTargetLerpActive)if(this._lookTargetLerp01+=this.context.time.deltaTime/this._lookTargetLerpDuration,this._lookTargetLerp01>=1)this.lerpLookTarget(this._lookTargetEndPosition,this._lookTargetEndPosition,1),this._lookTargetLerpActive=!1,this.dispatchEvent(new Vc(this,"lookat"));else{const e=D.easeInOutCubic(this._lookTargetLerp01);this.lerpLookTarget(this._lookTargetStartPosition,this._lookTargetEndPosition,e)}if(this._fovLerpActive&&this._cameraObject){const e=this._cameraObject;if(this._fovLerp01+=this.context.time.deltaTime/this._fovLerpDuration,this._fovLerp01>=1)e.fov=this._fovLerpEndValue,this._fovLerpActive=!1;else{const t=D.easeInOutCubic(this._fovLerp01);e.fov=D.lerp(this._fovLerpStartValue,this._fovLerpEndValue,t)}e.updateProjectionMatrix()}}if(this.targetBounds){const e=this._controls.target,t=this.targetBounds.worldPosition,i=B(this.targetBounds.worldScale).multiplyScalar(.5),n=B(t).sub(i),s=B(t).add(i),r=B(this._controls.target).clamp(n,s),a=.1;e.lerp(r,this.context.time.deltaTime/a),this._lookTargetLerpActive&&this._lookTargetEndPosition.lerp(r,this.context.time.deltaTime/(a*5)),Ft&&F.DrawWireBox(t,i.multiplyScalar(2),16755200)}if(this._controls){this.debugLog&&(this._controls.domElement=this.context.renderer.domElement);const e=1/(this.context.focusRectSettings?.zoom||1);if(this._controls.enabled=!this._shouldDisable&&this._camera===this.context.mainCameraComponent&&!this.context.isInXR&&!this._activePointerEvents.some(t=>t.used),this._controls.keys=this.enableKeys?Pf:tE,this._controls.autoRotate=this.autoRotate,this._controls.autoRotateSpeed=this.autoRotateSpeed,this._controls.enableZoom=this.enableZoom,this._controls.zoomSpeed=this.zoomSpeed,this._controls.zoomToCursor=this.zoomToCursor,this._controls.enableDamping=this.enableDamping,this._controls.dampingFactor=this.dampingFactor,this._controls.enablePan=this.enablePan,this._controls.panSpeed=e,this._controls.enableRotate=this.enableRotate,this._controls.minAzimuthAngle=this.minAzimuthAngle,this._controls.maxAzimuthAngle=this.maxAzimuthAngle,this._controls.minPolarAngle=this.minPolarAngle,this._controls.maxPolarAngle=this.maxPolarAngle,Cf||(this._camera?.threeCamera?.type==="PerspectiveCamera"?(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom,this._controls.minZoom=0,this._controls.maxZoom=1/0):(this._controls.minDistance=0,this._controls.maxDistance=1/0,this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom)),typeof Fu=="number"||Fu===!0){this._controls.enableDamping=!0;const t=typeof Fu=="number"?Fu:.99;this._controls.dampingFactor=Math.max(.001,1-Math.min(1,t))}this.allowInterrupt||(this._lookTargetLerpActive&&(this._controls.enablePan=!1),this._cameraLerpActive&&(this._controls.enableRotate=!1,this._controls.autoRotate=!1),(this._lookTargetLerpActive||this._cameraLerpActive)&&(this._controls.enableZoom=!1)),this.context.isInXR||(!Cf&&this.lookAtConstraint?.locked&&!this._lookTargetLerpActive&&this.setLookTargetFromConstraint(0,this.lookAtConstraint01),this._controls.update(this.context.time.deltaTime),Ft&&F.DrawWireSphere(this._controls.target,.1,65280))}}}__onPreRender=()=>{const e=this.context.pre_render_callbacks.indexOf(this.__onPreRender);e>=0&&this.context.pre_render_callbacks.splice(e,1),this.autoFit&&(this.autoFit=!1,this.fitCamera({centerCamera:"y",immediate:!0,objects:this.scene.children}))};setCameraAndLookTarget(e,t=!1){if(!e)return(A()||Ft)&&console.warn("[OrbitControls] setCameraAndLookTarget target is null"),!1;if(!(e instanceof k)&&!(e instanceof ui))return(A()||Ft)&&console.warn("[OrbitControls] setCameraAndLookTarget target is not an Object3D or Camera"),!1;e instanceof ui&&(e=e.gameObject);const i=e.worldPosition,n=e.worldForward;e instanceof XS&&(Ft&&console.debug("[OrbitControls] setCameraAndLookTarget flip forward direction for camera"),n.multiplyScalar(-1));const s=new vo(i,n);return Ft&&F.DrawRay(s.origin,s.direction,16711680,10),this.setTargetFromRaycast(s,t)||this.setLookTargetPosition(s.at(2,B()),t),this.setCameraTargetPosition(i,t),!0}setCameraTargetPosition(e,t=!1){e&&(e instanceof k&&(e=J(e)),this._cameraEndPosition||(this._cameraEndPosition=new b),this._cameraEndPosition.copy(e),t===!0?(this._cameraLerpActive=!1,this._cameraObject&&this._cameraObject.position.copy(this._cameraEndPosition)):this._cameraObject&&(this._cameraLerpActive=!0,this._cameraLerp01=0,this._cameraStartPosition.copy(this._cameraObject?.position),typeof t=="number"?this._cameraLerpDuration=t:this._cameraLerpDuration=this.targetLerpDuration))}get cameraLerpActive(){return this._cameraLerpActive}stopCameraLerp(){this._cameraLerpActive=!1}setFieldOfView(e,t=!1){if(!this._controls||typeof e!="number")return;const i=this._camera?.threeCamera;i&&(t===!0?i.fov=e:(this._fovLerpActive=!0,this._fovLerp01=0,this._fovLerpStartValue=i.fov,this._fovLerpEndValue=e,typeof t=="number"?this._fovLerpDuration=t:this._fovLerpDuration=this.targetLerpDuration))}setLookTargetPosition(e=null,t=!1){this._controls&&e&&(e instanceof k&&(e=J(e)),this._lookTargetEndPosition.copy(e),this._didSetTarget++,Ft&&(console.warn("OrbitControls: setLookTargetPosition",e,t),F.DrawWireSphere(this._lookTargetEndPosition,.2,16711680,2)),t===!0?this.lerpLookTarget(this._lookTargetEndPosition,this._lookTargetEndPosition,1):(this._lookTargetLerpActive=!0,this._lookTargetLerp01=0,this._lookTargetStartPosition.copy(this._controls.target),typeof t=="number"?this._lookTargetLerpDuration=t:this._lookTargetLerpDuration=this.targetLerpDuration))}get lookTargetLerpActive(){return this._lookTargetLerpActive}stopLookTargetLerp(){this._lookTargetLerpActive=!1}setLookTargetFromConstraint(e=0,t=1){if(!this._controls||this.lookAtConstraint?.enabled===!1)return!1;const i=this.lookAtConstraint?.sources;if(i&&i.length>0){const n=i[e];if(n)return n.getWorldPosition(this._lookTargetEndPosition),this.lerpLookTarget(this._controls.target,this._lookTargetEndPosition,t),!0}return!1}lerpLookTarget(e,t,i){this._controls&&(i>=1?this._controls.target.copy(t):this._controls.target.lerpVectors(e,t,i),this.lookAtConstraint&&this.lookAtConstraint.setConstraintPosition(this._controls.target))}setTargetFromRaycast(e,t=!1){if(!this.controls)return!1;const i=e?this.context.physics.raycastFromRay(e):this.context.physics.raycast();for(const n of i)if(n.distance>0&&x.isActiveInHierarchy(n.object)){const s=xf(n.object);if(s&&s.canvas?.screenspace)break;return this.setLookTargetPosition(n.point,t),!0}return!1}fitCamera(e,t){let i;if(Array.isArray(e)||e&&"type"in e?i=e:e&&typeof e=="object"&&!(e instanceof k)&&!Array.isArray(e)&&(t=e,i=t.objects),i&&!Array.isArray(i)&&(i=[i]),(!Array.isArray(i)||i&&i.length<=0)&&(i=this.context.scene.children),!Array.isArray(i)||i.length<=0){console.warn("No objects to fit camera to...");return}const n=Nw({objects:[...i],...t,autoApply:!1,context:this.context,camera:this._cameraObject,currentZoom:this._controls?.getDistance()||void 0,minZoom:this.minZoom,maxZoom:this.maxZoom});n&&(this.setLookTargetPosition(n.lookAt,t?.immediate||!1),this.setCameraTargetPosition(n.position,t?.immediate||!1),this.setFieldOfView(t?.fov,t?.immediate||!1),this.onBeforeRender())}_haveAttachedKeyboardEvents=!1}Oe([u()],fe.prototype,"autoTarget",2),Oe([u()],fe.prototype,"autoFit",2),Oe([u()],fe.prototype,"enableRotate",2),Oe([u()],fe.prototype,"autoRotate",2),Oe([u()],fe.prototype,"autoRotateSpeed",2),Oe([u()],fe.prototype,"minAzimuthAngle",2),Oe([u()],fe.prototype,"maxAzimuthAngle",2),Oe([u()],fe.prototype,"minPolarAngle",2),Oe([u()],fe.prototype,"maxPolarAngle",2),Oe([u()],fe.prototype,"enableKeys",2),Oe([u()],fe.prototype,"enableDamping",2),Oe([u()],fe.prototype,"dampingFactor",2),Oe([u()],fe.prototype,"enableZoom",2),Oe([u()],fe.prototype,"minZoom",2),Oe([u()],fe.prototype,"maxZoom",2),Oe([u()],fe.prototype,"zoomSpeed",2),Oe([u()],fe.prototype,"enablePan",2),Oe([u(jr)],fe.prototype,"lookAtConstraint",2),Oe([u()],fe.prototype,"lookAtConstraint01",2),Oe([u()],fe.prototype,"allowInterrupt",2),Oe([u()],fe.prototype,"middleClickToFocus",2),Oe([u()],fe.prototype,"doubleClickToFocus",2),Oe([u()],fe.prototype,"clickBackgroundToFitScene",2),Oe([u()],fe.prototype,"targetLerpDuration",1),Oe([u(k)],fe.prototype,"targetBounds",2);var iE=Object.defineProperty,nE=Object.getOwnPropertyDescriptor,Zt=(o,e,t,i)=>{for(var n=i>1?void 0:i?nE(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&iE(e,t,n),n},Fr=(o=>(o[o.None=0]="None",o[o.Skybox=1]="Skybox",o[o.SolidColor=2]="SolidColor",o[o.Uninitialized=4]="Uninitialized",o))(Fr||{});const Ms=v("debugcam"),Xw=v("debugscreenpointtoray"),Ut=class ld extends R{get isCamera(){return!0}get aspect(){return this._cam instanceof ae?this._cam.aspect:this.context.domWidth/this.context.domHeight}set aspect(e){this._cam instanceof ae&&this._cam.aspect!==e&&(this._cam.aspect=e,this._cam.updateProjectionMatrix())}get fieldOfView(){return this._cam instanceof ae?this._cam.fov:this._fov}set fieldOfView(e){const t=this.fieldOfView!=e;if(this._fov=e,t&&this._cam&&this._cam instanceof ae){if(this._fov===void 0){console.warn("Can not set undefined fov on PerspectiveCamera");return}this._cam.fov=this._fov,this._cam.updateProjectionMatrix()}}get nearClipPlane(){return this._nearClipPlane}set nearClipPlane(e){const t=this._nearClipPlane!=e;this._nearClipPlane=e,this._cam&&(t||this._cam.near!=e)&&(this._cam.near=e,this._cam.updateProjectionMatrix())}_nearClipPlane=.1;get farClipPlane(){return this._farClipPlane}set farClipPlane(e){const t=this._farClipPlane!=e;this._farClipPlane=e,this._cam&&(t||this._cam.far!=e)&&(this._cam.far=e,this._cam.updateProjectionMatrix())}_farClipPlane=1e3;applyClippingPlane(){this._cam&&(this._cam.near=this._nearClipPlane,this._cam.far=this._farClipPlane,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(e){if(typeof e=="string")switch(e){case"skybox":e=1;break;case"solidcolor":e=2;break;default:e=0;break}e!==this._clearFlags&&(this._clearFlags=e,this.applyClearFlagsIfIsActiveCamera())}orthographic=!1;orthographicSize=5;ARBackgroundAlpha=0;set cullingMask(e){this._cullingMask=e,this._cam&&(this._cam.layers.mask=e)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}_cullingMask=4294967295;set cullingLayer(e){this.cullingMask=(1<<e|0)>>>0}set backgroundBlurriness(e){e!==this._backgroundBlurriness&&(e===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(e,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}_backgroundBlurriness=void 0;set backgroundIntensity(e){e!==this._backgroundIntensity&&(e===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(e,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}_backgroundIntensity=void 0;set backgroundRotation(e){e!==this._backgroundRotation&&(e===void 0?this._backgroundRotation=void 0:this._backgroundRotation=e,this.applyClearFlagsIfIsActiveCamera())}get backgroundRotation(){return this._backgroundRotation}_backgroundRotation=void 0;set environmentIntensity(e){this._environmentIntensity=e}get environmentIntensity(){return this._environmentIntensity}_environmentIntensity=void 0;get backgroundColor(){return this._backgroundColor??null}set backgroundColor(e){e&&(this._backgroundColor||(this._backgroundColor=new se(1,1,1,1)),this._backgroundColor.copy(e),(!("alpha"in e)||e.alpha===void 0)&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera())}set targetTexture(e){this._targetTexture=e}get targetTexture(){return this._targetTexture}_targetTexture=null;_backgroundColor;_fov;_cam=null;_clearFlags=2;_skybox;get cam(){return this.threeCamera}get threeCamera(){return this.activeAndEnabled&&this.buildCamera(),this._cam}static _origin=new b;static _direction=new b;screenPointToRay(e,t,i){const n=this.threeCamera,s=ld._origin;s.set(e,t,-1),this.context.input.convertScreenspaceToRaycastSpace(s),Xw&&console.log("screenPointToRay",e.toFixed(2),t.toFixed(2),"now:",s.x.toFixed(2),s.y.toFixed(2),"isInXR:"+this.context.isInXR),s.z=-1,s.unproject(n);const r=ld._direction.set(s.x,s.y,s.z),a=J(n);return r.sub(a),r.normalize(),i?(i.set(a,r),i):new vo(a.clone(),r.clone())}_frustum;getFrustum(){return this._frustum||(this._frustum=new lb,this.updateFrustum()),this._frustum}updateFrustum(){this._frustum||(this._frustum=new lb),this._frustum.setFromProjectionMatrix(this.getProjectionScreenMatrix(this._projScreenMatrix,!0),this.context.renderer.coordinateSystem)}getProjectionScreenMatrix(e,t){return t&&this._projScreenMatrix.multiplyMatrices(this.threeCamera.projectionMatrix,this.threeCamera.matrixWorldInverse),e===this._projScreenMatrix?e:e.copy(this._projScreenMatrix)}_projScreenMatrix=new K;awake(){Xw&&window.addEventListener("pointerdown",e=>{const t=e.clientX,i=e.clientY;console.log("touch",t.toFixed(2),i.toFixed(2));const n=this.screenPointToRay(t,i),s="#"+Math.floor(Math.random()*16777215).toString(16);F.DrawRay(n.origin,n.direction,s,10)})}onEnable(){Ms&&console.log(`Camera enabled: "${this.name}". ClearFlags=${Fr[this._clearFlags]}`,this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),sE(this)),this.applyClearFlagsIfIsActiveCamera({applySkybox:!0})}onDisable(){this.context.removeCamera(this)}onLeaveXR(e){this.fieldOfView=this._fov}onBeforeRender(){if(this._cam&&(this._frustum&&this.updateFrustum(),this._clearFlags===2&&this.applyClearFlagsIfIsActiveCamera(),this._targetTexture)){this.context.isManagedExternally&&(this._warnedAboutExternalRenderer||(this._warnedAboutExternalRenderer=!0,console.warn("Rendering with external renderer is not supported yet. This may not work or throw errors. Please remove the the target texture from your camera: "+this.name,this.targetTexture))),this.context.composer;const e=this.context.renderer;if(e){const t=this.context.mainCameraComponent;this.applyClearFlags(),this._targetTexture.render(this.context.scene,this._cam,e),t?.applyClearFlags()}}}buildCamera(){if(this._cam)return;const e=this.gameObject.isCamera;let t=null;if(e?(t=this.gameObject,t?.layers.enableAll(),t instanceof ae&&(this._fov=t.fov)):t=this.gameObject.children[0],t&&t.isCamera)t instanceof ae&&(this._fov&&(t.fov=this._fov),t.near=this._nearClipPlane,t.far=this._farClipPlane,t.updateProjectionMatrix());else if(!this.orthographic)t=new ae(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),this.fieldOfView&&(t.fov=this.fieldOfView),this.gameObject.add(t);else{const i=this.orthographicSize*100;t=new bd(window.innerWidth/-i,window.innerWidth/i,window.innerHeight/i,window.innerHeight/-i,this._nearClipPlane,this._farClipPlane),this.gameObject.add(t)}this._cam=t,this._cam.layers.mask=this._cullingMask,this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(e){this.context.mainCameraComponent===this&&this.applyClearFlags(e)}applyClearFlags(e){if(!this._cam){Ms&&console.log("Camera does not exist (apply clear flags)");return}if(this.fieldOfView=this.fieldOfView,Ms){const i=`[Camera] Apply ClearFlags: ${Fr[this._clearFlags]} - "${this.name}"`;console.debug(i)}const t=this.context.domElement.getAttribute("background-image")||this.context.domElement.getAttribute("background-color");switch(this._clearFlags){case 0:return;case 1:if(ld.backgroundShouldBeTransparent(this.context)&&(!this.ARBackgroundAlpha||this.ARBackgroundAlpha<.001)){this.context.scene.background=null,this.context.renderer.setClearColor(0,0);return}(!this.scene.background||!this._skybox||e?.applySkybox===!0)&&this.applySceneSkybox(),this._backgroundBlurriness!==void 0&&!this.context.domElement.getAttribute("background-blurriness")?this.context.scene.backgroundBlurriness=this._backgroundBlurriness:Ms&&console.warn(`Camera "${this.name}" has no background blurriness`),this._backgroundIntensity!==void 0&&!this.context.domElement.getAttribute("background-intensity")&&(this.context.scene.backgroundIntensity=this._backgroundIntensity),this._backgroundRotation!==void 0&&!this.context.domElement.getAttribute("background-rotation")?this.context.scene.backgroundRotation=this._backgroundRotation:Ms&&console.warn(`Camera "${this.name}" has no background intensity`);break;case 2:if(this._backgroundColor&&!t){let i=this._backgroundColor.alpha;ld.backgroundShouldBeTransparent(this.context)&&(i=this.ARBackgroundAlpha??0),this.context.scene.background=null,this.context.xr?.isVR?this.context.renderer.setClearColor(e_(this._backgroundColor).convertLinearToSRGB()):this.context.renderer.setClearColor(this._backgroundColor,i)}else this._backgroundColor||Ms&&console.warn(`[Camera] has no background color "${this.name}" `);break;case 4:t||(this.context.scene.background=null,this.context.renderer.setClearColor(0,0));break}}applySceneSkybox(){this._skybox||(this._skybox=new oE(this)),this._skybox.apply()}static backgroundShouldBeTransparent(e){const t=e.renderer.xr?.getSession();if(!t)return!1;if(typeof t._transparent=="boolean")return t._transparent;const i=t.environmentBlendMode;Ms&&Ee("Environment blend mode: "+i+" on "+navigator.userAgent);let n=i==="additive"||i==="alpha-blend";if(e.isInAR&&i==="opaque"){if(navigator.userAgent?.includes("OculusBrowser"))n=!0;else if(navigator.userAgent?.includes("Mozilla")&&navigator.userAgent?.includes("Mobile WebXRViewer/v2"))n=!0;else if(L.isNeedleAppClip())return!0}return t._transparent=n,n}};Zt([u()],Ut.prototype,"aspect",1),Zt([u()],Ut.prototype,"fieldOfView",1),Zt([u()],Ut.prototype,"nearClipPlane",1),Zt([u()],Ut.prototype,"farClipPlane",1),Zt([u()],Ut.prototype,"clearFlags",1),Zt([u()],Ut.prototype,"orthographic",2),Zt([u()],Ut.prototype,"orthographicSize",2),Zt([u()],Ut.prototype,"ARBackgroundAlpha",2),Zt([u()],Ut.prototype,"cullingMask",1),Zt([u()],Ut.prototype,"backgroundBlurriness",1),Zt([u()],Ut.prototype,"backgroundIntensity",1),Zt([u(st)],Ut.prototype,"backgroundRotation",1),Zt([u()],Ut.prototype,"environmentIntensity",1),Zt([u(se)],Ut.prototype,"backgroundColor",1),Zt([u(_o)],Ut.prototype,"targetTexture",1);let ui=Ut;class oE{_camera;_skybox;get context(){return this._camera?.context}constructor(e){this._camera=e}apply(){if(this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),!this._skybox)this._did_log_failed_to_find_skybox||(this._did_log_failed_to_find_skybox=!0,console.warn(`Camera "${this._camera.name}" has no skybox texture. ${this._camera.sourceId}`));else if(this.context.scene.background!==this._skybox){const e=this.context.domElement.getAttribute("background-image")||this.context.domElement.getAttribute("background-color");Ms&&console.debug(`[Camera] Apply Skybox ${this._skybox?.name} ${e} - "${this._camera.name}"`),e?.length||(this._skybox.mapping=Nn,this.context.scene.background=this._skybox)}}}function sE(o){v("freecam")&&o.context.mainCameraComponent===o&&x.getOrAddComponent(o.gameObject,fe)}class Fo extends R{get listener(){return this._listener==null&&(this._listener=new QS),this._listener}_listener=null;onEnable(){jn.registerWaitForInteraction(this.onInteraction),this.addListenerIfItExists()}onDisable(){jn.unregisterWaitForInteraction(this.onInteraction),this.removeListenerIfItExists()}onInteraction=()=>{this.destroyed||this.listener==null||this.addListenerIfItExists()};addListenerIfItExists(){const e=this._listener;if(!e||e?.parent)return;const t=this.context.mainCameraComponent||x.getComponentInParent(this.gameObject,ui);t?.threeCamera?t.threeCamera.add(e):this.gameObject.add(e),e.filter?(e.gain.connect(e.filter),e.filter.connect(e.context.destination)):e.gain.connect(e.context.destination)}removeListenerIfItExists(){const e=this._listener;e&&(e.removeFromParent(),e.filter&&e.filter.disconnect(),e.gain&&e.gain.disconnect())}}var rE=Object.defineProperty,aE=Object.getOwnPropertyDescriptor,kn=(o,e,t,i)=>{for(var n=i>1?void 0:i?aE(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&rE(e,t,n),n};const Mt=v("debugaudio"),Ki=class nr extends R{static get userInteractionRegistered(){return jn.userInteractionRegistered}static registerWaitForAllowAudio(e){jn.registerWaitForInteraction(e)}clip="";playOnAwake=!1;preload=!0;playInBackground=!0;get isPlaying(){return this.sound?.isPlaying??!1}get duration(){return this.sound?.buffer?.duration}get time01(){const e=this.duration;return e&&this.sound?this.sound?.context.currentTime/e:0}set time01(e){const t=this.duration;t&&this.sound&&(this.time=e*t)}get time(){return this.sound?.source?this.sound.source?.context.currentTime-this._lastContextTime+this.sound.offset:0}set time(e){if(this.sound){if(e===this.sound.offset)return;const t=this.isPlaying;this.stop(),this.sound.offset=e,t&&this.play()}}get loop(){return this.sound&&(this._loop=this.sound.getLoop()),this._loop}set loop(e){this._loop=e,this.sound&&this.sound.setLoop(e)}get spatialBlend(){return this._spatialBlend}set spatialBlend(e){e!==this._spatialBlend&&(this._spatialBlend=e,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(e){this._minDistance!==e&&(this._minDistance=e,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(e){this._maxDistance!==e&&(this._maxDistance=e,this._needUpdateSpatialDistanceSettings=!0)}_spatialBlend=0;_minDistance=1;_maxDistance=100;get volume(){return this._volume}set volume(e){this._volume=e,this.sound&&!this.context.application.muted&&(Mt&&console.log(this.name,"audio set volume",e),this.sound.setVolume(e))}_volume=1;set pitch(e){this.sound&&this.sound.setPlaybackRate(e)}get pitch(){return this.sound?this.sound.getPlaybackRate():1}rollOffMode=0;_loop=!1;sound=null;helper=null;wasPlaying=!1;audioLoader=null;shouldPlay=!1;_lastClipStartedLoading=null;_audioElement=null;get Sound(){if(!this.sound&&nr.userInteractionRegistered){let e=this.gameObject.getComponent(Fo)??this.context.mainCamera.getComponent(Fo)??Ga(Fo,this.context,!1);!e&&this.context.mainCamera&&(e=this.context.mainCamera.addComponent(Fo)),e?.listener?(this.sound=new YS(e.listener),this.gameObject?.add(this.sound)):Mt&&console.warn("No audio listener found in scene - can not play audio")}return this.sound}get ShouldPlay(){return this.shouldPlay}get audioContext(){return this.sound?.context}awake(){Mt&&console.log("[AudioSource]",this),this.audioLoader=new xm,this.playOnAwake&&(this.shouldPlay=!0),this.preload&&typeof this.clip=="string"&&this.audioLoader.load(this.clip,this.createAudio,()=>{},console.error)}onEnable(){this.sound&&this.gameObject.add(this.sound),nr.userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():nr.registerWaitForAllowAudio(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.onNewClip(this.clip)}),globalThis.addEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.addEventListener(mg.MuteChanged,this.onApplicationMuteChanged)}onDisable(){globalThis.removeEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.removeEventListener(mg.MuteChanged,this.onApplicationMuteChanged),this.pause()}onVisibilityChanged=()=>{switch(document.visibilityState){case"hidden":(this.playInBackground===!1||L.isMobileDevice())&&(this.wasPlaying=this.isPlaying,this.isPlaying&&this.pause());break;case"visible":Mt&&console.log("visible",this.enabled,this.playOnAwake,!this.isPlaying,nr.userInteractionRegistered,this.wasPlaying),this.enabled&&this.playOnAwake&&!this.isPlaying&&nr.userInteractionRegistered&&this.wasPlaying&&this.play();break}};onApplicationMuteChanged=()=>{this.context.application.muted?this.sound?.setVolume(0):this.sound?.setVolume(this.volume)};createAudio=e=>{if(this.destroyed){Mt&&console.warn("AudioSource destroyed, not creating audio",this.name);return}Mt&&console.log("AudioBuffer finished loading",e);const t=this.Sound;if(!t){Mt&&console.warn("Failed getting sound?",this.name);return}t.isPlaying&&t.stop(),e&&t.setBuffer(e),t.loop=this._loop,this.context.application.muted?t.setVolume(0):t.setVolume(this.volume),t.autoplay=this.shouldPlay&&nr.userInteractionRegistered,this.applySpatialDistanceSettings(),t.isPlaying&&t.stop(),nr.registerWaitForAllowAudio(this.__onAllowAudioCallback)};__onAllowAudioCallback=()=>{this.shouldPlay&&this.play()};applySpatialDistanceSettings(){const e=this.sound;if(!e)return;this._needUpdateSpatialDistanceSettings=!1;const t=D.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(Mt&&console.log(this.name,this._minDistance,this._maxDistance,this.spatialBlend,"Ref distance="+t),e.setRefDistance(t),e.setMaxDistance(Math.max(.01,this._maxDistance)),this.rollOffMode){case 0:e.setDistanceModel("exponential");break;case 1:e.setDistanceModel("linear");break;case 2:console.warn("Custom rolloff for AudioSource is not supported: "+this.name);break}this.spatialBlend>0?Mt&&!this.helper&&(this.helper=new JC(e,e.getRefDistance()),e.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}async onNewClip(e){if(e&&(this.clip=e),typeof e=="string")if(Mt&&console.log(e),e.endsWith(".mp3")||e.endsWith(".wav")){if(this.audioLoader||(this.audioLoader=new xm),this.shouldPlay=!0,this._lastClipStartedLoading===e){Mt&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=e,Mt&&console.log("load audio",e);const t=await this.audioLoader.loadAsync(e).catch(console.error);if(this.destroyed)return;this._lastClipStartedLoading===e&&(this._lastClipStartedLoading=null),t&&this.createAudio(t)}else console.warn("Unsupported audio clip type",e);else this.shouldPlay=!0,this.createAudio()}play(e=void 0){!e&&this.clip&&(e=this.clip),e!==void 0&&typeof e!="string"&&!(e instanceof MediaStream)&&(A()&&console.warn("Called play on AudioSource with unknown argument type:",e+`
963
963
  Using the assigned clip instead:`,this.clip),e=this.clip);let t=!this.sound||e&&e!==this.clip;if(typeof e=="string"&&!this.audioLoader&&(t=!0),(e instanceof MediaStream||typeof e=="string")&&(this.clip=e),t){this.shouldPlay=!0,this.onNewClip(e);return}if(this.shouldPlay=!0,this._hasEnded=!1,Mt&&console.log("play",this.sound?.getVolume(),this.sound),this.sound&&!this.sound.isPlaying){const i=this.context.application.muted;i&&this.sound.setVolume(0),this.gameObject?.add(this.sound),this.clip instanceof MediaStream?(this.sound.setMediaStreamSource(this.clip),this._audioElement||(this._audioElement=document.createElement("audio"),this._audioElement.style.display="none"),this._audioElement.parentNode||this.context.domElement.shadowRoot?.append(this._audioElement),this._audioElement.srcObject=this.clip,this._audioElement.autoplay=!1):(this._audioElement&&this._audioElement.remove(),this.sound.play(i?.1:0))}}pause(){Mt&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&this.sound.source&&(this._lastContextTime=this.sound?.context.currentTime,this.sound.pause()),this._audioElement?.remove()}stop(){Mt&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.source&&(this._lastContextTime=this.sound?.context.currentTime,Mt&&console.log(this._lastContextTime),this.sound.stop()),this._audioElement?.remove()}_lastContextTime=0;_hasEnded=!0;_needUpdateSpatialDistanceSettings=!1;update(){this.helper&&(this.isPlaying&&this.helper.update(),this.helper.visible=this.isPlaying),this._needUpdateSpatialDistanceSettings&&this.applySpatialDistanceSettings(),this.sound&&!this.sound.isPlaying&&this.shouldPlay&&!this._hasEnded&&(this._hasEnded=!0,Mt&&console.log("Audio clip ended",this.clip),this.dispatchEvent(new CustomEvent("ended",{detail:this})))}};kn([u(URL)],Ki.prototype,"clip",2),kn([u()],Ki.prototype,"playOnAwake",2),kn([u()],Ki.prototype,"preload",2),kn([u()],Ki.prototype,"playInBackground",2),kn([u()],Ki.prototype,"loop",1),kn([u()],Ki.prototype,"spatialBlend",1),kn([u()],Ki.prototype,"minDistance",1),kn([u()],Ki.prototype,"maxDistance",1),kn([u()],Ki.prototype,"volume",1),kn([u()],Ki.prototype,"pitch",1),kn([u()],Ki.prototype,"rollOffMode",2);let Ai=Ki;const lE=v("debugavatar");class Ie extends R{static getAvatar(e){return e>=0&&e<Ie.instances.length?Ie.instances[e]:null}static instances=[];static onAvatarMarkerCreated(e){return Ie._onNewAvatarMarkerAdded.push(e),e}static onAvatarMarkerDestroyed(e){return Ie._onAvatarMarkerDestroyed.push(e),e}static _onNewAvatarMarkerAdded=[];static _onAvatarMarkerDestroyed=[];connectionId;avatar;awake(){Ie.instances.push(this),lE&&console.log(this);for(const e of Ie._onNewAvatarMarkerAdded)e({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){Ie.instances.splice(Ie.instances.indexOf(this),1);for(const e of Ie._onAvatarMarkerDestroyed)e({avatarMarker:this,gameObject:this.gameObject})}isLocalAvatar(){return this.connectionId===this.context.connection.connectionId}}class Ur{static Pois=[];static LastChangeTime=0;static Add(e,t,i=null){if(t){for(const n of this.Pois)if(n.obj===t)return;this.Pois.push({obj:t,avatar:i}),this.LastChangeTime=e.time.time}}static Remove(e,t){if(t){for(const i of this.Pois)if(i.obj===t){this.Pois.splice(this.Pois.indexOf(i),1),this.LastChangeTime=e?.time.time??W.Current?.time.time;return}}}}class cE{guid;position=new b}class $c extends R{set controlledTarget(e){this.target=e;const t=C.get("MoveRandom");if(t&&this.target){const i=x.getComponent(this.target,t);i&&i.destroy()}}target=null;avatar=null;_model=null;_targetModel=new cE;_currentTargetObject=null;_lastUpdateTime=0;_lookDuration=0;_lastPoiChangedTime=0;awake(){if(this.avatar=x.getComponentInParent(this.gameObject,Ie),this.avatar){const e=x.getComponentInParent(this.gameObject,Ie);this._model=new _g(this.context.connection,this.guid),e?.isLocalAvatar&&this._model.requestOwnership()}this.context.connection.beginListen("avatar-look-target-changed",e=>{this.target&&e&&e.guid===this.avatar?.guid&&ft(this.target,e.position)})}update(){if((!this.context.connection.isConnected||this._model?.hasOwnership)&&(Ur.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=Ur.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){const e=J(this._currentTargetObject);ft(this.target,e),this.context.connection.isConnected&&this.avatar&&(this.context.connection.send("avatar-look-target-changed",this._targetModel),this._targetModel.guid=this.avatar.guid,this._targetModel.position.copy(e))}}selectTarget(){if(this.context.time.time-this._lastUpdateTime>this._lookDuration){this._lastUpdateTime=this.context.time.time,this._lookDuration=Math.random()*.5+.2;const e=Ur.Pois;if(e.length>0){const t=e[Math.floor(Math.random()*e.length)];if(t&&t.obj){if(t.avatar&&t.avatar===this.avatar)return;this._currentTargetObject=t.obj}}}}}function Qw(o){const e=o;return!!(e.parser&&e.parser.json)}var Uu=(o=>(o[o.None=0]="None",o[o.DontExport=1]="DontExport",o))(Uu||{});function Yw(o){return o&&o.isComponent}const hE=Symbol("object"),Of=new ki(()=>new b,20);class Zw{_point;_normal;_tangentVelocity;distance;impulse;friction;get point(){return Of.get().set(this._point.x,this._point.y,this._point.z)}get normal(){return Of.get().set(this._normal.x,this._normal.y,this._normal.z)}get tangentVelocity(){return Of.get().set(this._tangentVelocity.x,this._tangentVelocity.y,this._tangentVelocity.z)}constructor(e,t,i,n,s,r){this._point=e,this.distance=t,this._normal=i,this.impulse=n,this.friction=s,this._tangentVelocity=r}}class Kw{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 Jw{object;collider;constructor(e,t){this.object=e,this.collider=t}}const De=v("debugnetworkingstreams");var Kn=(o=>(o.Connected="peer-user-connected",o.StreamReceived="receive-stream",o.StreamEnded="call-ended",o.Disconnected="peer-user-disconnected",o.UserJoined="user-joined",o))(Kn||{});class kf{type="call-ended";userId;direction;constructor(e,t){this.userId=e,this.direction=t}}class ex{type="receive-stream";userId;stream;target;constructor(e,t,i){this.userId=e,this.stream=t,this.target=i}}class dE{guid;peerId;dontSave=!0;constructor(e,t){this.guid=e.id,this.peerId=t}}var tx=(o=>(o.Incoming="incoming",o.Outgoing="outgoing",o))(tx||{});class uE extends Sm{peerId;userId;direction;call;get stream(){return this._stream}_stream=null;_isDisposed=!1;close(){this._isDisposed||(this._isDisposed=!0,this.call.close(),Jn(this._stream))}get isOpen(){return this.call.peerConnection?.connectionState==="connected"}get isOpening(){return this.call.peerConnection?.connectionState==="connecting"}get isClosed(){return!this.isOpen||this._isDisposed}constructor(e,t,i,n=null){super(),this.peerId=t.peer,this.userId=e,this.call=t,this.direction=i,this._stream=n,t.on("stream",s=>{if(De&&console.log("Receive stream",`
964
964
  Audio:`,s.getAudioTracks(),`
965
965
  Video:`,s.getVideoTracks()),this._stream=s,i==="incoming"){const r=new ex(e,s,this);this.dispatchEvent(r)}}),t.on("close",()=>{this.dispatchEvent(new kf(e,i))})}}function ix(o){return o=o.replace("a=fmtp:111 minptime=10;useinbandfec=1","a=fmtp:111 ptime=5;useinbandfec=1;stereo=1;maxplaybackrate=48000;maxaveragebitrat=128000;sprop-stereo=1"),o}class hs extends Sm{static instances=new Map;static getOrCreate(e,t){if(hs.instances.has(t))return hs.instances.get(t);const i=new hs(e,t);return hs.instances.set(t,i),i}getMyPeerId(){if(this.context.connection.connectionId)return this.getPeerIdFromUserId(this.context.connection.connectionId)}getPeerIdFromUserId(e){return this.id+"-"+e}getUserIdFromPeerId(e){return e.substring(this.id.length+1)}makeCall(e,t){if(!t?.id){De?console.warn("Can not make a call: mediastream has no id or is undefined"):console.debug("Can not make a call: mediastream has no id or is undefined");return}const i={metadata:{userId:this.context.connection.connectionId,streamId:t.id},sdpTransform:s=>ix(s)},n=this._peer?.call(e,t,i);if(n){const s=this.registerCall(n,"outgoing",t);return De&&console.warn(`\u{1F4DE} CALL ${e}`,`
@@ -1643,4 +1643,4 @@ Error:`,r),null}}updateColliderCollisionGroups(e){const t=e[Gt],i=e.membership;l
1643
1643
  justify-content: center;
1644
1644
  gap: .5rem;
1645
1645
  }
1646
- `),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.#o),wu(lf,{element:this.#t}),this.#s?.disconnect(),this.#s??=new MutationObserver(()=>this.#l()),this.#s.observe(this.#e,{attributes:!0}),X0&&console.log("Needle Button updated")}#l(){this.#e&&(this.#e.style.display==="none"?this.style.display="none":this.style.display==="none"&&(this.style.display=""))}#r=e=>{X0&&console.log("Needle Button clicked"),!e.defaultPrevented&&this.#e&&this.#e.click()}}typeof window<"u"&&!window.customElements.get(pS)&&window.customElements.define(pS,mS);const rd=v("debugavatar");class Q0{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(s=>s.layers.set(2))}}class gS{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 s=new Bn;i=x.instantiate(Ta(t,e.scene),s)}}else i=t;if(!i)return null;const n=this.findAvatar(i);return n.isValid?(rd&&console.log("[Custom Avatar] valid config",t,rd?n:""),n):(console.warn("[Custom Avatar] config isn't valid",t,rd?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(rd&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){const n=await fetch("./"+t);let s=null;if(n.ok){const r=await n.blob();r&&(s=await r.arrayBuffer())}return s?(await vn().parseSync(e,s,null,0))?.scene??null:null}const i=new Po;return ff(i,e),new Promise((n,s)=>{const r=this.avatarRegistryUrl+"/"+t;i.load(r,async a=>{await vn().createBuiltinComponents(e,r,a,null,void 0),n(a.scene)},a=>{rd&&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 s=this.findAvatarPart(i,["left","hand"]),r=this.findAvatarPart(i,["right","hand"]);if(!n){n=t;const a=new b;new Si().setFromObject(n).getSize(a);const l=Math.max(a.x,a.y,a.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+l+" meters! Should be < 0.3m"),l>.3&&n.scale.multiplyScalar(1/l*.3)}return new Q0(t,n,s,r)}findAvatarPart(e,t){const i=e.name.toLowerCase();let n=!0;for(const s of t){if(!n)break;i.indexOf(s)===-1&&(n=!1)}if(n)return e;if(e.children)for(const s of e.children){const r=this.findAvatarPart(s,t);if(r)return r}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}}class fS{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(e){}}class yS{}const DL=Object.freeze(Object.defineProperty({__proto__:null,ActionBuilder:ye,ActionCollection:Zx,ActionModel:wi,AlignmentConstraint:Bc,Animation:Bt,AnimationCurve:bh,AnimationExtension:ap,AnimationTrackHandler:Nh,Animator:bt,AnimatorController:un,Antialiasing:Sh,Attractor:Tl,AudioExtension:_a,AudioListener:Fo,AudioSource:Ai,AudioTrackHandler:ds,Avatar:js,AvatarBlink_Simple:zr,AvatarEyeLook_Rotation:Tf,AvatarLoader:gS,AvatarMarker:Ie,AvatarModel:Q0,Avatar_Brain_LookAt:$c,Avatar_MouthShapes:Hc,Avatar_MustacheShake:Rf,Avatar_POI:Ur,AxesHelper:nl,BaseUIComponent:hn,BasicIKConstraint:If,BehaviorExtension:Ty,BehaviorModel:Lt,BloomEffect:Ep,BoxCollider:Wu,BoxGizmo:Jr,BoxHelperComponent:Pt,Button:es,CallInfo:Bo,Camera:ui,CameraTargetReachedEvent:Vc,Canvas:Pl,CanvasGroup:Ns,CapsuleCollider:Uo,ChangeMaterialOnClick:by,ChangeTransformOnClick:Xr,CharacterController:Nr,CharacterControllerInput:No,ChromaticAberration:Ch,ClickThrough:Jp,ColorAdjustments:Xs,ColorBySpeedModule:Rl,ColorOverLifetimeModule:Sp,ContactShadows:qc,ControlTrackHandler:Gp,CursorFollow:ma,CustomBranding:Kr,Deletable:Ff,DeleteBox:lr,DepthOfField:An,DeviceFlag:Vu,DocumentExtension:fS,DragControls:$r,DropListener:Vo,Duplicatable:ty,EffectWrapper:Oh,EmissionModule:Yo,EmphasizeOnClick:yl,EnvironmentScene:Zp,EventList:de,EventListEvent:Iu,EventSystem:si,EventTrigger:Zu,FieldWithDefault:Px,FixedJoint:Qy,Fog:Ol,GltfExport:ay,GltfExportBox:sy,Gradient:ta,Graphic:dh,GraphicRaycaster:ju,GridHelper:kl,GridLayoutGroup:zy,GroundProjectedEnv:Yn,GroupActionModel:qr,HideOnStart:pn,HingeJoint:mh,HorizontalLayoutGroup:Uy,get HoverAnimation(){return go},Image:Bl,InheritVelocityModule:i0,InputField:E0,InstanceHandle:Ca,InstancingHandler:va,Interactable:Bf,Keyframe:bi,LODGroup:fh,LODModel:Ml,Light:yi,LimitVelocityOverLifetimeModule:ht,LogStats:jf,LookAt:T0,LookAtConstraint:jr,MainModule:Vt,MarkerTrackHandler:Hp,MaskableGraphic:uh,MeshCollider:Es,MeshRenderer:Zc,MinMaxCurve:Y,MinMaxGradient:ia,NeedleMenu:ro,NestedGltf:yh,Networking:Jy,NoiseModule:ve,ObjectRaycaster:Ti,OffsetConstraint:ea,OpenURL:Fl,OrbitControls:fe,Outline:Sl,Padding:Zr,ParticleBurst:xp,ParticleSubEmitter:n0,ParticleSystem:wh,ParticleSystemRenderer:rn,PhysicsExtension:Ay,PixelationEffect:kh,PlayAnimationOnClick:th,PlayAudioOnClick:Ls,PlayableDirector:da,PlayerColor:Ql,PointerEventData:md,PostProcessingHandler:v0,PreliminaryAction:bl,PreliminaryTrigger:ih,RawImage:Qp,Rect:o1,RectTransform:Rn,ReflectionProbe:Yc,RegisteredAnimationInfo:cr,RemoteSkybox:Bp,Renderer:Kt,RendererLightmap:Kf,Rigidbody:Ke,RotationBySpeedModule:sn,RotationOverLifetimeModule:Tn,SceneSwitcher:Ye,ScreenCapture:Ys,ScreenSpaceAmbientOcclusion:Zo,ScreenSpaceAmbientOcclusionN8:In,ScrollFollow:ts,SeeThrough:Jo,SetActiveOnClick:_y,ShadowCatcher:Lh,ShapeModule:t0,SharpeningEffect:Rh,SignalAsset:$p,SignalReceiver:zh,SignalReceiverEvent:Uh,SignalTrackHandler:Wh,Size:n1,SizeBySpeedModule:_i,SizeOverLifetimeModule:na,SkinnedMeshRenderer:Jf,SmoothFollow:Up,SpatialGrabRaycaster:ba,SpatialHtml:$h,SpatialTrigger:zp,SpatialTriggerReceiver:ho,SpectatorCamera:Np,SphereCollider:ol,SplineContainer:ha,SplineData:uo,SplineWalker:ln,Sprite:Ho,SpriteData:vl,SpriteRenderer:gi,SpriteSheet:_l,SubEmitterSystem:kp,SyncedCamera:x0,SyncedRoom:Ln,SyncedTransform:On,TapGestureTrigger:wy,TeleportTarget:up,TestRunner:P0,TestSimulateUserData:O0,Text:Wt,TextBuilder:By,TextExtension:fp,TextureSheetAnimationModule:$t,TiltShiftEffect:co,ToneMappingEffect:qs,TrailModule:Fe,TransformData:Ne,TransformGizmo:ua,TriggerBuilder:Nt,TriggerModel:or,UIRaycastUtils:wf,UIRootComponent:lh,USDZExporter:En,USDZText:Cl,USDZUIExtension:Vy,UsageMarker:Xc,VariantAction:fy,VelocityOverLifetimeModule:$e,VerticalLayoutGroup:Fy,VideoPlayer:ut,get ViewBox(){return nt},Vignette:aa,VisibilityAction:nh,Voip:Rs,Volume:Il,VolumeParameter:U,VolumeProfile:Mp,WebARCameraBackground:Qh,WebARSessionRoot:Ni,WebXR:pp,WebXRImageTracking:Yh,WebXRImageTrackingModel:ns,WebXRPlaneTracking:os,WebXRTrackedImage:Yl,XRControllerFollow:is,XRControllerModel:Go,XRControllerMovement:Li,XRFlag:Ji,XRRig:om,XRState:oi,__Ignore:yS},Symbol.toStringTag,{value:"Module"})),ad=v("debugmissingcamera");pe.registerCallback(ue.MissingCamera,o=>{ad&&console.warn("Creating missing camera");const e=o.context.scene,t=new ae;t.name="Default Fallback Camera",e.add(t);const i=new ui;if(i.sourceId=o.files?.[0]?.src??"unknown",i.fieldOfView=35,o.context.domElement.getAttribute("transparent")!=null)i.clearFlags=Fr.Uninitialized;else if(o.context.domElement.getAttribute("background-image")?.length||o.context.lightmaps.tryGetSkybox(i.sourceId))i.clearFlags=Fr.Skybox;else{if(i.clearFlags=Fr.SolidColor,!o.context.domElement.getAttribute("background-color")){let s="#efefef";typeof window!==void 0&&window.matchMedia("(prefers-color-scheme: dark)").matches&&(s="#1f1f1f"),e.background=new oe(s)}if(!e.environment){const s=new $C(o.context.renderer),r=new Zp("neutral");e.environment=s.fromScene(r,.025).texture}}const n=Mr(t,i,!0);return t.position.x=0,t.position.y=1,t.position.z=2,o.context.domElement?.cameraControls!=!1&&bS(o.context,n),n}),pe.registerCallback(ue.ContextCreated,o=>{if(!o.context.mainCamera){ad&&console.log("Will not auto-fit because a default camera exists");return}if(o.context.domElement?.cameraControls==!0){if(Zb(o.context.mainCamera)?.isCameraController==!0){ad&&console.log("Will not auto-fit because a camera controller exists");return}bS(o.context)}});function bS(o,e){e=e??o.mainCameraComponent;const t=e?.gameObject;if(ad&&console.log("Creating default camera controls",e?.name),t){const i=Oc(t,fe);i.sourceId=e?.sourceId??"unknown";const n=o.domElement.getAttribute("auto-rotate");i.autoRotate=n!="0"&&n?.toLowerCase()!="false";const s=Number.parseFloat(n||".5");i.autoRotateSpeed=isNaN(s)?.5:s,ad&&console.log("Auto-rotate",i.autoRotate,"speed:",i.autoRotateSpeed);const r=o.domElement.getAttribute("auto-fit");i.autoFit=r!=="0"&&r?.toLowerCase()!="false",i.autoTarget=!0}else console.warn("Missing camera object, can not add orbit controls")}pe.registerCallback(ue.ContextCreated,o=>{const e=o.context.domElement.getAttribute("autoplay");if(e!==void 0&&(e===""||e==="true"||e==="1")&&o.files)for(const t of o.files)x.foreachComponent(t.file.scene,i=>{if(i.enabled!==!1){if(i instanceof Bt&&i.playAutomatically||i instanceof bt||i instanceof da&&i.playOnAwake===!0)return!0;if(i instanceof Bt)return i.playAutomatically=!0,!0;if(i instanceof da)return i.playOnAwake=!0,!0}},!0)!==!0&&xs.autoplayAnimations(t.file)});var Y0;(o=>{function e(t,i=!1,n=.75){const s=new ha,r=1-D.clamp(n,0,1);return t.forEach((a,l)=>{const c=new b;l<t.length-1?c.subVectors(t[l+1],a).normalize().multiplyScalar(r):i&&t.length>1&&c.subVectors(t[0],a).normalize().multiplyScalar(r);const h=new uo;h.position.copy(a),h.tangentIn.copy(c),h.tangentOut.copy(c),s.addKnot(h)}),s.closed=i,s}o.createFromPoints=e})(Y0||(Y0={}));class jL extends xP{constructor(){super(new Worker(URL.createObjectURL(new Blob([`import '${new URL("./generateMeshBVH.worker-iyfPIK6R.js",import.meta.url).toString()}';`],{type:"text/javascript"})),{type:"module"})),this.name="GenerateMeshBVHWorker"}runTask(e,t,i={}){return new Promise((n,s)=>{if(t.getAttribute("position").isInterleavedBufferAttribute||t.index&&t.index.isInterleavedBufferAttribute)throw new Error("GenerateMeshBVHWorker: InterleavedBufferAttribute are not supported for the geometry attributes.");e.onerror=c=>{s(new Error(`[GenerateMeshBVHWorker] ${c.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=c=>{const{data:h}=c;if(h.error)s(new Error(h.error)),e.onmessage=null;else if(h.serialized){const{serialized:d,position:p}=h,m=SP.deserialize(d,t,{setIndex:!1}),f=Object.assign({setBoundingBox:!0},i);if(t.attributes.position.array=p,d.index)if(t.index)t.index.array=d.index;else{const g=new gt(d.index,1,!1);t.setIndex(g)}f.setBoundingBox&&(t.boundingBox=m.getBoundingBox(new Si)),i.onProgress&&i.onProgress(h.progress),n(m),e.onmessage=null}else i.onProgress&&i.onProgress(h.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(c=>c.buffer).filter(c=>typeof SharedArrayBuffer>"u"||!(c instanceof SharedArrayBuffer)))})}}const BL=Object.freeze(Object.defineProperty({__proto__:null,GenerateMeshBVHWorker:jL},Symbol.toStringTag,{value:"Module"}));export{hE as $physicsKey,ye as ActionBuilder,Zx as ActionCollection,wi as ActionModel,Jv as Addressables,Bc as AlignmentConstraint,Ka as AmbientMode,Bt as Animation,bh as AnimationCurve,ap as AnimationExtension,Nh as AnimationTrackHandler,xs as AnimationUtils,bt as Animator,Ps as AnimatorConditionMode,un as AnimatorController,bf as AnimatorControllerParameterType,Fc as AnimatorStateInfo,Sh as Antialiasing,jn as Application,sv as AssetDatabase,ne as AssetReference,Tl as Attractor,_a as AudioExtension,Fo as AudioListener,Ai as AudioSource,ds as AudioTrackHandler,js as Avatar,zr as AvatarBlink_Simple,Tf as AvatarEyeLook_Rotation,gS as AvatarLoader,Ie as AvatarMarker,Q0 as AvatarModel,$c as Avatar_Brain_LookAt,Hc as Avatar_MouthShapes,Rf as Avatar_MustacheShake,Ur as Avatar_POI,Ja as Axes,nl as AxesHelper,lg as BUILD_TIME,hn as BaseUIComponent,If as BasicIKConstraint,Ty as BehaviorExtension,Lt as BehaviorModel,Ir as BlobStorage,Ep as BloomEffect,Wu as BoxCollider,Jr as BoxGizmo,Pt as BoxHelperComponent,es as Button,Fn as ButtonsFactory,tx as CallDirection,Bo as CallInfo,ui as Camera,Vc as CameraTargetReachedEvent,Pl as Canvas,Ns as CanvasGroup,Uo as CapsuleCollider,by as ChangeMaterialOnClick,Xr as ChangeTransformOnClick,Nr as CharacterController,No as CharacterControllerInput,Ch as ChromaticAberration,ki as CircularBuffer,Fr as ClearFlags,Jp as ClickThrough,po as ClipExtrapolation,en as Collider,Kw as Collision,Tu as CollisionDetectionMode,Xs as ColorAdjustments,Rl as ColorBySpeedModule,Sp as ColorOverLifetimeModule,yR as Component,R as Component$1,eu as ComponentLifecycleEvents,DL as Components,$_ as ConnectionEvents,Zw as ContactPoint,qc as ContactShadows,W as Context,tR as ContextArgs,ue as ContextEvent,pe as ContextRegistry,Gp as ControlTrackHandler,ma as CursorFollow,Kr as CustomBranding,Re as CustomShader,bu as DefaultReflectionMode,Ff as Deletable,lr as DeleteBox,An as DepthOfField,Vu as DeviceFlag,L as DeviceUtilities,fS as DocumentExtension,$r as DragControls,zf as DragMode,Vo as DropListener,ty as Duplicatable,Oh as EffectWrapper,Yo as EmissionModule,yl as EmphasizeOnClick,fd as EngineLoadingView,Zp as EnvironmentScene,de as EventList,Iu as EventListEvent,si as EventSystem,Zu as EventTrigger,Px as FieldWithDefault,Sa as FileReference,tw as FileReferenceSerializer,IE as FileSpawnModel,cx as File_Event,Qy as FixedJoint,Ol as Fog,xe as FrameEvent,zd as GENERATOR,x as GameObject,F as Gizmos,ay as GltfExport,sy as GltfExportBox,ta as Gradient,dh as Graphic,ju as GraphicRaycaster,rr as Graphics,kl as GridHelper,zy as GridLayoutGroup,Yn as GroundProjectedEnv,qr as GroupActionModel,Uu as HideFlags,pn as HideOnStart,mh as HingeJoint,Uy as HorizontalLayoutGroup,Xk as HostData,go as HoverAnimation,Bl as Image,xa as ImageReference,ew as ImageReferenceSerializer,i0 as InheritVelocityModule,T_ as Input,ci as InputEventQueue,Te as InputEvents,E0 as InputField,Ca as InstanceHandle,va as InstancingHandler,dn as InstancingUtil,vv as InstantiateEvent,Dt as InstantiateIdProvider,Bn as InstantiateOptions,Bf as Interactable,Xh as InternalScreenshotUtils,yk as JoinedRoomResponse,rk as KeyEventArgs,bi as Keyframe,fh as LODGroup,Ml as LODModel,bk as LeftRoomResponse,yi as Light,cw as LightData,ht as LimitVelocityOverLifetimeModule,vL as LoadingElementOptions,jf as LogStats,Mi as LogType,T0 as LookAt,jr as LookAtConstraint,T as MODULES,Vt as MainModule,Hp as MarkerTrackHandler,k0 as MarkerType,uh as MaskableGraphic,D as Mathf,Es as MeshCollider,Zc as MeshRenderer,Y as MinMaxCurve,ia as MinMaxGradient,xc as NEEDLE_ENGINE_FEATURE_FLAGS,pc as NEKeyboardEvent,Ro as NEPointerEvent,mS as NeedleButtonElement,Wf as NeedleEngineModelLoader,$0 as NeedleEngineWebComponent,ro as NeedleMenu,Wd as NeedlePatchesKey,pg as NeedleXRController,Z as NeedleXRSession,q_ as NeedleXRSync,J_ as NeedleXRUtils,yh as NestedGltf,G_ as NetworkConnection,Kn as NetworkedStreamEvents,gd as NetworkedStreams,Jy as Networking,xv as NewInstanceModel,ve as NoiseModule,Ti as ObjectRaycaster,Cr as ObjectUtils,ea as OffsetConstraint,Id as OneEuroFilter,qm as OneEuroFilterXYZ,Fl as OpenURL,fe as OrbitControls,Sl as Outline,H_ as OwnershipEvent,_g as OwnershipModel,Da as PUBLIC_KEY,Zr as Padding,xp as ParticleBurst,n0 as ParticleSubEmitter,wh as ParticleSystem,Gs as ParticleSystemBaseBehaviour,rn as ParticleSystemRenderer,wp as ParticleSystemShapeType,hs as PeerHandle,W_ as PeerNetworking,ql as Physics,Ay as PhysicsExtension,_t as PhysicsMaterialCombine,kh as PixelationEffect,th as PlayAnimationOnClick,Ls as PlayAudioOnClick,da as PlayableDirector,Ql as PlayerColor,nn as PlayerState,t1 as PlayerStateEvent,ky as PlayerSync,ow as PlayerView,sw as PlayerViewManager,md as PointerEventData,$d as PointerType,it as PostProcessingEffect,dt as PostProcessingEffectOrder,v0 as PostProcessingHandler,bl as PreliminaryAction,ih as PreliminaryTrigger,As as PreviewHelper,Sr as PrimitiveType,le as Progress,Wm as PromiseAllWithErrors,Nm as PromiseErrorResult,se as RGBAColor,Zl as RapierPhysics,Qp as RawImage,vs as RaycastOptions,o1 as Rect,Rn as RectTransform,Yc as ReflectionProbe,cr as RegisteredAnimationInfo,Bp as RemoteSkybox,_o as RenderTexture,Hw as RenderTextureSerializer,Kt as Renderer,lw as RendererData,Kf as RendererLightmap,Ke as Rigidbody,Qe as RigidbodyConstraints,ie as RoomEvents,sn as RotationBySpeedModule,Tn as RotationOverLifetimeModule,Gu as SceneLightSettings,Ye as SceneSwitcher,Ys as ScreenCapture,Zo as ScreenSpaceAmbientOcclusion,In as ScreenSpaceAmbientOcclusionN8,ts as ScrollFollow,Jo as SeeThrough,wn as SendQueue,qg as SerializationContext,_y as SetActiveOnClick,Lh as ShadowCatcher,t0 as ShapeModule,Jw as ShapeOverlapResult,Rh as SharpeningEffect,$p as SignalAsset,zh as SignalReceiver,Uh as SignalReceiverEvent,Wh as SignalTrackHandler,n1 as Size,_i as SizeBySpeedModule,na as SizeOverLifetimeModule,Jf as SkinnedMeshRenderer,Up as SmoothFollow,ba as SpatialGrabRaycaster,$h as SpatialHtml,zp as SpatialTrigger,ho as SpatialTriggerReceiver,Np as SpectatorCamera,ol as SphereCollider,Rg as SphereIntersection,ha as SplineContainer,uo as SplineData,Y0 as SplineUtils,ln as SplineWalker,Ho as Sprite,vl as SpriteData,gi as SpriteRenderer,_l as SpriteSheet,SR as StateMachineBehaviour,kf as StreamEndedEvent,ex as StreamReceivedEvent,kp as SubEmitterSystem,x0 as SyncedCamera,Ln as SyncedRoom,On as SyncedTransform,wy as TapGestureTrigger,up as TeleportTarget,P0 as TestRunner,RL as TestSceneUtils,O0 as TestSimulateUserData,Wt as Text,By as TextBuilder,fp as TextExtension,$t as TextureSheetAnimationModule,co as TiltShiftEffect,dw as Time,qs as ToneMappingEffect,jl as TrackHandler,Ui as TrackType,Fe as TrailModule,Ne as TransformData,ua as TransformGizmo,Nt as TriggerBuilder,or as TriggerModel,C as TypeStore,wf as UIRaycastUtils,lh as UIRootComponent,ly as USDDocument,ot as USDObject,Lx as USDWriter,En as USDZExporter,jx as USDZExporter$1,Cl as USDZText,Vy as USDZUIExtension,Gw as UriSerializer,Xc as UsageMarker,_k as UserJoinedOrLeftRoomModel,_n as VERSION,fy as VariantAction,$e as VelocityOverLifetimeModule,Fy as VerticalLayoutGroup,ut as VideoPlayer,nt as ViewBox,Lo as ViewDevice,aa as Vignette,nh as VisibilityAction,Rs as Voip,Il as Volume,U as VolumeParameter,Mp as VolumeProfile,OM as WaitForFrames,iw as WaitForPromise,tf as WaitForSeconds,ls as Watch,Qh as WebARCameraBackground,Ni as WebARSessionRoot,pp as WebXR,sr as WebXRButtonFactory,Yh as WebXRImageTracking,ns as WebXRImageTrackingModel,os as WebXRPlaneTracking,Yl as WebXRTrackedImage,is as XRControllerFollow,Go as XRControllerModel,Li as XRControllerMovement,Ji as XRFlag,om as XRRig,oi as XRState,eo as XRStateFlag,yS as __Ignore,Bk as __internalNotifyObjectDestroyed,Mo as activeInHierarchyFieldName,Um as addAttributeChangeCallback,Cn as addComponent,QE as addCustomExtensionPlugin,Mr as addNewComponent,Nd as addPatch,cu as apply,gR as applyHMRChanges,Fv as applyPrototypeExtensions,wv as beginListenDestroy,Cv as beginListenInstantiate,fg as binaryIdentifierCasts,eR as build_scene_functions,vr as builtinComponentKeyName,V0 as calculateProgress01,eO as clearMessages,zR as colorSerializer,Mv as compareAssociation,Lu as componentSerializer,c_ as copyTexture,Fw as createMotion,hi as debugNet,gc as debugOwner,Nx as decompressGpuTexture,nc as deepClone,ko as delay,oc as delayForFrames,au as deserializeObject,Qi as destroy,Wv as destroyComponentInstance,hx as determineMimeTypeFromExtension,Pe as disposeObjectResources,Jn as disposeStream,uc as editorGuidKeyName,La as enableSpatialConsole,WR as euler,GR as eventListSerializer,AL as exportAsGLTF,Zg as findByGuid,Ga as findObjectOfType,Hv as findObjectsOfType,Eg as findResourceUsers,Nw as fitCamera,d_ as fitObjectIntoVolume,Ar as foreachComponent,mu as foreachComponentEnumerator,bO as forward,fw as generateQRCode,Sv as generateSeed,Xt as getBoundingBox,Zb as getCameraController,Rr as getComponent,Mc as getComponentInChildren,Rc as getComponentInParent,kc as getComponents,Ha as getComponentsInChildren,lu as getComponentsInParent,Ex as getFormattedDate,Ot as getIconElement,af as getIconTexture,vn as getLoader,Oc as getOrAddComponent,v as getParam,wO as getParentHierarchyPath,AP as getPath,pk as getPeerOptions,z_ as getPeerjsInstance,Uk as getResourceUserCount,e_ as getTempColor,ai as getTempQuaternion,B as getTempVector,tc as getUrlParams,h_ as getVisibleInCustomShadowRendering,o_ as getWorldDirection,eg as getWorldEuler,J as getWorldPosition,_e as getWorldQuaternion,Bd as getWorldRotation,Ge as getWorldScale,Do as hasCommercialLicense,Lc as hasIndieLicense,Au as hasPointerEventComponent,Qn as hasProLicense,f_ as hideDebugConsole,Wx as imageToCanvas,Qa as instantiate,wx as invokeLoadedImportPluginHooks,E_ as invokeXRSessionEnd,R_ as invokeXRSessionStart,Gv as isActiveInHierarchy,qa as isActiveSelf,FP as isAndroidDevice,l_ as isAnimationAction,Yw as isComponent,MP as isDebugMode,LP as isDesktop,Tr as isDestroyed,A as isDevEnvironment,jk as isDisposed,EL as isExporting,Qw as isGLTFModel,Lb as isHostedOnGlitch,yf as isHotReloadEnabled,pR as isHotReloading,jP as isIPad,yw as isIconElement,Vi as isLocalNetwork,zP as isMacOS,DP as isMobileDevice,UP as isMozillaXR,VP as isQuest,av as isResourceTrackingEnabled,WP as isSafari,du as isUsingInstancing,NP as isiOS,BP as isiPad,mL as loadAsset,L1 as loadPMREM,W0 as loadSync,Fd as logHierarchy,hO as lookAtInverse,rc as lookAtObject,dO as lookAtScreenPoint,EP as makeId,zb as makeIdFromRandomWords,Ii as makeNameSafe,qv as markAsInstancedRendered,$P as microphonePermissionsGranted,kP as nameof,jb as nameofFactory,$w as objectSerializer,sk as offXRSessionEnd,ok as offXRSessionStart,dR as onAfterRender,hR as onBeforeRender,lR as onClear,cR as onDestroy,Pw as onInitialized,Ou as onStart,Ow as onUpdate,ug as onXRSessionEnd,Vd as onXRSessionStart,nS as parseSync,u_ as placeOnSurface,ng as postprocessFBXMaterials,LR as prefix,Bb as pushState,TP as randomNumber,yg as registerBinaryType,Su as registerComponent,Xf as registerComponentExtension,an as registerCustomEffectType,Qf as registerExportExtensions,Xu as registerExtensions,Aw as registerHotReloadType,cg as registerLoader,Ov as registerPrefabProvider,Uv as registerPrototypeExtensions,Wg as registerType,Wb as relativePathPrefix,zm as removeAttributeChangeCallback,Yg as removeComponent,YE as removeCustomImportExtensionType,ik as removePatch,fs as resolveUrl,Nb as sanitizeString,Y1 as saveImage,ZI as screenshot,B0 as screenshot2,Ug as sendDestroyed,u as serializable,Av as serializeObject,Xe as serializeable,Ec as setActive,Gb as setAllowBalloonMessages,YP as setAllowOverlayMessages,Dd as setAutoFitEnabled,Xm as setCameraController,Qv as setDestroyed,RO as setDevEnvironment,cv as setDisposable,Xa as setDontDestroy,jm as setOrAddParamsToUrl,RP as setParam,ic as setParamWithoutReload,mk as setPeerOptions,Dk as setResourceTrackingEnabled,Bm as setState,ig as setVisibleInCustomShadowRendering,tg as setWorldEuler,ft as setWorldPosition,gr as setWorldPositionXYZ,bn as setWorldQuaternion,Jm as setWorldQuaternionXYZW,a_ as setWorldRotation,ac as setWorldRotationXYZ,Ia as setWorldScale,hc as showBalloonError,Ee as showBalloonMessage,be as showBalloonWarning,rg as showDebugConsole,cO as slerp,Cc as syncDestroy,Oy as syncField,zg as syncInstantiate,xO as textureToCanvas,Vb as toSourceId,F_ as tryCastBinary,ux as tryDetermineMimetypeFromBinary,dx as tryDetermineMimetypeFromURL,Ta as tryFindObject,U_ as tryGetGuid,Iw as unregisterHotReloadType,Fm as unwatchWrite,Kb as useForAutoFit,kt as validate,Td as watchWrite};
1646
+ `),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.#o),wu(lf,{element:this.#t}),this.#s?.disconnect(),this.#s??=new MutationObserver(()=>this.#l()),this.#s.observe(this.#e,{attributes:!0}),X0&&console.log("Needle Button updated")}#l(){this.#e&&(this.#e.style.display==="none"?this.style.display="none":this.style.display==="none"&&(this.style.display=""))}#r=e=>{X0&&console.log("Needle Button clicked"),!e.defaultPrevented&&this.#e&&this.#e.click()}}typeof window<"u"&&!window.customElements.get(pS)&&window.customElements.define(pS,mS);const rd=v("debugavatar");class Q0{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(s=>s.layers.set(2))}}class gS{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 s=new Bn;i=x.instantiate(Ta(t,e.scene),s)}}else i=t;if(!i)return null;const n=this.findAvatar(i);return n.isValid?(rd&&console.log("[Custom Avatar] valid config",t,rd?n:""),n):(console.warn("[Custom Avatar] config isn't valid",t,rd?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(rd&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){const n=await fetch("./"+t);let s=null;if(n.ok){const r=await n.blob();r&&(s=await r.arrayBuffer())}return s?(await vn().parseSync(e,s,null,0))?.scene??null:null}const i=new Po;return ff(i,e),new Promise((n,s)=>{const r=this.avatarRegistryUrl+"/"+t;i.load(r,async a=>{await vn().createBuiltinComponents(e,r,a,null,void 0),n(a.scene)},a=>{rd&&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 s=this.findAvatarPart(i,["left","hand"]),r=this.findAvatarPart(i,["right","hand"]);if(!n){n=t;const a=new b;new Si().setFromObject(n).getSize(a);const l=Math.max(a.x,a.y,a.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+l+" meters! Should be < 0.3m"),l>.3&&n.scale.multiplyScalar(1/l*.3)}return new Q0(t,n,s,r)}findAvatarPart(e,t){const i=e.name.toLowerCase();let n=!0;for(const s of t){if(!n)break;i.indexOf(s)===-1&&(n=!1)}if(n)return e;if(e.children)for(const s of e.children){const r=this.findAvatarPart(s,t);if(r)return r}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}}class fS{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(e){}}class yS{}const DL=Object.freeze(Object.defineProperty({__proto__:null,ActionBuilder:ye,ActionCollection:Zx,ActionModel:wi,AlignmentConstraint:Bc,Animation:Bt,AnimationCurve:bh,AnimationExtension:ap,AnimationTrackHandler:Nh,Animator:bt,AnimatorController:un,Antialiasing:Sh,Attractor:Tl,AudioExtension:_a,AudioListener:Fo,AudioSource:Ai,AudioTrackHandler:ds,Avatar:js,AvatarBlink_Simple:zr,AvatarEyeLook_Rotation:Tf,AvatarLoader:gS,AvatarMarker:Ie,AvatarModel:Q0,Avatar_Brain_LookAt:$c,Avatar_MouthShapes:Hc,Avatar_MustacheShake:Rf,Avatar_POI:Ur,AxesHelper:nl,BaseUIComponent:hn,BasicIKConstraint:If,BehaviorExtension:Ty,BehaviorModel:Lt,BloomEffect:Ep,BoxCollider:Wu,BoxGizmo:Jr,BoxHelperComponent:Pt,Button:es,CallInfo:Bo,Camera:ui,CameraTargetReachedEvent:Vc,Canvas:Pl,CanvasGroup:Ns,CapsuleCollider:Uo,ChangeMaterialOnClick:by,ChangeTransformOnClick:Xr,CharacterController:Nr,CharacterControllerInput:No,ChromaticAberration:Ch,ClickThrough:Jp,ColorAdjustments:Xs,ColorBySpeedModule:Rl,ColorOverLifetimeModule:Sp,ContactShadows:qc,ControlTrackHandler:Gp,CursorFollow:ma,CustomBranding:Kr,Deletable:Ff,DeleteBox:lr,DepthOfField:An,DeviceFlag:Vu,DocumentExtension:fS,DragControls:$r,DropListener:Vo,Duplicatable:ty,EffectWrapper:Oh,EmissionModule:Yo,EmphasizeOnClick:yl,EnvironmentScene:Zp,EventList:de,EventListEvent:Iu,EventSystem:si,EventTrigger:Zu,FieldWithDefault:Px,FixedJoint:Qy,Fog:Ol,GltfExport:ay,GltfExportBox:sy,Gradient:ta,Graphic:dh,GraphicRaycaster:ju,GridHelper:kl,GridLayoutGroup:zy,GroundProjectedEnv:Yn,GroupActionModel:qr,HideOnStart:pn,HingeJoint:mh,HorizontalLayoutGroup:Uy,get HoverAnimation(){return go},Image:Bl,InheritVelocityModule:i0,InputField:E0,InstanceHandle:Ca,InstancingHandler:va,Interactable:Bf,Keyframe:bi,LODGroup:fh,LODModel:Ml,Light:yi,LimitVelocityOverLifetimeModule:ht,LogStats:jf,LookAt:T0,LookAtConstraint:jr,MainModule:Vt,MarkerTrackHandler:Hp,MaskableGraphic:uh,MeshCollider:Es,MeshRenderer:Zc,MinMaxCurve:Y,MinMaxGradient:ia,NeedleMenu:ro,NestedGltf:yh,Networking:Jy,NoiseModule:ve,ObjectRaycaster:Ti,OffsetConstraint:ea,OpenURL:Fl,OrbitControls:fe,Outline:Sl,Padding:Zr,ParticleBurst:xp,ParticleSubEmitter:n0,ParticleSystem:wh,ParticleSystemRenderer:rn,PhysicsExtension:Ay,PixelationEffect:kh,PlayAnimationOnClick:th,PlayAudioOnClick:Ls,PlayableDirector:da,PlayerColor:Ql,PointerEventData:md,PostProcessingHandler:v0,PreliminaryAction:bl,PreliminaryTrigger:ih,RawImage:Qp,Rect:o1,RectTransform:Rn,ReflectionProbe:Yc,RegisteredAnimationInfo:cr,RemoteSkybox:Bp,Renderer:Kt,RendererLightmap:Kf,Rigidbody:Ke,RotationBySpeedModule:sn,RotationOverLifetimeModule:Tn,SceneSwitcher:Ye,ScreenCapture:Ys,ScreenSpaceAmbientOcclusion:Zo,ScreenSpaceAmbientOcclusionN8:In,ScrollFollow:ts,SeeThrough:Jo,SetActiveOnClick:_y,ShadowCatcher:Lh,ShapeModule:t0,SharpeningEffect:Rh,SignalAsset:$p,SignalReceiver:zh,SignalReceiverEvent:Uh,SignalTrackHandler:Wh,Size:n1,SizeBySpeedModule:_i,SizeOverLifetimeModule:na,SkinnedMeshRenderer:Jf,SmoothFollow:Up,SpatialGrabRaycaster:ba,SpatialHtml:$h,SpatialTrigger:zp,SpatialTriggerReceiver:ho,SpectatorCamera:Np,SphereCollider:ol,SplineContainer:ha,SplineData:uo,SplineWalker:ln,Sprite:Ho,SpriteData:vl,SpriteRenderer:gi,SpriteSheet:_l,SubEmitterSystem:kp,SyncedCamera:x0,SyncedRoom:Ln,SyncedTransform:On,TapGestureTrigger:wy,TeleportTarget:up,TestRunner:P0,TestSimulateUserData:O0,Text:Wt,TextBuilder:By,TextExtension:fp,TextureSheetAnimationModule:$t,TiltShiftEffect:co,ToneMappingEffect:qs,TrailModule:Fe,TransformData:Ne,TransformGizmo:ua,TriggerBuilder:Nt,TriggerModel:or,UIRaycastUtils:wf,UIRootComponent:lh,USDZExporter:En,USDZText:Cl,USDZUIExtension:Vy,UsageMarker:Xc,VariantAction:fy,VelocityOverLifetimeModule:$e,VerticalLayoutGroup:Fy,VideoPlayer:ut,get ViewBox(){return nt},Vignette:aa,VisibilityAction:nh,Voip:Rs,Volume:Il,VolumeParameter:U,VolumeProfile:Mp,WebARCameraBackground:Qh,WebARSessionRoot:Ni,WebXR:pp,WebXRImageTracking:Yh,WebXRImageTrackingModel:ns,WebXRPlaneTracking:os,WebXRTrackedImage:Yl,XRControllerFollow:is,XRControllerModel:Go,XRControllerMovement:Li,XRFlag:Ji,XRRig:om,XRState:oi,__Ignore:yS},Symbol.toStringTag,{value:"Module"})),ad=v("debugmissingcamera");pe.registerCallback(ue.MissingCamera,o=>{ad&&console.warn("Creating missing camera");const e=o.context.scene,t=new ae;t.name="Default Fallback Camera",e.add(t);const i=new ui;if(i.sourceId=o.files?.[0]?.src??"unknown",i.fieldOfView=35,o.context.domElement.getAttribute("transparent")!=null)i.clearFlags=Fr.Uninitialized;else if(o.context.domElement.getAttribute("background-image")?.length||o.context.lightmaps.tryGetSkybox(i.sourceId))i.clearFlags=Fr.Skybox;else{if(i.clearFlags=Fr.SolidColor,!o.context.domElement.getAttribute("background-color")){let s="#efefef";typeof window!==void 0&&window.matchMedia("(prefers-color-scheme: dark)").matches&&(s="#1f1f1f"),e.background=new oe(s)}if(!e.environment){const s=new $C(o.context.renderer),r=new Zp("neutral");e.environment=s.fromScene(r,.025).texture}}const n=Mr(t,i,!0);return t.position.x=0,t.position.y=1,t.position.z=2,o.context.domElement?.cameraControls!=!1&&bS(o.context,n),n}),pe.registerCallback(ue.ContextCreated,o=>{if(!o.context.mainCamera){ad&&console.log("Will not auto-fit because a default camera exists");return}if(o.context.domElement?.cameraControls==!0){if(Zb(o.context.mainCamera)?.isCameraController==!0){ad&&console.log("Will not auto-fit because a camera controller exists");return}bS(o.context)}});function bS(o,e){e=e??o.mainCameraComponent;const t=e?.gameObject;if(ad&&console.log("Creating default camera controls",e?.name),t){const i=Oc(t,fe);i.sourceId=e?.sourceId??"unknown";const n=o.domElement.getAttribute("auto-rotate");i.autoRotate=n!="0"&&n?.toLowerCase()!="false";const s=Number.parseFloat(n||".5");i.autoRotateSpeed=isNaN(s)?.5:s,ad&&console.log("Auto-rotate",i.autoRotate,"speed:",i.autoRotateSpeed);const r=o.domElement.getAttribute("auto-fit");i.autoFit=r!=="0"&&r?.toLowerCase()!="false",i.autoTarget=!0}else console.warn("Missing camera object, can not add orbit controls")}pe.registerCallback(ue.ContextCreated,o=>{const e=o.context.domElement.getAttribute("autoplay");if(e!==void 0&&(e===""||e==="true"||e==="1")&&o.files)for(const t of o.files)x.foreachComponent(t.file.scene,i=>{if(i.enabled!==!1){if(i instanceof Bt&&i.playAutomatically||i instanceof bt||i instanceof da&&i.playOnAwake===!0)return!0;if(i instanceof Bt)return i.playAutomatically=!0,!0;if(i instanceof da)return i.playOnAwake=!0,!0}},!0)!==!0&&xs.autoplayAnimations(t.file)});var Y0;(o=>{function e(t,i=!1,n=.75){const s=new ha,r=1-D.clamp(n,0,1);return t.forEach((a,l)=>{const c=new b;l<t.length-1?c.subVectors(t[l+1],a).normalize().multiplyScalar(r):i&&t.length>1&&c.subVectors(t[0],a).normalize().multiplyScalar(r);const h=new uo;h.position.copy(a),h.tangentIn.copy(c),h.tangentOut.copy(c),s.addKnot(h)}),s.closed=i,s}o.createFromPoints=e})(Y0||(Y0={}));class jL extends xP{constructor(){super(new Worker(URL.createObjectURL(new Blob([`import '${new URL("./generateMeshBVH.worker-iyfPIK6R.js",import.meta.url).toString()}';`],{type:"text/javascript"})),{type:"module"})),this.name="GenerateMeshBVHWorker"}runTask(e,t,i={}){return new Promise((n,s)=>{if(t.getAttribute("position").isInterleavedBufferAttribute||t.index&&t.index.isInterleavedBufferAttribute)throw new Error("GenerateMeshBVHWorker: InterleavedBufferAttribute are not supported for the geometry attributes.");e.onerror=c=>{s(new Error(`[GenerateMeshBVHWorker] ${c.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=c=>{const{data:h}=c;if(h.error)s(new Error(h.error)),e.onmessage=null;else if(h.serialized){const{serialized:d,position:p}=h,m=SP.deserialize(d,t,{setIndex:!1}),f=Object.assign({setBoundingBox:!0},i);if(t.attributes.position.array=p,d.index)if(t.index)t.index.array=d.index;else{const g=new gt(d.index,1,!1);t.setIndex(g)}f.setBoundingBox&&(t.boundingBox=m.getBoundingBox(new Si)),i.onProgress&&i.onProgress(h.progress),n(m),e.onmessage=null}else i.onProgress&&i.onProgress(h.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(c=>c.buffer).filter(c=>typeof SharedArrayBuffer>"u"||!(c instanceof SharedArrayBuffer)))})}}const BL=Object.freeze(Object.defineProperty({__proto__:null,GenerateMeshBVHWorker:jL},Symbol.toStringTag,{value:"Module"}));export{hE as $physicsKey,ye as ActionBuilder,Zx as ActionCollection,wi as ActionModel,Jv as Addressables,Bc as AlignmentConstraint,Ka as AmbientMode,Bt as Animation,bh as AnimationCurve,ap as AnimationExtension,Nh as AnimationTrackHandler,xs as AnimationUtils,bt as Animator,Ps as AnimatorConditionMode,un as AnimatorController,bf as AnimatorControllerParameterType,Fc as AnimatorStateInfo,Sh as Antialiasing,jn as Application,sv as AssetDatabase,ne as AssetReference,Tl as Attractor,_a as AudioExtension,Fo as AudioListener,Ai as AudioSource,ds as AudioTrackHandler,js as Avatar,zr as AvatarBlink_Simple,Tf as AvatarEyeLook_Rotation,gS as AvatarLoader,Ie as AvatarMarker,Q0 as AvatarModel,$c as Avatar_Brain_LookAt,Hc as Avatar_MouthShapes,Rf as Avatar_MustacheShake,Ur as Avatar_POI,Ja as Axes,nl as AxesHelper,lg as BUILD_TIME,hn as BaseUIComponent,If as BasicIKConstraint,Ty as BehaviorExtension,Lt as BehaviorModel,Ir as BlobStorage,Ep as BloomEffect,Wu as BoxCollider,Jr as BoxGizmo,Pt as BoxHelperComponent,es as Button,Fn as ButtonsFactory,tx as CallDirection,Bo as CallInfo,ui as Camera,Vc as CameraTargetReachedEvent,Pl as Canvas,Ns as CanvasGroup,Uo as CapsuleCollider,by as ChangeMaterialOnClick,Xr as ChangeTransformOnClick,Nr as CharacterController,No as CharacterControllerInput,Ch as ChromaticAberration,ki as CircularBuffer,Fr as ClearFlags,Jp as ClickThrough,po as ClipExtrapolation,en as Collider,Kw as Collision,Tu as CollisionDetectionMode,Xs as ColorAdjustments,Rl as ColorBySpeedModule,Sp as ColorOverLifetimeModule,yR as Component,R as Component$1,eu as ComponentLifecycleEvents,DL as Components,$_ as ConnectionEvents,Zw as ContactPoint,qc as ContactShadows,W as Context,tR as ContextArgs,ue as ContextEvent,pe as ContextRegistry,Gp as ControlTrackHandler,ma as CursorFollow,Kr as CustomBranding,Re as CustomShader,bu as DefaultReflectionMode,Ff as Deletable,lr as DeleteBox,An as DepthOfField,Vu as DeviceFlag,L as DeviceUtilities,fS as DocumentExtension,$r as DragControls,zf as DragMode,Vo as DropListener,ty as Duplicatable,Oh as EffectWrapper,Yo as EmissionModule,yl as EmphasizeOnClick,fd as EngineLoadingView,Zp as EnvironmentScene,de as EventList,Iu as EventListEvent,si as EventSystem,Zu as EventTrigger,Px as FieldWithDefault,Sa as FileReference,tw as FileReferenceSerializer,IE as FileSpawnModel,cx as File_Event,Qy as FixedJoint,Ol as Fog,xe as FrameEvent,zd as GENERATOR,x as GameObject,F as Gizmos,ay as GltfExport,sy as GltfExportBox,ta as Gradient,dh as Graphic,ju as GraphicRaycaster,rr as Graphics,kl as GridHelper,zy as GridLayoutGroup,Yn as GroundProjectedEnv,qr as GroupActionModel,Uu as HideFlags,pn as HideOnStart,mh as HingeJoint,Uy as HorizontalLayoutGroup,Xk as HostData,go as HoverAnimation,Bl as Image,xa as ImageReference,ew as ImageReferenceSerializer,i0 as InheritVelocityModule,T_ as Input,ci as InputEventQueue,Te as InputEvents,E0 as InputField,Ca as InstanceHandle,va as InstancingHandler,dn as InstancingUtil,vv as InstantiateEvent,Dt as InstantiateIdProvider,Bn as InstantiateOptions,Bf as Interactable,Xh as InternalScreenshotUtils,yk as JoinedRoomResponse,rk as KeyEventArgs,bi as Keyframe,fh as LODGroup,Ml as LODModel,bk as LeftRoomResponse,yi as Light,cw as LightData,ht as LimitVelocityOverLifetimeModule,vL as LoadingElementOptions,jf as LogStats,Mi as LogType,T0 as LookAt,jr as LookAtConstraint,T as MODULES,Vt as MainModule,Hp as MarkerTrackHandler,k0 as MarkerType,uh as MaskableGraphic,D as Mathf,Es as MeshCollider,Zc as MeshRenderer,Y as MinMaxCurve,ia as MinMaxGradient,xc as NEEDLE_ENGINE_FEATURE_FLAGS,pc as NEKeyboardEvent,Ro as NEPointerEvent,mS as NeedleButtonElement,Wf as NeedleEngineModelLoader,$0 as NeedleEngineWebComponent,ro as NeedleMenu,Wd as NeedlePatchesKey,pg as NeedleXRController,Z as NeedleXRSession,q_ as NeedleXRSync,J_ as NeedleXRUtils,yh as NestedGltf,G_ as NetworkConnection,Kn as NetworkedStreamEvents,gd as NetworkedStreams,Jy as Networking,xv as NewInstanceModel,ve as NoiseModule,Ti as ObjectRaycaster,Cr as ObjectUtils,ea as OffsetConstraint,Id as OneEuroFilter,qm as OneEuroFilterXYZ,Fl as OpenURL,fe as OrbitControls,Sl as Outline,H_ as OwnershipEvent,_g as OwnershipModel,Da as PUBLIC_KEY,Zr as Padding,xp as ParticleBurst,n0 as ParticleSubEmitter,wh as ParticleSystem,Gs as ParticleSystemBaseBehaviour,rn as ParticleSystemRenderer,wp as ParticleSystemShapeType,hs as PeerHandle,W_ as PeerNetworking,ql as Physics,Ay as PhysicsExtension,_t as PhysicsMaterialCombine,kh as PixelationEffect,th as PlayAnimationOnClick,Ls as PlayAudioOnClick,da as PlayableDirector,Ql as PlayerColor,nn as PlayerState,t1 as PlayerStateEvent,ky as PlayerSync,ow as PlayerView,sw as PlayerViewManager,md as PointerEventData,$d as PointerType,it as PostProcessingEffect,dt as PostProcessingEffectOrder,v0 as PostProcessingHandler,bl as PreliminaryAction,ih as PreliminaryTrigger,As as PreviewHelper,Sr as PrimitiveType,le as Progress,Wm as PromiseAllWithErrors,Nm as PromiseErrorResult,se as RGBAColor,Zl as RapierPhysics,Qp as RawImage,vs as RaycastOptions,o1 as Rect,Rn as RectTransform,Yc as ReflectionProbe,cr as RegisteredAnimationInfo,Bp as RemoteSkybox,_o as RenderTexture,Hw as RenderTextureSerializer,Kt as Renderer,lw as RendererData,Kf as RendererLightmap,Ke as Rigidbody,Qe as RigidbodyConstraints,ie as RoomEvents,sn as RotationBySpeedModule,Tn as RotationOverLifetimeModule,Gu as SceneLightSettings,Ye as SceneSwitcher,Ys as ScreenCapture,Zo as ScreenSpaceAmbientOcclusion,In as ScreenSpaceAmbientOcclusionN8,ts as ScrollFollow,Jo as SeeThrough,wn as SendQueue,qg as SerializationContext,_y as SetActiveOnClick,Lh as ShadowCatcher,t0 as ShapeModule,Jw as ShapeOverlapResult,Rh as SharpeningEffect,$p as SignalAsset,zh as SignalReceiver,Uh as SignalReceiverEvent,Wh as SignalTrackHandler,n1 as Size,_i as SizeBySpeedModule,na as SizeOverLifetimeModule,Jf as SkinnedMeshRenderer,Up as SmoothFollow,ba as SpatialGrabRaycaster,$h as SpatialHtml,zp as SpatialTrigger,ho as SpatialTriggerReceiver,Np as SpectatorCamera,ol as SphereCollider,Rg as SphereIntersection,ha as SplineContainer,uo as SplineData,Y0 as SplineUtils,ln as SplineWalker,Ho as Sprite,vl as SpriteData,gi as SpriteRenderer,_l as SpriteSheet,SR as StateMachineBehaviour,kf as StreamEndedEvent,ex as StreamReceivedEvent,kp as SubEmitterSystem,x0 as SyncedCamera,Ln as SyncedRoom,On as SyncedTransform,wy as TapGestureTrigger,up as TeleportTarget,P0 as TestRunner,RL as TestSceneUtils,O0 as TestSimulateUserData,Wt as Text,By as TextBuilder,fp as TextExtension,$t as TextureSheetAnimationModule,co as TiltShiftEffect,dw as Time,qs as ToneMappingEffect,jl as TrackHandler,Ui as TrackType,Fe as TrailModule,Ne as TransformData,ua as TransformGizmo,Nt as TriggerBuilder,or as TriggerModel,C as TypeStore,wf as UIRaycastUtils,lh as UIRootComponent,ly as USDDocument,ot as USDObject,Lx as USDWriter,jx as USDZExporter,En as USDZExporter$1,Cl as USDZText,Vy as USDZUIExtension,Gw as UriSerializer,Xc as UsageMarker,_k as UserJoinedOrLeftRoomModel,_n as VERSION,fy as VariantAction,$e as VelocityOverLifetimeModule,Fy as VerticalLayoutGroup,ut as VideoPlayer,nt as ViewBox,Lo as ViewDevice,aa as Vignette,nh as VisibilityAction,Rs as Voip,Il as Volume,U as VolumeParameter,Mp as VolumeProfile,OM as WaitForFrames,iw as WaitForPromise,tf as WaitForSeconds,ls as Watch,Qh as WebARCameraBackground,Ni as WebARSessionRoot,pp as WebXR,sr as WebXRButtonFactory,Yh as WebXRImageTracking,ns as WebXRImageTrackingModel,os as WebXRPlaneTracking,Yl as WebXRTrackedImage,is as XRControllerFollow,Go as XRControllerModel,Li as XRControllerMovement,Ji as XRFlag,om as XRRig,oi as XRState,eo as XRStateFlag,yS as __Ignore,Bk as __internalNotifyObjectDestroyed,Mo as activeInHierarchyFieldName,Um as addAttributeChangeCallback,Cn as addComponent,QE as addCustomExtensionPlugin,Mr as addNewComponent,Nd as addPatch,cu as apply,gR as applyHMRChanges,Fv as applyPrototypeExtensions,wv as beginListenDestroy,Cv as beginListenInstantiate,fg as binaryIdentifierCasts,eR as build_scene_functions,vr as builtinComponentKeyName,V0 as calculateProgress01,eO as clearMessages,zR as colorSerializer,Mv as compareAssociation,Lu as componentSerializer,c_ as copyTexture,Fw as createMotion,hi as debugNet,gc as debugOwner,Nx as decompressGpuTexture,nc as deepClone,ko as delay,oc as delayForFrames,au as deserializeObject,Qi as destroy,Wv as destroyComponentInstance,hx as determineMimeTypeFromExtension,Pe as disposeObjectResources,Jn as disposeStream,uc as editorGuidKeyName,La as enableSpatialConsole,WR as euler,GR as eventListSerializer,AL as exportAsGLTF,Zg as findByGuid,Ga as findObjectOfType,Hv as findObjectsOfType,Eg as findResourceUsers,Nw as fitCamera,d_ as fitObjectIntoVolume,Ar as foreachComponent,mu as foreachComponentEnumerator,bO as forward,fw as generateQRCode,Sv as generateSeed,Xt as getBoundingBox,Zb as getCameraController,Rr as getComponent,Mc as getComponentInChildren,Rc as getComponentInParent,kc as getComponents,Ha as getComponentsInChildren,lu as getComponentsInParent,Ex as getFormattedDate,Ot as getIconElement,af as getIconTexture,vn as getLoader,Oc as getOrAddComponent,v as getParam,wO as getParentHierarchyPath,AP as getPath,pk as getPeerOptions,z_ as getPeerjsInstance,Uk as getResourceUserCount,e_ as getTempColor,ai as getTempQuaternion,B as getTempVector,tc as getUrlParams,h_ as getVisibleInCustomShadowRendering,o_ as getWorldDirection,eg as getWorldEuler,J as getWorldPosition,_e as getWorldQuaternion,Bd as getWorldRotation,Ge as getWorldScale,Do as hasCommercialLicense,Lc as hasIndieLicense,Au as hasPointerEventComponent,Qn as hasProLicense,f_ as hideDebugConsole,Wx as imageToCanvas,Qa as instantiate,wx as invokeLoadedImportPluginHooks,E_ as invokeXRSessionEnd,R_ as invokeXRSessionStart,Gv as isActiveInHierarchy,qa as isActiveSelf,FP as isAndroidDevice,l_ as isAnimationAction,Yw as isComponent,MP as isDebugMode,LP as isDesktop,Tr as isDestroyed,A as isDevEnvironment,jk as isDisposed,EL as isExporting,Qw as isGLTFModel,Lb as isHostedOnGlitch,yf as isHotReloadEnabled,pR as isHotReloading,jP as isIPad,yw as isIconElement,Vi as isLocalNetwork,zP as isMacOS,DP as isMobileDevice,UP as isMozillaXR,VP as isQuest,av as isResourceTrackingEnabled,WP as isSafari,du as isUsingInstancing,NP as isiOS,BP as isiPad,mL as loadAsset,L1 as loadPMREM,W0 as loadSync,Fd as logHierarchy,hO as lookAtInverse,rc as lookAtObject,dO as lookAtScreenPoint,EP as makeId,zb as makeIdFromRandomWords,Ii as makeNameSafe,qv as markAsInstancedRendered,$P as microphonePermissionsGranted,kP as nameof,jb as nameofFactory,$w as objectSerializer,sk as offXRSessionEnd,ok as offXRSessionStart,dR as onAfterRender,hR as onBeforeRender,lR as onClear,cR as onDestroy,Pw as onInitialized,Ou as onStart,Ow as onUpdate,ug as onXRSessionEnd,Vd as onXRSessionStart,nS as parseSync,u_ as placeOnSurface,ng as postprocessFBXMaterials,LR as prefix,Bb as pushState,TP as randomNumber,yg as registerBinaryType,Su as registerComponent,Xf as registerComponentExtension,an as registerCustomEffectType,Qf as registerExportExtensions,Xu as registerExtensions,Aw as registerHotReloadType,cg as registerLoader,Ov as registerPrefabProvider,Uv as registerPrototypeExtensions,Wg as registerType,Wb as relativePathPrefix,zm as removeAttributeChangeCallback,Yg as removeComponent,YE as removeCustomImportExtensionType,ik as removePatch,fs as resolveUrl,Nb as sanitizeString,Y1 as saveImage,ZI as screenshot,B0 as screenshot2,Ug as sendDestroyed,u as serializable,Av as serializeObject,Xe as serializeable,Ec as setActive,Gb as setAllowBalloonMessages,YP as setAllowOverlayMessages,Dd as setAutoFitEnabled,Xm as setCameraController,Qv as setDestroyed,RO as setDevEnvironment,cv as setDisposable,Xa as setDontDestroy,jm as setOrAddParamsToUrl,RP as setParam,ic as setParamWithoutReload,mk as setPeerOptions,Dk as setResourceTrackingEnabled,Bm as setState,ig as setVisibleInCustomShadowRendering,tg as setWorldEuler,ft as setWorldPosition,gr as setWorldPositionXYZ,bn as setWorldQuaternion,Jm as setWorldQuaternionXYZW,a_ as setWorldRotation,ac as setWorldRotationXYZ,Ia as setWorldScale,hc as showBalloonError,Ee as showBalloonMessage,be as showBalloonWarning,rg as showDebugConsole,cO as slerp,Cc as syncDestroy,Oy as syncField,zg as syncInstantiate,xO as textureToCanvas,Vb as toSourceId,F_ as tryCastBinary,ux as tryDetermineMimetypeFromBinary,dx as tryDetermineMimetypeFromURL,Ta as tryFindObject,U_ as tryGetGuid,Iw as unregisterHotReloadType,Fm as unwatchWrite,Kb as useForAutoFit,kt as validate,Td as watchWrite};