import{n as e}from"./rolldown-runtime.CYVBeYYp.js";import{A as t,Ar as n,Bt as r,F as i,Fr as a,Ft as o,Nt as s,On as c,Rr as l,S as u,St as ee,Xt as te,Zt as ne,_ as re,c as ie,fn as d,gn as f,gr as ae,hn as oe,in as se,tt as ce,wn as le,x as p}from"./three@0.169.19.js";import{$ as ue,$a as de,$i as fe,A as pe,Br as me,C as he,Ci as ge,Cn as _e,D as ve,Da as ye,Di as be,Dn as xe,Dt as Se,E as Ce,En as we,G as Te,Gi as Ee,Gr as De,Gt as Oe,H as m,Hn as ke,Ho as Ae,Ii as je,J as Me,Ja as Ne,Ji as Pe,Jr as Fe,Ka as h,Kr as Ie,L as Le,La as Re,Lr as ze,M as Be,Mi as Ve,Na as He,O as Ue,Oi as We,On as Ge,Ot as Ke,P as qe,Pi as Je,Pn as Ye,Q as Xe,Qi as Ze,Ro as Qe,S as $e,Si as et,T as tt,Ti as nt,Tn as rt,Tt as it,Ua as g,Uo as at,Ut as ot,V as st,Vn as ct,Wi as lt,Wo as ut,X as _,Xa as dt,Xr as ft,Y as pt,Yr as mt,Z as ht,_ as gt,_a as v,_n as _t,a as vt,ai as yt,b as bt,ba as y,bi as xt,co as b,ct as x,d as St,dn as S,eo as C,f as Ct,fn as wt,g as Tt,gi as Et,gr as w,h as Dt,ht as Ot,i as kt,j as At,ja as jt,ji as Mt,jo as Nt,jt as Pt,k as Ft,kn as It,l as Lt,n as Rt,na as zt,o as Bt,ot as Vt,p as Ht,q as Ut,qr as T,r as Wt,ra as E,s as Gt,st as Kt,t as qt,ti as D,u as Jt,un as O,v as Yt,va as k,vi as Xt,w as Zt,wi as Qt,wn as $t,x as en,xi as tn,y as nn,yi as rn,za as an}from"./needle-engine-ui.B3WhUziG.js";import{l as on}from"./three-examples.extras@0.169.19.js";import{C as sn,S as A,n as cn,t as ln}from"./three-examples@0.169.19.js";import{$ as un,A as dn,B as fn,Bt as pn,C as mn,Ct as hn,D as gn,Dt as _n,E as vn,Et as yn,F as bn,G as xn,Gt as Sn,H as Cn,I as wn,It as Tn,J as En,Jt as Dn,K as On,Kt as kn,L as An,Nt as jn,O as Mn,Ot as Nn,P as Pn,Q as Fn,Qt as In,R as Ln,Rt as Rn,S as zn,St as Bn,T as Vn,U as Hn,Ut as Un,V as Wn,Vt as Gn,W as Kn,Wt as qn,X as Jn,Xt as Yn,Y as Xn,Z as Zn,Zt as Qn,_ as $n,_t as er,a as tr,at as nr,b as rr,bt as ir,cn as ar,d as or,et as sr,f as cr,fn as lr,g as ur,h as dr,i as fr,it as pr,k as mr,kt as hr,ln as gr,m as _r,mn as vr,n as yr,nt as br,o as xr,ot as Sr,p as Cr,pn as wr,q as Tr,qt as Er,r as Dr,rt as Or,sn as kr,t as Ar,tt as jr,v as Mr,vt as Nr,w as Pr,wt as Fr,x as Ir,xt as Lr,y as Rr,yt as zr,z as Br,zt as Vr}from"./needle-engine-webxr.XIy9opUR.js";import{A as Hr,B as Ur,C as Wr,Ct as Gr,D as Kr,E as qr,Et as Jr,F as Yr,G as Xr,H as Zr,I as Qr,K as $r,L as ei,M as ti,Mt as ni,N as ri,Nt as ii,O as ai,P as oi,Q as si,R as ci,S as li,St as ui,T as di,Tt as fi,U as pi,V as mi,W as hi,X as gi,_ as _i,_t as vi,a as yi,at as bi,b as xi,bt as Si,c as Ci,ct as wi,d as Ti,dt as Ei,f as Di,ft as Oi,g as ki,gt as Ai,h as ji,ht as Mi,i as Ni,it as Pi,j as Fi,jt as Ii,k as Li,l as Ri,lt as zi,m as Bi,mt as Vi,n as Hi,nt as Ui,o as Wi,ot as Gi,p as Ki,pt as qi,q as Ji,r as Yi,s as Xi,st as Zi,t as Qi,u as $i,ut as ea,v as ta,vt as na,w as ra,wt as ia,x as aa,xt as oa,y as sa,yt as ca,z as la}from"./needle-engine.extras.BMGdeUIm.js";import{C as ua,D as da,E as fa,S as pa,T as ma,a as ha,b as ga,c as _a,d as va,f as ya,g as ba,h as xa,i as Sa,l as Ca,m as wa,o as Ta,p as Ea,r as Da,s as Oa,t as ka,u as Aa,v as ja,w as Ma,x as Na,y as Pa}from"./needle-engine-particles.W2HGH_-A.js";import{a as Fa,c as Ia,d as La,f as Ra,g as za,h as Ba,i as Va,l as Ha,m as Ua,n as Wa,o as Ga,p as Ka,r as qa,s as Ja,t as Ya,u as Xa,y as Za}from"./needle-engine.extras.BWlo-D5V.js";import{a as Qa,t as $a}from"./three-mesh-bvh.B-oXEGo2.js";var j=void 0,M=null,N=null,P=!1,eo=null,to=`terminal`;b(`console`)&&ro();var no=Symbol(`consoleParent`);function ro(){if(j){j.showSwitch();return}uo()}function io(){j&&(j.hide(),j.hideSwitch())}function ao(){eo||=setInterval(so,500)}var oo=0;function so(){let e=dt(),t=e!==oo;oo=e,t&&co()}function co(){ro(),N&&(N.setAttribute(`error`,`true`),N.innerText=`🤬`)}function lo(){N&&(N.removeAttribute(`error`),N.innerText=to)}function uo(e=!1){if(j!==void 0||P)return;P=!0;let t=document.createElement(`script`);t.onload=()=>{if(!globalThis.VConsole){console.warn(`🌵 Debug console failed to load.`),P=!1,j=null;return}P=!1,ao(),j=new VConsole({pluginOrder:[`default`,`needle-console`]});let t=globalThis[`needle:codegen_files`];if(t&&t.length>0&&j.addPlugin(fo()),j.addPlugin(bo()),j.addPlugin(xo()),M=No(),M&&(M[no]=M.parentElement,M.style.position=`absolute`,M.style.zIndex=(2**53-1).toString()),j.setSwitchPosition(20,30),N=Mo(),N){N.innerText=to,N.addEventListener(`click`,lo);let t=document.createElement(`style`);t.innerHTML=`
                #__vconsole .vc-switch {
                    border: 1px solid rgba(255, 255, 255, .1);
                    border-radius: 50%;
                    width: 40px;
                    height: 40px;
                    padding: 0;
                    line-height: 40px;
                    font-size: ${40*.4}px;
                    text-align: center;
                    background: #ffffff5c;
                    backdrop-filter: blur(16px);
                    -webkit-backdrop-filter: blur(16px);
                    user-select: none;
                    pointer-events: auto;
                    transition: transform .2s ease-in-out;
                    box-shadow: 0px 7px 0.5rem 0px rgb(0 0 0 / 6%), inset 0px 0px 1.3rem rgba(0,0,0,.05);

                    font-family: 'Material Symbols Outlined';
                    color: black;
                    font-size: 2.3em;
                    font-weight: 100;
                }
                #__vconsole .vc-switch:hover {
                    cursor: pointer;
                    transform: scale(1.1);
                    transition: transform .1s ease-in-out, background .1s linear;
                    background: rgba(245, 245, 245, .8);
                    outline: rgba(0, 0, 0, .05) 1px solid;
                }
                #__vconsole .vc-switch[error] {
                    background: rgba(255,0,0,.2);
                    animation: vconsole-notify 1s ease-in-out;
                    line-height: 35px;
                }
                @keyframes vconsole-notify {
                    from {
                        transform: scale(1, 1);
                    }
                    10% {
                        transform: scale(1.3, 1.3);
                    }
                    70% {
                        transform: scale(1.4, 1.4);
                    }
                    to {
                        transform: scale(1, 1);
                    }
                }
                #__vconsole .vc-panel {
                    font-family: monospace;
                    font-size: 11px;
                }
                #__vconsole .vc-plugin-box.vc-actived {
                    height: 100%;
                }
                #__vconsole .vc-mask {
                    overflow: hidden;
                }
            `,M?.prepend(t),e===!0&&dt()<=0&&io(),console.log(`🌵 Debug console has loaded`)}},t.onerror=()=>{console.warn(`🌵 Debug console failed to load.`+(window.crossOriginIsolated?`This page is using cross-origin isolation, so external scripts can't be loaded.`:``)),P=!1,j=null},t.src=`https://cdn.jsdelivr.net/npm/vconsole@3.15.1/dist/vconsole.min.js`,document.body.appendChild(t)}function fo(){if(!globalThis.VConsole)return;let e=new VConsole.VConsolePlugin(`needle-console`,`🌵 Inspect glTF`),t=()=>document.querySelector(`#__vc_plug_`+e._id+` iframe`);return e.on(`renderTab`,function(t){let n=globalThis[`needle:codegen_files`];if(!n||n.length===0)return;let r=globalThis[`needle:codegen_files`][0],i=r.indexOf(`?`);i>-1&&(r=r.substring(0,i));let a=location.protocol+`//`+location.host+location.pathname+`/`+r;e.fullUrl=`https://viewer.needle.tools?inspect&file=`+encodeURIComponent(a),t(`<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>`)}),e.on(`show`,function(){let n=t();n&&n.src!==e.fullUrl&&(n.src=e.fullUrl)}),e.on(`hide`,function(){let e=t();e&&(e.src=``)}),e.on(`addTopBar`,function(n){var r=[];r.push({name:`Open in new window ↗`,onClick:function(t){window.open(e.fullUrl,`_blank`),j?.hide()}}),r.push({name:`Reload`,onClick:function(n){let r=t();r&&(r.src=e.fullUrl)}}),r.push({name:`Fullscreen`,onClick:function(e){let n=t();n.requestFullscreen?n.requestFullscreen():n.webkitRequestFullscreen instanceof Function&&n.webkitRequestFullscreen()}}),n(r)}),e}var po=`padding: 10px; font-family: monospace;`,mo=`margin-bottom: 10px;`,F=`margin-bottom: 10px; margin-top: 15px;`,ho=`width: 100%; border-collapse: collapse; border: 1px solid rgba(0,0,0,0.1); table-layout: fixed;`,go=`border: 1px solid rgba(0,0,0,0.1); padding: 5px;`,_o=go,vo=go+` word-break: break-all;`;function I(e,t=!1){t&&e.sort((e,t)=>!!t.value-+!!e.value);let n=`<table style='${ho}'>`;n+=`<tbody>`;for(let t of e){let e=typeof t.value==`boolean`?t.value?`✅`:`❌`:t.value;n+=`<tr><td style='${_o}'>${t.label}</td><td style='${vo}'>${e}</td></tr>`}return n+=`</tbody></table>`,n}function yo(){try{if(document.createElement(`canvas`).getContext(`webgl2`))return`✅`}catch{}return`❌`}function bo(){if(!globalThis.VConsole)return;let e=new VConsole.VConsolePlugin(`device-utilities`,`📱 Device Info`);return e.on(`renderTab`,function(e){let t=`<div style='${po}'>`,n=jo();t+=`<h3 style='${mo}'>Device: ${n}</h3>`,t+=I([{label:`💻 Desktop`,value:C.isDesktop()},{label:`📱 Mobile Device`,value:C.isMobileDevice()},{label:`🍎 iOS`,value:C.isiOS()},{label:`📱 iPad`,value:C.isiPad()},{label:`🤖 Android`,value:C.isAndroidDevice()},{label:`🦊 Mozilla XR`,value:C.isMozillaXR()},{label:`🌵 Needle App Clip`,value:C.isNeedleAppClip()},{label:`🍏 macOS`,value:C.isMacOS()},{label:`👓 VisionOS`,value:C.isVisionOS()},{label:`🧭 Safari`,value:C.isSafari()},{label:`🕶️ Meta Quest`,value:C.isQuest()},{label:`🔗 QuickLook AR Support`,value:C.supportsQuickLookAR()}],!0);let r=[],i=C.getiOSVersion();i&&r.push({label:`🍎 iOS Version`,value:i});let a=C.getChromeVersion();a&&r.push({label:`🌐 Chrome Version`,value:a});let o=C.getSafariVersion();o&&r.push({label:`🧭 Safari Version`,value:o}),r.length>0&&(t+=I(r,!1)),t+=`</div>`,t+=`<div style='${po} margin-top: 20px;'>`,t+=`<h3 style='${mo}'>User Agent Info</h3>`;let s=[{label:`User Agent`,value:navigator.userAgent},{label:`Platform`,value:navigator.platform},{label:`App Version`,value:navigator.appVersion},{label:`User Agent Data`,value:navigator.userAgentData?`Platform: ${navigator.userAgentData.platform}, Mobile: ${navigator.userAgentData.mobile}`:`Not supported`},{label:`WebXR`,value:`xr`in navigator?`✅`:`❌`},{label:`WebGPU`,value:`gpu`in navigator?`✅`:`❌`},{label:`WebGL 2`,value:yo()}];t+=I(s,!1),t+=`</div>`,e(t)}),e}function xo(){if(!globalThis.VConsole)return;let e=new VConsole.VConsolePlugin(`graphics-info`,`🎨 Graphics Info`);return e.on(`renderTab`,async function(e){let t=`<div style='${po}'>`,n=So();n.length>0&&(t+=`<h3 style='${F}'>General GPU Info</h3>`,t+=I(n,!1));let r=wo();r.length>0&&(t+=`<h3 style='${F}'>WebGL</h3>`,t+=I(r,!1));let i=To();i.length>0&&(t+=`<h3 style='${F}'>WebGL 2 Features</h3>`,t+=I(i,!1));let a=Eo();a.length>0&&(t+=`<h3 style='${F}'>WebGL Limits</h3>`,t+=I(a,!1));let o=Do();o.length>0&&(t+=`<h3 style='${F}'>Texture Formats</h3>`,t+=I(o,!1));let s=await Oo();if(s.length>0&&(t+=`<h3 style='${F}'>WebGPU</h3>`,t+=I(s,!1)),C.isSafari()){let e=Ao();e.length>0&&(t+=`<h3 style='${F}'>Safari GPU Info</h3>`,t+=I(e,!1))}t+=`</div>`,e(t)}),e}function So(){let e=[],t=window.devicePixelRatio;e.push({label:`Device Pixel Ratio`,value:t.toString()}),e.push({label:`Width (px)`,value:(window.innerWidth*t).toString()}),e.push({label:`Height (px)`,value:(window.innerHeight*t).toString()});let n=C.isMobileDevice()?150:96,r=screen.width/n,i=screen.height/n,a=r*2.54,o=i*2.54;e.push({label:`Estimated Width (cm)`,value:a.toFixed(1)}),e.push({label:`Estimated Height (cm)`,value:o.toFixed(1)});let s=ko();if(s){e.push({label:`GPU`,value:s.renderer}),e.push({label:`Driver`,value:s.vendor}),e.push({label:`ANGLE`,value:s.angle||`Not detected`});let t=Co(s.renderer);t&&(t.manufacturer&&e.push({label:`Manufacturer`,value:t.manufacturer}),t.cardVersion&&e.push({label:`Card Version`,value:t.cardVersion}),t.brand&&e.push({label:`Brand`,value:t.brand}),e.push({label:`Integrated`,value:t.integrated?`Yes`:`No`}),t.layer&&e.push({label:`WebGL Layer`,value:t.layer}))}return e}function Co(e){if(!e)return null;let t=(e,t)=>{let n=t.match(e);return n&&n[0]},n=t(/(ANGLE)/g,e)||void 0,r=t(/((NVIDIA|AMD|Intel)[^\d]*[^\s]+)/,e)||e,i=r.split(` `);i.shift();let a=t(/(NVIDIA|AMD|Intel)/g,r)||void 0;return{manufacturer:a,cardVersion:i.length>0?i.pop():void 0,brand:i.length>0?i.join(` `):void 0,integrated:a===`Intel`,layer:n,card:r}}function wo(){let e=[],t=ko();return t&&(e.push({label:`📊 WebGL Version`,value:t.version}),e.push({label:`🎮 WebGL 2 Available`,value:yo()})),e}function To(){let e=[];try{let t=document.createElement(`canvas`).getContext(`webgl2`);if(!t)return e;e.push({label:`Float Color Buffer`,value:t.getExtension(`EXT_color_buffer_float`)?`✅`:`❌`}),e.push({label:`Anisotropic Filtering`,value:t.getExtension(`EXT_texture_filter_anisotropic`)?`✅`:`❌`}),e.push({label:`Float Texture Linear`,value:t.getExtension(`OES_texture_float_linear`)?`✅`:`❌`}),e.push({label:`S3TC Compression`,value:t.getExtension(`WEBGL_compressed_texture_s3tc`)?`✅`:`❌`}),e.push({label:`ETC Compression`,value:t.getExtension(`WEBGL_compressed_texture_etc`)?`✅`:`❌`}),e.push({label:`PVRTC Compression`,value:t.getExtension(`WEBGL_compressed_texture_pvrtc`)?`✅`:`❌`}),e.push({label:`ASTC Compression`,value:t.getExtension(`WEBGL_compressed_texture_astc`)?`✅`:`❌`})}catch{}return e}function Eo(){let e=[];try{let t=document.createElement(`canvas`),n=t.getContext(`webgl2`)||t.getContext(`webgl`);if(!n)return e;let r=n instanceof WebGL2RenderingContext;e.push({label:`📏 Max Texture Size`,value:n.getParameter(n.MAX_TEXTURE_SIZE).toString()}),e.push({label:`🎨 Max Renderbuffer Size`,value:n.getParameter(n.MAX_RENDERBUFFER_SIZE).toString()}),e.push({label:`🔗 Max Vertex Attribs`,value:n.getParameter(n.MAX_VERTEX_ATTRIBS).toString()}),e.push({label:`🎯 Max Texture Units`,value:n.getParameter(n.MAX_TEXTURE_IMAGE_UNITS).toString()}),r&&(e.push({label:`⚡ Max Samples`,value:n.getParameter(n.MAX_SAMPLES).toString()}),e.push({label:`🔄 Max Uniform Buffer Bindings`,value:n.getParameter(n.MAX_UNIFORM_BUFFER_BINDINGS).toString()}),e.push({label:`📐 Max 3D Texture Size`,value:n.getParameter(n.MAX_3D_TEXTURE_SIZE).toString()}))}catch{}return e}function Do(){let e=[];try{document.createElement(`canvas`).getContext(`webgl`)&&(e.push({label:`WebGL 1 RGBA`,value:`✅`}),e.push({label:`WebGL 1 RGB`,value:`✅`}));let t=document.createElement(`canvas`).getContext(`webgl2`);t&&(e.push({label:`WebGL 2 RGBA32F`,value:t.getExtension(`EXT_color_buffer_float`)?`✅`:`❌`}),e.push({label:`WebGL 2 RGB32F`,value:t.getExtension(`EXT_color_buffer_float`)?`✅`:`❌`}),e.push({label:`WebGL 2 R11F_G11F_B10F`,value:`✅`}),e.push({label:`WebGL 2 RGB565`,value:`✅`}),e.push({label:`WebGL 2 RGB5_A1`,value:`✅`}),e.push({label:`WebGL 2 RGBA4444`,value:`✅`}))}catch{}return e}async function Oo(){let e=[];if(!(`gpu`in navigator))return e.push({label:`🚀 WebGPU Support`,value:`❌ Not supported`}),e;e.push({label:`🚀 WebGPU Support`,value:`✅ Supported`});try{let t=await navigator.gpu.requestAdapter();if(!t)return e.push({label:`🎯 Adapter`,value:`No adapter available`}),e;e.push({label:`🎯 Adapter`,value:t.name||`Unknown Adapter`});let n=await t.requestDevice();e.push({label:`🔧 Device`,value:n.label||`WebGPU Device`}),e.push({label:`📏 Max Texture 2D`,value:n.limits.maxTextureDimension2D.toString()}),e.push({label:`📐 Max Texture 3D`,value:n.limits.maxTextureDimension3D.toString()}),e.push({label:`📊 Max Texture Array Layers`,value:n.limits.maxTextureArrayLayers.toString()}),e.push({label:`💾 Max Buffer Size`,value:`${(n.limits.maxBufferSize/1024/1024).toFixed(1)}MB`}),e.push({label:`🔗 Max Bind Groups`,value:n.limits.maxBindGroups.toString()})}catch(t){e.push({label:`❌ Error`,value:t.message})}return e}function ko(){try{let e=document.createElement(`canvas`),t=e.getContext(`webgl2`)||e.getContext(`webgl`);if(!t)return null;let n=t.getExtension(`WEBGL_debug_renderer_info`),r=n?t.getParameter(n.UNMASKED_RENDERER_WEBGL):t.getParameter(t.RENDERER),i=n?t.getParameter(n.UNMASKED_VENDOR_WEBGL):t.getParameter(t.VENDOR),a=t.getParameter(t.VERSION),o;if(r&&r.includes(`ANGLE`)){let e=r.match(/ANGLE \(([^)]+)\)/);e&&(o=e[1])}return{renderer:r,vendor:i,version:a,angle:o}}catch{return null}}function Ao(){let e=[];try{let t=document.createElement(`canvas`).getContext(`webgl`);if(t){let n=t.getExtension(`WEBGL_debug_renderer_info`);if(n){let r=t.getParameter(n.UNMASKED_RENDERER_WEBGL);r&&r.includes(`Apple`)&&e.push({label:`🍎 Apple GPU`,value:r})}}}catch{}try{let t=document.createElement(`canvas`).getContext(`webgl`);t&&(t.getSupportedExtensions()||[]).includes(`WEBGL_compressed_texture_pvrtc`)&&e.push({label:`🗜️ PVRTC Support`,value:`✅`})}catch{}return e}function jo(){return C.isQuest()?`Meta Quest`:C.isVisionOS()?`Vision Pro`:C.isiOS()?C.isiPad()?`iPad`:`iPhone/iPod`:C.isAndroidDevice()?`Android Device`:C.isMozillaXR()?`Mozilla XR Browser`:C.isNeedleAppClip()?`Needle App Clip`:C.isMacOS()?`Mac`:C.isDesktop()?`Desktop PC`:`Unknown Device`}function Mo(){return document.querySelector(`#__vconsole .vc-switch`)||null}function No(){return document.querySelector(`#__vconsole`)||null}var Po=new class extends T{constructor(){super([t,S],`ColorSerializer`)}onDeserialize(e){if(e!=null)return e.a===void 0?e.alpha===void 0?new t(e.r,e.g,e.b):new S(e.r,e.g,e.b,e.alpha):new S(e.r,e.g,e.b,e.a)}onSerialize(e){if(e!=null)return e.a===void 0?{r:e.r,g:e.g,b:e.b}:{r:e.r,g:e.g,b:e.b,a:e.a}}},Fo=new class extends T{constructor(){super([ce],`EulerSerializer`)}onDeserialize(e,t){if(e!=null){if(e.order)return new ce(e.x,e.y,e.z,e.order);if(e.x!=null)return new ce(e.x,e.y,e.z)}}onSerialize(e,t){return{x:e.x,y:e.y,z:e.z,order:e.order}}},Io=new class extends T{constructor(){super(d,`ObjectSerializer`)}onSerialize(e,t){if(t.objectToNode!==void 0&&e.uuid){let n=t.objectToNode[e.uuid];return D&&console.log(n,e.name,e.uuid),{node:n}}}onDeserialize(e,t){if(typeof e==`string`){if(e.endsWith(`.glb`)||e.endsWith(`.gltf`)){if(t.serializable instanceof Array&&t.serializable.includes(me))return;h()&&E(`Detected wrong usage of @serializable with Object3D or GameObject. Instead you should use AssetReference here! Please see the console for details.`);let e=t.target?.constructor?.name;console.warn(`Wrong usage of @serializable detected in your script \"${e}\"\n\nIt looks like you used @serializable(Object3D) or @serializable(GameObject) for a prefab or scene reference which is exported to a separate glTF file.\n\nTo fix this please change your code to:\n\n@serializable(AssetReference)\n${t.path}! : AssetReference;\n\0`)}return}if(e){if(e.node!==void 0&&t.nodeToObject){let n=t.nodeToObject[e.node];return D&&console.log(`Deserialized object reference?`,e,n,t?.nodeToObject),n||console.warn(`Did not find node: `+e.node,t.nodeToObject,t.object),n}else if(e.guid){if(!t.context){console.error(`Missing context`);return}let n,r=t.gltf?.scene;return r&&(n=x.findByGuid(e.guid,r)),n||=x.findByGuid(e.guid,t.context.scene),n?(n&&n.isComponent===!0&&(D&&console.warn(`Deserialized object reference is a component`),n=n.gameObject),D&&console.log(`Deserialized object reference?`,e,n,t?.nodeToObject)):((h()||D)&&console.warn(`Could not resolve object reference`,t.path,e,t.target,t.context.scene),e.could_not_resolve=!0),n}}}},Lo=new class extends T{constructor(){super([Vt,Vt],`ComponentSerializer`)}onSerialize(e,t){if(e?.guid)return{guid:e.guid}}onDeserialize(e,t){if(e?.guid){if(e.___persistentAsset){D&&console.log(`Skipping component deserialization because it's a persistent asset`,e);return}let n=t.path;D&&console.log(e.guid,t.root,t.object,t.target);let r=this.findObjectForGuid(e.guid,t.root);if(r||t.context&&(r=this.findObjectForGuid(e.guid,t.context?.scene),r))return r;(h()||D)&&console.warn(`Could not resolve component reference: "`+n+`" using guid `+e.guid,t.target),e.could_not_resolve=!0;return}}findObjectForGuid(e,t){if(t.guid===e)return t;let n=x.foreachComponent(t,t=>{if(t.guid===e)return t},!1);if(n!==void 0)return n;for(let n=0;n<t.children.length;n++){let r=t.children[n],i=this.findObjectForGuid(e,r);if(i)return i}}},Ro=new class extends T{constructor(){super([_])}onSerialize(e,t){console.log(`TODO: SERIALIZE EVENT`)}onDeserialize(e,t){if(typeof e==`function`)return new _([new pt(e,null,[],!0)]);if(e&&e.type===`EventList`){D&&console.log(`DESERIALIZE EVENT`,e);let n=[];if(e.calls&&Array.isArray(e.calls))for(let r of e.calls){D&&console.log(r);let e=Lo.findObjectForGuid(r.target,t.root);!e&&t.context?.scene&&(e=Lo.findObjectForGuid(r.target,t.context?.scene));let i=r.method?.length>0;if(e&&i){let t=()=>{let t=r.method[0].toUpperCase()+r.method.slice(1);if(typeof e[t]==`function`){console.warn(`EventList method:\nCould not find method ${r.method} on object ${e.name}. Please rename ${r.method} to ${t}?\n`,e[t],`
 in script: `,e),E(`EventList methods must start with lowercase letter, see console for details`);return}else console.warn(`EventList method:\nCould not find method ${r.method} on object ${e.name}`,e,typeof e[r.method])};if(typeof e[r.method]!=`function`){let n=!1,i=e;for(;i;){let e=Object.getOwnPropertyDescriptor(i,r.method);if(e&&(e.writable===!0||e.set)){n=!0;break}i=Object.getPrototypeOf(i)}!n&&(h()||D)&&t()}}function a(e){if(typeof e==`object`){let n=Io.onDeserialize(e,t);if(n||=Lo.onDeserialize(e,t),n)return n}return e}if(e){let t=r.argument;if(t===void 0?r.arguments!==void 0&&(t=r.arguments.map(a)):t=a(t),e[r.method]===void 0)console.warn(`EventList method not found: \"${r.method}\" on ${e?.name}`);else{t!==void 0&&!Array.isArray(t)&&(t=[t]);let i=new pt(e,r.method,t,r.enabled);n.push(i)}}else h()&&console.warn(`[Dev] EventList: Could not find event listener in scene (${t.object?.name})`,r)}let r=new _(n);D&&console.log(r);let i=t.target;return i!==void 0&&t.path!==void 0&&r.setEventTarget(t.path,i),r}}},zo=new WeakMap,Bo=ae.prototype.clone;ae.prototype.clone=function(){let e=Bo.call(this);return zo.has(e)||zo.set(e,this),e};var Vo=class extends T{constructor(){super([Me,a])}onSerialize(e,t){}onDeserialize(e,t){if(e instanceof ae&&t.type===Me){let t=e;zo.has(t)&&(t=zo.get(t)),t.isRenderTargetTexture=!0,t.flipY=!0,t.offset.y=1,t.repeat.y=-1,t.needsUpdate=!0,t.mipmaps=[],t instanceof i&&(t.isCompressedTexture=!1,t.format=c);let n=new Me(t.image.width,t.image.height,{colorSpace:r});return n.texture=t,n}}};new Vo;var Ho=class extends T{constructor(){super([URL])}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e==`string`&&e.length>0)return Nt(t.gltfId,e)}};new Ho;var Uo=!1;function Wo(){Uo||(Uo=!0,ut.registerCallback(at.ContextCreated,e=>{let t=e.context.domElement.getAttribute(`autoplay`);if(t!==void 0&&(t===``||t===`true`||t===`1`)&&e.files)for(let t of e.files)x.foreachComponent(t.file.scene,e=>{if(e.enabled!==!1){if(e instanceof vr&&e.playAutomatically||e instanceof Xe||e instanceof oa&&e.playOnAwake===!0)return!0;if(e instanceof vr)return e.playAutomatically=!0,!0;if(e instanceof oa)return e.playOnAwake=!0,!0}},!0)!==!0&&Ze.autoplayAnimations(t.file)}))}var L=b(`debugmissingcamera`),Go=!1;function Ko(){Go||(Go=!0,ut.registerCallback(at.MissingCamera,e=>{L&&console.warn(`Creating missing camera`);let n=e.context.scene,r=new f;r.name=`Default Fallback Camera`,n.add(r);let i=new he;if(i.sourceId=e.files?.[0]?.src??`unknown`,i.fieldOfView=35,e.context.domElement.getAttribute(`transparent`)!=null)i.clearFlags=Zt.Uninitialized;else if(e.context.domElement.getAttribute(`background-image`)?.length||e.context.lightmaps.tryGetSkybox(i.sourceId))i.clearFlags=Zt.Skybox;else{if(i.clearFlags=Zt.SolidColor,!e.context.domElement.getAttribute(`background-color`)){let e=`#efefef`;window.matchMedia(`(prefers-color-scheme: dark)`).matches&&(e=`#1f1f1f`),n.background=new t(e)}if(!n.environment){let t=new oe(e.context.renderer),r=new Si(`neutral`);n.environment=t.fromScene(r,.025).texture}}let a=Ot(r,i,!0);return r.position.x=0,r.position.y=1,r.position.z=2,e.context.domElement?.cameraControls!=0&&qo(e.context,a),a}),ut.registerCallback(at.ContextCreated,e=>{if(!e.context.mainCamera){L&&console.log(`Will not auto-fit because a default camera exists`);return}if(e.context.domElement?.cameraControls==1){if(an(e.context.mainCamera)?.isCameraController==1){L&&console.log(`Will not auto-fit because a camera controller exists`);return}qo(e.context)}}))}function qo(e,t){t??=e.mainCameraComponent;let n=t?.gameObject;if(L&&console.log(`Creating default camera controls`,t?.name),n){let r=it(n,Ce);r.sourceId=t?.sourceId??`unknown`;let i=e.domElement.getAttribute(`auto-rotate`);r.autoRotate=i!=`0`&&i?.toLowerCase()!=`false`;let a=Number.parseFloat(i||`.5`);r.autoRotateSpeed=isNaN(a)?.5:a,L&&console.log(`Auto-rotate`,r.autoRotate,`speed:`,r.autoRotateSpeed);let o=e.domElement.getAttribute(`auto-fit`);r.autoFit=o!==`0`&&o?.toLowerCase()!=`false`,r.autoTarget=!0}else console.warn(`Missing camera object, can not add orbit controls`)}function Jo(){ze.registerWaitForInteraction(()=>{let e=ie.getContext();e.addEventListener(`statechange`,()=>{setTimeout(()=>{let t=e.state;(t===`suspended`||t===`interrupted`)&&e.resume().then(()=>{console.log(`AudioContext resumed successfully`)}).catch(e=>{console.log(`Failed to resume AudioContext: `+e)})},500)})})}var R=D;b(`debugtypestore`)&&console.log(fe);function Yo(e,t){let n=ft(e,t);return n===void 0?null:n}var Xo=new De,Zo=Symbol(`deserialize-queue`);async function Qo(e,t,n,r=null,i){if(!n){console.debug(`Can not create component instances: gltf is null`);return}let a=[],o=r;typeof o==`number`&&(o=new yt(r));let s=t.indexOf(`?`);t=s===-1?t:t.substring(0,s);let c=new Ie(n.scene);c.gltfId=t,c.context=e,c.gltf=n,c.nodeToObject=i?.nodeToObjectMap,c.implementationInformation=Xo;let l=e[Zo];if(l||=e[Zo]=[],n.scenes)for(let e of n.scenes)await ts(c,e,l,a,0);if(n.children)for(let e of n.children)await ts(c,e,l,a,0);e.new_scripts_pre_setup_callbacks.push(()=>{let t=e[Zo];if(t){for(let e of t)ns(e,c);t.length=0}if(o){let e={},t=[];es(n,o,e,t);for(let r of n.scenes)es(r,o,e,t);for(let n of t)n.resolveGuids(e)}})}var $o=Symbol(`original-component-name`),z=new Map;function es(e,t,n,r){if(t===null||!e)return;let i=e.guid,a=e.guid;if(a?.length&&(z.has(a)||(R&&console.log(`Creating InstanceIdProvider with key "`+a+`" for object `+e.name),z.set(a,new yt(a)))),e.guid=(a&&z.get(a)||t).generateUUID(),i&&i!==`invalid`&&(n[i]=e.guid),e&&e.userData&&e.userData.components)for(let i of e.userData.components){if(i===null)continue;let e=i.guid;e?z.has(e)||(R&&console.log(`Creating InstanceIdProvider with key "`+e+`" for component `+i[$o]),z.set(e,new yt(e))):R&&console.warn(`Can not create IdProvider: component `+i[$o]+` has no guid`,i.guid);let a=z.get(e)||t,o=i.guid;i.guid=a.generateUUID(),o&&o!==`invalid`&&(n[o]=i.guid),i.resolveGuids&&r.push(i)}if(e.children)for(let i of e.children)es(i,t,n,r)}var B=[];async function ts(e,t,n,r,i){if(!t)return;let a=t.userData;if(a){let r=a.builtin_components;if(r&&r.length>0)for(let i of r)try{if(i===null)continue;let r=fe.get(i.name);if(r||=await fe.getAsync(i.name),r){let a=new r;a.sourceId=e.gltfId,Fe(a,i,e.implementationInformation),a.context=e.context,`guid`in i&&(a[Pe]=i.guid),a[$o]=i.name,Ot(t,a,!1),n.push({instance:a,compData:i,obj:t}),a.isCamera&&e.context&&e.context.mainCamera===null&&a.tag===`MainCamera`&&e.context.setCurrentCamera(a),e.context?.physics?.engine?.isInitialized===!1&&(a.isCollider||a.isRigidbody)&&e.context?.physics.engine?.initialize()}else R&&console.debug(`unknown component: `+i.name),B.includes(i.name)||B.push(i.name)}catch(e){console.error(i.name+` - `+e.message,e)}}if(t.children)for(let a of t.children)await ts(e,a,n,r,i+1);if(B.length>0&&i===0){let e=B.join(`, `);console.warn(`Unknown components in scene: ${e}`),B.length=0,Ae()&&zt(`<strong>Unknown components in scene</strong>:\n\n${e}\n\nThis could mean you forgot to add a npmdef to your ExportInfo\n<a href="https://engine.needle.tools/docs/project_structure.html#creating-and-installing-a-npmdef" target="_blank">documentation</a>`,{type:Ne.Warn})}}function ns(e,t){let{instance:n,compData:r,obj:i}=e;t.object=i,t.target=n,mt(n,r,t),R&&console.debug(`add `+r.name,r,n)}var rs=class{createBuiltinComponents(e,t,n,r,i){return Qo(e,t,n,r,i)}writeBuiltinComponentData(e,t){return Yo(e,t)}parseSync(e,t,n,r){return ls(e,t,n,r)}loadSync(e,t,n,r,i){return us(e,t,n,r,i)}};function is(){We(rs)}var as=b(`printGltf`)||b(`printgltf`),os=b(`debugfileformat`);async function ss(e,t,n){let r=await gi(e,{useExtension:!0})||`unknown`;os&&console.debug(`Determined file type: '${r}' for url '${e}'`,{registeredModelLoaderCallbacks:si});for(let n of si){let{callback:i}=n,a=i({context:t,url:e,mimetype:r});if(a instanceof Promise&&await a,a)return console.debug(`Using custom loader (${n.name||`unnamed`}) for ${r} at '${e}'`),a}switch(r){case`unsupported`:return null;default:case`unknown`:{console.warn(`Unknown file type (${r}). Needle Engine will fallback to the GLTFLoader - To support more model formats please create a Needle loader plugin.\nUse import { NeedleEngineModelLoader } from \"@needle-tools/engine\" namespace to register your loader.`,e);let i=new A;return await hr(i,t,e,n),i}case`model/fbx`:case`model/vnd.autodesk.fbx`:return new cn;case`model/obj`:return new ln;case`model/vnd.usdz+zip`:case`model/vnd.usd+zip`:case`model/vnd.usda+zip`:return console.warn(r.toUpperCase()+` files are not supported.`),null;case`model/gltf+json`:case`model/gltf-binary`:case`model/vrm`:{let r=new A;return await hr(r,t,e,n),r}case`application/materialx+xml`:return new jn}}function cs(e,t){return us(t?.context||_t.Current,e,e,t?.seed||null,t?.onprogress)}async function ls(e,t,n,r){typeof n!=`string`&&(console.warn(`Parse gltf binary without path, this might lead to errors in resolving extensions. Please provide the source path of the gltf/glb file`,n,typeof n),n=``),as&&console.log(`Parse glTF`,n);let i=await ss(n,e,n);if(!i)return;let{componentsExtension:a}=ds(i,e);if(i instanceof ln){typeof t!=`string`&&(t=new TextDecoder().decode(t));let o=i.parse(t);return await V(i,e,n,o,r,a)}if(!(i instanceof A)){if(!(`parse`in i)||typeof i.parse!=`function`){console.error(`Loader does not support parse`);return}let o=i.parse(t,n);return await V(i,e,n,o,r,a)}return new Promise((o,s)=>{try{let s=n.split(`?`)[0].trimEnd(),c=s.split(`/`);c.length>0&&c[c.length-1]!==``&&c.pop(),s=c.join(`/`),s.endsWith(`/`)||(s+=`/`),i.resourcePath=s,i.parse(t,``,async t=>{o(await V(i,e,n,t,r,a))},e=>{console.error(`Loading asset at "`+n+`" failed
`,e),o(void 0)})}catch(e){console.error(e),s(e)}})}async function us(e,t,n,r,i){ps(t);let a=await ss(t,e,n);if(!a)return;let{componentsExtension:o}=ds(a,e);return a instanceof A?new Promise((s,c)=>{try{a.load(t,async t=>{s(await V(a,e,n,t,r,o))},e=>{i?.call(a,e)},e=>{console.error(`Loading asset at "`+t+`" failed
`,e),s(void 0)})}catch(e){console.error(e),c(e)}}):await V(a,e,t,await a.loadAsync(t,i),r,o)}function ds(e,t){let n=_n(e);return e instanceof A&&Vn(e,t),{componentsExtension:n}}async function V(e,n,r,i,a,o){if(as&&console.warn(`Loaded`,r,i),i==null)return console.error(`Loaded model is null '${r}' - please make sure the loader is registered correctly`),{scene:new d,animations:[],scenes:[]};if(typeof i!=`object`)return console.error(`Loaded model is not an object '${r}' - please make sure the loader is registered correctly`),{scene:new d,animations:[],scenes:[]};if(i instanceof d)i={scene:i,animations:i.animations,scenes:[i]};else if(i instanceof u){let e=new se({color:new t(14540253)}),n=new ne(i,e);i={scene:n,animations:[],scenes:[n]}}else Array.isArray(i.scenes)===!1&&console.error(`[Needle Engine] The loaded model object does not have a scenes property '${r}' - please make sure the loader is registered correctly and three.js is not imported multiple times.`);return r.includes(`?`)&&(r=r.split(`?`)[0]),ms(e,i),je(i)&&(yn(r,i,n),await be().createBuiltinComponents(n,r,i,a,o||void 0)),await fs(i.scene,n,n.mainCamera),i}async function fs(e,t,n){n||=t.mainCamera;try{n?await t.renderer.compileAsync(e,n,t.scene).catch(e=>{console.warn(e.message)}):Se(e,t)}catch(e){console.warn(e?.message||e)}}function ps(e){if(new URL(e,window.location.href).href.startsWith(`file://`)){let e=`Hi - it looks like you are trying to load a local file which will not work. You need to use a webserver to serve your files.
Please refer to the documentation on <a href="https://fwd.needle.tools/needle-engine/docs/local-server">https://docs.needle.tools</a> or ask for help in our <a href="https://discord.needle.tools">discord community</a>`;zt(e),console.warn(e)}}function ms(e,t){if(`scenes`in t){for(let e of t.scenes)if(e&&!e.animations?.length)for(let n of t.animations)e.animations.includes(n)||e.animations.push(n)}if(e instanceof cn||e instanceof ln){let e=t;e instanceof d||(e=t.scene||t.scenes.find(e=>e)),e.traverse(e=>{let t=e;t?.isMesh&&ye(t,t.material)})}}var hs=!1;function gs(){hs||(hs=!0,Object.defineProperty(f.prototype,`fov`,{get:function(){return this._fov},set:function(e){let t=e!==this._fov;this._fov=e,t&&this.view!==void 0&&this.updateProjectionMatrix()},configurable:!0}),Object.defineProperty(f.prototype,`near`,{get:function(){return this._near},set:function(e){let t=e!==this._near;this._near=e,t&&this.view!==void 0&&this.updateProjectionMatrix()},configurable:!0}),Object.defineProperty(f.prototype,`far`,{get:function(){return this._far},set:function(e){let t=e!==this._far;this._far=e,t&&this.view!==void 0&&this.updateProjectionMatrix()},configurable:!0}))}var _s=!1;function vs(){_s||(_s=!0,n.prototype.slerp=function(e,t){return Re(this,e,t)},Oe(n))}var ys=h(),bs=class extends HTMLElement{static observedAttributes=[`ar`,`vr`,`quicklook`,`qrcode`];constructor(){super(),this.removeEventListener(`click`,this.#l),this.addEventListener(`click`,this.#l)}attributeChangedCallback(e,t,n){this.#s()}#e;#t;#n;#r;#i;#a;#o;#s(){if(this.#r?.remove(),this.getAttribute(`ar`)!=null)this.#i??=new Br,this.#r=this.#i.createARButton(),this.setAttribute(`aria-label`,`Enter augmented reality mode`);else if(this.getAttribute(`vr`)!=null)this.#i??=new Br,this.#r=this.#i.createVRButton(),this.setAttribute(`aria-label`,`Enter virtual reality mode`);else if(this.getAttribute(`quicklook`)!=null)this.#i??=new Br,this.#r=this.#i.createQuicklookButton(),this.setAttribute(`aria-label`,`View in AR with Apple Quick Look`);else if(this.getAttribute(`qrcode`)!=null)this.#a??=new It,this.#r=this.#a.createQRCode({anchorElement:this}),this.setAttribute(`aria-label`,`Share application with QR code`);else{ys?console.warn(`No button type specified for <needle-button>. Use either ar, vr or quicklook attribute.`):console.debug(`No button type specified for <needle-button>. Use either ar, vr or quicklook attribute.`),this.setAttribute(`aria-label`,`Needle Button with no specified type`);return}this.#e??=this.attachShadow({mode:`open`}),this.#t??=document.createElement(`slot`),this.#n??=document.createElement(`style`),this.#n.innerHTML=`
            button {
                all: unset;
            }
        `,this.getAttribute(`unstyled`)??(this.#n.innerHTML+=`
            :host {
                display: inline-flex;
                align-items: center;
                justify-content: center;
                width: fit-content;

                padding: 0.4rem .5rem;
                border-radius: 100vw;
                
                background: rgba(245, 245, 245, .8);
                backdrop-filter: blur(10px);

                cursor: pointer;
                color: black;
                outline: rgba(0,0,0,.05) 1px solid;

                transition: all .2s;
            }
            :host(:hover) {
                background: rgba(255, 255, 255, 1);
                transition: background .2s;
            }
            slot {
                display: flex;
                align-items: center;
                justify-content: center;
                gap: .5rem;
            }
`),this.#t.innerHTML=this.#r.innerHTML,this.#t.style.cssText=`display: flex; align-items: center; justify-content: center;`,this.#r.innerHTML=this.#t.outerHTML,this.#e.innerHTML=this.#r.outerHTML,this.#e.prepend(this.#n),we(xe,{element:this.#e}),this.#o?.disconnect(),this.#o??=new MutationObserver(()=>this.#c()),this.#o.observe(this.#r,{attributes:!0}),ys&&console.log(`Needle Button updated`,this)}#c(){this.#r&&(this.#r.style.display===`none`?this.style.display=`none`:this.style.display===`none`&&(this.style.display=``))}#l=e=>{ys&&console.log(`Needle Button clicked`,{defaultPrevented:e.defaultPrevented,hasButton:!!this.#r}),!e.defaultPrevented&&this.#r&&this.#r.click()}},H=b(`debugoverlay`),xs=`quit-ar`,Ss=class{get ARContainer(){return this.arContainer}arContainer=null;currentSession=null;_createdAROnlyElements=[];_reparentedObjects=[];contentElement=null;originalDomOverlayParent=null;requestEndAR=()=>{this.onRequestedEndAR()};onBegin(e,t,n){if(this.currentSession=n,this.arContainer=t,C.isMozillaXR()||C.isNeedleAppClip()){let n=e.domElement.children;for(let e=0;e<n?.length;e++){let t=n[e];if(!t||t===this.arContainer)return;this._reparentedObjects.push({el:t,previousParent:t.parentElement}),this.arContainer?.appendChild(t)}t?(this.originalDomOverlayParent=t.parentNode,this.originalDomOverlayParent&&(console.log(`Reparent DOM Overlay to body`,t,t.style.display),t.style.display=``,t.style.visibility=``,document.body.appendChild(t))):console.warn(`WebXRViewer: No DOM Overlay found`)}this.ensureQuitARButton(this.arContainer)}onEnd(e){for(let e of this._createdAROnlyElements)e.remove&&e.remove();for(let e of this._reparentedObjects){let t=e.el;e.previousParent?.appendChild(t)}this._reparentedObjects.length=0,C.isMozillaXR()&&setTimeout(()=>{let t=e.renderer.domElement;t&&e.domElement.shadowRoot?.prepend(t);let n=document.querySelectorAll(`*`);for(var r=0;r<n.length;r++){let e=n[r];e&&e._displayChanged!==void 0&&e._displayWas!==void 0&&(e.style.display=e._displayWas)}},10)}createOverlayContainer(e){if(this.contentElement)return this.contentElement;H&&console.log(`Setup overlay container`);let t=e.shadowRoot.querySelector(`.content`);this.contentElement=t;let n=e.shadowRoot.querySelector(`.overlay-content`);return n&&t.appendChild(n),H&&!C.isMobileDevice()&&this.ensureQuitARButton(t),t}onRequestedEndAR(){this.currentSession&&=(this.currentSession.end(),null)}ensureQuitARButton(e){let t=document.createElement(`slot`);if(t.style.display=`contents`,t.style.padding=`10px`,t.setAttribute(`name`,`quit-ar`),this.appendElement(t,e),this._createdAROnlyElements.push(t),t.style.pointerEvents=`auto`,C.isNeedleAppClip()){globalThis.NEEDLE_ENGINE_APPCLIP_DISABLE_MENU=!0;let e=document.querySelector(`meta[name="viewport"]`);e&&!e.getAttribute(`content`)?.includes(`viewport-fit=`)&&e.setAttribute(`content`,e.getAttribute(`content`)+`,viewport-fit=cover`)}let n=document.querySelector(`.${xs}`);if(n){n.addEventListener(`click`,this.requestEndAR),H&&n.addEventListener(`click`,()=>console.log(`Clicked quit-ar button`));return}t.addEventListener(`click`,this.requestEndAR),H&&t.addEventListener(`click`,()=>console.log(`Clicked fallback close button`));let r=document.createElement(`div`);r.style.cssText=`
            position: fixed;
            top: 0;
            right: 0;
            z-index: 600;
            pointer-events: all;
            padding-top: env(safe-area-inset-top, 0px);
            padding-right: calc(env(safe-area-inset-right, 0px) + 10px);
        `,this.appendElement(r,t);var i=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);i.classList.add(`quit-ar-button`),i.setAttribute(`width`,`40px`),i.setAttribute(`height`,`40px`),i.style.cssText=`
            background: rgba(255, 255, 255, .4);
            -webkit-backdrop-filter: blur(8px);
            backdrop-filter: blur(8px);
            border-radius: 50%;
            box-shadow: 0 0 5px rgba(0,0,0,.3);
            outline: 1px solid rgba(255, 255, 255, .6);
            display: flex;
            justify-content: center;
            align-items: center;
        `,r.appendChild(i);var a=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);a.setAttribute(`d`,`M 12,12 L 28,28 M 28,12 12,28`),a.setAttribute(`stroke`,`#000000`),a.setAttribute(`stroke-width`,`2px`),a.style.cssText=`
            /**filter: drop-shadow(0 0px 1.2px rgba(0,0,0,.7));**/
        `,i.appendChild(a),H&&console.log(`Created fallback close button`,i,e)}appendElement(e,t){return t.shadowRoot?t.shadowRoot.appendChild(e):t.appendChild(e)}},U=b(`debugloading`),W=b(`debugloadingrendering`);b(`debuglicense`);var Cs=class{className;additionalClasses},G=0,ws;function Ts(e){U&&console.log(e.progress.loaded.toFixed(0)+`/`+e.progress.total.toFixed(0),e);let t=e.count,n=e.progress.total;n===0||n===void 0?(ws!==e.name&&(G=0),ws=e.name,G+=(1-G)*.001,U&&E(`Loading `+e.name+` did not report total size`)):G=e.progress.loaded/n;let r=e.index/t+G/t;return g.clamp01(r)}var Es=class e{static LoadingContainerClassName=`loading`;loadingProgress=0;_element;_progress=0;_allowCustomLoadingElement=!0;_loadingElement;_loadingTextContainer=null;_loadingBar=null;_loadingBarFinishedColor=null;_messageContainer=null;_loadingElementOptions;constructor(e,t){this._element=e,this._loadingElementOptions=t}async onLoadingBegin(t){let n=this._element.shadowRoot||this._element;if(U&&console.warn(`Begin Loading`),!this._loadingElement){for(let t=0;t<n.children.length;t++){let r=n.children[t];if(r.classList.contains(e.LoadingContainerClassName)){if(!this._allowCustomLoadingElement){U&&console.warn(`Remove custom loading container`),n.removeChild(r);continue}this._loadingElement=this.createLoadingElement(r)}}this._loadingElement||=this.createLoadingElement()}this._progress=0,this.loadingProgress=0,this._loadingElement.style.display=`flex`,n.appendChild(this._loadingElement),this.smoothProgressLoop(),this.setMessage(t??``)}onLoadingUpdate(e,t){if(!this._loadingElement?.parentNode)return;let n=0;typeof e==`number`?n=e:(`index`in e&&(n=Ts(e)),!t&&`name`in e&&this.setMessage(`loading `+e.name)),this.loadingProgress=n,t&&this.setMessage(t),this.updateDisplay()}onLoadingFinished(){U&&console.warn(`Finished Loading`),W||(this.loadingProgress=1,this.onDoneLoading())}setMessage(e){this._messageContainer&&(this._messageContainer.innerText=e)}_progressLoop;smoothProgressLoop(){if(this._progressLoop)return;let e=1/12;W&&(e=1/500,typeof W==`number`&&(e*=W)),this._progressLoop=setInterval(()=>{this.loadingProgress>=.95&&!W&&(e=.9),this._progress=g.lerp(this._progress,this.loadingProgress,e*this.loadingProgress),this.updateDisplay()},e)}onDoneLoading(){if(this._loadingElement){U&&console.log(`Hiding loading element`);let e=this._loadingElement;e.animate([{opacity:1},{opacity:0}],{duration:200,easing:`ease-in-out`}).addEventListener(`finish`,()=>{e.style.display=`none`,e.remove()})}this._progressLoop&&clearInterval(this._progressLoop),this._progressLoop=null}updateDisplay(){let e=this._progress,t=(e*100).toFixed(0)+`%`;this._loadingBar&&(this._loadingBar.style.width=e*100+`%`,e>=1&&this._loadingBarFinishedColor&&(this._loadingBar.style.background=this._loadingBarFinishedColor)),this._loadingTextContainer&&(this._loadingTextContainer.textContent=t)}createLoadingElement(t){U&&!t&&console.log(`Creating loading element`),this._loadingElement=t||document.createElement(`div`);let n=this._element.getAttribute(`loading-style`);(!n||n===`auto`)&&(n=window.matchMedia(`(prefers-color-scheme: dark)`).matches?`dark`:`light`);let r=Xt();if(!t){this._loadingElement.style.position=`absolute`,this._loadingElement.style.width=`100%`,this._loadingElement.style.height=`100%`,this._loadingElement.style.left=`0`,this._loadingElement.style.top=`0`,this._loadingElement.style.overflow=`hidden`;let e=this._element.getAttribute(`loading-background`);e?this._loadingElement.style.background=e:this._loadingElement.style.backgroundColor=`transparent`,this._loadingElement.style.display=`flex`,this._loadingElement.style.alignItems=`center`,this._loadingElement.style.justifyContent=`center`,this._loadingElement.style.zIndex=`0`,this._loadingElement.style.flexDirection=`column`,this._loadingElement.style.pointerEvents=`none`,this._loadingElement.style.color=`white`,this._loadingElement.style.fontFamily=`system-ui, Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"`,this._loadingElement.style.fontSize=`1rem`,n===`light`?this._loadingElement.style.color=`rgba(0,0,0,.6)`:this._loadingElement.style.color=`rgba(255,255,255,.3)`}let i=this._loadingElementOptions?.className??e.LoadingContainerClassName;if(this._loadingElement.classList.add(i),this._loadingElementOptions?.additionalClasses)for(let e of this._loadingElementOptions.additionalClasses)this._loadingElement.classList.add(e);let a=document.createElement(`div`);a.style.cssText=`
            position: relative;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            width: 100%;
            height: 100%;
            pointer-events: none;
        `,this._loadingElement.appendChild(a);let o=this._element.getAttribute(`poster`);if(o!==null&&o!==`0`){let e=document.createElement(`div`),t=o?.length?`0px`:`50px`;e.style.cssText=`
            position: absolute;
            left: 0;
            top: 0;
            bottom: 0;
            right: 0;
            z-index: -1;
            overflow: hidden;

            margin: -${t};
            background: url('${o?.length?o:`/include/poster.webp`}') center center no-repeat;
            background-size: cover;
            filter: blur(${t});
        `,this._loadingElement.appendChild(e)}let s=document.createElement(`img`);if(s.style.userSelect=`none`,s.style.objectFit=`contain`,s.style.transform=`translateY(30px)`,s.style.opacity=`0.0000001`,s.style.transition=`transform 1s ease-out .2s, opacity .3s ease-in-out .2s`,s.src=Ye,r&&this._element){let e=this._element.getAttribute(`logo-src`);e&&(s.src=e,setTimeout(()=>{s.style.opacity=`1`,s.style.transform=`translateY(0px)`},1))}s.style.width=`80%`,s.style.height=`min(1000px, max(15%, 50px))`,a.appendChild(s);let c=document.createElement(`div`);c.style.cssText=`
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        width: 100%;
        opacity: 0;
        transition: opacity 1s ease-in-out 4s;
        `,setTimeout(()=>{c.style.opacity=`1`},1),this._loadingElement.appendChild(c);let l=document.createElement(`div`);return l.style.display=`flex`,l.style.width=`100%`,l.style.height=`5px`,l.style.position=`absolute`,l.style.left=`0`,l.style.top=`0px`,l.style.opacity=`0`,l.style.transition=`opacity 1s ease-in-out`,l.style.backgroundColor=`rgba(240,240,240,.5)`,setTimeout(()=>{l.style.opacity=`1`},1),this._loadingElement.appendChild(l),this._loadingBar=document.createElement(`div`),l.appendChild(this._loadingBar),this._loadingBar.style.backgroundAttachment=`fixed`,this._loadingBar.style.background=`#c4c4c4ab`,this._loadingBarFinishedColor=`#ddddddab`,this._loadingBar.style.width=`0%`,this._loadingBar.style.height=`100%`,this._loadingElement}},K=b(`debugwebcomponent`),Ds=`vr`,Os=`desktop`,ks=[`ar`,Ds,Os],q=`ar-session-active`,J=`desktop-session-active`,As=[`src`,`hash`,`camera-controls`,`dracoDecoderPath`,`dracoDecoderType`,`ktx2DecoderPath`,`public-key`,`version`,`tone-mapping`,`tone-mapping-exposure`,`background-blurriness`,`background-color`,`environment-intensity`,`focus-rect`,`loadstart`,`progress`,`loadfinished`],js=class extends HTMLElement{static get observedAttributes(){return As}get loadingProgress01(){return this._loadingProgress01}get loadingFinished(){return this.loadingProgress01>.999}get cameraControls(){let e=this.getAttribute(`camera-controls`);return e==null?null:!(e===null||e===`False`||e===`false`||e===`0`||e===`none`)}set cameraControls(e){e===null?this.removeAttribute(`camera-controls`):this.setAttribute(`camera-controls`,e?`true`:`false`)}getContext(){return new Promise((e,t)=>{if(this._context&&this.loadingFinished)e(this._context);else{let t=()=>{this.removeEventListener(`loadfinished`,t),this._context&&this.loadingFinished&&e(this._context)};this.addEventListener(`loadfinished`,t)}})}get context(){return this._context}_context;_overlay_ar;_loadingProgress01=0;_loadingView;_previousSrc=null;_didFullyLoad=!1;_didInitialize=!1;constructor(){super(),this.attachShadow({mode:`open`,delegatesFocus:!0});let e=document.createElement(`template`);e.innerHTML=`<style>
    :host {
        position: absolute;
        display: block;
        width: max(600px, 100%);
        height: max(300px, 100%);
        touch-action: none;

        -webkit-tap-highlight-color: transparent;
    }

    @media (max-width: 600px) {
        :host {
            width: 100%;
        }
    }
    @media (max-height: 300px) {
        :host {
            height: 100%;
        }
    }

    :host > div.canvas-wrapper {
        width: 100%;
        height: 100%;
    }

    :host canvas {   
        position: absolute;
        user-select: none;
        -webkit-user-select: none;

        /** allow touch panning but no pinch zoom **/
        /** but this doesnt work yet: 
         * touch-action: pan-x, pan-y;
         **/
        
        -webkit-touch-callout: none;
        -webkit-user-drag: none;
        -webkit-user-modify: none;

        left: 0;
        top: 0;
    }
    :host .content {
        position: absolute;
        top: 0;
        width: 100%;
        height: 100%;
        visibility: visible;
        z-index: 500; /* < must be less than the webxr buttons element */
        pointer-events: none;
    }
    :host .overlay-content {
        position: absolute;
        user-select: auto;
        pointer-events: all;
    }
    :host slot[name="quit-ar"]:hover {
        cursor: pointer;
    }
    :host .quit-ar-button {
        position: absolute;
        /** top: env(titlebar-area-y); this doesnt work **/
        top: 60px; /** camera access needs a bit more space **/
        right: 20px;
        z-index: 9999;
    }
</style>
<div class="canvas-wrapper"> <!-- this wrapper is necessary for WebXR https://github.com/meta-quest/immersive-web-emulator/issues/55 -->
    <canvas data-needle-engine-version=${Ee}></canvas>
</div>
<div class="content">
    <slot class="overlay-content" style="display: contents;"></slot>
</div>
`,this.shadowRoot.appendChild(e.content.cloneNode(!0)),we(Ge,{element:this.shadowRoot}),this.addEventListener(`ready`,this.onReady),this.addEventListener(`error`,this.onError)}ensureInitialized(){this._didInitialize||(this._didInitialize=!0,this.initializeDom())}initializeDom(){rt(),this.setAttribute(`role`,`application`),this.setAttribute(`aria-label`,`Needle Engine 3D scene`)}connectedCallback(){if(K&&console.log(`<needle-engine> connected`),this.ensureInitialized(),this.setPublicKey(),this.setVersion(),(this.getAttribute(`tabindex`)===null||this.getAttribute(`tabindex`)===void 0)&&this.setAttribute(`tabindex`,`0`),this._overlay_ar=new Ss,this.getOrCreateContext(),this.addEventListener(`xr-session-started`,this.onXRSessionStarted),this.onSetupDesktop(),!this.getAttribute(`src`)){let e=globalThis[`needle:codegen_files`];K&&console.log(`src is null, trying to load from globalThis["needle:codegen_files"]`,e),e&&(K&&console.log(`globalThis["needle:codegen_files"]`,e),this.setAttribute(`src`,e))}K&&console.log(`src`,this.getAttribute(`src`));let e=this._loadId;setTimeout(()=>{this.isConnected!==!1&&e===this._loadId&&this.onLoad()},1)}disconnectedCallback(){this.removeEventListener(`xr-session-started`,this.onXRSessionStarted),this._didFullyLoad=!1;let e=this.getAttribute(`keep-alive`),t=e==null||e?.length>0&&e!==`true`&&e!==`1`;K&&console.warn(`<needle-engine> disconnected, keep-alive: "`+e+`"`,typeof e,`Dispose=`,t),t?(K&&console.warn(`<needle-engine> dispose`),this._context?.dispose(),this._context=null,this._lastSourceFiles=null,this._loadId+=1):K&&console.warn(`<needle-engine> is not disposed because keep-alive is set`)}connectedMoveCallback(){}attributeChangedCallback(e,t,n){switch(K&&console.log(`attributeChangedCallback`,e,t,n),e){case`src`:K&&console.warn(`<needle-engine src>
changed from "`,t,`" to "`,n,`"`),this.onLoad();break;case`hash`:this._context&&(this._context.hash=n);break;case`loadstart`:case`progress`:case`loadfinished`:typeof n==`string`&&n.length>0&&(K&&console.log(e+` attribute changed`,n),this.registerEventFromAttribute(e,n));break;case`dracoDecoderPath`:K&&console.log(`dracoDecoderPath`,n),vn(n);break;case`dracoDecoderType`:n===`wasm`||n===`js`?(K&&console.log(`dracoDecoderType`,n),gn(n)):console.error(`Invalid dracoDecoderType`,n,`expected js or wasm`);break;case`ktx2DecoderPath`:K&&console.log(`ktx2DecoderPath`,n),Mn(n);break;case`tonemapping`:case`tone-mapping`:case`tone-mapping-exposure`:case`background-blurriness`:case`background-color`:case`environment-intensity`:this.applyAttributes();break;case`public-key`:n!=`npk_95953b9200a35d0aaefda4761b4646dd1e3a100122be365466f01340a7236289`&&this.setPublicKey();break;case`version`:n!=`5.0.3`&&this.setVersion();break;case`focus-rect`:{let e=this.getAttribute(`focus-rect`);if(e){let t=this.getOrCreateContext();if(e===null)t.setCameraFocusRect(null);else if(typeof e==`string`&&e.length>0){let n=document.querySelector(e);n||console.warn(`No element found for focus-rect selector: ${e}`),t.setCameraFocusRect(n instanceof HTMLElement?n:null)}else e instanceof HTMLElement?t.setCameraFocusRect(e):console.warn(`Invalid focus-rect value. Expected a CSS selector string or an HTMLElement.`,e)}}break}}get toneMapping(){return this.getAttribute(`tonemapping`)||this.getAttribute(`tone-mapping`)}_loadId=0;_abortController=null;_lastSourceFiles=null;_createContextPromise=null;getOrCreateContext(){return this._context||=(K&&console.warn(`Create new context`),new _t({domElement:this})),this._context}async onLoad(){if(!this.isConnected)return;let e=this.getOrCreateContext(),t=this.getSourceFiles();if(!this.checkIfSourceHasChanged(t,this._lastSourceFiles))return;this._abortController&&=(K&&console.warn(`Abort previous loading process`),this._abortController.abort(),null),this._lastSourceFiles=t;let n=++this._loadId;if((t==null||t.length<=0)&&(K&&console.warn(`Clear scene`,t),e.clear(),n!==this._loadId))return;let r=this.getAttribute(`alias`);this.classList.add(`loading`);let i=Et();this.ensureLoadStartIsRegistered();let a=this.dispatchEvent(new CustomEvent(`loadstart`,{detail:{context:e,alias:r},cancelable:!0}));if(i){let e=this.getAttribute(`hide-loading-overlay`);e!=null&&e!==`0`&&(a=!1)}a===!1&&!i&&(h()||(a=!0),console.warn(`Needle Engine: You need a commercial license to override the default loading view. Visit https://needle.tools/pricing`),h()&&E(`You need a <a target="_blank" href="https://needle.tools/pricing">commercial license</a> to override the default loading view. This will not work in production.`)),!this._loadingView&&a&&(this._loadingView=new Es(this)),a&&(this._didFullyLoad===!0?setTimeout(()=>{this._loadingView&&this._loadingProgress01<.3&&this._loadId===n&&this._loadingView.onLoadingBegin(`begin load`)},300):this._loadingView?.onLoadingBegin(`begin load`)),K&&console.warn(`--------------
Needle Engine: Begin loading `+n+`
`,t),this.onBeforeBeginLoading();let o=[],s={context:this._context,name:``,progress:{},index:0,count:t.length,totalProgress01:this._loadingProgress01},c=new CustomEvent(`progress`,{detail:s}),l=[],u=new AbortController;this._abortController=u;let ee={files:t,abortSignal:u.signal,onLoadingProgress:e=>{if(K&&console.debug(`Loading progress: `,e),u.signal.aborted)return;let t=e.index;!l[t]&&e.name&&(l[t]=Ms(e.name)),e.name=l[t],a&&this._loadingView?.onLoadingUpdate(e),s.name=e.name,s.progress=e.progress,this._loadingProgress01=Ts(e),s.totalProgress01=this._loadingProgress01,this.dispatchEvent(c)},onLoadingFinished:(e,t,n)=>{K&&console.debug(`Finished loading \"${t}\" (aborted? ${u.signal.aborted})`),!u.signal.aborted&&n&&o.push({src:t,file:n})}};Ns(this);let te=this.getAttribute(`hash`);te!=null&&(e.hash=te),e.alias=r,this._createContextPromise=e.create(ee);let ne=await this._createContextPromise;if(this.applyAttributes(),K&&console.warn(`--------------
Needle Engine: finished loading `+n+`
`,t,`Aborted? ${u.signal.aborted}`),u.signal.aborted){console.log(`Loading finished but aborted...`);return}if(this._loadId!==n){console.log(`Load id changed during loading process`);return}this._loadingProgress01=1,a&&ne&&this._loadingView?.onLoadingUpdate(1,`creating scene`),this._didFullyLoad=!0,this.classList.remove(`loading`),this.classList.add(`loading-finished`),this.dispatchEvent(new CustomEvent(`loadfinished`,{detail:{context:this._context,src:r,loadedFiles:o}}))}applyAttributes(){let e=this.getOrCreateContext();if(e.renderer){let t=ct(this.toneMapping);t!==void 0&&(e.renderer.toneMapping=t);let n=this.getAttribute(`tone-mapping-exposure`);if(n!=null){let t=parseFloat(n);isNaN(t)||(e.renderer.toneMappingExposure=t)}}let t=this.getAttribute(`background-blurriness`);if(t!=null){let n=parseFloat(t);isNaN(n)||(e.scene.backgroundBlurriness=n)}let n=this.getAttribute(`environment-intensity`);if(n!=null){let t=parseFloat(n);isNaN(t)||(e.scene.environmentIntensity=t)}let r=this.getAttribute(`background-color`);if(e.renderer)if(typeof r==`string`&&r.length>0){let t=S.fromColorRepresentation(r);K&&console.debug(`<needle-engine> background-color changed, str:`,r,`→`,t),e.renderer.setClearColor(t,t.alpha),e.scene.background=null}else this.getAttribute(`background-image`)&&this.setAttribute(`background-image`,this.getAttribute(`background-image`))}onXRSessionStarted=()=>{let e=this.getOrCreateContext(),t=e.xrSessionMode;t===`immersive-ar`?this.onEnterAR(e.xrSession):t===`immersive-vr`&&this.onEnterVR(e.xrSession),e.xrSession?.addEventListener(`end`,()=>{this.dispatchEvent(new CustomEvent(`xr-session-ended`,{detail:{session:e.xrSession,context:this._context,sessionMode:t}})),t===`immersive-ar`?this.onExitAR(e.xrSession):t===`immersive-vr`&&this.onExitVR(e.xrSession)})};onReady=()=>this._loadingView?.onLoadingFinished();onError=()=>this._loadingView?.setMessage(`Loading failed!`);getSourceFiles(){let e=this.getAttribute(`src`);if(!e)return[];let t;t=Array.isArray(e)?e:e.startsWith(`[`)&&e.endsWith(`]`)?JSON.parse(e):e.includes(`,`)?e.split(`,`):[e];for(let e=t.length-1;e>=0;e--){let n=t[e];(n===`null`||n===`undefined`||n?.length<=0)&&t.splice(e,1)}return t}checkIfSourceHasChanged(e,t){if(e?.length!==t?.length||e==null&&t!==null||e!==null&&t==null)return!0;if(e!==null&&t!==null){for(let n=0;n<e?.length;n++)if(e[n]!==t[n])return!0}return!1}_previouslyRegisteredMap=new Map;ensureLoadStartIsRegistered(){let e=this.getAttribute(`loadstart`);e&&this.registerEventFromAttribute(`loadstart`,e)}registerEventFromAttribute(e,t){let n=this._previouslyRegisteredMap.get(e);if(n&&(this._previouslyRegisteredMap.delete(e),this.removeEventListener(e,n)),typeof t==`string`&&t.length>0)try{let n=(0,eval)(t);typeof n==`function`&&(this._previouslyRegisteredMap.set(e,n),this.addEventListener(e,e=>n?.call(globalThis,this.getOrCreateContext(),e)))}catch(n){console.error(`Error registering event `+e+`="`+t+`" failed with the following error:
`,n)}}setPublicKey(){this.setAttribute(`public-key`,lt)}setVersion(){this.setAttribute(`version`,Ee)}getAROverlayContainer(){return this._overlay_ar.createOverlayContainer(this)}getVROverlayContainer(){for(let e=0;e<this.children.length;e++){let t=this.children[e];if(t.classList.contains(`vr`))return t}return null}onEnterAR(e){let t=this.getOrCreateContext();this.onSetupAR();let n=this.getAROverlayContainer();this._overlay_ar.onBegin(t,n,e),this.dispatchEvent(new CustomEvent(`enter-ar`,{detail:{session:e,context:t,htmlContainer:this._overlay_ar?.ARContainer}}))}onExitAR(e){let t=this.getOrCreateContext();this._overlay_ar.onEnd(t),this.onSetupDesktop(),this.dispatchEvent(new CustomEvent(`exit-ar`,{detail:{session:e,context:t,htmlContainer:this._overlay_ar?.ARContainer}}))}onEnterVR(e){let t=this.getOrCreateContext();this.onSetupVR(),this.dispatchEvent(new CustomEvent(`enter-vr`,{detail:{session:e,context:t}}))}onExitVR(e){let t=this.getOrCreateContext();this.onSetupDesktop(),this.dispatchEvent(new CustomEvent(`exit-vr`,{detail:{session:e,context:t}}))}onSetupAR(){this.classList.add(q),this.classList.remove(J);let e=this.getAROverlayContainer();K&&console.warn(`onSetupAR:`,e),e&&(e.classList.add(q),e.classList.remove(J)),this.foreachHtmlElement(e=>this.setupElementsForMode(e,`ar`))}onSetupVR(){this.classList.remove(q),this.classList.remove(J),this.foreachHtmlElement(e=>this.setupElementsForMode(e,Ds))}onSetupDesktop(){this.classList.remove(q),this.classList.add(J);let e=this.getAROverlayContainer();e&&(e.classList.remove(q),e.classList.add(J)),this.foreachHtmlElement(e=>this.setupElementsForMode(e,Os))}setupElementsForMode(e,t,n=null){if(e!==this._context?.renderer?.domElement&&!(e.id===`VRButton`||e.id===`ARButton`))if(e.classList.contains(t))e.style.visibility=`visible`,e.style.display===`none`&&(e.style.display=`block`);else for(let t of ks)e.classList.contains(t)&&(e.style.visibility=`hidden`,e.style.display=`none`)}foreachHtmlElement(e){for(let t=0;t<this.children.length;t++){let n=this.children[t];n.style&&e(n)}}onBeforeBeginLoading(){let e=this.getAttribute(`dracoDecoderPath`);e&&(K&&console.log(`using custom draco decoder path`,e),vn(e));let t=this.getAttribute(`dracoDecoderType`);t&&(K&&console.log(`using custom draco decoder type`,t),gn(t));let n=this.getAttribute(`ktx2DecoderPath`);n&&(K&&console.log(`using custom ktx2 decoder path`,n),Mn(n))}setAttribute(e,t){super.setAttribute(e,typeof t==`string`?t:String(t))}getAttribute(e){return super.getAttribute(e)}addEventListener(e,t,n){return super.addEventListener(e,t,n)}};function Ms(e){if(e.startsWith(`blob:`))return`blob`;let t=e.split(`/`),n=t[t.length-1],r=n.indexOf(`?`);r>0&&(n=n.substring(0,r));let i=n.indexOf(`=`);i>0&&(n=n.substring(i));let a=n.split(`.`).pop(),o=a?[`glb`,`gltf`,`usdz`,`usd`,`fbx`,`obj`,`mtl`].indexOf(a.toLowerCase()):-1;if(a&&o>=0&&(n=n.substring(0,n.length-a.length-1)),n=decodeURIComponent(n),n.length>3){let e=``,t=!1,r=[`(`,`)`,`[`,`]`,`{`,`}`,`:`,`;`,`,`,`.`,`!`,`?`];for(let i=0;i<n.length;i++){let a=n[i];(a===`_`||a===`-`)&&(a=` `),!(a===` `&&e.length<=0)&&(r.includes(a)||(e.length===0&&(a=a.toUpperCase()),!(t&&a===` `)&&(t&&(a=a.toUpperCase()),t=!1,e+=a,a===` `&&(t=!0))))}return h()&&n!==e&&console.debug(`Generated display name: "`+n+`" → "`+e+`"`),e.trim()}return n}function Ns(e){Qt(t=>{let n=e.getAttribute(`loading-blur`);if(n!==null&&n!==`0`&&t.domElement===e){let r=t.lodsManager.manager?.awaitLoading({frames:5,signal:AbortSignal.timeout(1e4),maxPromisesPerObject:1}).catch(e=>{}),i=`20px`;if(n.endsWith(`px`)&&(i=n),t.scene.background===null){let n=e,a=t.renderer.domElement,o=a.style.filter,s=a.style.overflow;a.style.filter+=`blur(${i})`,n.style.overflow=`hidden`,r?.then(()=>{let e=a.animate([{filter:`blur(0px)`}],{duration:170,easing:`ease-in`});e.onfinish=()=>{a.style.filter=o,n.style.overflow=s}})}else{let e=document.createElement(`div`);t.domElement.prepend(e),e.style.cssText=`position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 10; pointer-events: none`,e.style.backdropFilter=`blur(${i})`,r?.then(()=>{let t=e.animate([{backdropFilter:`blur(0px)`,opacity:0}],{duration:170,easing:`ease-in`});t.onfinish=()=>{e.remove()}})}}},{once:!0})}function Ps(){typeof window>`u`||(window.customElements.get(`needle-engine`)||window.customElements.define(`needle-engine`,js),window.customElements.get(`needle-button`)||window.customElements.define(`needle-button`,bs),window.customElements.get(`needle-logo-element`)||window.customElements.define(`needle-logo-element`,$t),window.customElements.get(`needle-menu`)||window.customElements.define(`needle-menu`,_e))}var Fs=!1;function Is(){Fs||(Fs=!0,Ps(),er(),ke(),Vr(),gs(),ot(),vs(),Qi(),is(),setTimeout(Jo,1e3),Ko(),Wo(),vi(),ca())}var Y=b(`debugphysics`),Ls=b(`debugcolliderplacement`),Rs=b(`debugcollisions`),zs=b(`showcolliders`),Bs=b(`debugraycasts`),X=Symbol(`needle component`),Z=Symbol(`physics body`),Vs=Symbol(`rigidbody`);globalThis.NEEDLE_USE_RAPIER=globalThis.NEEDLE_USE_RAPIER===void 0?!0:globalThis.NEEDLE_USE_RAPIER,Y&&console.log(`Use Rapier`,!0,globalThis.NEEDLE_USE_RAPIER),ut.registerCallback(at.ContextCreationStart,e=>{Y&&console.log(`Register rapier physics backend`),e.context.physics.engine=new Hs(e.context)});var Hs=class e{debugRenderColliders=!1;debugRenderRaycasts=!1;removeBody(e){if(Y&&console.log(`REMOVE BODY`,e?.name,e[Z]),!e)return;this.validate();let t=e[Z];if(e[Z]=null,t&&this.world){let t=this.objects.findIndex(t=>t===e);if(t>=0){let e=this.bodies[t];if(this.bodies.splice(t,1),this.objects.splice(t,1),e instanceof w.RAPIER_PHYSICS.MODULE.Collider){let t=e;this.world?.removeCollider(t,!0);let n=t.parent();n&&n.numColliders()<=0&&(n[X]||this.world?.removeRigidBody(n))}else e instanceof w.RAPIER_PHYSICS.MODULE.RigidBody&&(e.numColliders()<=0?this.world?.removeRigidBody(e):h()&&(e.did_log_removing||setTimeout(()=>{e.numColliders()>0&&(e.did_log_removing=!0,console.warn(`RapierPhysics: removing rigidbody with colliders from the physics world is not possible right now, please remove the colliders first`))},1)))}}}setColliderEnabled(e,t){let n=e[Z];return n?(n.setEnabled(t),Y&&console.log(`SET COLLIDER ENABLED`,e.name,t),!0):!1}updateBody(e,t,n){if(this.validate(),this.enabled&&!(e.destroyed||!e.gameObject)&&!(!t&&!n))if(e.isCollider===!0)console.warn(`TODO: implement updating collider position`);else{let r=e,i=r[Z];i&&this.syncPhysicsBody(r.gameObject,i,t,n)}}updateProperties(e){if(this.validate(),e.isCollider){let t=e,n=t[Z];n&&(this.internalUpdateColliderProperties(t,n),t.sharedMaterial&&this.updatePhysicsMaterial(t))}else{let t=e,n=this.internal_getRigidbody(t);n&&this.internalUpdateRigidbodyProperties(t,n)}}addForce(e,t,n){this.validate();let r=this.internal_getRigidbody(e);r?r.addForce(t,n):this._isInitialized&&console.warn(`Physics Body doesn't exist: can not apply force (does your object with the Rigidbody have a collider?)`)}addImpulse(e,t,n){this.validate();let r=this.internal_getRigidbody(e);r?r.applyImpulse(t,n):this._isInitialized&&console.warn(`Physics Body doesn't exist: can not apply impulse (does your object with the Rigidbody have a collider?)`)}getLinearVelocity(e){this.validate();let t=this.internal_getRigidbody(e);return t?t.linvel():null}getAngularVelocity(e){this.validate();let t=this.internal_getRigidbody(e);return t?t.angvel():null}resetForces(e,t){this.validate(),this.internal_getRigidbody(e)?.resetForces(t)}resetTorques(e,t){this.validate(),this.internal_getRigidbody(e)?.resetTorques(t)}applyImpulse(e,t,n){this.validate();let r=this.internal_getRigidbody(e);r?r.applyImpulse(t,n):this._isInitialized&&console.warn(`Rigidbody doesn't exist: can not apply impulse (does your object with the Rigidbody have a collider?)`)}wakeup(e){this.validate();let t=this.internal_getRigidbody(e);t?t.wakeUp():this._isInitialized&&console.warn(`Rigidbody doesn't exist: can not wake up (does your object with the Rigidbody have a collider?)`)}isSleeping(e){return this.validate(),this.internal_getRigidbody(e)?.isSleeping()}setAngularVelocity(e,t,n){this.validate();let r=this.internal_getRigidbody(e);r?r.setAngvel(t,n):this._isInitialized&&console.warn(`Rigidbody doesn't exist: can not set angular velocity (does your object with the Rigidbody have a collider?)`)}setLinearVelocity(e,t,n){this.validate();let r=this.internal_getRigidbody(e);r?r.setLinvel(t,n):this._isInitialized&&console.warn(`Rigidbody doesn't exist: can not set linear velocity (does your object with the Rigidbody have a collider?)`)}context;_initializePromise;_isInitialized=!1;constructor(e){this.context=e}get isInitialized(){return this._isInitialized}async initialize(){return this._initializePromise||=this.internalInitialization(),this._initializePromise}async internalInitialization(){return b(`__nophysics`)?(console.warn(`Physics are disabled`),!1):(Y&&console.log(`Initialize rapier physics engine`),`env`in import.meta,this._hasCreatedWorld?(console.error(`Invalid call to create physics world: world is already created`),!0):(this._hasCreatedWorld=!0,w.RAPIER_PHYSICS.MAYBEMODULE??(Y&&console.trace(`Loading rapier physics engine`),await(await w.RAPIER_PHYSICS.load()).init()),Y&&console.log(`Physics engine initialized, creating world...`),this._world=new w.RAPIER_PHYSICS.MODULE.World(this._gravity),this.rapierRay=new w.RAPIER_PHYSICS.MODULE.Ray({x:0,y:0,z:0},{x:0,y:0,z:1}),this.enabled=!0,this._isInitialized=!0,Y&&console.log(`Physics world created`),!0))}validate(){this._isInitialized||Y&&(this._lastWarnTime=this._lastWarnTime??0,Date.now()-this._lastWarnTime>1e3&&(this._lastWarnTime=Date.now(),console.warn(`Physics engine is not initialized`)))}rapierRay;raycastVectorsBuffer=new de(()=>new n,10);raycast(e,t,n){if(!this._isInitialized)return console.log(`Physics engine is not initialized`),null;let r=n?.maxDistance,i=n?.solid;r===void 0&&(r=1/0),i===void 0&&(i=!0);let a=this.getPhysicsRay(this.rapierRay,e,t);if(!a)return null;(this.debugRenderRaycasts||Bs)&&O.DrawRay(a.origin,a.dir,255,1);let o=this.world?.castRay(a,r,i,n?.queryFilterFlags,n?.filterGroups,void 0,void 0,e=>{let t=e[X];return n?.filterPredicate?n.filterPredicate(t):n?.useIgnoreRaycastLayer===!1?!0:!t?.gameObject.layers.isEnabled(2)});if(o){let e=a.pointAt(o.timeOfImpact),t=this.raycastVectorsBuffer.get();return t.set(e.x,e.y,e.z),{point:t,collider:o.collider[X]}}return null}raycastAndGetNormal(e,t,n){if(!this._isInitialized)return null;let r=n?.maxDistance,i=n?.solid;r===void 0&&(r=1/0),i===void 0&&(i=!0);let a=this.getPhysicsRay(this.rapierRay,e,t);if(!a)return null;(this.debugRenderRaycasts||Bs)&&O.DrawRay(a.origin,a.dir,255,1);let o=this.world?.castRayAndGetNormal(a,r,i,n?.queryFilterFlags,n?.filterGroups,void 0,void 0,e=>{let t=e[X];return n?.filterPredicate?n.filterPredicate(t):n?.useIgnoreRaycastLayer===!1?!0:!t?.gameObject.layers.isEnabled(2)});if(o){let e=a.pointAt(o.timeOfImpact),t=o.normal,n=this.raycastVectorsBuffer.get(),r=this.raycastVectorsBuffer.get();return n.set(e.x,e.y,e.z),r.set(t.x,t.y,t.z),{point:n,normal:r,collider:o.collider[X]}}return null}getPhysicsRay(e,t,n){let r=this.context?.mainCamera;if(t===void 0){let e=this.context?.input.getPointerPosition(0);if(e)t=e;else return null}if(t.z===void 0){if(!r)return console.error(`Can not perform raycast from 2d point - no main camera found`),null;let e=this.raycastVectorsBuffer.get();e.x=t.x,e.y=t.y,e.z=0,(e.x>1||e.y>1||e.y<-1||e.x<-1)&&(Y&&console.warn(`Converting screenspace to raycast space`,e),this.context?.input.convertScreenspaceToRaycastSpace(e)),e.unproject(r),t=e}let i=t;e.origin.x=i.x,e.origin.y=i.y,e.origin.z=i.z;let a=this.raycastVectorsBuffer.get();if(n)a.set(n.x,n.y,n.z);else{if(!r)return console.error(`Can not perform raycast - no camera found`),null;a.set(e.origin.x,e.origin.y,e.origin.z);let t=v(r);a.sub(t)}return a.normalize(),e.dir.x=a.x,e.dir.y=a.y,e.dir.z=a.z,e}rapierSphere=null;rapierBox=null;rapierColliderArray=[];rapierIdentityRotation={x:0,y:0,z:0,w:1};rapierForwardVector={x:0,y:0,z:1};sphereOverlap(e,t){return this.rapierSphere??=new w.RAPIER_PHYSICS.MODULE.Ball(t),this.rapierSphere.radius=t,(this.debugRenderRaycasts||Bs)&&O.DrawWireSphere(e,t,3359999,1),this.shapeOverlap(e,this.rapierIdentityRotation,this.rapierSphere)}boxOverlap(e,t,n=null){return n===null&&(n=this.rapierIdentityRotation),this.rapierBox??=new w.RAPIER_PHYSICS.MODULE.Cuboid(1,1,1),this.rapierBox.halfExtents.x=t.x*.5,this.rapierBox.halfExtents.y=t.y*.5,this.rapierBox.halfExtents.z=t.z*.5,(this.debugRenderRaycasts||Bs)&&O.DrawWireBox(e,t,3359999,1,!0,n),this.shapeOverlap(e,n,this.rapierBox)}shapeOverlap(e,t,n){return this.rapierColliderArray.length=0,!this._isInitialized||!this.world||this.world.intersectionsWithShape(e,t,n,e=>{let t=e[X],n=new Je(t.gameObject,t);return this.rapierColliderArray.push(n),!0},void 0,void 0,void 0,void 0,e=>e.isSensor()?!1:e[X].gameObject.layers.isEnabled(2)==0),this.rapierColliderArray}enabled=!1;get world(){return this._world}_tempPosition=new n;_tempQuaternion=new le;_tempScale=new n;_tempMatrix=new te;static _didLoadPhysicsEngine=!1;_isUpdatingPhysicsWorld=!1;get isUpdating(){return this._isUpdatingPhysicsWorld}_world;_hasCreatedWorld=!1;eventQueue;collisionHandler;objects=[];bodies=[];_meshCache=new Map;_gravity={x:0,y:-9.81,z:0};get gravity(){return this.world?.gravity??this._gravity}set gravity(e){this.world?this.world.gravity=e:this._gravity=e}clearCaches(){this._meshCache.clear(),this.eventQueue?.raw&&this.eventQueue?.free(),this.world?.bodies&&this.world?.free()}async addBoxCollider(e,t){if(this._isInitialized||await this.initialize(),!e.activeAndEnabled)return;if(!this.enabled){Y&&console.warn(`Physics are disabled`);return}let n=e.gameObject,r=y(n,this._tempPosition).multiply(t);r.multiplyScalar(.5),r.x<0&&(r.x=Math.abs(r.x)),r.y<0&&(r.y=Math.abs(r.y)),r.z<0&&(r.z=Math.abs(r.z));let i=1e-7;r.x<i&&(r.x=i),r.y<i&&(r.y=i),r.z<i&&(r.z=i);let a=w.RAPIER_PHYSICS.MODULE.ColliderDesc.cuboid(r.x,r.y,r.z);this.createCollider(e,a)}async addSphereCollider(e){if(this._isInitialized||await this.initialize(),!e.activeAndEnabled)return;if(!this.enabled){Y&&console.warn(`Physics are disabled`);return}let t=w.RAPIER_PHYSICS.MODULE.ColliderDesc.ball(.5);this.createCollider(e,t),this.updateProperties(e)}async addCapsuleCollider(e,t,n){if(this._isInitialized||await this.initialize(),!e.activeAndEnabled)return;if(!this.enabled){Y&&console.warn(`Physics are disabled`);return}let r=e.gameObject.worldScale;r.x=Math.abs(r.x),r.y=Math.abs(r.y);let i=n*r.x;t=Math.max(t,i);let a=g.clamp(t*.5*r.y-n*r.x,0,2**53-1),o=w.RAPIER_PHYSICS.MODULE.ColliderDesc.capsule(a,i);this.createCollider(e,o)}async addMeshCollider(e,t,n,r){let i=t.geometry;if(!i){Y&&console.warn(`Missing mesh geometry`,t.name);return}i.index?.array?.length||(console.warn(`Your MeshCollider is missing vertices or indices in the assined mesh \"${t.name}\". Consider providing an indexed geometry.`),i=sn(i));let a=null,o=i.getAttribute(`position`);if(o instanceof ee){let e=o.count;a=new Float32Array(e*3);for(let t=0;t<e;t++){let e=o.getX(t),n=o.getY(t),r=o.getZ(t);a[t*3]=e,a[t*3+1]=n,a[t*3+2]=r}}else a=o.array;if(await this.initialize(),!this.enabled){Y&&console.warn(`Physics are disabled`);return}if(!e.activeAndEnabled)return;let s=i.index?.array,c=e.gameObject.worldScale.clone();if(r&&c.multiply(r),Math.abs(c.x-1)>1e-4||Math.abs(c.y-1)>1e-4||Math.abs(c.z-1)>1e-4){let t=`${i.uuid}_${c.x}_${c.y}_${c.z}_${n}`;if(this._meshCache.has(t))Y&&console.warn(`Use cached mesh collider`),a=this._meshCache.get(t);else{(Y||h())&&console.debug(`[Performance] Your MeshCollider \"${e.name}\" is scaled: consider applying the scale to the collider mesh instead (${c.x}, ${c.y}, ${c.z})`);let n=new Float32Array(a.length);for(let e=0;e<a.length;e+=3)n[e]=a[e]*c.x,n[e+1]=a[e+1]*c.y,n[e+2]=a[e+2]*c.z;a=n,this._meshCache.set(t,n)}}let l=n?w.RAPIER_PHYSICS.MODULE.ColliderDesc.convexHull(a):w.RAPIER_PHYSICS.MODULE.ColliderDesc.trimesh(a,s);l&&this.createCollider(e,l)}updatePhysicsMaterial(e){if(!e)return;let t=e.sharedMaterial,n=e[Z];if(n&&t){if(t.bounciness!==void 0&&n.setRestitution(t.bounciness),t.bounceCombine!==void 0)switch(t.bounceCombine){case m.Average:n.setRestitutionCombineRule(w.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case m.Maximum:n.setRestitutionCombineRule(w.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case m.Minimum:n.setRestitutionCombineRule(w.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case m.Multiply:n.setRestitutionCombineRule(w.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}if(t.dynamicFriction!==void 0&&n.setFriction(t.dynamicFriction),t.frictionCombine!==void 0)switch(t.frictionCombine){case m.Average:n.setFrictionCombineRule(w.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case m.Maximum:n.setFrictionCombineRule(w.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case m.Minimum:n.setFrictionCombineRule(w.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case m.Multiply:n.setFrictionCombineRule(w.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}}}getBody(e){return e?e[Z]:null}getComponent(e){return e?e[X]:null}createCollider(e,t){if(!this.world)throw Error(`Physics world not initialized`);let n=this._tempMatrix,r;e.attachedRigidbody?r=this.getRigidbody(e,this._tempMatrix):(Y&&console.log(`Create collider without rigidbody`,e.name),n.makeRotationFromQuaternion(k(e.gameObject)),n.setPosition(v(e.gameObject))),n.decompose(this._tempPosition,this._tempQuaternion,this._tempScale),this.tryApplyCenter(e,this._tempPosition),t.setTranslation(this._tempPosition.x,this._tempPosition.y,this._tempPosition.z),t.setRotation(this._tempQuaternion),t.setSensor(e.isTrigger);let i=e.sharedMaterial;if(i){if(i.bounciness!==void 0&&t.setRestitution(i.bounciness),i.bounceCombine!==void 0)switch(i.bounceCombine){case m.Average:t.setRestitutionCombineRule(w.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case m.Maximum:t.setRestitutionCombineRule(w.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case m.Minimum:t.setRestitutionCombineRule(w.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case m.Multiply:t.setRestitutionCombineRule(w.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}if(i.dynamicFriction!==void 0&&t.setFriction(i.dynamicFriction),i.frictionCombine!==void 0)switch(i.frictionCombine){case m.Average:t.setFrictionCombineRule(w.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case m.Maximum:t.setFrictionCombineRule(w.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case m.Minimum:t.setFrictionCombineRule(w.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case m.Multiply:t.setFrictionCombineRule(w.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}}e.attachedRigidbody?.autoMass===!1&&(t.setDensity(1e-6),t.setMass(1e-6));try{let n=this.world.createCollider(t,r);return n[X]=e,e[Z]=n,n.setActiveEvents(w.RAPIER_PHYSICS.MODULE.ActiveEvents.COLLISION_EVENTS),n.setActiveCollisionTypes(w.RAPIER_PHYSICS.MODULE.ActiveCollisionTypes.ALL),this.objects.push(e),this.bodies.push(n),this.updateColliderCollisionGroups(e),Y&&console.log(`Created collider`,e.name,n),n}catch(t){return console.error(`Error creating collider "`+e.name+`"
Error:`,t),null}}updateColliderCollisionGroups(e){let t=e[Z],n=e.membership,r=0;if(n==null)r=65535;else for(let e=0;e<n.length;e++){let t=n[e];t>31?console.error(`Rapier only supports 32 layers, layer ${t} is not supported`):r|=1<<Math.floor(t)}let i=e.filter,a=0;if(i==null)a=65535;else for(let e=0;e<i.length;e++){let t=i[e];t>31?console.error(`Rapier only supports 32 layers, layer ${t} is not supported`):a|=1<<Math.floor(t)}t.setCollisionGroups(r<<16|a)}getRigidbody(e,t){if(!this.world)throw Error(`Physics world not initialized`);let n=null;if(e.attachedRigidbody){let r=e.attachedRigidbody;if(n=r[Z],!n){let t=r.isKinematic&&!Ls;Y&&console.log(`Create rigidbody`,t);let i=t?w.RAPIER_PHYSICS.MODULE.RigidBodyDesc.kinematicPositionBased():w.RAPIER_PHYSICS.MODULE.RigidBodyDesc.dynamic(),a=v(e.attachedRigidbody.gameObject);i.setTranslation(a.x,a.y,a.z),i.setRotation(k(e.attachedRigidbody.gameObject)),i.centerOfMass=new w.RAPIER_PHYSICS.MODULE.Vector3(r.centerOfMass.x,r.centerOfMass.y,r.centerOfMass.z),n=this.world.createRigidBody(i),this.bodies.push(n),this.objects.push(r)}n[X]=r,r[Z]=n,this.internalUpdateRigidbodyProperties(r,n),this.getRigidbodyRelativeMatrix(e.gameObject,r.gameObject,t),e[Vs]=n}else{let r=w.RAPIER_PHYSICS.MODULE.RigidBodyDesc.kinematicPositionBased(),i=v(e.gameObject);r.setTranslation(i.x,i.y,i.z),r.setRotation(k(e.gameObject)),n=this.world.createRigidBody(r),t.identity(),n[X]=null}return n}internal_getRigidbody(e){return e.isCollider===!0?e[Vs]:e[Z]}internalUpdateColliderProperties(e,t){let n=t.shape,r=!1;switch(n.type){case w.RAPIER_PHYSICS.MODULE.ShapeType.Ball:{let i=n,a=e,o=e.gameObject,s=y(o,this._tempPosition),c=Math.abs(a.radius*s.x);r=i.radius!==c,i.radius=c,r&&t.setShape(i);break}case w.RAPIER_PHYSICS.MODULE.ShapeType.Cuboid:let i=n,a=e,o=e.gameObject,s=y(o,this._tempPosition),c=Math.abs(a.size.x*.5*s.x),l=Math.abs(a.size.y*.5*s.y),u=Math.abs(a.size.z*.5*s.z);r=i.halfExtents.x!==c||i.halfExtents.y!==l||i.halfExtents.z!==u,i.halfExtents.x=c,i.halfExtents.y=l,i.halfExtents.z=u,r&&t.setShape(i);break}if(r){let t=e.attachedRigidbody;t?.autoMass&&this.getBody(t)?.recomputeMassPropertiesFromColliders()}this.updateColliderCollisionGroups(e),e.isTrigger!==t.isSensor()&&t.setSensor(e.isTrigger)}internalUpdateRigidbodyProperties(e,t){if(t.enableCcd(e.collisionDetectionMode!==st.Discrete),t.setLinearDamping(e.drag),t.setAngularDamping(e.angularDrag),t.setGravityScale(e.useGravity?e.gravityScale:0,!0),e.dominanceGroup<=127&&e.dominanceGroup>=-127?t.setDominanceGroup(Math.floor(e.dominanceGroup)):t.setDominanceGroup(0),e.autoMass){t.setAdditionalMass(0,!1);for(let e=0;e<t.numColliders();e++)t.collider(e).setDensity(1);t.recomputeMassPropertiesFromColliders()}else{t.setAdditionalMass(e.mass,!1);for(let e=0;e<t.numColliders();e++)t.collider(e).setDensity(1e-7);t.recomputeMassPropertiesFromColliders()}t.setEnabledRotations(!e.lockRotationX,!e.lockRotationY,!e.lockRotationZ,!1),t.setEnabledTranslations(!e.lockPositionX,!e.lockPositionY,!e.lockPositionZ,!1),e.isKinematic?t.setBodyType(w.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicPositionBased,!1):t.setBodyType(w.RAPIER_PHYSICS.MODULE.RigidBodyType.Dynamic,!1)}lines;disabledLines;step(e){if(this.world&&this.enabled){if(this._isUpdatingPhysicsWorld=!0,this.eventQueue||=new w.RAPIER_PHYSICS.MODULE.EventQueue(!1),e===void 0||e<=0){this._isUpdatingPhysicsWorld=!1;return}else if(e!==void 0){let t=g.lerp(this.world.timestep,e,.8);this.world.timestep=t}try{this.world.step(this.eventQueue)}catch(e){console.warn(`Error running physics step`,{timestep:this.world.timestep},e)}this._isUpdatingPhysicsWorld=!1}}postStep(){this.world&&this.enabled&&(this._isUpdatingPhysicsWorld=!0,this.syncObjects(),this._isUpdatingPhysicsWorld=!1,this.eventQueue&&!this.collisionHandler&&(this.collisionHandler=new Us(this.world,this.eventQueue)),this.collisionHandler&&(this.collisionHandler.handleCollisionEvents(),this.collisionHandler.update()),this.updateDebugRendering(this.world))}updateDebugRendering(e){if(Y||Ls||zs||this.debugRenderColliders===!0){if(!this.lines){let e=new s({color:7855479,fog:!1});this.lines=new o(new u,e),this.lines.layers.disableAll(),this.lines.layers.enable(2)}if(!this.disabledLines){let e=new s({color:14514039,fog:!1});this.disabledLines=new o(new u,e),this.disabledLines.layers.disableAll(),this.disabledLines.layers.enable(2)}this.lines.parent!==this.context?.scene&&this.context?.scene.add(this.lines),this.disabledLines.parent!==this.context?.scene&&this.context?.scene.add(this.disabledLines);let t=e.debugRender(void 0,e=>e.isEnabled());this.lines.geometry.setAttribute(`position`,new p(t.vertices,3)),this.lines.geometry.setAttribute(`color`,new p(t.colors,4));let n=e.debugRender(void 0,e=>!e.isEnabled());this.disabledLines.geometry.setAttribute(`position`,new p(n.vertices,3)),this.disabledLines.geometry.setAttribute(`color`,new p(n.colors,4)),this.disabledLines.visible=n.vertices.length>0,(this.context.time.frame%30==0||this.lines.geometry.boundingSphere?.radius===0)&&(this.lines.geometry.computeBoundingSphere(),this.disabledLines.geometry.computeBoundingSphere())}else this.lines&&this.context?.scene.remove(this.lines),this.disabledLines&&this.context?.scene.remove(this.disabledLines)}syncObjects(){if(!Ls)for(let e=0;e<this.bodies.length;e++){let t=this.objects[e],n=this.bodies[e],r=t;if(r?.isCollider===!0&&!r.attachedRigidbody){let e=n.parent();e?this.syncPhysicsBody(t.gameObject,e,!0,!0):this.syncPhysicsBody(t.gameObject,n,!0,!0);continue}let i=n.translation(),a=n.rotation();if(Number.isNaN(i.x)||Number.isNaN(a.x)){!r.__COLLIDER_NAN&&h()&&(console.warn(`Collider has NaN values`,r.name,r.gameObject,n),r.__COLLIDER_NAN=!0);continue}let o=t.center;if(o&&o.isVector3){this._tempQuaternion.set(a.x,a.y,a.z,a.w);let e=this._tempPosition.copy(o).applyQuaternion(this._tempQuaternion),n=y(t.gameObject);e.multiply(n),i.x-=e.x,i.y-=e.y,i.z-=e.z}jt(t.gameObject,i.x,i.y,i.z),He(t.gameObject,a.x,a.y,a.z,a.w)}}syncPhysicsBody(e,t,n,r){if(t instanceof w.RAPIER_PHYSICS.MODULE.RigidBody){let i=v(e,this._tempPosition),a=k(e,this._tempQuaternion);switch(t.bodyType()){case w.RAPIER_PHYSICS.MODULE.RigidBodyType.Fixed:case w.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicPositionBased:case w.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicVelocityBased:n&&t.setNextKinematicTranslation(i),r&&t.setNextKinematicRotation(a);break;default:n&&t.setTranslation(i,!1),r&&t.setRotation(a,!1);break}}else if(t instanceof w.RAPIER_PHYSICS.MODULE.Collider){e.matrixWorldNeedsUpdate&&e.updateWorldMatrix(!0,!1),e.matrixWorld.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);let i=this._tempPosition,a=this._tempQuaternion,o=t[X];if(this.tryApplyCenter(o,i),n){let e=t.translation();(e.x!==i.x||e.y!==i.y||e.z!==i.z)&&t.setTranslation(i)}if(r){let e=t.rotation();(e.x!==a.x||e.y!==a.y||e.z!==a.z||e.w!==a.w)&&t.setRotation(a)}}}_tempCenterPos=new n;_tempCenterVec=new n;_tempCenterQuaternion=new le;tryApplyCenter(e,t){let n=e.center;n&&e.gameObject&&(n.x!==0||n.y!==0||n.z!==0)&&(this._tempCenterPos.x=n.x,this._tempCenterPos.y=n.y,this._tempCenterPos.z=n.z,y(e.gameObject,this._tempCenterVec),this._tempCenterPos.multiply(this._tempCenterVec),e.attachedRigidbody?this._tempCenterPos.applyQuaternion(e.gameObject.quaternion):(k(e.gameObject,this._tempCenterQuaternion),this._tempCenterPos.applyQuaternion(this._tempCenterQuaternion)),t.x+=this._tempCenterPos.x,t.y+=this._tempCenterPos.y,t.z+=this._tempCenterPos.z)}static _matricesBuffer=[];getRigidbodyRelativeMatrix(t,n,r,i){if(i===void 0&&(i=e._matricesBuffer,i.length=0),t===n){let e=y(t,this._tempPosition);r.makeScale(e.x,e.y,e.z);for(let e=i.length-1;e>=0;e--)r.multiply(i[e]);return r}return i.push(t.matrix),t.parent&&this.getRigidbodyRelativeMatrix(t.parent,n,r,i),r}static centerConnectionPos={x:0,y:0,z:0};static centerConnectionRot={x:0,y:0,z:0,w:1};addFixedJoint(t,n){if(!this.world){console.error(`Physics world not initialized`);return}let r=t[Z],i=n[Z];this.calculateJointRelativeMatrices(t.gameObject,n.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);let a=w.RAPIER_PHYSICS.MODULE.JointData.fixed(e.centerConnectionPos,e.centerConnectionRot,this._tempPosition,this._tempQuaternion),o=this.world.createImpulseJoint(a,r,i,!0);Y&&console.log(`ADD FIXED JOINT`,o)}addHingeJoint(e,t,n,r){if(!this.world){console.error(`Physics world not initialized`);return}let i=e[Z],a=t[Z];this.calculateJointRelativeMatrices(e.gameObject,t.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);let o=w.RAPIER_PHYSICS.MODULE.JointData.revolute(n,this._tempPosition,r),s=this.world.createImpulseJoint(o,i,a,!0);Y&&console.log(`ADD HINGE JOINT`,s)}calculateJointRelativeMatrices(e,t,n){e.updateWorldMatrix(!0,!1),t.updateWorldMatrix(!0,!1);let r=e.matrixWorld,i=t.matrixWorld;r.elements[0]=1,r.elements[5]=1,r.elements[10]=1,i.elements[0]=1,i.elements[5]=1,i.elements[10]=1,n.copy(i).premultiply(r.invert()).invert()}},Us=class{world;eventQueue;constructor(e,t){this.world=e,this.eventQueue=t}activeCollisions=[];activeCollisionsStay=[];activeTriggers=[];handleCollisionEvents(){this.eventQueue&&this.world&&this.eventQueue.drainCollisionEvents((e,t,n)=>{let r=this.world.getCollider(e),i=this.world.getCollider(t);if(!r||!i)return;let a=r[X],o=i[X];Rs&&console.log(`EVT`,a.name,o.name,n,r,i),a&&o&&(n?(this.onCollisionStarted(a,r,o,i),this.onCollisionStarted(o,i,a,r)):(this.onCollisionEnded(a,o),this.onCollisionEnded(o,a)))})}update(){this.onHandleCollisionStay()}onCollisionStarted(e,t,n,r){let i=null;if(e.isTrigger||n.isTrigger)Pt(e.gameObject,t=>{t.onTriggerEnter&&!t.destroyed&&t.onTriggerEnter(n),this.activeTriggers.push({collider:e,component:t,otherCollider:n})});else{let a=e.gameObject;this.world.contactPair(t,r,(t,r)=>{Pt(a,r=>{if(r.destroyed)return;let o=r.onCollisionEnter||r.onCollisionStay||r.onCollisionExit;if(o||Rs){if(!i){let e=[],r=t.normal();n instanceof Un&&n.convex&&(r.x=-r.x,r.y=-r.y,r.z=-r.z);for(let n=0;n<t.numSolverContacts();n++){let i=t.solverContactPoint(n),a=t.contactImpulse(n);if(i){let o=new Ve(i,t.contactDist(n),r,a,t.solverContactFriction(n),t.solverContactTangentVelocity(n));e.push(o),Rs&&O.DrawDirection(i,r,16711680,3,!0)}}i=new Mt(a,n,e)}if(o){let t={collider:e,component:r,collision:i};this.activeCollisions.push(t),r.onCollisionStay&&this.activeCollisionsStay.push(t),r.onCollisionEnter?.call(r,i)}}})})}}onHandleCollisionStay(){for(let e of this.activeCollisionsStay){let t=e.component;if(!t.destroyed&&t.activeAndEnabled&&t.onCollisionStay){if(e.collision.collider.destroyed)continue;let n=e.collision;t.onCollisionStay(n)}}for(let e of this.activeTriggers){let t=e.component;if(!t.destroyed&&t.activeAndEnabled&&t.onTriggerStay){let n=e.otherCollider;if(n.destroyed)continue;t.onTriggerStay(n)}}}onCollisionEnded(e,t){if(!(e.destroyed||t.destroyed)){for(let n=0;n<this.activeCollisions.length;n++){let r=this.activeCollisions[n],i=r.collider;if(i.destroyed||r.collision.collider.destroyed){this.activeCollisions.splice(n,1),n--;continue}if(i===e&&r.collision.collider===t){let e=r.component;if(this.activeCollisions.splice(n,1),n--,e.activeAndEnabled&&e.onCollisionExit){let t=r.collision;e.onCollisionExit(t)}}}for(let n=0;n<this.activeCollisionsStay.length;n++){let r=this.activeCollisionsStay[n],i=r.collider;if(i.destroyed||r.collision.collider.destroyed){this.activeCollisionsStay.splice(n,1),n--;continue}if(i===e&&r.collision.collider===t){let e=r.component;if(this.activeCollisionsStay.splice(n,1),n--,e.activeAndEnabled&&e.onCollisionExit){let t=r.collision;e.onCollisionExit(t)}}}for(let n=0;n<this.activeTriggers.length;n++){let r=this.activeTriggers[n],i=r.collider;if(i.destroyed||r.otherCollider.destroyed){this.activeTriggers.splice(n,1),n--;continue}if(i===e&&r.otherCollider===t){let e=r.component;if(this.activeTriggers.splice(n,1),n--,e.activeAndEnabled&&e.onTriggerExit){let t=r.otherCollider;e.onTriggerExit(t)}}}}}},Ws=0;function Gs(e){e?Ws++:Ws--}function Ks(){return Ws>0}var qs={binary:!0,animations:!0};async function Js(e){if(!e.context)throw Error(`No context provided to exportAsGLTF`);e.scene||=e.context.scene;let t={...qs,...e},{context:n}=t,r=new on;r.register(e=>new hi(e)),r.register(e=>new Zr(e)),r.register(e=>new pi(e)),Nn(r,t.context);let i={binary:t.binary,animations:Zs(n,t.scene,[])},a=new Xs;console.debug(`Exporting GLTF`,i),a.onBeforeExport(t),Gs(!0);let o=await r.parseAsync(t.scene,i).catch(e=>(console.error(e),null));if(Gs(!1),a.onAfterExport(t),!o)throw Error(`Failed to export GLTF`);if(t.downloadAs!=null){let e=null;if(o instanceof ArrayBuffer?e=new Blob([o],{type:`application/octet-stream`}):console.error(`Can not download GLTF as a blob`,o),e){let n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n;let i=t.downloadAs;!i.endsWith(`.glb`)&&!i.endsWith(`.gltf`)&&(i+=t.binary?`.glb`:`.gltf`),r.download=i,r.click()}}return o}var Ys=Symbol(`needle:weight`),Xs=class{_undo=[];onBeforeExport(e){e.context.animations.mixers.forEach(e=>{let t=Ze.tryGetActionsFromMixer(e);if(t)for(let e=0;e<t.length;e++){let n=t[e];n[Ys]=n.weight,n.weight=0,this._undo.push(()=>{n.weight=n[Ys]})}e.update(0)}),e.context.scene.traverse(e=>{if(!mi(e)){let t=e.parent;t&&(e.removeFromParent(),this._undo.push(()=>t.add(e)))}})}onAfterExport(e){this._undo.forEach(e=>e()),this._undo.length=0}};function Zs(e,t,n){e.animations.mixers.forEach(e=>{let t=Ze.tryGetActionsFromMixer(e);if(t)for(let e=0;e<t.length;e++){let r=t[e].getClip();n.push(r)}}),Array.isArray(t)||(t=[t]);for(let e of t)Ze.tryGetAnimationClipsFromObjectHierarchy(e,n);let r=new Set(n);return Array.from(r)}var Q=b(`debugavatar`),Qs=class{root;head;leftHand;rigthHand;get isValid(){return this.head!==null&&this.head!==void 0}constructor(e,t,n,r){this.root=e,this.head=t,this.leftHand=n,this.rigthHand=r,this.root?.traverse(e=>e.layers.set(2))}},$s=class{avatarRegistryUrl=null;async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error(`Can not create avatar: failed to provide id or root object`),null;let n=null;if(typeof t==`string`){if(n=await this.loadAvatar(e,t),!n){let r=new Ke;n=x.instantiate(Qe(t,e.scene),r)}}else n=t;if(!n)return null;let r=this.findAvatar(n);return r.isValid?(Q&&console.log(`[Custom Avatar] valid config`,t,Q?r:``),r):(console.warn(`[Custom Avatar] config isn't valid`,t,Q?r:``),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(Q&&console.log(`[Custom Avatar] `+t+`, loading...`),t.endsWith(`.glb`)||(t+=`.glb`),this.avatarRegistryUrl===null){let n=await fetch(`./`+t),r=null;if(n.ok){let e=await n.blob();e&&(r=await e.arrayBuffer())}return r?(await be().parseSync(e,r,null,0))?.scene??null:null}let n=new A;return Vn(n,e),new Promise((r,i)=>{let a=this.avatarRegistryUrl+`/`+t;n.load(a,async t=>{await be().createBuiltinComponents(e,a,t,null,void 0),r(t.scene)},e=>{Q&&console.log(`[Custom Avatar] `+e.loaded/e.total*100+`% loaded of `+e.total/1024+`kB`)},e=>{console.error(`[Custom Avatar] Error when loading: `+e),r(null)})})}cacheModel(e,t){}findAvatar(e){let t=e,r=t;r.children.length==1&&(r=e.children[0]);let i=this.findAvatarPart(r,[`head`]),a=this.findAvatarPart(r,[`left`,`hand`]),o=this.findAvatarPart(r,[`right`,`hand`]);if(!i){i=t;let e=new n;new re().setFromObject(i).getSize(e);let r=Math.max(e.x,e.y,e.z);console.warn(`[Custom Avatar] Normalizing head scale, it's too big: `+r+` meters! Should be < 0.3m`),r>.3&&i.scale.multiplyScalar(1/r*.3)}return new Qs(t,i,a,o)}findAvatarPart(e,t){let n=e.name.toLowerCase(),r=!0;for(let e of t){if(!r)break;n.indexOf(e)===-1&&(r=!1)}if(r)return e;if(e.children)for(let n of e.children){let e=this.findAvatarPart(n,t);if(e)return e}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}},ec=class{get extensionName(){return`DocumentExtension`}onAfterBuildDocument(e){}},tc=e({ActionBuilder:()=>jr,ActionCollection:()=>ei,ActionModel:()=>br,AlignmentConstraint:()=>Mi,Animation:()=>vr,AnimationCurve:()=>fa,AnimationExtension:()=>Fn,AnimationTrackHandler:()=>ui,Animator:()=>Xe,AnimatorController:()=>ue,Antialiasing:()=>Ba,Attractor:()=>qr,AudioExtension:()=>Zn,AudioListener:()=>wr,AudioSource:()=>lr,AudioTrackHandler:()=>Gr,Avatar:()=>mr,AvatarBlink_Simple:()=>kn,AvatarEyeLook_Rotation:()=>Sn,AvatarLoader:()=>$s,AvatarMarker:()=>gr,AvatarModel:()=>Qs,Avatar_Brain_LookAt:()=>kr,Avatar_MouthShapes:()=>Qn,Avatar_MustacheShake:()=>Yn,Avatar_POI:()=>ar,AxesHelper:()=>Vi,BaseUIComponent:()=>en,BasicIKConstraint:()=>qi,BehaviorExtension:()=>rr,BehaviorModel:()=>Or,BloomEffect:()=>Ua,BoxCollider:()=>pn,BoxGizmo:()=>cr,BoxHelperComponent:()=>Oi,Button:()=>Wt,CallInfo:()=>pt,Camera:()=>he,CameraTargetReachedEvent:()=>tt,Canvas:()=>Gt,CanvasGroup:()=>Bt,CapsuleCollider:()=>Gn,ChangeMaterialOnClick:()=>fn,ChangeTransformOnClick:()=>Wn,CharacterController:()=>ea,CharacterControllerInput:()=>Ei,ChromaticAberration:()=>Ka,ClickThrough:()=>Wi,ColorAdjustments:()=>La,ColorBySpeedModule:()=>Ta,ColorOverLifetimeModule:()=>Oa,ContactShadows:()=>Rn,ControlTrackHandler:()=>ia,CursorFollow:()=>yi,CustomBranding:()=>Cr,Deletable:()=>bi,DeleteBox:()=>Gi,DepthOfField:()=>Xa,DeviceFlag:()=>Pi,DocumentExtension:()=>ec,DragControls:()=>Ui,DropListener:()=>Ji,Duplicatable:()=>$r,EffectWrapper:()=>Ha,EmissionModule:()=>_a,EmphasizeOnClick:()=>Cn,EnvironmentScene:()=>Si,EventList:()=>_,EventListEvent:()=>ht,EventSystem:()=>ve,EventTrigger:()=>Xr,FieldWithDefault:()=>Nr,FixedJoint:()=>ri,Fog:()=>Qr,GltfExport:()=>la,GltfExportBox:()=>Ur,Gradient:()=>Ca,Graphic:()=>Dt,GraphicRaycaster:()=>Ft,GridHelper:()=>Yr,GridLayoutGroup:()=>Lt,GroundProjectedEnv:()=>Ut,GroupActionModel:()=>pr,HideOnStart:()=>Hn,HingeJoint:()=>oi,HorizontalLayoutGroup:()=>Jt,HoverAnimation:()=>Ni,Image:()=>kt,InheritVelocityModule:()=>Aa,InputField:()=>Rt,InstanceHandle:()=>hn,InstancingHandler:()=>Fr,Interactable:()=>Zi,Keyframe:()=>da,LODGroup:()=>Hr,LODModel:()=>Fi,Light:()=>ti,LimitVelocityOverLifetimeModule:()=>va,LogStats:()=>zi,LookAt:()=>Ci,LookAtConstraint:()=>Te,MainModule:()=>ya,MarkerTrackHandler:()=>fi,MaskableGraphic:()=>Tt,MeshCollider:()=>Un,MeshRenderer:()=>zr,MinMaxCurve:()=>Ea,MinMaxGradient:()=>wa,NeedleMenu:()=>dn,NestedGltf:()=>Li,Networking:()=>ai,NoiseModule:()=>xa,ObjectRaycaster:()=>pe,OffsetConstraint:()=>Kr,OpenURL:()=>Xi,OrbitControls:()=>Ce,Outline:()=>gt,Padding:()=>St,ParticleBurst:()=>ba,ParticleSubEmitter:()=>ha,ParticleSystem:()=>ka,ParticleSystemRenderer:()=>Da,PhysicsExtension:()=>Rr,PixelationEffect:()=>Ia,PlayAnimationOnClick:()=>Kn,PlayAudioOnClick:()=>xn,PlayableDirector:()=>oa,PlayerColor:()=>di,PointerEventData:()=>Be,PostProcessingHandler:()=>Wa,PreliminaryAction:()=>On,PreliminaryTrigger:()=>Tr,RawImage:()=>vt,Rect:()=>Yt,RectTransform:()=>nn,ReflectionProbe:()=>Tn,RegisteredAnimationInfo:()=>un,RemoteSkybox:()=>Ai,Renderer:()=>ir,RendererLightmap:()=>Bn,Rigidbody:()=>Le,RotationBySpeedModule:()=>ja,RotationOverLifetimeModule:()=>Pa,SceneSwitcher:()=>na,ScreenCapture:()=>Wr,ScreenSpaceAmbientOcclusion:()=>Ja,ScreenSpaceAmbientOcclusionN8:()=>Ga,ScrollFollow:()=>Yi,SeeThrough:()=>li,SetActiveOnClick:()=>En,ShadowCatcher:()=>aa,ShapeModule:()=>ga,SharpeningEffect:()=>Fa,SignalAsset:()=>Ii,SignalReceiver:()=>ni,SignalReceiverEvent:()=>ii,SignalTrackHandler:()=>Jr,Size:()=>bt,SizeBySpeedModule:()=>Na,SizeOverLifetimeModule:()=>pa,SkinnedMeshRenderer:()=>Lr,SmoothFollow:()=>xi,SpatialGrabRaycaster:()=>At,SpatialHtml:()=>qt,SpatialTrigger:()=>ta,SpatialTriggerReceiver:()=>sa,SpectatorCamera:()=>_i,SphereCollider:()=>qn,SplineContainer:()=>ji,SplineData:()=>ki,SplineWalker:()=>Bi,Sprite:()=>bn,SpriteData:()=>wn,SpriteRenderer:()=>An,SpriteSheet:()=>Ln,SubEmitterSystem:()=>Sa,SyncedCamera:()=>Ki,SyncedRoom:()=>Di,SyncedTransform:()=>qe,TapGestureTrigger:()=>Xn,TeleportTarget:()=>mn,TestRunner:()=>$i,TestSimulateUserData:()=>Ti,Text:()=>Ht,TextBuilder:()=>ur,TextExtension:()=>$n,TextureSheetAnimationModule:()=>ua,TiltShiftEffect:()=>Va,ToneMappingEffect:()=>Ra,TrailModule:()=>Ma,TransformData:()=>sr,TransformGizmo:()=>Ri,TriggerBuilder:()=>nr,TriggerModel:()=>Sr,UIRaycastUtils:()=>Ue,UIRootComponent:()=>$e,USDZExporter:()=>_r,USDZText:()=>Mr,USDZUIExtension:()=>dr,UsageMarker:()=>wi,VariantAction:()=>ci,VelocityOverLifetimeModule:()=>ma,VerticalLayoutGroup:()=>Ct,VideoPlayer:()=>ra,ViewBox:()=>Hi,Vignette:()=>qa,VisibilityAction:()=>Jn,Voip:()=>In,Volume:()=>Ya,VolumeParameter:()=>Za,VolumeProfile:()=>za,WebARCameraBackground:()=>xr,WebARSessionRoot:()=>Pn,WebXR:()=>Ir,WebXRImageTracking:()=>Dr,WebXRImageTrackingModel:()=>fr,WebXRPlaneTracking:()=>yr,WebXRTrackedImage:()=>tr,XRControllerFollow:()=>or,XRControllerModel:()=>Pr,XRControllerMovement:()=>zn,XRFlag:()=>Er,XRRig:()=>Ar,XRState:()=>Dn,__Ignore:()=>nc}),nc=class{},rc;(function(e){function t(e,t=!1,r=.75){let i=new ji,a=1-g.clamp(r,0,1);return e.forEach((r,o)=>{let s=new n;o<e.length-1?s.subVectors(e[o+1],r).normalize().multiplyScalar(a):t&&e.length>1&&s.subVectors(e[0],r).normalize().multiplyScalar(a);let c=new ki;c.position.copy(r),c.tangentIn.copy(s),c.tangentOut.copy(s),i.addKnot(c)}),i.closed=t,i}e.createFromPoints=t})(rc||={}),Is();var $={VERSION:Ee,Context:_t,NeedleXRSession:wt,assets:{loadFromURL:cs},types:fe,onStart:Qt,onUpdate:nt,onBeforeRender:xt,onAfterRender:rn,onInitializedContext:ge,onDestroyContext:et,onClearContext:tn};globalThis.Needle?.VERSION!==void 0&&console.warn(`Needle Engine is already imported: ${globalThis.Needle.VERSION}`);function ic(e){for(let t in e)$[t]=e[t]}ic(Kt),ic(tc);for(let e of Object.getOwnPropertyNames(x))switch(e){case`prototype`:case`constructor`:case`length`:case`name`:continue;default:$[e]=x[e];break}if(!globalThis.Needle)globalThis.Needle=$;else for(let e in $)globalThis.Needle[e]=$[e];globalThis.THREE?console.warn(`Three.js is already imported`):globalThis.THREE=l;var ac=class extends $a{constructor(){super(new Worker(new URL(``+new URL(`generateMeshBVH.worker-BRfdalWV.js`,import.meta.url).href,``+import.meta.url),{type:`module`})),this.name=`GenerateMeshBVHWorker`}runTask(e,t,n={}){return new Promise((r,i)=>{if(t.getAttribute(`position`).isInterleavedBufferAttribute||t.index&&t.index.isInterleavedBufferAttribute)throw Error(`GenerateMeshBVHWorker: InterleavedBufferAttribute are not supported for the geometry attributes.`);e.onerror=e=>{i(Error(`[GenerateMeshBVHWorker] ${e.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=a=>{let{data:o}=a;if(o.error)i(Error(o.error)),e.onmessage=null;else if(o.serialized){let{serialized:i,position:a}=o,s=Qa.deserialize(i,t,{setIndex:!1}),c=Object.assign({setBoundingBox:!0},n);if(t.attributes.position.array=a,i.index)if(t.index)t.index.array=i.index;else{let e=new p(i.index,1,!1);t.setIndex(e)}c.setBoundingBox&&(t.boundingBox=s.getBoundingBox(new re)),n.onProgress&&n.onProgress(o.progress),r(s),e.onmessage=null}else n.onProgress&&n.onProgress(o.progress)};let a=t.index?t.index.array:null,o=t.attributes.position.array,s=[o];a&&s.push(a),e.postMessage({index:a,position:o,options:{...n,onProgress:null,includedProgressCallback:!!n.onProgress,groups:[...t.groups]}},s.map(e=>e.buffer).filter(e=>typeof SharedArrayBuffer>`u`||!(e instanceof SharedArrayBuffer)))})}};export{Ro as C,ro as E,Fo as S,io as T,ls as _,$s as a,Po as b,Ks as c,Es as d,Cs as f,us as g,cs as h,ec as i,Hs as l,bs as m,rc as n,Qs as o,Ts as p,nc as r,Js as s,ac as t,js as u,Vo as v,Io as w,Lo as x,Ho as y};