@needle-tools/engine 4.9.3-next.002c20b → 4.9.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,7 +3,7 @@ Append any of these parameters to the URL to enable specific debug options.
3
3
  Example: ${i} will show an onscreen console window.`);const n=nr===!0?"":` (containing "${nr}")`;console.group("Available URL parameters:"+n);for(const s of Object.keys(o).sort())typeof nr=="string"&&!s.toLowerCase().includes(nr.toLowerCase())||(console.groupCollapsed(s),console.log("Reload with this flag enabled:"),console.log(o[s]),console.groupEnd());console.groupEnd()}},100);function Ul(){return new URLSearchParams(globalThis.location?.search)}function w(o){nr&&!vm.includes(o)&&vm.push(o);const e=Ul();if(e.has(o)){const t=e.get(o);if(t){const i=Number(t);return isNaN(i)?t:i}else return!0}return!1}nr=w("help");function sP(o,e){const t=Ul();t.has(o)?t.set(o,e):t.append(o,e),document.location.search=t.toString()}function zl(o,e,t=!0){const i=Ul();i.has(o)?e===null?i.delete(o):i.set(o,e):e!==null&&i.append(o,e),t?pb(o,i):xm(o,i)}function wm(o,e,t){o.has(e)?o.set(e,t.toString()):o.append(e,t.toString())}function pb(o,e,t){window.history.pushState(t,o,"?"+e.toString())}function xm(o,e,t){window.history.replaceState(t,o,"?"+e.toString())}function rP(o){for(var e="",t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",i=t.length,n=0;n<o;n++)e+=t.charAt(Math.floor(Math.random()*i));return e}function aP(o,e){return Math.floor(Math.random()*(e-o+1))+o}const mb=["smol","tiny","giant","interesting","smart","bright","dull","extreme","beautiful","pretty","dark","epic","salty","silly","funny","lame","lazy","loud","lucky","mad","mean","mighty","mysterious","nasty","odd","old","powerful","quiet","rapid","scary","shiny","shy","silly","smooth","sour","spicy","stupid","sweet","tasty","terrible","ugly","unusual","vast","wet","wild","witty","wrong","zany","zealous","zippy","zombie","zorro"],gb=["cat","dog","mouse","pig","cow","horse","sheep","chicken","duck","goat","panda","tiger","lion","elephant","monkey","bird","fish","snake","frog","turtle","hamster","penguin","kangaroo","whale","dolphin","crocodile","snail","ant","bee","beetle","butterfly","dragon","eagle","fish","giraffe","lizard","panda","penguin","rabbit","snake","spider","tiger","zebra"];function fb(){const o=mb[Math.floor(Math.random()*mb.length)],e=gb[Math.floor(Math.random()*gb.length)];return o+"_"+e}function yb(o){return o=o.replace(/[^a-z0-9áéíóúñü \.,_-]/gim,""),o.trim()}function _a(o,e,t=!0,i=!1){if(e==null)return null;if(e.userData&&e.userData.guid===o||e.guid==o)return e;if(i&&e.userData?.components){for(const n of e.userData.components)if(n.guid===o)return n}if(t){if(e.scenes)for(const n in e.scenes){const s=e.scenes[n],r=_a(o,s,t,i);if(r)return r}if(e.children)for(const n in e.children){const s=e.children[n],r=_a(o,s,t,i);if(r)return r}}}function Nl(o,e){if(o!=null&&typeof o=="object"){let t;Array.isArray(o)?t=[]:(t=Object.create(o),Object.assign(t,o));for(const i of Object.keys(o)){const n=o[i];e&&!e(o,i,n)?t[i]=n:n?.clone!==void 0&&typeof n.clone=="function"?t[i]=n.clone():t[i]=Nl(n,e)}return t}return o}function Dn(o){return new Promise((e,t)=>{setTimeout(e,o)})}function Wl(o,e){if(o<=0)return Promise.resolve();if(e||(e=ue.Current),!e)return Promise.reject("No context");const t=e.time.frameCount+o;return new Promise((i,n)=>{if(!e)return n("No context");const s=()=>{e.time.frameCount>=t&&(e.pre_update_callbacks.splice(e.pre_update_callbacks.indexOf(s),1),i())};e.pre_update_callbacks.push(s)})}const gd=w("debugresolveurl"),bb="rel:";function lP(o,e){return ls(o,e)}function ls(o,e){if(e===void 0)return gd&&console.warn("getPath: uri is undefined, returning uri",e),e;if(e.startsWith("./"))return e;if(e.startsWith("http"))return gd&&console.warn("getPath: uri is absolute, returning uri",e),e;if(o===void 0)return gd&&console.warn("getPath: source is undefined, returning uri",e),e;e.startsWith(bb)&&(e=e.substring(4));const t=o.lastIndexOf("/");if(t>=0){const i=o.substring(0,t+1);for(;i.endsWith("/")&&e.startsWith("/");)e=e.substring(1);const n=i+e;return gd&&console.log("source:",o,`changed uri
4
4
  from`,e,`
5
5
  to `,n,`
6
- basePath: `+i),n}return e}class cP{subscribeWrite(e){this.writeCallbacks.push(e)}unsubscribeWrite(e){const t=this.writeCallbacks.indexOf(e);t!==-1&&this.writeCallbacks.splice(t,1)}writeCallbacks=[];constructor(e,t){this._object=e,this._prop=t,this._wrapperProp=Symbol("$"+t),this.apply()}_applied=!1;_object;_prop;_wrapperProp;apply(){if(this._applied||!this._object)return;const e=this._object,t=this._prop;if(e[t]===void 0)return;this._applied=!0,e[this._wrapperProp]!==void 0&&console.warn("Watcher is being applied to an object that already has a wrapper property. This is not (yet) supported");const i=e[t];e[this._wrapperProp]=i,Object.defineProperty(e,t,{get:()=>e[this._wrapperProp],set:n=>{e[this._wrapperProp]=n;for(const s of this.writeCallbacks)s(n,this._prop)}})}revoke(){if(!this._applied||!this._object)return;this._applied=!1;const e=this._object,t=this._prop;Reflect.deleteProperty(e,t);const i=e[this._wrapperProp];e[t]=i,Reflect.deleteProperty(e,this._wrapperProp)}dispose(){this.revoke(),this.writeCallbacks.length=0,this._object=null}}class Ko{_watches=[];constructor(e,t){if(Array.isArray(t))for(const i of t)this._watches.push(new Ko(e,i));else this._watches.push(new cP(e,t))}subscribeWrite(e){for(const t of this._watches)t.subscribeWrite(e)}unsubscribeWrite(e){for(const t of this._watches)t.unsubscribeWrite(e)}apply(){for(const e of this._watches)e.apply()}revoke(){for(const e of this._watches)e.revoke()}dispose(){for(const e of this._watches)e.dispose();this._watches.length=0}}const va=Symbol("needle:watches");function fd(o,e){if(!o[va])if(o instanceof J)o[va]=new Ko(o,["x","y"]);else if(o instanceof b)o[va]=new Ko(o,["x","y","z"]);else if(o instanceof pe||o instanceof U)o[va]=new Ko(o,["x","y","z","w"]);else return!1;return o[va].subscribeWrite(e),!0}function Sm(o,e){if(!o)return;const t=o[va];t&&t.unsubscribeWrite(e)}var G;(o=>{let e;function t(){if(e!==void 0)return e;const W=window.navigator.userAgent,oe=/Windows|MacOS|Mac OS/.test(W),le=/Windows NT/.test(W)&&/Edg/.test(W)&&!/Win64/.test(W);return e=oe&&!le&&!v()}o.isDesktop=t;let i;function n(){return i!==void 0?i:typeof window.orientation<"u"||navigator.userAgent.indexOf("IEMobile")!==-1?i=!0:i=/iPhone|iPad|iPod|Android|IEMobile/i.test(navigator.userAgent)}o.isMobileDevice=n;function s(){return a()}o.isIPad=s;let r;function a(){return r!==void 0?r:r=/iPad/.test(navigator.userAgent)}o.isiPad=a;let l;function c(){return l!==void 0?l:l=/Android/.test(navigator.userAgent)}o.isAndroidDevice=c;let h;function d(){return h!==void 0?h:h=/WebXRViewer\//i.test(navigator.userAgent)}o.isMozillaXR=d;let p;function g(){if(p!==void 0)return p;if(navigator.userAgentData)return p=navigator.userAgentData.platform==="macOS";{const W=navigator.userAgent.toLowerCase();return p=W.includes("mac os x")||W.includes("macintosh")}}o.isMacOS=g;let f;function m(){return f!==void 0?f:f=g()&&"xr"in navigator}o.isVisionOS=m;let y;const _=["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"];function v(){return y!==void 0?y:y=_.includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}o.isiOS=v;let P;function R(){return P!==void 0||(P=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)),P}o.isSafari=R;let k;function A(){return k!==void 0?k:k=navigator.userAgent.includes("OculusBrowser")}o.isQuest=A;let L;function N(){return L!==void 0||(L=document.createElement("a").relList.supports("ar")),L}o.supportsQuickLookAR=N;async function j(){try{return(await navigator.permissions.query({name:"microphone"})).state!=="denied"}catch(W){return console.error("Error querying `microphone` permissions.",W),!1}}o.microphonePermissionsGranted=j;let q;function Y(){if(q!==void 0)return q;const W=navigator.userAgent.match(/iPhone OS (\d+_\d+)/);if(W&&(q=W[1].replace("_",".")),!q){const oe=navigator.userAgent.match(/(?:\(Macintosh;|iPhone;|iPad;).*Version\/(\d+\.\d+)/);oe&&(q=oe[1])}return q||(q=null),q}o.getiOSVersion=Y;let I;function V(){if(I!==void 0)return I;const W=navigator.userAgent.match(/(?:CriOS|Chrome)\/(\d+\.\d+\.\d+\.\d+)/);return W?I=W[1].replace("_","."):I=null,I}o.getChromeVersion=V})(G||(G={}));function hP(){return G.isDesktop()}function dP(){return G.isMobileDevice()}function uP(){return G.isiPad()}function pP(){return G.isiPad()}function mP(){return G.isAndroidDevice()}function gP(){return G.isMozillaXR()}function fP(){return G.isMacOS()}function yP(){return G.isiOS()}function bP(){return G.isSafari()}function _P(){return G.isQuest()}async function vP(){return G.microphonePermissionsGranted()}const cs=new WeakMap;function _b(o,e,t){if(!cs.get(o)){const n=new MutationObserver(s=>{wP(o,s)});cs.set(o,{observer:n,attributeChangedListeners:new Map}),n.observe(o,{attributes:!0})}const i=cs.get(o).attributeChangedListeners;i.has(e)||i.set(e,[]),i.get(e).push(t)}function vb(o,e,t){if(!cs.get(o))return;const i=cs.get(o).attributeChangedListeners;if(!i.has(e))return;const n=i.get(e),s=n.indexOf(t);s!==-1&&(n.splice(s,1),n.length<=0&&(i.delete(e),cs.get(o)?.observer.disconnect(),cs.delete(o)))}function wP(o,e){const t=cs.get(o).attributeChangedListeners;for(const i of e)if(i.type==="attributes"){const n=i.attributeName,s=o.getAttribute(n);if(t.has(n))for(const r of t.get(n))r(s)}}class Cm{reason;constructor(e){this.reason=e}}async function Pm(o){const e=await Promise.allSettled(o).catch(n=>[new Cm(n.message)]);let t=!1;const i=e.map(n=>"value"in n?n.value:(t=!0,new Cm(n.reason)));return{anyFailed:t,results:i}}async function wb(o){if(!globalThis.QRCode){const l="https://cdn.jsdelivr.net/gh/davidshimjs/qrcodejs@gh-pages/qrcode.min.js";let c=document.head.querySelector(`script[src="${l}"]`);c||(c=document.createElement("script"),c.src=l,document.head.appendChild(c)),await new Promise((h,d)=>{c.addEventListener("load",()=>{h(!0)})})}const e=globalThis.QRCode,t=o.domElement??document.createElement("div"),i=new e(t,{width:o.width??256,height:o.height??256,colorDark:"#000000",colorLight:"#ffffff",correctLevel:o.showLogo?e.CorrectionLevel.H:e.CorrectLevel.M,...o}),n=i?._oQRCode.moduleCount||0,s=i?._oDrawing?._elCanvas;let r=.25;n<40?r=Math.floor(n/4)/n:r=Math.floor(n/6)/n;const a=Math.floor(n/20)/n;try{const l=await xP(s,{showLogo:o.showLogo,logoSize:r,logoPadding:a}).catch(c=>{});l&&(t.innerHTML="",t.append(l))}catch{}if(o.showUrl!==!1&&o.text){const l=t.querySelector(".qr-code-link-label");let c=o.text.replace(/^(https?:\/\/)?(www\.)?/,"").replace(/\/+$/,"").replace(/\?+$/,"");if(c="Scan to visit "+c,l)l.textContent=c;else{const h=document.createElement("div");h.classList.add("qr-code-link-label"),o.text=c,h.textContent=o.text,h.addEventListener("click",d=>{d.stopImmediatePropagation()}),h.style.textAlign="center",h.style.fontSize="0.8em",h.style.marginTop="0.1em",h.style.color="#000000",h.style.fontFamily="'Roboto Flex', sans-serif",h.style.opacity="0.5",h.style.wordBreak="break-all",h.style.wordWrap="break-word",h.style.marginBottom="0.3em",t.style.width="calc(210px + 20px)",t.appendChild(h)}}return t}async function xP(o,e){if(!o)return;const t=8,i=20,n=e.logoPadding||1/32,s="transparent",r=0,a=new Image,l=document.querySelector("needle-engine")?.getAttribute("loading-logo-src")||hb;if(!l)return;let c=!1;e.showLogo!==!1&&(a.src=l,c=await new Promise((_,v)=>{a.onload=()=>_(!0),a.onerror=P=>{console.error("Error loading favicon image for QR code",P),_(!1)}}));const h=document.createElement("canvas");h.width=o.width+t,h.height=o.height+t;const d=h.getContext("2d");if(!d)return;d.fillStyle="#ffffff",d.fillRect(0,0,h.width,h.height),d.drawImage(o,t/2,t/2),d.imageSmoothingEnabled=!0,d.imageSmoothingQuality="high",d.mozImageSmoothingEnabled=!0,d.webkitImageSmoothingEnabled=!0,d.globalCompositeOperation="lighten";const p=d.createLinearGradient(0,0,0,h.height);p.addColorStop(0,"rgb(45, 45, 45)"),p.addColorStop(1,"rgb(45, 45, 45)"),d.fillStyle=p,d.fillRect(0,0,h.width,h.height),d.globalCompositeOperation="source-over";let g=Math.min(o.width,o.height)*(e.logoSize||.25),f=g;if(c){const _=a.width/a.height;_>1?f=g/_:g=f*_;const v=n*o.width,P=Math.max(g,f),R=Math.round(P+v),k=Math.round(P+v),A=(h.width-P)/2,L=(h.height-P)/2;d.shadowColor=s,d.shadowBlur=i;const N=r,j=Math.round(A-v/2),q=Math.round(L-v/2);d.beginPath(),d.moveTo(j+N,q),d.lineTo(j+R-N,q),d.quadraticCurveTo(j+R,q,j+R,q+N),d.lineTo(j+R,q+k-N),d.quadraticCurveTo(j+R,q+k,j+R-N,q+k),d.lineTo(j+N,q+k),d.quadraticCurveTo(j,q+k,j,q+k-N),d.lineTo(j,q+N),d.quadraticCurveTo(j,q,j+N,q),d.fillStyle="#ffffff",d.closePath(),d.fill(),d.clip(),d.shadowColor="transparent";const Y=(h.width-g)/2,I=(h.height-f)/2;d.drawImage(a,Y,I,g,f)}const m=h.toDataURL("image/png"),y=document.createElement("img");return y.src=m,y.style.width="100%",y.style.height="auto",y}const SP=w("debugdebug");let Om=!1;(w("noerrors")||w("nooverlaymessages"))&&(Om=!0);const km="needle_engine_global_error_container";var xi=(o=>(o[o.Log=0]="Log",o[o.Warn=1]="Warn",o[o.Error=2]="Error",o))(xi||{});function xb(){return Pb}const Mm=new Array;function CP(o){Mm.push(o)}let Rm=!1;function PP(...o){if(!Rm){Rm=!0;try{for(let e=0;e<Mm.length;e++)Mm[e](...o)}catch(e){console.error(e)}Rm=!1}}const Sb=console.error,OP=function(...o){Sb.apply(console,o),RP(o),or(2,o),MP(...o)};function Cb(o){Om=!o,o?console.error=OP:console.error=Sb}function kP(o){return Cb(o)}let Pb=0;function MP(...o){Pb+=1,PP(...o)}function RP(o){if(Array.isArray(o))for(let e=0;e<o.length;e++){const t=o[e];typeof t=="string"&&t.startsWith("THREE.PropertyBinding: Trying to update node for track:")&&(o[e]="Some animated objects couldn't be found: see console for details")}}function or(o,e,t,i){if(Om)return;const n=ue.Current?.domElement??document.querySelector("needle-engine");if(n){if(Array.isArray(e)){let s="";for(let r=0;r<e.length;r++){let a=e[r];a instanceof Error&&(a=a.message),typeof a!="object"&&(r>0&&(s+=" "),s+=a)}e=s}!e||e.length<=0||TP(o,n,e)}}const Vl=new Map;function TP(o,e,t){if(t==null)return;const i=IP(e);if(i.childElementCount>=20){const a=i.lastElementChild;kb(a)}t.length>400&&(t=t.substring(0,400)+"...");const n=t;if(Vl.has(n))return;const s=LP(o,t);i.prepend(s);const r=()=>{Vl.delete(n),kb(s)};Vl.set(n,r),setTimeout(r,1e4)}function EP(){SP&&console.log("Clearing messages");for(const o of Vl.values())o?.call(o);Vl.clear()}const AP=`
6
+ basePath: `+i),n}return e}class cP{subscribeWrite(e){this.writeCallbacks.push(e)}unsubscribeWrite(e){const t=this.writeCallbacks.indexOf(e);t!==-1&&this.writeCallbacks.splice(t,1)}writeCallbacks=[];constructor(e,t){this._object=e,this._prop=t,this._wrapperProp=Symbol("$"+t),this.apply()}_applied=!1;_object;_prop;_wrapperProp;apply(){if(this._applied||!this._object)return;const e=this._object,t=this._prop;if(e[t]===void 0)return;this._applied=!0,e[this._wrapperProp]!==void 0&&console.warn("Watcher is being applied to an object that already has a wrapper property. This is not (yet) supported");const i=e[t];e[this._wrapperProp]=i,Object.defineProperty(e,t,{get:()=>e[this._wrapperProp],set:n=>{e[this._wrapperProp]=n;for(const s of this.writeCallbacks)s(n,this._prop)}})}revoke(){if(!this._applied||!this._object)return;this._applied=!1;const e=this._object,t=this._prop;Reflect.deleteProperty(e,t);const i=e[this._wrapperProp];e[t]=i,Reflect.deleteProperty(e,this._wrapperProp)}dispose(){this.revoke(),this.writeCallbacks.length=0,this._object=null}}class Ko{_watches=[];constructor(e,t){if(Array.isArray(t))for(const i of t)this._watches.push(new Ko(e,i));else this._watches.push(new cP(e,t))}subscribeWrite(e){for(const t of this._watches)t.subscribeWrite(e)}unsubscribeWrite(e){for(const t of this._watches)t.unsubscribeWrite(e)}apply(){for(const e of this._watches)e.apply()}revoke(){for(const e of this._watches)e.revoke()}dispose(){for(const e of this._watches)e.dispose();this._watches.length=0}}const va=Symbol("needle:watches");function fd(o,e){if(!o[va])if(o instanceof J)o[va]=new Ko(o,["x","y"]);else if(o instanceof b)o[va]=new Ko(o,["x","y","z"]);else if(o instanceof pe||o instanceof U)o[va]=new Ko(o,["x","y","z","w"]);else return!1;return o[va].subscribeWrite(e),!0}function Sm(o,e){if(!o)return;const t=o[va];t&&t.unsubscribeWrite(e)}var G;(o=>{let e;function t(){if(e!==void 0)return e;const W=window.navigator.userAgent,oe=/Windows|MacOS|Mac OS/.test(W),le=/Windows NT/.test(W)&&/Edg/.test(W)&&!/Win64/.test(W);return e=oe&&!le&&!v()}o.isDesktop=t;let i;function n(){return i!==void 0?i:typeof window.orientation<"u"||navigator.userAgent.indexOf("IEMobile")!==-1?i=!0:i=/iPhone|iPad|iPod|Android|IEMobile/i.test(navigator.userAgent)}o.isMobileDevice=n;function s(){return a()}o.isIPad=s;let r;function a(){return r!==void 0?r:r=/iPad/.test(navigator.userAgent)}o.isiPad=a;let l;function c(){return l!==void 0?l:l=/Android/.test(navigator.userAgent)}o.isAndroidDevice=c;let h;function d(){return h!==void 0?h:h=/WebXRViewer\//i.test(navigator.userAgent)}o.isMozillaXR=d;let p;function m(){if(p!==void 0)return p;if(navigator.userAgentData)return p=navigator.userAgentData.platform==="macOS";{const W=navigator.userAgent.toLowerCase();return p=W.includes("mac os x")||W.includes("macintosh")}}o.isMacOS=m;let f;function g(){return f!==void 0?f:f=m()&&"xr"in navigator}o.isVisionOS=g;let y;const _=["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"];function v(){return y!==void 0?y:y=_.includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}o.isiOS=v;let P;function R(){return P!==void 0||(P=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)),P}o.isSafari=R;let k;function A(){return k!==void 0?k:k=navigator.userAgent.includes("OculusBrowser")}o.isQuest=A;let L;function N(){return L!==void 0||(L=document.createElement("a").relList.supports("ar")),L}o.supportsQuickLookAR=N;async function j(){try{return(await navigator.permissions.query({name:"microphone"})).state!=="denied"}catch(W){return console.error("Error querying `microphone` permissions.",W),!1}}o.microphonePermissionsGranted=j;let q;function Y(){if(q!==void 0)return q;const W=navigator.userAgent.match(/iPhone OS (\d+_\d+)/);if(W&&(q=W[1].replace("_",".")),!q){const oe=navigator.userAgent.match(/(?:\(Macintosh;|iPhone;|iPad;).*Version\/(\d+\.\d+)/);oe&&(q=oe[1])}return q||(q=null),q}o.getiOSVersion=Y;let I;function V(){if(I!==void 0)return I;const W=navigator.userAgent.match(/(?:CriOS|Chrome)\/(\d+\.\d+\.\d+\.\d+)/);return W?I=W[1].replace("_","."):I=null,I}o.getChromeVersion=V})(G||(G={}));function hP(){return G.isDesktop()}function dP(){return G.isMobileDevice()}function uP(){return G.isiPad()}function pP(){return G.isiPad()}function mP(){return G.isAndroidDevice()}function gP(){return G.isMozillaXR()}function fP(){return G.isMacOS()}function yP(){return G.isiOS()}function bP(){return G.isSafari()}function _P(){return G.isQuest()}async function vP(){return G.microphonePermissionsGranted()}const cs=new WeakMap;function _b(o,e,t){if(!cs.get(o)){const n=new MutationObserver(s=>{wP(o,s)});cs.set(o,{observer:n,attributeChangedListeners:new Map}),n.observe(o,{attributes:!0})}const i=cs.get(o).attributeChangedListeners;i.has(e)||i.set(e,[]),i.get(e).push(t)}function vb(o,e,t){if(!cs.get(o))return;const i=cs.get(o).attributeChangedListeners;if(!i.has(e))return;const n=i.get(e),s=n.indexOf(t);s!==-1&&(n.splice(s,1),n.length<=0&&(i.delete(e),cs.get(o)?.observer.disconnect(),cs.delete(o)))}function wP(o,e){const t=cs.get(o).attributeChangedListeners;for(const i of e)if(i.type==="attributes"){const n=i.attributeName,s=o.getAttribute(n);if(t.has(n))for(const r of t.get(n))r(s)}}class Cm{reason;constructor(e){this.reason=e}}async function Pm(o){const e=await Promise.allSettled(o).catch(n=>[new Cm(n.message)]);let t=!1;const i=e.map(n=>"value"in n?n.value:(t=!0,new Cm(n.reason)));return{anyFailed:t,results:i}}async function wb(o){if(!globalThis.QRCode){const l="https://cdn.jsdelivr.net/gh/davidshimjs/qrcodejs@gh-pages/qrcode.min.js";let c=document.head.querySelector(`script[src="${l}"]`);c||(c=document.createElement("script"),c.src=l,document.head.appendChild(c)),await new Promise((h,d)=>{c.addEventListener("load",()=>{h(!0)})})}const e=globalThis.QRCode,t=o.domElement??document.createElement("div"),i=new e(t,{width:o.width??256,height:o.height??256,colorDark:"#000000",colorLight:"#ffffff",correctLevel:o.showLogo?e.CorrectionLevel.H:e.CorrectLevel.M,...o}),n=i?._oQRCode.moduleCount||0,s=i?._oDrawing?._elCanvas;let r=.25;n<40?r=Math.floor(n/4)/n:r=Math.floor(n/6)/n;const a=Math.floor(n/20)/n;try{const l=await xP(s,{showLogo:o.showLogo,logoSize:r,logoPadding:a}).catch(c=>{});l&&(t.innerHTML="",t.append(l))}catch{}if(o.showUrl!==!1&&o.text){const l=t.querySelector(".qr-code-link-label");let c=o.text.replace(/^(https?:\/\/)?(www\.)?/,"").replace(/\/+$/,"").replace(/\?+$/,"");if(c="Scan to visit "+c,l)l.textContent=c;else{const h=document.createElement("div");h.classList.add("qr-code-link-label"),o.text=c,h.textContent=o.text,h.addEventListener("click",d=>{d.stopImmediatePropagation()}),h.style.textAlign="center",h.style.fontSize="0.8em",h.style.marginTop="0.1em",h.style.color="#000000",h.style.fontFamily="'Roboto Flex', sans-serif",h.style.opacity="0.5",h.style.wordBreak="break-all",h.style.wordWrap="break-word",h.style.marginBottom="0.3em",t.style.width="calc(210px + 20px)",t.appendChild(h)}}return t}async function xP(o,e){if(!o)return;const t=8,i=20,n=e.logoPadding||1/32,s="transparent",r=0,a=new Image,l=document.querySelector("needle-engine")?.getAttribute("loading-logo-src")||hb;if(!l)return;let c=!1;e.showLogo!==!1&&(a.src=l,c=await new Promise((_,v)=>{a.onload=()=>_(!0),a.onerror=P=>{console.error("Error loading favicon image for QR code",P),_(!1)}}));const h=document.createElement("canvas");h.width=o.width+t,h.height=o.height+t;const d=h.getContext("2d");if(!d)return;d.fillStyle="#ffffff",d.fillRect(0,0,h.width,h.height),d.drawImage(o,t/2,t/2),d.imageSmoothingEnabled=!0,d.imageSmoothingQuality="high",d.mozImageSmoothingEnabled=!0,d.webkitImageSmoothingEnabled=!0,d.globalCompositeOperation="lighten";const p=d.createLinearGradient(0,0,0,h.height);p.addColorStop(0,"rgb(45, 45, 45)"),p.addColorStop(1,"rgb(45, 45, 45)"),d.fillStyle=p,d.fillRect(0,0,h.width,h.height),d.globalCompositeOperation="source-over";let m=Math.min(o.width,o.height)*(e.logoSize||.25),f=m;if(c){const _=a.width/a.height;_>1?f=m/_:m=f*_;const v=n*o.width,P=Math.max(m,f),R=Math.round(P+v),k=Math.round(P+v),A=(h.width-P)/2,L=(h.height-P)/2;d.shadowColor=s,d.shadowBlur=i;const N=r,j=Math.round(A-v/2),q=Math.round(L-v/2);d.beginPath(),d.moveTo(j+N,q),d.lineTo(j+R-N,q),d.quadraticCurveTo(j+R,q,j+R,q+N),d.lineTo(j+R,q+k-N),d.quadraticCurveTo(j+R,q+k,j+R-N,q+k),d.lineTo(j+N,q+k),d.quadraticCurveTo(j,q+k,j,q+k-N),d.lineTo(j,q+N),d.quadraticCurveTo(j,q,j+N,q),d.fillStyle="#ffffff",d.closePath(),d.fill(),d.clip(),d.shadowColor="transparent";const Y=(h.width-m)/2,I=(h.height-f)/2;d.drawImage(a,Y,I,m,f)}const g=h.toDataURL("image/png"),y=document.createElement("img");return y.src=g,y.style.width="100%",y.style.height="auto",y}const SP=w("debugdebug");let Om=!1;(w("noerrors")||w("nooverlaymessages"))&&(Om=!0);const km="needle_engine_global_error_container";var xi=(o=>(o[o.Log=0]="Log",o[o.Warn=1]="Warn",o[o.Error=2]="Error",o))(xi||{});function xb(){return Pb}const Mm=new Array;function CP(o){Mm.push(o)}let Rm=!1;function PP(...o){if(!Rm){Rm=!0;try{for(let e=0;e<Mm.length;e++)Mm[e](...o)}catch(e){console.error(e)}Rm=!1}}const Sb=console.error,OP=function(...o){Sb.apply(console,o),RP(o),or(2,o),MP(...o)};function Cb(o){Om=!o,o?console.error=OP:console.error=Sb}function kP(o){return Cb(o)}let Pb=0;function MP(...o){Pb+=1,PP(...o)}function RP(o){if(Array.isArray(o))for(let e=0;e<o.length;e++){const t=o[e];typeof t=="string"&&t.startsWith("THREE.PropertyBinding: Trying to update node for track:")&&(o[e]="Some animated objects couldn't be found: see console for details")}}function or(o,e,t,i){if(Om)return;const n=ue.Current?.domElement??document.querySelector("needle-engine");if(n){if(Array.isArray(e)){let s="";for(let r=0;r<e.length;r++){let a=e[r];a instanceof Error&&(a=a.message),typeof a!="object"&&(r>0&&(s+=" "),s+=a)}e=s}!e||e.length<=0||TP(o,n,e)}}const Vl=new Map;function TP(o,e,t){if(t==null)return;const i=IP(e);if(i.childElementCount>=20){const a=i.lastElementChild;kb(a)}t.length>400&&(t=t.substring(0,400)+"...");const n=t;if(Vl.has(n))return;const s=LP(o,t);i.prepend(s);const r=()=>{Vl.delete(n),kb(s)};Vl.set(n,r),setTimeout(r,1e4)}function EP(){SP&&console.log("Clearing messages");for(const o of Vl.values())o?.call(o);Vl.clear()}const AP=`
7
7
 
8
8
  @import url('https://fonts.googleapis.com/css2?family=Roboto+Flex:opsz,wght@8..144,100..1000&display=swap');
9
9
 
@@ -79,7 +79,7 @@ void main(){
79
79
  // float linearDepth = (depth - 0.99) * 100.0; // Enhance near 1.0 values
80
80
  // gl_FragColor = vec4(linearDepth, linearDepth, linearDepth, 1.0);
81
81
  }
82
- }`})}reset(){this.uniforms.map.value=null,this.uniforms.flipY.value=!0,this.uniforms.writeDepth.value=!1,this.uniforms.depthTexture.value=null,this.needsUpdate=!0,this.uniformsNeedUpdate=!0}}class Ys{static planeGeometry=new In(2,2,1,1);static renderer=new er({antialias:!1,alpha:!0});static perspectiveCam=new de;static orthographicCam=new nd;static scene=new yi;static blitMaterial=new Qp;static mesh=new H(Ys.planeGeometry,Ys.blitMaterial);static copyTexture(e,t){t||(t=this.blitMaterial),this.blitMaterial.reset();const i=t||this.blitMaterial;i.uniforms.map.value=e,i.needsUpdate=!0,i.uniformsNeedUpdate=!0;const n=i.vertexShader;i.vertexShader=Qp.vertex;const s=this.mesh;s.material=i,s.frustumCulled=!1,this.scene.children.length=0,this.scene.add(s),this.renderer.setSize(e.image.width,e.image.height),this.renderer.clear(),this.renderer.render(this.scene,this.perspectiveCam);const r=new Re(this.renderer.domElement);return r.name="Copy",r.needsUpdate=!0,i.vertexShader=n,r}static blit(e,t,i){const{renderer:n=this.renderer,blitMaterial:s=this.blitMaterial,flipY:r=!1,depthTexture:a=null,depthTest:l=!0,depthWrite:c=!0}=i||{};this.blitMaterial.reset(),s.uniforms.map&&(s.uniforms.map.value=e),s.uniforms.flipY&&(s.uniforms.flipY.value=r),a?(s.uniforms.writeDepth=new Ni(!0),s.uniforms.depthTexture.value=a):(s.uniforms.writeDepth=new Ni(!1),s.uniforms.depthTexture.value=null),s.needsUpdate=!0,s.uniformsNeedUpdate=!0;const h=this.mesh;h.material=s,h.frustumCulled=!1,this.scene.children.length=0,this.scene.add(h);const d=n.getRenderTarget(),p=n.getContext(),g=p.getParameter(p.DEPTH_TEST),f=p.getParameter(p.DEPTH_WRITEMASK),m=p.getParameter(p.DEPTH_FUNC);l?n.getContext().enable(n.getContext().DEPTH_TEST):n.getContext().disable(n.getContext().DEPTH_TEST),n.state.buffers.depth.setMask(c),n.setClearColor(new ne(0,0,0),0),n.pixelRatio!==window.devicePixelRatio&&n.xr.isPresenting===!1&&n.setPixelRatio(window.devicePixelRatio),n.setRenderTarget(t),n.clear(),n.render(this.scene,this.perspectiveCam),n.setRenderTarget(d);const y=n.state.buffers.depth;y.setTest(g),y.setMask(f),y.setFunc(m)}static textureToCanvas(e,t=!1){if(!e)return null;(t===!0||e.isCompressedTexture===!0)&&(e=Nb(e));const i=e.image;if(JP(i)){const n=document.createElement("canvas");n.width=i.width,n.height=i.height;const s=n.getContext("2d");return s?(s.drawImage(i,0,0,i.width,i.height,0,0,n.width,n.height),n):(console.error("Failed getting canvas 2d context"),null)}return null}}function Nb(o){return Ys.copyTexture(o)}function ZP(o,e=!1){return Ys.textureToCanvas(o,e)}function JP(o){return typeof HTMLImageElement<"u"&&o instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&o instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&o instanceof OffscreenCanvas||typeof ImageBitmap<"u"&&o instanceof ImageBitmap}function eO(o){const e=o.type;return e==="Mesh"||e==="SkinnedMesh"}function Um(o,e){e?o["needle:rendercustomshadow"]=!0:o["needle:rendercustomshadow"]=!1}function Wb(o){return!!(o&&(o["needle:rendercustomshadow"]===!0||o["needle:rendercustomshadow"]==null))}function Wt(o,e=void 0,t=void 0,i=void 0){const n=i||new bi;n.makeEmpty();const s=[];function r(l){let c=!0;if(l.visible&&Tb(l)!==!1&&!(l.type==="TransformControlsGizmo"||l.type==="TransformControlsPlane")){if(l instanceof K1&&(c=!1),l instanceof Jp&&(c=!1),l instanceof ba&&(c=!1),l.isGizmo===!0&&(c=!1),l.material instanceof A0&&(c=!1),eO(l)||(c=!1),t&&l.layers.test(t)===!1&&(c=!1),c&&(e&&Array.isArray(e)&&e?.includes(l)||typeof e=="function"&&e(l)===!0))return;if(l.isUI!==!0){if(c){const h=l.children;l.children=s;const d=l.position,p=l.scale;if(Number.isNaN(d.x)||Number.isNaN(d.y)||Number.isNaN(d.z)){console.warn(`Object "${l.name}" has NaN values in position or scale.... will ignore it`,d,p);return}l.geometry===null&&(l.geometry=void 0),n.expandByObject(l,!0),l.children=h}for(const h of l.children)r(h)}}}let a=!1;Array.isArray(o)||(o=[o]);for(const l of o)l&&(a=!0,l.updateMatrixWorld(),r(l));return a||console.warn("No objects to fit camera to..."),n}function Vb(o,e,t){const i=Wt([o],t?.ignore),n=new b;i.getSize(n);const s=new b;i.getCenter(s);const r=new b;e.getSize(r);const a=new b;e.getCenter(a);const l=new b;l.set(r.x/n.x,r.y/n.y,r.z/n.z);const c=Math.min(l.x,l.y,l.z),h=t?.scale!==!1;if(h&&wa(o,$e(o).multiplyScalar(c)),t?.position!==!1){const d=new b;i.getCenter(d),d.y=i.min.y;const p=new b;e.getCenter(p),p.y=e.min.y;const g=p.clone().sub(d);h&&g.multiplyScalar(c),mt(o,Z(o).add(g))}return{boundsBefore:i,scale:l}}function $b(o,e){const t=Wt([o]),i=new b;t.getCenter(i),i.y=t.min.y;const n=e.clone().sub(i),s=Z(o);return mt(o,s.add(n)),{offset:n,bounds:t}}function zm(o,e,t,i){if(Array.isArray(e)){let r=!0;for(let a=0;a<e.length;a++)zm(o,e[a],a,e)||(r=!1);return r}if(e.type==="MeshStandardMaterial"||e.type==="MeshBasicMaterial")return!1;if(e["material:fbx"]!=null)return!0;const n=new ut;n["material:fbx"]=e;const s=e;return s&&(s.map?n.color.set(1,1,1):n.color.copyLinearToSRGB(s.color),n.emissive.copyLinearToSRGB(s.emissive),n.emissiveIntensity=s.emissiveIntensity,n.opacity=s.opacity,n.displacementScale=s.displacementScale,n.transparent=s.transparent,n.bumpMap=s.bumpMap,n.aoMap=s.aoMap,n.map=s.map,n.displacementMap=s.displacementMap,n.emissiveMap=s.emissiveMap,n.normalMap=s.normalMap,n.envMap=s.envMap,n.alphaMap=s.alphaMap,n.metalness=s.reflectivity,n.vertexColors=s.vertexColors,s.shininess&&(n.roughness=1-Math.sqrt(s.shininess)/10),n.needsUpdate=!0),t===void 0?o.material=n:i[t]=n,!0}let Cd=!1;CP((...o)=>{E()&&ue.Current?.isInXR&&(ar(!0),Hb("error",...o))});function ar(o){if(o){if(Cd)return;Cd=!0,iO()}else{if(!Cd)return;Cd=!1,nO()}}const Gl={log:void 0,warn:void 0,error:void 0};class tO{familyName="needle-xr";root=null;context=null;defaultFontSize=.06;constructor(){this.ensureFont()}onEnable(){this.context=ue.Current||ue.All[0],this.context.pre_render_callbacks.push(this.onBeforeRender)}onDisable(){this.context?.pre_render_callbacks.splice(this.context?.pre_render_callbacks.indexOf(this.onBeforeRender),1),this.root?.removeFromParent()}targetObject=new O;userForwardViewPoint=new b;oneEuroFilter=new Tm(90,.8);_lastElementRemoveTime=0;onBeforeRender=()=>{const e=this.context?.mainCamera;if(this.context&&e instanceof de){const t=this.getRoot();Number.isNaN(t.position.x)&&t.position.set(0,0,0),Number.isNaN(t.quaternion.x)&&t.quaternion.set(0,0,0,1),this.context.scene.add(this.targetObject);const i=this.context.xr?.rigScale??1,n=3.5*i,s=e.worldForward;s.y=0,s.normalize().multiplyScalar(n),this.userForwardViewPoint.copy(e.worldPosition).sub(s),this.targetObject.position.distanceTo(this.userForwardViewPoint)>2*i&&(this.targetObject.position.copy(this.userForwardViewPoint),$l(this.targetObject,e,!0,!0),this.targetObject.rotateY(Math.PI)),this.oneEuroFilter.filter(this.targetObject.position,t.position,this.context.time.time);const r=this.context.time.deltaTime;if(t.quaternion.slerp(this.targetObject.quaternion,r*5),t.scale.setScalar(i),this.targetObject.removeFromParent(),this.context.scene.add(t),this.context.time.time-this._lastElementRemoveTime>.1){this._lastElementRemoveTime=this.context.time.time;const a=Date.now();for(let l=0;l<this._activeTexts.length;l++){const c=this._activeTexts[l];if(c instanceof Ce.Text&&a-c._activatedTime>2e4){c.removeFromParent(),this._textBuffer.push(c),this._activeTexts.splice(l,1);break}}}}};addLog(e,t){const i=this.getRoot(),n=this.getText();let s=16777215,r=0;switch(e){case"log":s=16777215,r=0;break;case"warn":s=16772761,r=4465152;break;case"error":s=16755370,r=7798784;break}t.length>1e3&&(t=t.substring(0,1e3)+"...");const a=new Date().toISOString().split("T")[1].split(".")[0];n.textContent="["+a+"] "+t,n.visible=!0,n._activatedTime=Date.now(),i.add(n),this._activeTexts.push(n),this.context&&this.context.scene.add(i),n.set({backgroundColor:s,color:r}),Ce.update()}ensureFont(){let e=Ce.FontLibrary.getFontFamily(this.familyName);e||(e=Ce.FontLibrary.addFontFamily(this.familyName),e.addVariant("normal","normal","./include/needle/arial-msdf.json","./include/needle/arial.png")?.addEventListener("ready",()=>{Ce.update()}))}textOptions={fontSize:this.defaultFontSize,fontFamily:this.familyName,padding:.03,margin:.005,color:0,backgroundColor:16777215,backgroundOpacity:.4,borderRadius:.03,offset:.025};_textBuffer=[];_activeTexts=[];getText(){const e=this.getRoot();if(this._textBuffer.length>0){const i=this._textBuffer.pop();return i.visible=!0,setTimeout(()=>this.disableDepthTestRecursive(i),100),i}if(e.children.length>20&&this._activeTexts.length>0)return this._activeTexts.shift();const t=new Ce.Text(this.textOptions);return setTimeout(()=>this.disableDepthTestRecursive(t),500),setTimeout(()=>this.disableDepthTestRecursive(t),1500),t}disableDepthTestRecursive(e,t=0){for(let n=0;n<e.children.length;n++){const s=e.children[n];s instanceof O&&this.disableDepthTestRecursive(s,t+1)}e.renderOrder=10*t,e.layers.set(2);const i=e.material;i&&(i.depthWrite=!1,i.depthTest=!1,i.transparent=!0),t===0&&Ce.update()}getRoot(){if(this.root)return this.root;const e=this.defaultFontSize,t={boxSizing:"border-box",fontFamily:this.familyName,width:"2.6",fontSize:e,color:0,lineHeight:1,backgroundColor:16777215,backgroundOpacity:0,whiteSpace:"pre-wrap",flexDirection:"column-reverse"};return this.root=new Ce.Block(t),this.root}}let lr=null;function iO(){lr||(lr=new tO),lr.onEnable();for(const o in Gl){Gl[o]=console[o];let e=!1;console[o]=function(){if(Gl[o]?.apply(console,arguments),!e)try{e=!0,Hb(o,...arguments)}finally{e=!1}}}}function nO(){lr?.onDisable();for(const o in Gl)console[o]=Gl[o]}const ql=new Map;function Hb(o,...e){try{switch(ql.clear(),o){case"log":lr?.addLog("log",t());break;case"warn":lr?.addLog("warn",t());break;case"error":lr?.addLog("error",t());break}}catch(s){console.error("Error in spatial console",s)}finally{ql.clear()}function t(){let s="";for(let r=0;r<e.length;r++){const a=e[r];s+=i(a),r<e.length-1&&(s+=", ")}return s}function i(s,r=0){if(typeof s=="string")return'"'+s+'"';if(typeof s=="number"){if(s%1!==0){const a=s.toFixed(5),l=a.indexOf(".");let c=a.length-1;for(;c>l&&a[c]==="0";)c--;return a.substring(0,c+1)}return s.toString()}else if(Array.isArray(s)){let a="[";for(let l=0;l<s.length;l++){const c=s[l];a+=i(c,r+1),l<s.length-1&&(a+=", ")}return a+="]",a}else{if(s===null)return"null";if(s===void 0)return"undefined";if(typeof s=="function")return s.name+"()"}if(s instanceof J)return`(${i(s.x)}, ${i(s.y)})`;if(s instanceof b)return`(${i(s.x)}, ${i(s.y)}, ${i(s.z)})`;if(s instanceof pe)return`(${i(s.x)}, ${i(s.y)}, ${i(s.z)}, ${i(s.w)})`;if(s instanceof U)return`(${i(s.x)}, ${i(s.y)}, ${i(s.z)}, ${i(s.w)})`;if(s instanceof ve||s instanceof Re)return s.name;if(s instanceof I0)return`[${s.elements.join(", ")}]`;if(s instanceof ee)return`[${s.elements.join(", ")}]`;if(s instanceof is)return s.mask.toString();if(typeof s=="object"){if(ql.has(s))return"*";let a=`{
82
+ }`})}reset(){this.uniforms.map.value=null,this.uniforms.flipY.value=!0,this.uniforms.writeDepth.value=!1,this.uniforms.depthTexture.value=null,this.needsUpdate=!0,this.uniformsNeedUpdate=!0}}class Ys{static planeGeometry=new In(2,2,1,1);static renderer=new er({antialias:!1,alpha:!0});static perspectiveCam=new de;static orthographicCam=new nd;static scene=new yi;static blitMaterial=new Qp;static mesh=new H(Ys.planeGeometry,Ys.blitMaterial);static copyTexture(e,t){t||(t=this.blitMaterial),this.blitMaterial.reset();const i=t||this.blitMaterial;i.uniforms.map.value=e,i.needsUpdate=!0,i.uniformsNeedUpdate=!0;const n=i.vertexShader;i.vertexShader=Qp.vertex;const s=this.mesh;s.material=i,s.frustumCulled=!1,this.scene.children.length=0,this.scene.add(s),this.renderer.setSize(e.image.width,e.image.height),this.renderer.clear(),this.renderer.render(this.scene,this.perspectiveCam);const r=new Re(this.renderer.domElement);return r.name="Copy",r.needsUpdate=!0,i.vertexShader=n,r}static blit(e,t,i){const{renderer:n=this.renderer,blitMaterial:s=this.blitMaterial,flipY:r=!1,depthTexture:a=null,depthTest:l=!0,depthWrite:c=!0}=i||{};this.blitMaterial.reset(),s.uniforms.map&&(s.uniforms.map.value=e),s.uniforms.flipY&&(s.uniforms.flipY.value=r),a?(s.uniforms.writeDepth=new Ni(!0),s.uniforms.depthTexture.value=a):(s.uniforms.writeDepth=new Ni(!1),s.uniforms.depthTexture.value=null),s.needsUpdate=!0,s.uniformsNeedUpdate=!0;const h=this.mesh;h.material=s,h.frustumCulled=!1,this.scene.children.length=0,this.scene.add(h);const d=n.getRenderTarget(),p=n.getContext(),m=p.getParameter(p.DEPTH_TEST),f=p.getParameter(p.DEPTH_WRITEMASK),g=p.getParameter(p.DEPTH_FUNC);l?n.getContext().enable(n.getContext().DEPTH_TEST):n.getContext().disable(n.getContext().DEPTH_TEST),n.state.buffers.depth.setMask(c),n.setClearColor(new ne(0,0,0),0),n.pixelRatio!==window.devicePixelRatio&&n.xr.isPresenting===!1&&n.setPixelRatio(window.devicePixelRatio),n.setRenderTarget(t),n.clear(),n.render(this.scene,this.perspectiveCam),n.setRenderTarget(d);const y=n.state.buffers.depth;y.setTest(m),y.setMask(f),y.setFunc(g)}static textureToCanvas(e,t=!1){if(!e)return null;(t===!0||e.isCompressedTexture===!0)&&(e=Nb(e));const i=e.image;if(JP(i)){const n=document.createElement("canvas");n.width=i.width,n.height=i.height;const s=n.getContext("2d");return s?(s.drawImage(i,0,0,i.width,i.height,0,0,n.width,n.height),n):(console.error("Failed getting canvas 2d context"),null)}return null}}function Nb(o){return Ys.copyTexture(o)}function ZP(o,e=!1){return Ys.textureToCanvas(o,e)}function JP(o){return typeof HTMLImageElement<"u"&&o instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&o instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&o instanceof OffscreenCanvas||typeof ImageBitmap<"u"&&o instanceof ImageBitmap}function eO(o){const e=o.type;return e==="Mesh"||e==="SkinnedMesh"}function Um(o,e){e?o["needle:rendercustomshadow"]=!0:o["needle:rendercustomshadow"]=!1}function Wb(o){return!!(o&&(o["needle:rendercustomshadow"]===!0||o["needle:rendercustomshadow"]==null))}function Wt(o,e=void 0,t=void 0,i=void 0){const n=i||new bi;n.makeEmpty();const s=[];function r(l){let c=!0;if(l.visible&&Tb(l)!==!1&&!(l.type==="TransformControlsGizmo"||l.type==="TransformControlsPlane")){if(l instanceof K1&&(c=!1),l instanceof Jp&&(c=!1),l instanceof ba&&(c=!1),l.isGizmo===!0&&(c=!1),l.material instanceof A0&&(c=!1),eO(l)||(c=!1),t&&l.layers.test(t)===!1&&(c=!1),c&&(e&&Array.isArray(e)&&e?.includes(l)||typeof e=="function"&&e(l)===!0))return;if(l.isUI!==!0){if(c){const h=l.children;l.children=s;const d=l.position,p=l.scale;if(Number.isNaN(d.x)||Number.isNaN(d.y)||Number.isNaN(d.z)){console.warn(`Object "${l.name}" has NaN values in position or scale.... will ignore it`,d,p);return}l.geometry===null&&(l.geometry=void 0),n.expandByObject(l,!0),l.children=h}for(const h of l.children)r(h)}}}let a=!1;Array.isArray(o)||(o=[o]);for(const l of o)l&&(a=!0,l.updateMatrixWorld(),r(l));return a||console.warn("No objects to fit camera to..."),n}function Vb(o,e,t){const i=Wt([o],t?.ignore),n=new b;i.getSize(n);const s=new b;i.getCenter(s);const r=new b;e.getSize(r);const a=new b;e.getCenter(a);const l=new b;l.set(r.x/n.x,r.y/n.y,r.z/n.z);const c=Math.min(l.x,l.y,l.z),h=t?.scale!==!1;if(h&&wa(o,$e(o).multiplyScalar(c)),t?.position!==!1){const d=new b;i.getCenter(d),d.y=i.min.y;const p=new b;e.getCenter(p),p.y=e.min.y;const m=p.clone().sub(d);h&&m.multiplyScalar(c),mt(o,Z(o).add(m))}return{boundsBefore:i,scale:l}}function $b(o,e){const t=Wt([o]),i=new b;t.getCenter(i),i.y=t.min.y;const n=e.clone().sub(i),s=Z(o);return mt(o,s.add(n)),{offset:n,bounds:t}}function zm(o,e,t,i){if(Array.isArray(e)){let r=!0;for(let a=0;a<e.length;a++)zm(o,e[a],a,e)||(r=!1);return r}if(e.type==="MeshStandardMaterial"||e.type==="MeshBasicMaterial")return!1;if(e["material:fbx"]!=null)return!0;const n=new ut;n["material:fbx"]=e;const s=e;return s&&(s.map?n.color.set(1,1,1):n.color.copyLinearToSRGB(s.color),n.emissive.copyLinearToSRGB(s.emissive),n.emissiveIntensity=s.emissiveIntensity,n.opacity=s.opacity,n.displacementScale=s.displacementScale,n.transparent=s.transparent,n.bumpMap=s.bumpMap,n.aoMap=s.aoMap,n.map=s.map,n.displacementMap=s.displacementMap,n.emissiveMap=s.emissiveMap,n.normalMap=s.normalMap,n.envMap=s.envMap,n.alphaMap=s.alphaMap,n.metalness=s.reflectivity,n.vertexColors=s.vertexColors,s.shininess&&(n.roughness=1-Math.sqrt(s.shininess)/10),n.needsUpdate=!0),t===void 0?o.material=n:i[t]=n,!0}let Cd=!1;CP((...o)=>{E()&&ue.Current?.isInXR&&(ar(!0),Hb("error",...o))});function ar(o){if(o){if(Cd)return;Cd=!0,iO()}else{if(!Cd)return;Cd=!1,nO()}}const Gl={log:void 0,warn:void 0,error:void 0};class tO{familyName="needle-xr";root=null;context=null;defaultFontSize=.06;constructor(){this.ensureFont()}onEnable(){this.context=ue.Current||ue.All[0],this.context.pre_render_callbacks.push(this.onBeforeRender)}onDisable(){this.context?.pre_render_callbacks.splice(this.context?.pre_render_callbacks.indexOf(this.onBeforeRender),1),this.root?.removeFromParent()}targetObject=new O;userForwardViewPoint=new b;oneEuroFilter=new Tm(90,.8);_lastElementRemoveTime=0;onBeforeRender=()=>{const e=this.context?.mainCamera;if(this.context&&e instanceof de){const t=this.getRoot();Number.isNaN(t.position.x)&&t.position.set(0,0,0),Number.isNaN(t.quaternion.x)&&t.quaternion.set(0,0,0,1),this.context.scene.add(this.targetObject);const i=this.context.xr?.rigScale??1,n=3.5*i,s=e.worldForward;s.y=0,s.normalize().multiplyScalar(n),this.userForwardViewPoint.copy(e.worldPosition).sub(s),this.targetObject.position.distanceTo(this.userForwardViewPoint)>2*i&&(this.targetObject.position.copy(this.userForwardViewPoint),$l(this.targetObject,e,!0,!0),this.targetObject.rotateY(Math.PI)),this.oneEuroFilter.filter(this.targetObject.position,t.position,this.context.time.time);const r=this.context.time.deltaTime;if(t.quaternion.slerp(this.targetObject.quaternion,r*5),t.scale.setScalar(i),this.targetObject.removeFromParent(),this.context.scene.add(t),this.context.time.time-this._lastElementRemoveTime>.1){this._lastElementRemoveTime=this.context.time.time;const a=Date.now();for(let l=0;l<this._activeTexts.length;l++){const c=this._activeTexts[l];if(c instanceof Ce.Text&&a-c._activatedTime>2e4){c.removeFromParent(),this._textBuffer.push(c),this._activeTexts.splice(l,1);break}}}}};addLog(e,t){const i=this.getRoot(),n=this.getText();let s=16777215,r=0;switch(e){case"log":s=16777215,r=0;break;case"warn":s=16772761,r=4465152;break;case"error":s=16755370,r=7798784;break}t.length>1e3&&(t=t.substring(0,1e3)+"...");const a=new Date().toISOString().split("T")[1].split(".")[0];n.textContent="["+a+"] "+t,n.visible=!0,n._activatedTime=Date.now(),i.add(n),this._activeTexts.push(n),this.context&&this.context.scene.add(i),n.set({backgroundColor:s,color:r}),Ce.update()}ensureFont(){let e=Ce.FontLibrary.getFontFamily(this.familyName);e||(e=Ce.FontLibrary.addFontFamily(this.familyName),e.addVariant("normal","normal","./include/needle/arial-msdf.json","./include/needle/arial.png")?.addEventListener("ready",()=>{Ce.update()}))}textOptions={fontSize:this.defaultFontSize,fontFamily:this.familyName,padding:.03,margin:.005,color:0,backgroundColor:16777215,backgroundOpacity:.4,borderRadius:.03,offset:.025};_textBuffer=[];_activeTexts=[];getText(){const e=this.getRoot();if(this._textBuffer.length>0){const i=this._textBuffer.pop();return i.visible=!0,setTimeout(()=>this.disableDepthTestRecursive(i),100),i}if(e.children.length>20&&this._activeTexts.length>0)return this._activeTexts.shift();const t=new Ce.Text(this.textOptions);return setTimeout(()=>this.disableDepthTestRecursive(t),500),setTimeout(()=>this.disableDepthTestRecursive(t),1500),t}disableDepthTestRecursive(e,t=0){for(let n=0;n<e.children.length;n++){const s=e.children[n];s instanceof O&&this.disableDepthTestRecursive(s,t+1)}e.renderOrder=10*t,e.layers.set(2);const i=e.material;i&&(i.depthWrite=!1,i.depthTest=!1,i.transparent=!0),t===0&&Ce.update()}getRoot(){if(this.root)return this.root;const e=this.defaultFontSize,t={boxSizing:"border-box",fontFamily:this.familyName,width:"2.6",fontSize:e,color:0,lineHeight:1,backgroundColor:16777215,backgroundOpacity:0,whiteSpace:"pre-wrap",flexDirection:"column-reverse"};return this.root=new Ce.Block(t),this.root}}let lr=null;function iO(){lr||(lr=new tO),lr.onEnable();for(const o in Gl){Gl[o]=console[o];let e=!1;console[o]=function(){if(Gl[o]?.apply(console,arguments),!e)try{e=!0,Hb(o,...arguments)}finally{e=!1}}}}function nO(){lr?.onDisable();for(const o in Gl)console[o]=Gl[o]}const ql=new Map;function Hb(o,...e){try{switch(ql.clear(),o){case"log":lr?.addLog("log",t());break;case"warn":lr?.addLog("warn",t());break;case"error":lr?.addLog("error",t());break}}catch(s){console.error("Error in spatial console",s)}finally{ql.clear()}function t(){let s="";for(let r=0;r<e.length;r++){const a=e[r];s+=i(a),r<e.length-1&&(s+=", ")}return s}function i(s,r=0){if(typeof s=="string")return'"'+s+'"';if(typeof s=="number"){if(s%1!==0){const a=s.toFixed(5),l=a.indexOf(".");let c=a.length-1;for(;c>l&&a[c]==="0";)c--;return a.substring(0,c+1)}return s.toString()}else if(Array.isArray(s)){let a="[";for(let l=0;l<s.length;l++){const c=s[l];a+=i(c,r+1),l<s.length-1&&(a+=", ")}return a+="]",a}else{if(s===null)return"null";if(s===void 0)return"undefined";if(typeof s=="function")return s.name+"()"}if(s instanceof J)return`(${i(s.x)}, ${i(s.y)})`;if(s instanceof b)return`(${i(s.x)}, ${i(s.y)}, ${i(s.z)})`;if(s instanceof pe)return`(${i(s.x)}, ${i(s.y)}, ${i(s.z)}, ${i(s.w)})`;if(s instanceof U)return`(${i(s.x)}, ${i(s.y)}, ${i(s.z)}, ${i(s.w)})`;if(s instanceof ve||s instanceof Re)return s.name;if(s instanceof I0)return`[${s.elements.join(", ")}]`;if(s instanceof ee)return`[${s.elements.join(", ")}]`;if(s instanceof is)return s.mask.toString();if(typeof s=="object"){if(ql.has(s))return"*";let a=`{
83
83
  `;a+=n(r);const l=Object.keys(s);let c="";for(let h=0;h<l.length;h++){const d=l[h],p=s[d];if(ql.has(p)){c+="";continue}ql.set(p,!0),c+=d+":"+i(p,r+1),h<l.length-1&&(c+=", "),c.length>=60&&(c+=`
84
84
  `,c+=n(r),a+=c,c="")}return a+=c,a+=`
85
85
  }`,a}return s}function n(s){let r="";for(let a=0;a<s;a++)r+=" ";return r}}const oO=w("nodevlogs");function Te(o,e=xi.Log){or(e,o)}function ge(o){Te(o,xi.Warn)}function Xl(o){Te(o,xi.Error)}let Nm,Wm;function E(){if(oO)return!1;if(Nm!==void 0)return Nm;if(Wm!==void 0)return Wm;let o=Wi();return o||(o=window.location.hostname.endsWith(".local-credentialless.webcontainer.io")),Wm=o,o}function sO(o){Nm=o}let Vi,cr=null,Bn=null,Ql=!1,Gb=null;const qb="terminal",rO=w("console");rO&&Vm();const aO=Symbol("consoleParent");function Vm(){if(Vi){Vi.showSwitch();return}uO()}function Xb(){Vi&&(Vi.hide(),Vi.hideSwitch())}function lO(){Gb||(Gb=setInterval(cO,500))}let Qb=0;function cO(){const o=xb(),e=o!==Qb;Qb=o,e&&hO()}function hO(){Vm(),Bn&&(Bn.setAttribute("error","true"),Bn.innerText="\u{1F92C}")}function dO(){Bn&&(Bn.removeAttribute("error"),Bn.innerText=qb)}function uO(o=!1){if(Vi!==void 0||Ql)return;Ql=!0;const e=document.createElement("script");e.onload=()=>{if(!globalThis.VConsole){console.warn("\u{1F335} Debug console failed to load."),Ql=!1,Vi=null;return}Ql=!1,lO(),Vi=new VConsole({pluginOrder:["default","needle-console"]});const t=globalThis["needle:codegen_files"];if(t&&t.length>0&&Vi.addPlugin(pO()),cr=gO(),cr&&(cr[aO]=cr.parentElement,cr.style.position="absolute",cr.style.zIndex=Number.MAX_SAFE_INTEGER.toString()),Vi.setSwitchPosition(20,30),Bn=mO(),Bn){Bn.innerText=qb,Bn.addEventListener("click",dO);const i=document.createElement("style"),n=40;i.innerHTML=`
@@ -141,7 +141,7 @@ void main(){
141
141
  #__vconsole .vc-mask {
142
142
  overflow: hidden;
143
143
  }
144
- `,cr?.prepend(i),o===!0&&xb()<=0&&Xb(),console.log("\u{1F335} Debug console has loaded")}},e.onerror=()=>{console.warn("\u{1F335} Debug console failed to load."+(window.crossOriginIsolated?"This page is using cross-origin isolation, so external scripts can't be loaded.":"")),Ql=!1,Vi=null},e.src="https://cdn.jsdelivr.net/npm/vconsole@3.15.1/dist/vconsole.min.js",document.body.appendChild(e)}function pO(){if(!globalThis.VConsole)return;const o=new VConsole.VConsolePlugin("needle-console","\u{1F335} Inspect glTF"),e=()=>document.querySelector("#__vc_plug_"+o._id+" iframe");return o.on("renderTab",function(t){const i=globalThis["needle:codegen_files"];if(!i||i.length===0)return;let n=globalThis["needle:codegen_files"][0];const s=n.indexOf("?");s>-1&&(n=n.substring(0,s));const r=location.protocol+"//"+location.host+location.pathname+"/"+n,a=encodeURIComponent(r);o.fullUrl="https://viewer.needle.tools?inspect&file="+a;var l='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';t(l)}),o.on("show",function(){const t=e();t&&t.src!==o.fullUrl&&(t.src=o.fullUrl)}),o.on("hide",function(){const t=e();t&&(t.src="")}),o.on("addTopBar",function(t){var i=new Array;i.push({name:"Open in new window \u2197",onClick:function(n){window.open(o.fullUrl,"_blank"),Vi?.hide()}}),i.push({name:"Reload",onClick:function(n){const s=e();s&&(s.src=o.fullUrl)}}),i.push({name:"Fullscreen",onClick:function(n){const s=e();s.requestFullscreen?s.requestFullscreen():s.webkitRequestFullscreen instanceof Function&&s.webkitRequestFullscreen()}}),t(i)}),o}function mO(){return document.querySelector("#__vconsole .vc-switch")||null}function gO(){return document.querySelector("#__vconsole")||null}const Yb=w("debugdefines");hs('if(!globalThis["NEEDLE_ENGINE_VERSION"]) globalThis["NEEDLE_ENGINE_VERSION"] = "0.0.0";'),hs('if(!globalThis["NEEDLE_ENGINE_GENERATOR"]) globalThis["NEEDLE_ENGINE_GENERATOR"] = "unknown";'),hs('if(!globalThis["NEEDLE_PROJECT_BUILD_TIME"]) globalThis["NEEDLE_PROJECT_BUILD_TIME"] = "unknown";'),hs('if(!globalThis["NEEDLE_PUBLIC_KEY"]) globalThis["NEEDLE_PUBLIC_KEY"] = "unknown";'),hs('globalThis["__NEEDLE_ENGINE_VERSION__"] = "4.9.3";'),hs('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";'),hs('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Thu Sep 18 2025 09:34:12 GMT+0000 (Coordinated Universal Time)";'),hs('globalThis["__NEEDLE_PUBLIC_KEY__"] = "'+NEEDLE_PUBLIC_KEY+'";');const mn="4.9.3",Pd="undefined",$m="Thu Sep 18 2025 09:34:12 GMT+0000 (Coordinated Universal Time)";Yb&&console.log(`Engine version: ${mn} (generator: ${Pd})
144
+ `,cr?.prepend(i),o===!0&&xb()<=0&&Xb(),console.log("\u{1F335} Debug console has loaded")}},e.onerror=()=>{console.warn("\u{1F335} Debug console failed to load."+(window.crossOriginIsolated?"This page is using cross-origin isolation, so external scripts can't be loaded.":"")),Ql=!1,Vi=null},e.src="https://cdn.jsdelivr.net/npm/vconsole@3.15.1/dist/vconsole.min.js",document.body.appendChild(e)}function pO(){if(!globalThis.VConsole)return;const o=new VConsole.VConsolePlugin("needle-console","\u{1F335} Inspect glTF"),e=()=>document.querySelector("#__vc_plug_"+o._id+" iframe");return o.on("renderTab",function(t){const i=globalThis["needle:codegen_files"];if(!i||i.length===0)return;let n=globalThis["needle:codegen_files"][0];const s=n.indexOf("?");s>-1&&(n=n.substring(0,s));const r=location.protocol+"//"+location.host+location.pathname+"/"+n,a=encodeURIComponent(r);o.fullUrl="https://viewer.needle.tools?inspect&file="+a;var l='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';t(l)}),o.on("show",function(){const t=e();t&&t.src!==o.fullUrl&&(t.src=o.fullUrl)}),o.on("hide",function(){const t=e();t&&(t.src="")}),o.on("addTopBar",function(t){var i=new Array;i.push({name:"Open in new window \u2197",onClick:function(n){window.open(o.fullUrl,"_blank"),Vi?.hide()}}),i.push({name:"Reload",onClick:function(n){const s=e();s&&(s.src=o.fullUrl)}}),i.push({name:"Fullscreen",onClick:function(n){const s=e();s.requestFullscreen?s.requestFullscreen():s.webkitRequestFullscreen instanceof Function&&s.webkitRequestFullscreen()}}),t(i)}),o}function mO(){return document.querySelector("#__vconsole .vc-switch")||null}function gO(){return document.querySelector("#__vconsole")||null}const Yb=w("debugdefines");hs('if(!globalThis["NEEDLE_ENGINE_VERSION"]) globalThis["NEEDLE_ENGINE_VERSION"] = "0.0.0";'),hs('if(!globalThis["NEEDLE_ENGINE_GENERATOR"]) globalThis["NEEDLE_ENGINE_GENERATOR"] = "unknown";'),hs('if(!globalThis["NEEDLE_PROJECT_BUILD_TIME"]) globalThis["NEEDLE_PROJECT_BUILD_TIME"] = "unknown";'),hs('if(!globalThis["NEEDLE_PUBLIC_KEY"]) globalThis["NEEDLE_PUBLIC_KEY"] = "unknown";'),hs('globalThis["__NEEDLE_ENGINE_VERSION__"] = "4.9.3";'),hs('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";'),hs('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Mon Sep 15 2025 07:49:39 GMT+0000 (Coordinated Universal Time)";'),hs('globalThis["__NEEDLE_PUBLIC_KEY__"] = "'+NEEDLE_PUBLIC_KEY+'";');const mn="4.9.3",Pd="undefined",$m="Mon Sep 15 2025 07:49:39 GMT+0000 (Coordinated Universal Time)";Yb&&console.log(`Engine version: ${mn} (generator: ${Pd})
145
145
  Project built at ${$m}`);const xa=NEEDLE_PUBLIC_KEY,_o="needle_isActiveInHierarchy",hr="builtin_components",Yl="needle_editor_guid";function hs(o){try{(0,eval)(o)}catch(e){Yb&&console.error(e)}}let Kb,Zb=null;function gn(){return Kb}function Hm(o){if(o==null){console.warn("Oh no: someone tried registering a non-existend gltf-loader. When you see this log it might mean that needle-engine is being imported multiple times. Please check your project setup.");return}Zb!==o&&(Zb=o,Kb=new o)}const Si=Symbol("shadowDomOwner"),fO=w("debugpatch");function Od(o,e,t,i){const n=fO===e;if(!t&&!i)return;const s=e+"___needle";bO(o,e,t,i);const r=Object.getOwnPropertyDescriptor(o,e),a=o[e];n&&console.log("Patch",o.constructor.name,e,r,a),r?(n&&console.log("Apply patch with existing descriptor",o.constructor.name,e,r),typeof r.value=="function"&&(o[e]=e_(r.value,o,e))):(n&&console.log("Create patch with new property",o.constructor.name,e,r),Object.defineProperty(o,e,{set:function(l){if(typeof l=="function")this[s]=e_(l,o,e);else{const c=this[s];t_(o,e,this,c,l),this[s]=l,i_(o,e,this,c,l)}},get:function(){const l=this[s];return typeof l=="function"&&l[s]?l[s]:l}}))}function yO(o,e,t){const i=qm(o,e);if(i)for(let n=i.length-1;n>=0;n--){const s=i[n];s.prefix===t&&(s.prefix=null),s.postfix===t&&(s.postfix=null),!s.prefix&&!s.postfix&&i.splice(n,1)}}const Jb=Symbol("Needle:Patches:WrappedFunction");function e_(o,e,t){if(o[Jb])return o;const i=function(...n){t_(e,t,this,...n);const s=o.apply(this,n);return i_(e,t,this,s,...n),s};return i[Jb]=!0,i}const kd="Needle:Patches";function Gm(){return globalThis[kd]||(globalThis[kd]=new WeakMap),globalThis[kd]}function qm(o,e){const t=Gm().get(o);return t?t.get(e):null}function bO(o,e,t,i){let n=Gm().get(o);n||(n=new Map,Gm().set(o,n));let s=n.get(e);s||(s=[],n.set(e,s)),s.push({prefix:t,postfix:i})}function t_(o,e,t,...i){if(!t)return;const n=qm(o,e);if(n)for(const s of n)s.prefix?.call(t,...i)}function i_(o,e,t,i,...n){if(!t)return;const s=qm(o,e);if(s)for(const r of s)r.postfix?.call(t,i,...n)}const Sa=[];function Md(o){Sa.indexOf(o)===-1&&Sa.push(o)}function _O(o){const e=Sa.indexOf(o);e!==-1&&Sa.splice(e,1)}const Ca=[];function Xm(o){Ca.indexOf(o)===-1&&Ca.push(o)}function vO(o){const e=Ca.indexOf(o);e!==-1&&Ca.splice(e,1)}function n_(o){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-start",{detail:o}));for(let e=0;e<Sa.length;e++)Sa[e](o)}function o_(o){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-end",{detail:o}));for(let e=0;e<Ca.length;e++)Ca[e](o)}const ot=w("debuginput");var Rd=(o=>(o.Mouse="mouse",o.Touch="touch",o.Controller="controller",o.Hand="hand",o))(Rd||{}),Ee=(o=>(o.PointerDown="pointerdown",o.PointerUp="pointerup",o.PointerMove="pointermove",o.KeyDown="keydown",o.KeyUp="keyup",o.KeyPressed="keypress",o))(Ee||{});class vo extends PointerEvent{clientZ;deviceIndex;origin;source;mode;get isSpatial(){return this.mode!="screen"}get ray(){return this._ray||(this._ray=new ns(this.space.worldPosition.clone(),this.space.worldForward.clone())),this._ray}set ray(e){this._ray=e}get hasRay(){return this._ray!==void 0}_ray;space;isClick=!1;isDoubleClick=!1;get used(){return this._used}_used=!1;use(){this._used=!0}get pointerId(){return this._pointerid}_pointerid;get pointerType(){return this._pointerType}_pointerType;get type(){return this._type}_type;metadata={};intersections=new Array;constructor(e,t,i){super(e,i),this.clientZ=i.clientZ,this._pointerid=i.pointerId,this._pointerType=i.pointerType,this._type=e,this.deviceIndex=i.deviceIndex,this.origin=i.origin,this.source=t,this.mode=i.mode,this._ray=i.ray,this.space=i.device}_immediatePropagationStopped=!1;get immediatePropagationStopped(){return this._immediatePropagationStopped}_propagationStopped=!1;get propagationStopped(){return this._immediatePropagationStopped||this._propagationStopped}stopImmediatePropagation(){this._immediatePropagationStopped=!0,super.stopImmediatePropagation(),this.source?.stopImmediatePropagation()}stopPropagation(){this._propagationStopped=!0,super.stopPropagation(),this.source?.stopPropagation(),ot&&console.warn("Stop propagation...",this.pointerId,this.pointerType)}}class Kl extends KeyboardEvent{source;constructor(e,t,i){super(e,i),this.source=t}stopImmediatePropagation(){super.stopImmediatePropagation(),this.source?.stopImmediatePropagation()}}class wO{key;keyType;source;constructor(e){this.key=e.key,this.keyType=e.type,this.source=e}}var ii=(o=>(o[o.Early=-100]="Early",o[o.Default=0]="Default",o[o.Late=100]="Late",o))(ii||{});class s_{_eventListeners={};addEventListener(e,t,i){if(this._eventListeners[e]||(this._eventListeners[e]=[]),!t||typeof t!="function"){console.error("Invalid call to addEventListener: callback is required and must be a function!");return}i?i={...i}:i={};let n=0;i?.queue!=null&&(n=i.queue);const s=this._eventListeners[e],r=s.find(a=>a.priority===n);r?r.listeners.push({callback:t,options:i}):(s.push({priority:n,listeners:[{callback:t,options:i}]}),s.sort((a,l)=>a.priority-l.priority))}removeEventListener(e,t,i){if(!this._eventListeners[e]||!t)return;const n=this._eventListeners[e];if(i?.queue!=null){const s=n.find(a=>a.priority===i.queue);if(!s)return;const r=s.listeners.findIndex(a=>a.callback===t);r>=0&&s.listeners.splice(r,1)}else for(const s of n){const r=s.listeners.findIndex(a=>a.callback===t);r>=0&&s.listeners.splice(r,1)}}dispatchEvent(e){let t=!1;if(e instanceof Kl){const i=this._eventListeners[e.type];if(i)for(const n of i)for(let s=0;s<n.listeners.length;s++){const r=n.listeners[s];if(r.options?.signal?.aborted){n.listeners.splice(s,1),s--;continue}r.options.once&&(n.listeners.splice(s,1),s--),r.callback(e)}}if(e instanceof vo){const i=this._eventListeners[e.type];if(i)for(const n of i){if(t)break;for(let s=0;s<n.listeners.length;s++){const r=n.listeners[s];if(r.options?.signal?.aborted){n.listeners.splice(s,1),s--;continue}if(e.immediatePropagationStopped){t=!0,ot&&console.log("immediatePropagationStopped",e.type);break}else e.propagationStopped&&(t=!0,ot&&console.log("propagationStopped",e.type));r.options.once&&(n.listeners.splice(s,1),s--),r.callback(e)}}}}_doubleClickTimeThreshold=.2;_longPressTimeThreshold=1;get mousePosition(){return this._pointerPositions[0]}get mousePositionRC(){return this._pointerPositionsRC[0]}get mouseDown(){return this._pointerDown[0]}get mouseUp(){return this._pointerUp[0]}get mouseClick(){return this._pointerClick[0]}get mouseDoubleClick(){return this._pointerDoubleClick[0]}get mousePressed(){return this._pointerPressed[0]}get mouseWheelChanged(){return this.getMouseWheelChanged(0)}get click(){return this._pointerClick[0]}get doubleClick(){return this._pointerDoubleClick[0]}getGamepad(e=0){return typeof navigator<"u"&&"getGamepads"in navigator&&navigator.getGamepads()[e]||null}_setCursorTypes=[];setCursorPointer(){this.setCursor("pointer")}setCursorNormal(){this.unsetCursor("pointer")}setCursor(e){this._setCursorTypes.push(e),this._setCursorTypes.length>10&&this._setCursorTypes.shift(),this.updateCursor()}unsetCursor(e){for(let t=this._setCursorTypes.length-1;t>=0;t--)if(this._setCursorTypes[t]===e){this._setCursorTypes.splice(t,1),this.updateCursor();break}}updateCursor(){this._setCursorTypes?.length==0?this.context.domElement.style.cursor="default":this.context.domElement.style.cursor=this._setCursorTypes[this._setCursorTypes.length-1]}getIsPointerIdInUse(e){for(const t of this._pointerEventsPressed)if(t.pointerId===e&&t.used)return!0;return!1}getPointerPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&e++;return e}getPointerPosition(e){return e>=this._pointerPositions.length?null:this._pointerPositions[e]}getPointerPositionLastFrame(e){return e>=this._pointerPositionsLastFrame.length?null:this._pointerPositionsLastFrame[e]}getPointerPositionDelta(e){return e>=this._pointerPositionsDelta.length?null:this._pointerPositionsDelta[e]}getPointerPositionRC(e){return e>=this._pointerPositionsRC.length?null:this._pointerPositionsRC[e]}getPointerDown(e){return e>=this._pointerDown.length?!1:this._pointerDown[e]}getPointerUp(e){return e>=this._pointerUp.length?!1:this._pointerUp[e]}getPointerPressed(e){return e>=this._pointerPressed.length?!1:this._pointerPressed[e]}getPointerClicked(e){return e>=this._pointerClick.length?!1:this._pointerClick[e]}getPointerDoubleClicked(e){return e>=this._pointerDoubleClick.length?!1:this._pointerDoubleClick[e]}getPointerDownTime(e){return e>=this._pointerDownTime.length?-1:this._pointerDownTime[e]}getPointerUpTime(e){return e>=this._pointerUpTime.length?-1:this._pointerUpTime[e]}getPointerLongPress(e){return e>=this._pointerDownTime.length?!1:this.getPointerPressed(e)&&this.context.time.time-this._pointerDownTime[e]>this._longPressTimeThreshold}getIsMouse(e){return e<0||e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="mouse"}getIsTouch(e){return e<0||e>=this._pointerTypes.length?!1:this._pointerTypes[e]==="touch"}getTouchesPressedCount(){let e=0;for(let t=0;t<this._pointerPressed.length;t++)this._pointerPressed[t]&&this.getIsTouch(t)&&e++;return e}getMouseWheelChanged(e=0){return e>=this._mouseWheelChanged.length?!1:this._mouseWheelChanged[e]}getMouseWheelDeltaY(e=0){return e>=this._mouseWheelDeltaY.length?0:this._mouseWheelDeltaY[e]}getPointerEvent(e){if(!(e>=this._pointerEvent.length))return this._pointerEvent[e]??void 0}*foreachPointerId(e){for(let t=0;t<this._pointerTypes.length;t++)if(this._pointerIsActive(t)){if(e!==void 0){const i=this._pointerTypes[t];if(Array.isArray(e)){let n=!1;for(const s of e)if(i===s){n=!0;break}if(!n)continue}else if(e!==i)continue}yield t}}*foreachTouchId(){for(let e=0;e<this._pointerTypes.length;e++)this._pointerTypes[e]==="touch"&&this._pointerIsActive[e]&&(yield e)}_pointerIsActive(e){return e<0?!1:this._pointerPressed[e]||this._pointerDown[e]||this._pointerUp[e]}context;_pointerDown=[!1];_pointerUp=[!1];_pointerClick=[!1];_pointerDoubleClick=[!1];_pointerPressed=[!1];_pointerPositions=[new J];_pointerPositionsLastFrame=[new J];_pointerPositionsDelta=[new J];_pointerPositionsRC=[new J];_pointerPositionDown=[new b];_pointerDownTime=[];_pointerUpTime=[];_pointerUpTimestamp=[];_pointerIds=[];_pointerTypes=[""];_mouseWheelChanged=[!1];_mouseWheelDeltaY=[0];_pointerEvent=[];_pointerEventsPressed=[];_pointerSpace=[];_pressedStack=new Map;onDownButton(e,t){let i=this._pressedStack.get(e);i||(i=[],this._pressedStack.set(e,i)),i.push(t)}onReleaseButton(e,t){const i=this._pressedStack.get(e);if(!i)return;const n=i.indexOf(t);n>=0&&i.splice(n,1)}getFirstPressedButtonForPointer(e){const t=this._pressedStack.get(e);if(t)return t[0]}getLatestPressedButtonForPointer(e){const t=this._pressedStack.get(e);if(t)return t[t.length-1]}getKeyDown(e){if(e!==void 0)return this.isKeyDown(e);for(const t in this.keysPressed){const i=this.keysPressed[t];if(i.startFrame===this.context.time.frameCount)return i.key}return null}getKeyPressed(e){if(e!==void 0)return this.isKeyPressed(e);for(const t in this.keysPressed){const i=this.keysPressed[t];if(i.pressed)return i.key}return null}getKeyUp(e){if(e!==void 0)return this.isKeyUp(e);for(const t in this.keysPressed){const i=this.keysPressed[t];return i.pressed===!1&&i.frame===this.context.time.frameCount}return null}isKeyDown(e){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const t=this.getCodeForCommonKeyName(e);if(t!==null){for(const n of t)if(this.isKeyDown(n))return!0;return!1}const i=this.keysPressed[e];return i?i.startFrame===this.context.time.frameCount&&i.pressed:!1}isKeyUp(e){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const t=this.getCodeForCommonKeyName(e);if(t!==null){for(const n of t)if(this.isKeyUp(n))return!0;return!1}const i=this.keysPressed[e];return i?i.frame===this.context.time.frameCount&&i.pressed===!1:!1}isKeyPressed(e){if(!this.context.application.isVisible||!this.context.application.hasFocus)return!1;const t=this.getCodeForCommonKeyName(e);if(t!==null){for(const n of t)if(this.isKeyPressed(n))return!0;return!1}const i=this.keysPressed[e];return i&&i.pressed||!1}getCodeForCommonKeyName(e){if(e.length===1){if(e>="0"&&e<="9")return["Digit"+e];if(e>="a"&&e<="z")return["Key"+e.toUpperCase()];if(e==" ")return["Space"]}switch(e){case"shift":case"Shift":return["ShiftLeft","ShiftRight"];case"control":case"Control":return["ControlLeft","ControlRight"];case"alt":case"Alt":return["AltLeft","AltRight"]}return null}createInputEvent(e){switch(e.type){case"pointerdown":ot&&Te("Create Pointer down"),this.onDownButton(e.deviceIndex,e.button),this.onDown(e);break;case"pointermove":ot&&Te("Create Pointer move"),this.onMove(e);break;case"pointerup":ot&&Te("Create Pointer up"),this.onUp(e),this.onReleaseButton(e.deviceIndex,e.button);break}}convertScreenspaceToRaycastSpace(e){return e.x=(e.x-this.context.domX)/this.context.domWidth*2-1,e.y=-((e.y-this.context.domY)/this.context.domHeight)*2+1,e}constructor(e){this.context=e,this.context.post_render_callbacks.push(this.onEndOfFrame)}_htmlEventSource;bindEvents(){this.unbindEvents(),this._htmlEventSource=this.context.renderer.domElement,window.addEventListener("contextmenu",this.onContextMenu),this._htmlEventSource.addEventListener("pointerdown",this.onPointerDown,{passive:!0}),window.addEventListener("pointermove",this.onPointerMove,{passive:!0,capture:!0}),window.addEventListener("pointerup",this.onPointerUp,{passive:!0}),window.addEventListener("pointercancel",this.onPointerCancel,{passive:!0}),window.addEventListener("touchstart",this.onTouchStart,{passive:!0}),window.addEventListener("touchmove",this.onTouchMove,{passive:!0}),window.addEventListener("touchend",this.onTouchEnd,{passive:!0}),this._htmlEventSource.addEventListener("wheel",this.onMouseWheel,{passive:!0}),window.addEventListener("wheel",this.onWheelWindow,{passive:!0}),window.addEventListener("keydown",this.onKeyDown,!1),window.addEventListener("keypress",this.onKeyPressed,!1),window.addEventListener("keyup",this.onKeyUp,!1),window.addEventListener("blur",this.onLostFocus)}unbindEvents(){for(const e in this._eventListeners)this._eventListeners[e].length=0;window.removeEventListener("contextmenu",this.onContextMenu),this._htmlEventSource?.removeEventListener("pointerdown",this.onPointerDown),window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),window.removeEventListener("pointercancel",this.onPointerCancel),window.removeEventListener("touchstart",this.onTouchStart),window.removeEventListener("touchmove",this.onTouchMove),window.removeEventListener("touchend",this.onTouchEnd),this._htmlEventSource?.removeEventListener("wheel",this.onMouseWheel,!1),window.removeEventListener("wheel",this.onWheelWindow,!1),window.removeEventListener("keydown",this.onKeyDown,!1),window.removeEventListener("keypress",this.onKeyPressed,!1),window.removeEventListener("keyup",this.onKeyUp,!1),window.removeEventListener("blur",this.onLostFocus)}dispose(){const e=this.context.post_render_callbacks.indexOf(this.onEndOfFrame);e>=0&&this.context.post_render_callbacks.splice(e,1),this.unbindEvents()}onLostFocus=()=>{for(const e in this.keysPressed)this.keysPressed[e].pressed=!1};_receivedPointerMoveEventsThisFrame=new Array;onEndOfFrame=()=>{this._receivedPointerMoveEventsThisFrame.length=0;for(let e=0;e<this._pointerUp.length;e++)this._pointerUp[e]=!1;for(let e=0;e<this._pointerDown.length;e++)this._pointerDown[e]=!1;for(let e=0;e<this._pointerClick.length;e++)this._pointerClick[e]=!1;for(let e=0;e<this._pointerDoubleClick.length;e++)this._pointerDoubleClick[e]=!1;for(const e of this._pointerPositionsDelta)e.set(0,0);for(let e=0;e<this._mouseWheelChanged.length;e++)this._mouseWheelChanged[e]=!1;for(let e=0;e<this._mouseWheelDeltaY.length;e++)this._mouseWheelDeltaY[e]=0};canReceiveInput(e){return e.target===this.context.renderer?.domElement||e.target===this.context.domElement||this.context.isInAR||this.context.isInAR&&e.target===document.body&&G.isMozillaXR()?!0:(ot&&console.warn("CanReceiveInput:False for",e.target),!1)}onContextMenu=e=>{this.canReceiveInput(e)!==!1&&e instanceof PointerEvent&&e.pointerType};keysPressed={};onKeyDown=e=>{if(ot&&console.log(`key down ${e.code}, ${this.context.application.hasFocus}`,e),!this.context.application.hasFocus)return;const t=this.keysPressed[e.code];if(t&&t.pressed)return;this.keysPressed[e.code]={pressed:!0,frame:this.context.time.frameCount+1,startFrame:this.context.time.frameCount+1,key:e.key,code:e.code};const i=new Kl("keydown",e,e);this.onDispatchEvent(i)};onKeyPressed=e=>{if(!this.context.application.hasFocus)return;const t=this.keysPressed[e.code];if(!t)return;t.pressed=!0,t.frame=this.context.time.frameCount+1;const i=new Kl("keypress",e,e);this.onDispatchEvent(i)};onKeyUp=e=>{if(!this.context.application.hasFocus)return;const t=this.keysPressed[e.code];if(!t)return;t.pressed=!1,t.frame=this.context.time.frameCount+1;const i=new Kl("keyup",e,e);this.onDispatchEvent(i)};onWheelWindow=e=>{document.pointerLockElement&&this.onMouseWheel(e)};onMouseWheel=e=>{if(this.canReceiveInput(e)===!1)return;this._mouseWheelDeltaY.length<=0&&this._mouseWheelDeltaY.push(0),this._mouseWheelChanged.length<=0&&this._mouseWheelChanged.push(!1),this._mouseWheelChanged[0]=!0;const t=this._mouseWheelDeltaY[0];this._mouseWheelDeltaY[0]=t+e.deltaY};onPointerDown=e=>{if(this.context.isInAR||this.canReceiveInput(e)===!1)return;e.target instanceof HTMLElement&&e.target.setPointerCapture(e.pointerId);const t=this.getPointerId(e);ot&&Te(`pointer down #${t}, identifier:${e.pointerId}`);const i=this.getAndUpdateSpatialObjectForScreenPosition(t,e.clientX,e.clientY),n=new vo("pointerdown",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:t,button:e.button,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,buttonName:this.getButtonName(e),device:i,pressure:e.pressure});this.onDown(n)};onPointerMove=e=>{if(this.context.isInAR||this._receivedPointerMoveEventsThisFrame.includes(e.pointerId))return;this._receivedPointerMoveEventsThisFrame.push(e.pointerId);let t=e.button;e.pointerType==="mouse"&&(t=this.getFirstPressedButtonForPointer(0)??0);const i=this.getPointerId(e,t);t===-1&&(t=i);const n=this.getAndUpdateSpatialObjectForScreenPosition(i,e.clientX,e.clientY),s=new vo("pointermove",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:i,button:t,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,buttonName:this.getButtonName(e),device:n,pressure:e.pressure});this.onMove(s)};onPointerCancel=e=>{this.context.isInAR||(ot&&console.log("Pointer cancel",e),this.onPointerUp(e))};onPointerUp=e=>{if(this.context.isInAR)return;e.target instanceof HTMLElement&&e.target.releasePointerCapture(e.pointerId);const t=this.getPointerId(e),i=new vo("pointerup",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:t,button:e.button,clientX:e.clientX,clientY:e.clientY,pointerType:e.pointerType,buttonName:this.getButtonName(e),device:this.getAndUpdateSpatialObjectForScreenPosition(t,e.clientX,e.clientY),pressure:e.pressure});this.onUp(i),this._pointerIds[t]=-1,ot&&console.log("ID="+t,"PointerId="+e.pointerId,"ALL:",[...this._pointerIds])};getPointerId(e,t){return e.pointerType==="mouse"?0+(t??e.button):this.getPointerIndex(e.pointerId)}getButtonName(e){const t=e.button;if(e.pointerType==="mouse")switch(t){case 0:return"left";case 1:return"middle";case 2:return"right"}return"unknown"}onTouchStart=e=>{if(this.context.isInAR)for(let t=0;t<e.changedTouches.length;t++){const i=e.changedTouches[t],n=this.getPointerIndex(i.identifier),s=this.getAndUpdateSpatialObjectForScreenPosition(n,i.clientX,i.clientY),r=new vo("pointerdown",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:0,clientX:i.clientX,clientY:i.clientY,pointerType:"touch",buttonName:"unknown",device:s,pressure:i.force});this.onDown(r)}};onTouchMove=e=>{if(this.context.isInAR)for(let t=0;t<e.changedTouches.length;t++){const i=e.changedTouches[t],n=this.getPointerIndex(i.identifier),s=this.getAndUpdateSpatialObjectForScreenPosition(n,i.clientX,i.clientY),r=new vo("pointermove",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:0,clientX:i.clientX,clientY:i.clientY,pointerType:"touch",buttonName:"unknown",device:s,pressure:i.force});this.onMove(r)}};onTouchEnd=e=>{if(this.context.isInAR)for(let t=0;t<e.changedTouches.length;t++){const i=e.changedTouches[t],n=this.getPointerIndex(i.identifier),s=new vo("pointerup",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:0,clientX:i.clientX,clientY:i.clientY,pointerType:"touch",buttonName:"unknown",device:this.getAndUpdateSpatialObjectForScreenPosition(n,i.clientX,i.clientY),pressure:i.force});this.onUp(s),this._pointerIds[n]=-1}};tempNearPlaneVector=new b;tempFarPlaneVector=new b;tempLookMatrix=new ee;getAndUpdateSpatialObjectForScreenPosition(e,t,i){let n=this._pointerSpace[e];n||(n=new O,this._pointerSpace[e]=n),this._pointerSpace[e]=n;const s=this.context.mainCamera;if(s){const r=this.tempNearPlaneVector.set(t,i,-1);this.convertScreenspaceToRaycastSpace(r);const a=this.tempFarPlaneVector.set(r.x,r.y,1);r.unproject(s),a.unproject(s);const l=s.worldUp||$(0,1,0).applyQuaternion(be(s));this.tempLookMatrix.lookAt(a,r,l),n.position.set(r.x,r.y,r.z),n.quaternion.setFromRotationMatrix(this.tempLookMatrix)}return n}isInRect(e){if(this.context.isInXR)return!0;const t=this.context.domElement.getBoundingClientRect(),i=e.clientX,n=e.clientY,s=i>=t.x&&i<=t.right&&n>=t.y&&n<=t.bottom;return ot&&!s&&console.log("Not in rect",t,i,n),s}onDown(e){const t=e.pointerId;if(this.getPointerPressed(t)&&console.warn(`Received pointerDown for pointerId that is already pressed: ${t}`,ot?e:""),ot&&console.log(e.pointerType,"DOWN",t),!!this.isInRect(e)){for(this.setPointerState(t,this._pointerPressed,!0),this.setPointerState(t,this._pointerDown,!0),this.setPointerStateT(t,this._pointerEvent,e.source);t>=this._pointerTypes.length;)this._pointerTypes.push(e.pointerType);for(this._pointerTypes[t]=e.pointerType;t>=this._pointerPositionDown.length;)this._pointerPositionDown.push(new b);for(this._pointerPositionDown[t].set(e.clientX,e.clientY,e.clientZ??0);t>=this._pointerPositions.length;)this._pointerPositions.push(new J);this._pointerPositions[t].set(e.clientX,e.clientY),t>=this._pointerDownTime.length&&this._pointerDownTime.push(0),this._pointerDownTime[t]=this.context.time.realtimeSinceStartup,this.updatePointerPosition(e),this._pointerEventsPressed.push(e),this.onDispatchEvent(e)}}onMove(e){const t=e.pointerId,i=this.getPointerPressed(t);i===!1&&!this.isInRect(e)||e.pointerType==="touch"&&!i||(this.updatePointerPosition(e),this.setPointerStateT(t,this._pointerEvent,e.source),this.onDispatchEvent(e))}onUp(e){const t=e.pointerId;if(!this.getPointerPressed(t)){ot&&console.log(e.pointerType,"UP",t,"was not down");return}ot&&console.log(e.pointerType,"UP",t),this.setPointerState(t,this._pointerPressed,!1),this.setPointerStateT(t,this._pointerEvent,e.source),this.setPointerState(t,this._pointerUp,!0),this.updatePointerPosition(e);for(let a=this._pointerEventsPressed.length-1;a>=0;a--)if(this._pointerEventsPressed[a].pointerId===t){this._pointerEventsPressed.splice(a,1);break}if(!this._pointerPositionDown[t]){ot&&ge("Received pointer up event without matching down event for button: "+t),console.warn("Received pointer up event without matching down event for button: "+t);return}const i=this._pointerUpTime[t],n=this._pointerDownTime[t],s=this.context.time.realtimeSinceStartup,r=s-n;if(t>=this._pointerUpTime.length&&this._pointerUpTime.push(-99),this._pointerUpTime[t]=s,r<1){let a=e.clientX-this._pointerPositionDown[t].x,l=e.clientY-this._pointerPositionDown[t].y,c=0;if(e.isSpatial&&e.clientZ!=null&&(c=e.clientZ-this._pointerPositionDown[t].z,a*=200,l*=200,c*=200),Math.abs(a)<5&&Math.abs(l)<5&&Math.abs(c)<5){this.setPointerState(t,this._pointerClick,!0),e.isClick=!0;const h=s-i;ot&&console.log("CLICK",t,a,l,c,h),h<this._doubleClickTimeThreshold&&h>0&&(this.setPointerState(t,this._pointerDoubleClick,!0),e.isDoubleClick=!0)}}this.onDispatchEvent(e)}updatePointerPosition(e){const t=e.pointerId;for(;t>=this._pointerPositions.length;)this._pointerPositions.push(new J);for(;t>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new J);for(;t>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new J);const i=this._pointerPositionsLastFrame[t];i.copy(this._pointerPositions[t]);const n=this._pointerPositionsDelta[t];let s=e.clientX-i.x,r=e.clientY-i.y;if(e.source instanceof MouseEvent||e.source instanceof TouchEvent){const h=e.source;s===0&&h.movementX!==0&&(s=h.movementX||0),r===0&&h.movementY!==0&&(r=h.movementY||0)}n.x+=s,n.y+=r,this._pointerPositions[t].x=e.clientX,this._pointerPositions[t].y=e.clientY;const a=e.clientX,l=e.clientY;for(;t>=this._pointerPositionsRC.length;)this._pointerPositionsRC.push(new J);const c=this._pointerPositionsRC[t];c.set(a,l),this.convertScreenspaceToRaycastSpace(c)}getPointerIndex(e){let t=-1;for(let i=0;i<this._pointerIds.length;i++){if(this._pointerIds[i]===e)return i;t===-1&&this._pointerIds[i]===-1&&(t=i)}return t!==-1?(this._pointerIds[t]=e,t):(ot&&console.log("PUSH pointerId:",e),this._pointerIds.push(e),this._pointerIds.length-1)}setPointerState(e,t,i){t[e]=i}setPointerStateT(e,t,i){return t[e]=i,i}onDispatchEvent(e){const t=z.Current;try{z.Current=this.context,this.dispatchEvent(e)}finally{z.Current=t}}}const Pa=new ee().makeRotationY(Math.PI),$i=new U().setFromAxisAngle(new b(0,1,0),Math.PI),xO=w("debugwebxr");class SO{priority=-1e5;gameObject;isXRRig(){return!0}get isActive(){return this.gameObject.visible}constructor(){if(this.gameObject=new O,this.gameObject.name="Implicit XR Rig",xO){const e=cg(16733661);e.position.y+=.5,this.gameObject.add(e)}}}const wo=w("debugwebxr"),Td=w("debugcustomgesture"),CO="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",PO="generic-trigger",OO=new U().setFromEuler(new nt(uo.degToRad(0),uo.degToRad(-90),uo.degToRad(-90))),kO=new b(.04,-.04,0);class Qm{xr;get context(){return this.xr.context}inputSource;index=0;emitEvents=!0;get connected(){return this._connected}_connected=!0;get isTracking(){return this._isTracking}_isTracking=!1;get gamepad(){return this.__gamepad??=this.inputSource.gamepad}__gamepad;get isHand(){return this.hand!=null}get hand(){return this.__hand??=this.inputSource.hand}__hand;get handObject(){return this.context.renderer.xr.getHand(this.index)}get profiles(){return this.inputSource.profiles}get layout(){return this._layout}get targetRayMode(){return this.inputSource.targetRayMode}get targetRaySpace(){return this.inputSource.targetRaySpace}get gripSpace(){return this.inputSource.gripSpace}get side(){return this.__side??=this.inputSource.handedness}__side=void 0;get isRight(){return this.side==="right"}get isLeft(){return this.side==="left"}get isStylus(){return this._isMxInk}getHitTestSource(){return this._hitTestSource||this._requestHitTestSource(),this._hitTestSource}get hasHitTestSource(){return this._hitTestSource}cancelHitTestSource(){this._hitTestSource&&(this._hitTestSource.cancel(),this._hitTestSource=void 0)}_hitTestSource=void 0;_hasSelectEvent=!1;get hasSelectEvent(){return this._hasSelectEvent}_isMxInk=!1;_isMetaQuestTouchController=!1;getHitTest(){return this.xr.getHitTest(this)}_handJointPoses=new Map;getHandJointPose(e,t){if(t=t||this.xr.frame,!this.hand||!t?.getJointPose||!this.xr.referenceSpace)return null;let i=this._handJointPoses?.get(e);return i||(i=t.getJointPose(e,this.xr.referenceSpace),i&&this._handJointPoses.set(e,i),i)}_gripMatrix=new ee;_gripPosition=new b;_gripQuaternion=new U;_linearVelocity=new b;_rayPositionRaw=new b;_rayRotationRaw=new U;_rayMatrix=new ee;_rayPosition=new b;_rayQuaternion=new U;get gripPosition(){return $(this._gripPosition)}get gripQuaternion(){return ti(this._gripQuaternion)}get gripMatrix(){return this._gripMatrix}get gripLinearVelocity(){return $(this._linearVelocity).applyQuaternion($i)}get rayPosition(){return $(this._rayPosition)}get rayQuaternion(){return ti(this._rayQuaternion)}get gripWorldPosition(){return $(this._gripWorldPosition)}_gripWorldPosition=new b;get gripWorldQuaternion(){return ti(this._gripWorldQuaternion)}_gripWorldQuaternion=new U;get rayWorldPosition(){return $(this._rayWorldPosition)}_rayWorldPosition=new b;updateRayWorldPosition(){const e=this.xr.context.mainCamera?.parent;this._rayWorldPosition.copy(this._rayPositionRaw),e&&this._rayWorldPosition.applyMatrix4(e.matrixWorld)}get rayWorldQuaternion(){return ti(this._rayWorldQuaternion)}_rayWorldQuaternion=new U;get pinchPosition(){return $(this._pinchPosition)}_pinchPosition=new b;updateRayWorldQuaternion(){const e=this.xr.context.mainCamera?.parent,t=e?be(e):void 0;this._rayWorldQuaternion.copy(this._rayRotationRaw).multiply($i),t&&this._rayWorldQuaternion.premultiply(t)}get ray(){return this._ray.origin.copy(this.rayWorldPosition),this._ray.direction.copy($(0,0,1).applyQuaternion(this.rayWorldQuaternion)),this._ray}_ray;_hand_wristDotUp=void 0;get handWristDotUp(){if(this._hand_wristDotUp!==void 0)return this._hand_wristDotUp;const e=this.handObject?.joints.wrist;if(e){const t=$(0,1,0).applyQuaternion(e.quaternion),i=$(0,1,0).dot(t);return this._hand_wristDotUp=i}}get isHandUpsideDown(){return this.handWristDotUp!==void 0?this.handWristDotUp<-.7:!1}get isTeleportGesture(){return this.isHandUpsideDown&&this.getGesture("pinch")?.isDown}get object(){return this._object}_object;_gripSpaceObject;_raySpaceObject;model=null;_debugAxesHelper=new _i(.15);_debugGripAxesHelper=new _i(.07);_debugRayAxesHelper=new _i(.07);async getModelUrl(){return this.getMotionController?.then(e=>e?.assetUrl||null)}constructor(e,t,i){this.xr=e,this.inputSource=t,this.index=i,this._object=new O,this._object.name=`NeedleXRController_${i}`,wo&&(this._object.add(this._debugAxesHelper),this._gripSpaceObject=new O,this._raySpaceObject=new O,this._gripSpaceObject.name=`NeedleXRController_${i}_gripSpace`,this._raySpaceObject.name=`NeedleXRController_${i}_raySpace`,this._gripSpaceObject.add(this._debugGripAxesHelper),this._raySpaceObject.add(this._debugRayAxesHelper),this.xr.context.scene.add(this._gripSpaceObject),this.xr.context.scene.add(this._raySpaceObject)),this.xr.context.scene.add(this._object),this._ray=new ns,this.pointerInit={origin:this,pointerType:this.hand?"hand":"controller",deviceIndex:this.index,pointerId:-1,mode:this.inputSource.targetRayMode,ray:this._ray,device:this._object,buttonName:"none"},this.initialize(),this.subscribeEvents()}_hitTestSourcePromise=null;_requestHitTestSource(){return this._hitTestSourcePromise?this._hitTestSourcePromise:this.xr.mode==="immersive-ar"&&this.inputSource.targetRayMode==="tracked-pointer"&&this.xr.session.requestHitTestSourceForTransientInput?this._hitTestSourcePromise=this.xr.session.requestHitTestSourceForTransientInput({profile:this.inputSource.profiles[0],offsetRay:new XRRay})?.then(e=>(this._hitTestSourcePromise=null,this.connected?this._hitTestSource=e:(e.cancel(),null)))??null:null}onPointerHits=e=>{};onUpdate(e){this.onUpdateFrame(e),this.updateInputEvents(),this.onUpdateMove()}onRenderDebug(){F.DrawSphere(this.rayWorldPosition,.003),F.DrawDirection(this.rayWorldPosition,$(0,0,10).applyQuaternion(this.rayWorldQuaternion));const e=(this.inputSource.gripSpace?this.gripWorldPosition:this.object.worldPosition).sub(this.object.worldForward.multiplyScalar(.1)),t=this.inputSource.profiles.join(`
146
146
  `);let i=`Controller[${this.index}] (${this.inputSource.targetRayMode}, ${this.side})
147
147
  C:${this.connected?"x":"-"} T:${this.isTracking?"x":"-"} Hand:${this.inputSource.hand?"x":"-"} Pen: ${this._isMxInk?"x":"-"}`;if(this.inputSource.hand&&(i+=`
@@ -149,7 +149,7 @@ Pinch: ${this.getGesture("pinch")?.value.toFixed(3)}`),i+=`
149
149
  `+t,i+=`
150
150
  `+(this.inputSource.targetRaySpace?"Ray: x":"Ray: -")+(this.inputSource.gripSpace?" Grip: x":" Grip: -")+(this.inputSource.gamepad?` Gamepad: ${this.inputSource.gamepad.mapping}`:" Gamepad: -"),this.inputSource.gamepad){const n=this.inputSource.gamepad;let s="[btns "+n.buttons.length+"]: "+n.buttons.map(r=>r.value.toPrecision(1)).join(",");s+=`
151
151
  [axes `+n.axes.length+"]: "+n.axes.map(r=>r.toPrecision(1)).join(","),i+=`
152
- `+s}F.DrawLabel(e,i,.006)}onUpdateFrame(e){if(this._handJointPoses.clear(),this._hand_wristDotUp=void 0,!this.xr.referenceSpace||!this.inputSource.gamepad?.connected){this._isTracking=!1;return}const t=e.getPose(this.inputSource.targetRaySpace,this.xr.referenceSpace);this._isTracking=t!=null;let i=null,n=null,s=null,r=null;if(t){const h=t.transform;this._rayMatrix.fromArray(h.matrix).premultiply(Pa),this._rayMatrix.decompose(this._rayPosition,this._rayQuaternion,$(1,1,1)),s=$(h.position),r=ti(h.orientation),this._rayPositionRaw.copy(s),this._rayRotationRaw.copy(r)}if(this.inputSource.gripSpace){const h=e.getPose(this.inputSource.gripSpace,this.xr.referenceSpace);if(h){const d=h.transform;if(i=$(d.position),n=ti(d.orientation),this._gripMatrix.fromArray(d.matrix).premultiply(Pa),this._gripMatrix.decompose(this._gripPosition,this._gripQuaternion,$(1,1,1)),"linearVelocity"in h&&h.linearVelocity){const p=h.linearVelocity;this._linearVelocity.set(p.x,p.y,p.z)}}}this.xr.context.mainCamera?.parent&&(this._object.parent!==this.xr.context.mainCamera?.parent&&this.xr.context.mainCamera.parent.add(this._object),this._gripSpaceObject!==void 0&&this._gripSpaceObject?.parent!==this.xr.context.mainCamera?.parent&&this.xr.context.mainCamera.parent.add(this._gripSpaceObject),this._raySpaceObject!==void 0&&this._raySpaceObject?.parent!==this.xr.context.mainCamera?.parent&&this.xr.context.mainCamera.parent.add(this._raySpaceObject));const a=this.hand;if(a){let h=!1;const d=a.get("wrist"),p=d&&this.getHandJointPose(d,e);if(p){h=!0;const m=p.transform.position,y=p.transform.orientation;this._object.position.set(m.x,m.y,m.z),this._object.quaternion.set(y.x,y.y,y.z,y.w).multiply($i)}h||(this._object.position.copy(this._rayPosition),this._object.quaternion.copy(this._rayQuaternion).multiply($i));const g=a.get("middle-finger-metacarpal"),f=g&&this.getHandJointPose(g,e);f&&(this._gripMatrix.fromArray(f.transform.matrix).premultiply(Pa),this._gripMatrix.decompose(this._gripPosition,this._gripQuaternion,$(1,1,1)),i=$().copy(f.transform.position),n=ti().copy(f.transform.orientation),n.multiply(OO),i.add($(kO).applyQuaternion(n)))}else this.inputSource.gripSpace&&this.targetRayMode==="transient-pointer"&&i&&n?(this._object.position.copy(i),this._object.quaternion.copy(n).multiply($i)):s&&r&&(this._object.position.copy(s),this._object.quaternion.copy(r).multiply($i));wo&&(s&&r&&(this._raySpaceObject?.position.copy(s),this._raySpaceObject?.quaternion.copy(r).multiply($i)),i&&n&&(this._gripSpaceObject?.position.copy(i),this._gripSpaceObject?.quaternion.copy(n).multiply($i)));const l=this.xr.context.mainCamera?.parent,c=l?be(l):void 0;i&&n&&(this._gripWorldPosition.copy(i),l&&this._gripWorldPosition.applyMatrix4(l.matrixWorld),this._gripWorldQuaternion.copy(n),this._gripWorldQuaternion.multiply($i),c&&this._gripWorldQuaternion.premultiply(c)),this.updateRayWorldPosition(),this.updateRayWorldQuaternion()}onDisconnected(){this._connected=!1,wo&&console.warn("Controller disconnected",this.index);for(const e of this._object.children)this.xr.context.scene.attach(e);this._object?.removeFromParent(),this._debugAxesHelper?.removeFromParent(),this._debugGripAxesHelper?.removeFromParent(),this._debugRayAxesHelper?.removeFromParent(),this._gripSpaceObject?.removeFromParent(),this._raySpaceObject?.removeFromParent(),this.unsubscribeEvents(),this._hitTestSource&&(this._hitTestSource.cancel(),this._hitTestSource=void 0)}getButton(e){if(!this._layout)return;switch(e){case"primary-button":if(this.isLeft)e="x-button";else if(this.isRight)e="a-button";else return;break;case"primary":return this.hand?this.getGesture("pinch"):this.toNeedleGamepadButton(0,e);case"xr-standard-trigger":if(this.inputSource.gamepad)return this.toNeedleGamepadButton(0,e);break;case"xr-standard-squeeze":if(this.inputSource.gamepad)return this.toNeedleGamepadButton(1,e);break;case"xr-standard-thumbstick":if(this.inputSource.gamepad)return this.toNeedleGamepadButton(3,e);break}if(this._buttonMap.has(e))return this.toNeedleGamepadButton(this._buttonMap.get(e),e);const t=this._layout?.components[e];if(t?.gamepadIndices)switch(t.type){case"button":case"squeeze":if(this.inputSource.gamepad){const i=t.gamepadIndices.button;return this._buttonMap.set(e,i),this.toNeedleGamepadButton(i,e)}break;default:console.warn("Unsupported component type",t.type);break}this._buttonMap.set(e,void 0)}getGesture(e){const t=this.states[e];if(!t)return null;this.states[e]=t;const i=this._needleGamepadButtons[e]||new a_(void 0,e);return i.pressed=t.pressed,i.value=t.value,i.isDown=t.isDown,i.isUp=t.isUp,this._needleGamepadButtons[e]=i,i}getPointerId(e){if((e==="primary"||e==="pinch")&&(e=0),typeof e!="number"){const t=this._buttonMap.get(e);if(t===void 0)return;e=t}return this.index*10+e}_needleGamepadButtons={};toNeedleGamepadButton(e,t){if(!this.inputSource.gamepad?.buttons)return;const i=this.inputSource.gamepad?.buttons[e],n=this.states[e],s=this._needleGamepadButtons[e]||new a_(e,t);return i&&(s.pressed=i.pressed,s.value=i.value,s.touched=i.touched),n&&(s.isDown=n.isDown,s.isUp=n.isUp),this._needleGamepadButtons[e]=s,s}getStick(e){if(!this._layout)return{x:0,y:0,z:0};if(this.isHand)return{x:0,y:0,z:0};e==="primary"&&this._layout.components["xr-standard-thumbstick"]&&(e="xr-standard-thumbstick");const t=this._layout?.components[e];if(t?.gamepadIndices)switch(t.type){case"thumbstick":if(this.inputSource.gamepad){const i=t.gamepadIndices.xAxis,n=t.gamepadIndices.yAxis;let s=this.inputSource.gamepad.axes[i]||0,r=this.inputSource.gamepad.axes[n]||0;s*=-1,r*=-1;const a=t.gamepadIndices.button,l=this.inputSource.gamepad?.buttons[a]?.value||0;return{x:s,y:r,z:l}}}return{x:0,y:0,z:0}}_buttonMap=new Map;_motioncontroller;_layout;getMotionController;initialize(){if(this._hasSelectEvent=this.profiles.includes("generic-hand-select")||this.profiles.some(e=>e.startsWith("generic-trigger")),this._isMetaQuestTouchController=this.profiles.includes("meta-quest-touch-plus")||this.profiles.includes("oculus-touch-v3"),this._isMxInk=this.profiles.includes("logitech-mx-ink"),!this._layout){if(this.inputSource.targetRayMode==="transient-pointer")return;const e=jC(this.inputSource,CO,PO);this.getMotionController=e.then(t=>{if(!this.connected)return null;this._motioncontroller=new DC(this.inputSource,t.profile,t.assetPath||"");const i=t.profile.layouts[this.inputSource.handedness];if(this._layout=i,this._layout&&!this._layout.gamepad?.length){this._layout.gamepad=[];for(const n in this._layout.components){const s=this._layout.components[n];this._layout.gamepad[s.gamepadIndices.button]=n}}return this._motioncontroller}).catch(t=>(this.inputSource&&console.warn("Couldn't initialize motion controller profile for ",this.inputSource,t),null))}}emitPointerDownEvent=!0;emitPointerUpEvent=!0;emitPointerMoveEvent=!0;pointerMoveDistanceThreshold=.03;pointerMoveAngleThreshold=.05;subscribeEvents(){this.xr.session.addEventListener("selectstart",this.onSelectStart),this.xr.session.addEventListener("selectend",this.onSelectEnd),this.xr.session.addEventListener("squeezestart",this.onSequeezeStart),this.xr.session.addEventListener("squeezeend",this.onSequeezeEnd)}unsubscribeEvents(){this.xr.session.removeEventListener("selectstart",this.onSelectStart),this.xr.session.removeEventListener("selectend",this.onSelectEnd),this.xr.session.removeEventListener("squeezestart",this.onSequeezeStart),this.xr.session.removeEventListener("squeezeend",this.onSequeezeEnd)}_selectButtonIndex=void 0;_squeezeButtonIndex=void 0;onSelectStart=e=>{if(!this.emitPointerDownEvent||this.inputSource!==e.inputSource)return;this.onUpdateFrame(e.frame),this._hasSelectEvent=!0;const t=this._layout?.selectComponentId,i=this._layout?.components[t]?.gamepadIndices?.button;i!==void 0&&(this._selectButtonIndex=i),!Td&&(wo&&F.DrawDirection(this.rayWorldPosition,$(0,.01,1).applyQuaternion(this.rayWorldQuaternion),16711680,10),this.emitPointerEvent(Ee.PointerDown,this._selectButtonIndex||0,"xr-standard-trigger",!0,e))};onSelectEnd=e=>{this.emitPointerUpEvent&&(Td||this.inputSource===e.inputSource&&this.emitPointerEvent(Ee.PointerUp,this._selectButtonIndex||0,"xr-standard-trigger",!0,e))};onSequeezeStart=e=>{this.emitPointerDownEvent&&this.inputSource===e.inputSource&&(this._squeezeButtonIndex=this._layout?.components["xr-standard-squeeze"]?.gamepadIndices?.button,this._squeezeButtonIndex!==void 0&&(wo&&F.DrawDirection(this.rayWorldPosition,$(0,.01,1).applyQuaternion(this.rayWorldQuaternion),255,10),this.emitPointerEvent(Ee.PointerDown,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,e)))};onSequeezeEnd=e=>{this.emitPointerUpEvent&&this.inputSource===e.inputSource&&this._squeezeButtonIndex!==void 0&&this.emitPointerEvent(Ee.PointerUp,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,e)};states={};updateInputEvents(){if(this.gamepad?.buttons){for(let e=0;e<this.gamepad.buttons.length;e++){const t=this.gamepad.buttons[e],i=this.states[e]||new r_;let n=null;this._isMxInk&&(e===4||e===5)?(t.value>0&&!i.pressed?(n="pointerdown",i.isDown=!0,i.isUp=!1):t.value===0&&i.pressed?(n="pointerup",i.isDown=!1,i.isUp=!0):i.pressed&&(n="pointermove",i.isDown=!1,i.isUp=!1),i.pressed=t.value>0,i.value=t.value):(t.pressed&&!i.pressed?(n="pointerdown",i.isDown=!0,i.isUp=!1):!t.pressed&&i.pressed?(n="pointerup",i.isDown=!1,i.isUp=!0):(i.isDown=!1,i.isUp=!1),i.pressed=t.pressed,i.value=t.value),this.states[e]=i;const s=e!==this._selectButtonIndex&&e!==this._squeezeButtonIndex;if(n!=null&&s){let r=this._layout?.gamepad[e];this._isMxInk&&e===4&&(r="stylus-touch"),this._isMxInk&&e===5&&(r="stylus-tip"),(wo||Td)&&console.log("Emitting pointer event",n,e,r,t.value,this.gamepad,this._layout),this.emitPointerEvent(n,e,r??"none",!1,null,t.value)}}if(this._isMetaQuestTouchController){const e=this.gamepad.buttons.length-1,t=this.states[e];if(t&&t.isDown){const i=this.context.menu;i.spatialMenuIsVisible?i.setSpatialMenuVisible(!1):this.context.menu.setSpatialMenuVisible(!0)}}}if(this.hand){const e=this.handObject;if(e){const t=e.joints["index-finger-tip"],i=e.joints["thumb-tip"];if(t&&i){const n=t.position.distanceTo(i.position);this._pinchPosition.lerpVectors(t.position,i.position,.5);const s=this.xr.context.mainCamera?.parent;if(s&&this._pinchPosition.applyMatrix4(s.matrixWorld),n!==0){const r=this.states.pinch||new r_,a=(.02+.01)*1.5;r.value=1-(n-.02)/a;const l=n<.02-.01,c=n>.02+.01;l&&!r.pressed?(Td&&console.log("pinch start",n),r.isDown=!0,r.isUp=!1,r.pressed=!0):c&&r.pressed?(r.isDown=!1,r.isUp=!0,r.pressed=!1):(r.isDown=!1,r.isUp=!1),this.states.pinch=r}}}}}_didMoveLastFrame=!1;_lastPointerMovePosition=new b;_lastPointerMoveQuaternion=new U;onUpdateMove(){if(!this.emitPointerMoveEvent)return;let e=!1;if(this._lastPointerMovePosition.distanceTo(this.gripWorldPosition)>this.pointerMoveDistanceThreshold*this.xr.rigScale&&(e=!0),e||this._lastPointerMoveQuaternion.angleTo(this.gripWorldQuaternion)>this.pointerMoveAngleThreshold&&(e=!0),e){this._didMoveLastFrame=!0,this._lastPointerMovePosition.copy(this.gripWorldPosition),this._lastPointerMoveQuaternion.copy(this.gripWorldQuaternion),wo&&F.DrawLabel(this.rayWorldPosition.add(this.object.worldForward.multiplyScalar(.1)),"move",.01);let t=this.xr.context.input.getFirstPressedButtonForPointer(this.index);t===void 0&&(t=0);const i=this.gamepad?.buttons[t]?.value;this.emitPointerEvent("pointermove",t,"none",!1,null,i)}else this._didMoveLastFrame=!1}pointerInit;emitPointerEvent(e,t,i,n,s=null,r){if(!this.emitEvents){wo&&e!==Ee.PointerMove&&console.warn("Pointer events are disabled for this controller",this.index,e,t);return}if(this.xr.mode==="immersive-vr"||this.xr.isPassThrough){this.pointerInit.origin=this,this.pointerInit.pointerId=this.getPointerId(t),this.pointerInit.pointerType=this.hand?"hand":"controller",this.pointerInit.button=t,this.pointerInit.buttonName=i,this.pointerInit.isPrimary=n,this.pointerInit.mode=this.inputSource.targetRayMode,this.pointerInit.ray=this.ray,this.pointerInit.device=this.object,this.pointerInit.pressure=r,this.pointerInit.clientX=this._rayPosition.x/this.xr.rigScale,this.pointerInit.clientY=this._rayPosition.y/this.xr.rigScale,this.pointerInit.clientZ=this._rayPosition.z/this.xr.rigScale;const a=z.Current;z.Current=this.xr.context,wo&&e!=="pointermove"&&console.warn("Pointer event",e,t,i,{...this.pointerInit}),this.xr.context.input.createInputEvent(new vo(e,s,this.pointerInit)),z.Current=a}}}class r_{isDown=!1;isUp=!1;pressed=!1;value=0}class a_{index;name;touched=!1;pressed=!1;value=0;isDown=!1;isUp=!1;constructor(e,t){this.index=e,this.name=t}}var Ym=(o=>(o.Visible="application-visible",o.Hidden="application-hidden",o.MuteChanged="application-mutechanged",o))(Ym||{});let Ed=!1;const Oa=[];function dr(){if(Ed)return;E()&&console.debug("User interaction registered: audio can now be played"),Ed=!0;const o=[...Oa];Oa.length=0,o.forEach(e=>e())}document.addEventListener("mousedown",dr),document.addEventListener("pointerup",dr),document.addEventListener("click",dr),document.addEventListener("dragstart",dr),document.addEventListener("touchend",dr),document.addEventListener("keydown",dr);class Tn extends EventTarget{static get userInteractionRegistered(){return Ed}static registerWaitForAllowAudio=Tn.registerWaitForInteraction;static registerWaitForInteraction(e){if(e!==null){if(Ed){e();return}Oa.indexOf(e)===-1&&Oa.push(e)}}static unregisterWaitForInteraction(e){const t=Oa.indexOf(e);t!==-1&&Oa.splice(t,1)}_mute=!1;get muted(){return this._mute}set muted(e){e!==this._mute&&(this._mute=e,this.dispatchEvent(new Event("application-mutechanged")))}context;get hasFocus(){return document.hasFocus()}get isVisible(){return this._isVisible}_isVisible=!0;constructor(e){super(),this.context=e,window.addEventListener("visibilitychange",this.onVisiblityChanged.bind(this),!1)}onVisiblityChanged(e){switch(e.target.visibilityState){case"hidden":this._isVisible=!1,this.dispatchEvent(new Event("application-hidden"));break;case"visible":this._isVisible=!0,this.dispatchEvent(new Event("application-visible"));break}}}const ka=new Map,Ma=new Map;let l_=0;function xo(o,e,t){if(ka.has(e)||ka.set(e,new Array),ka.get(e).push({method:o,options:{once:!1,...t}}),l_<30){const i=Ma.get(e);i&&i?.length>100&&(l_+=1,console.warn(`You have ${i.length} methods registered for Event ${e}.
152
+ `+s}F.DrawLabel(e,i,.006)}onUpdateFrame(e){if(this._handJointPoses.clear(),this._hand_wristDotUp=void 0,!this.xr.referenceSpace||!this.inputSource.gamepad?.connected){this._isTracking=!1;return}const t=e.getPose(this.inputSource.targetRaySpace,this.xr.referenceSpace);this._isTracking=t!=null;let i=null,n=null,s=null,r=null;if(t){const h=t.transform;this._rayMatrix.fromArray(h.matrix).premultiply(Pa),this._rayMatrix.decompose(this._rayPosition,this._rayQuaternion,$(1,1,1)),s=$(h.position),r=ti(h.orientation),this._rayPositionRaw.copy(s),this._rayRotationRaw.copy(r)}if(this.inputSource.gripSpace){const h=e.getPose(this.inputSource.gripSpace,this.xr.referenceSpace);if(h){const d=h.transform;if(i=$(d.position),n=ti(d.orientation),this._gripMatrix.fromArray(d.matrix).premultiply(Pa),this._gripMatrix.decompose(this._gripPosition,this._gripQuaternion,$(1,1,1)),"linearVelocity"in h&&h.linearVelocity){const p=h.linearVelocity;this._linearVelocity.set(p.x,p.y,p.z)}}}this.xr.context.mainCamera?.parent&&(this._object.parent!==this.xr.context.mainCamera?.parent&&this.xr.context.mainCamera.parent.add(this._object),this._gripSpaceObject!==void 0&&this._gripSpaceObject?.parent!==this.xr.context.mainCamera?.parent&&this.xr.context.mainCamera.parent.add(this._gripSpaceObject),this._raySpaceObject!==void 0&&this._raySpaceObject?.parent!==this.xr.context.mainCamera?.parent&&this.xr.context.mainCamera.parent.add(this._raySpaceObject));const a=this.hand;if(a){let h=!1;const d=a.get("wrist"),p=d&&this.getHandJointPose(d,e);if(p){h=!0;const g=p.transform.position,y=p.transform.orientation;this._object.position.set(g.x,g.y,g.z),this._object.quaternion.set(y.x,y.y,y.z,y.w).multiply($i)}h||(this._object.position.copy(this._rayPosition),this._object.quaternion.copy(this._rayQuaternion).multiply($i));const m=a.get("middle-finger-metacarpal"),f=m&&this.getHandJointPose(m,e);f&&(this._gripMatrix.fromArray(f.transform.matrix).premultiply(Pa),this._gripMatrix.decompose(this._gripPosition,this._gripQuaternion,$(1,1,1)),i=$().copy(f.transform.position),n=ti().copy(f.transform.orientation),n.multiply(OO),i.add($(kO).applyQuaternion(n)))}else this.inputSource.gripSpace&&this.targetRayMode==="transient-pointer"&&i&&n?(this._object.position.copy(i),this._object.quaternion.copy(n).multiply($i)):s&&r&&(this._object.position.copy(s),this._object.quaternion.copy(r).multiply($i));wo&&(s&&r&&(this._raySpaceObject?.position.copy(s),this._raySpaceObject?.quaternion.copy(r).multiply($i)),i&&n&&(this._gripSpaceObject?.position.copy(i),this._gripSpaceObject?.quaternion.copy(n).multiply($i)));const l=this.xr.context.mainCamera?.parent,c=l?be(l):void 0;i&&n&&(this._gripWorldPosition.copy(i),l&&this._gripWorldPosition.applyMatrix4(l.matrixWorld),this._gripWorldQuaternion.copy(n),this._gripWorldQuaternion.multiply($i),c&&this._gripWorldQuaternion.premultiply(c)),this.updateRayWorldPosition(),this.updateRayWorldQuaternion()}onDisconnected(){this._connected=!1,wo&&console.warn("Controller disconnected",this.index);for(const e of this._object.children)this.xr.context.scene.attach(e);this._object?.removeFromParent(),this._debugAxesHelper?.removeFromParent(),this._debugGripAxesHelper?.removeFromParent(),this._debugRayAxesHelper?.removeFromParent(),this._gripSpaceObject?.removeFromParent(),this._raySpaceObject?.removeFromParent(),this.unsubscribeEvents(),this._hitTestSource&&(this._hitTestSource.cancel(),this._hitTestSource=void 0)}getButton(e){if(!this._layout)return;switch(e){case"primary-button":if(this.isLeft)e="x-button";else if(this.isRight)e="a-button";else return;break;case"primary":return this.hand?this.getGesture("pinch"):this.toNeedleGamepadButton(0,e);case"xr-standard-trigger":if(this.inputSource.gamepad)return this.toNeedleGamepadButton(0,e);break;case"xr-standard-squeeze":if(this.inputSource.gamepad)return this.toNeedleGamepadButton(1,e);break;case"xr-standard-thumbstick":if(this.inputSource.gamepad)return this.toNeedleGamepadButton(3,e);break}if(this._buttonMap.has(e))return this.toNeedleGamepadButton(this._buttonMap.get(e),e);const t=this._layout?.components[e];if(t?.gamepadIndices)switch(t.type){case"button":case"squeeze":if(this.inputSource.gamepad){const i=t.gamepadIndices.button;return this._buttonMap.set(e,i),this.toNeedleGamepadButton(i,e)}break;default:console.warn("Unsupported component type",t.type);break}this._buttonMap.set(e,void 0)}getGesture(e){const t=this.states[e];if(!t)return null;this.states[e]=t;const i=this._needleGamepadButtons[e]||new a_(void 0,e);return i.pressed=t.pressed,i.value=t.value,i.isDown=t.isDown,i.isUp=t.isUp,this._needleGamepadButtons[e]=i,i}getPointerId(e){if((e==="primary"||e==="pinch")&&(e=0),typeof e!="number"){const t=this._buttonMap.get(e);if(t===void 0)return;e=t}return this.index*10+e}_needleGamepadButtons={};toNeedleGamepadButton(e,t){if(!this.inputSource.gamepad?.buttons)return;const i=this.inputSource.gamepad?.buttons[e],n=this.states[e],s=this._needleGamepadButtons[e]||new a_(e,t);return i&&(s.pressed=i.pressed,s.value=i.value,s.touched=i.touched),n&&(s.isDown=n.isDown,s.isUp=n.isUp),this._needleGamepadButtons[e]=s,s}getStick(e){if(!this._layout)return{x:0,y:0,z:0};if(this.isHand)return{x:0,y:0,z:0};e==="primary"&&this._layout.components["xr-standard-thumbstick"]&&(e="xr-standard-thumbstick");const t=this._layout?.components[e];if(t?.gamepadIndices)switch(t.type){case"thumbstick":if(this.inputSource.gamepad){const i=t.gamepadIndices.xAxis,n=t.gamepadIndices.yAxis;let s=this.inputSource.gamepad.axes[i]||0,r=this.inputSource.gamepad.axes[n]||0;s*=-1,r*=-1;const a=t.gamepadIndices.button,l=this.inputSource.gamepad?.buttons[a]?.value||0;return{x:s,y:r,z:l}}}return{x:0,y:0,z:0}}_buttonMap=new Map;_motioncontroller;_layout;getMotionController;initialize(){if(this._hasSelectEvent=this.profiles.includes("generic-hand-select")||this.profiles.some(e=>e.startsWith("generic-trigger")),this._isMetaQuestTouchController=this.profiles.includes("meta-quest-touch-plus")||this.profiles.includes("oculus-touch-v3"),this._isMxInk=this.profiles.includes("logitech-mx-ink"),!this._layout){if(this.inputSource.targetRayMode==="transient-pointer")return;const e=jC(this.inputSource,CO,PO);this.getMotionController=e.then(t=>{if(!this.connected)return null;this._motioncontroller=new DC(this.inputSource,t.profile,t.assetPath||"");const i=t.profile.layouts[this.inputSource.handedness];if(this._layout=i,this._layout&&!this._layout.gamepad?.length){this._layout.gamepad=[];for(const n in this._layout.components){const s=this._layout.components[n];this._layout.gamepad[s.gamepadIndices.button]=n}}return this._motioncontroller}).catch(t=>(this.inputSource&&console.warn("Couldn't initialize motion controller profile for ",this.inputSource,t),null))}}emitPointerDownEvent=!0;emitPointerUpEvent=!0;emitPointerMoveEvent=!0;pointerMoveDistanceThreshold=.03;pointerMoveAngleThreshold=.05;subscribeEvents(){this.xr.session.addEventListener("selectstart",this.onSelectStart),this.xr.session.addEventListener("selectend",this.onSelectEnd),this.xr.session.addEventListener("squeezestart",this.onSequeezeStart),this.xr.session.addEventListener("squeezeend",this.onSequeezeEnd)}unsubscribeEvents(){this.xr.session.removeEventListener("selectstart",this.onSelectStart),this.xr.session.removeEventListener("selectend",this.onSelectEnd),this.xr.session.removeEventListener("squeezestart",this.onSequeezeStart),this.xr.session.removeEventListener("squeezeend",this.onSequeezeEnd)}_selectButtonIndex=void 0;_squeezeButtonIndex=void 0;onSelectStart=e=>{if(!this.emitPointerDownEvent||this.inputSource!==e.inputSource)return;this.onUpdateFrame(e.frame),this._hasSelectEvent=!0;const t=this._layout?.selectComponentId,i=this._layout?.components[t]?.gamepadIndices?.button;i!==void 0&&(this._selectButtonIndex=i),!Td&&(wo&&F.DrawDirection(this.rayWorldPosition,$(0,.01,1).applyQuaternion(this.rayWorldQuaternion),16711680,10),this.emitPointerEvent(Ee.PointerDown,this._selectButtonIndex||0,"xr-standard-trigger",!0,e))};onSelectEnd=e=>{this.emitPointerUpEvent&&(Td||this.inputSource===e.inputSource&&this.emitPointerEvent(Ee.PointerUp,this._selectButtonIndex||0,"xr-standard-trigger",!0,e))};onSequeezeStart=e=>{this.emitPointerDownEvent&&this.inputSource===e.inputSource&&(this._squeezeButtonIndex=this._layout?.components["xr-standard-squeeze"]?.gamepadIndices?.button,this._squeezeButtonIndex!==void 0&&(wo&&F.DrawDirection(this.rayWorldPosition,$(0,.01,1).applyQuaternion(this.rayWorldQuaternion),255,10),this.emitPointerEvent(Ee.PointerDown,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,e)))};onSequeezeEnd=e=>{this.emitPointerUpEvent&&this.inputSource===e.inputSource&&this._squeezeButtonIndex!==void 0&&this.emitPointerEvent(Ee.PointerUp,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,e)};states={};updateInputEvents(){if(this.gamepad?.buttons){for(let e=0;e<this.gamepad.buttons.length;e++){const t=this.gamepad.buttons[e],i=this.states[e]||new r_;let n=null;this._isMxInk&&(e===4||e===5)?(t.value>0&&!i.pressed?(n="pointerdown",i.isDown=!0,i.isUp=!1):t.value===0&&i.pressed?(n="pointerup",i.isDown=!1,i.isUp=!0):i.pressed&&(n="pointermove",i.isDown=!1,i.isUp=!1),i.pressed=t.value>0,i.value=t.value):(t.pressed&&!i.pressed?(n="pointerdown",i.isDown=!0,i.isUp=!1):!t.pressed&&i.pressed?(n="pointerup",i.isDown=!1,i.isUp=!0):(i.isDown=!1,i.isUp=!1),i.pressed=t.pressed,i.value=t.value),this.states[e]=i;const s=e!==this._selectButtonIndex&&e!==this._squeezeButtonIndex;if(n!=null&&s){let r=this._layout?.gamepad[e];this._isMxInk&&e===4&&(r="stylus-touch"),this._isMxInk&&e===5&&(r="stylus-tip"),(wo||Td)&&console.log("Emitting pointer event",n,e,r,t.value,this.gamepad,this._layout),this.emitPointerEvent(n,e,r??"none",!1,null,t.value)}}if(this._isMetaQuestTouchController){const e=this.gamepad.buttons.length-1,t=this.states[e];if(t&&t.isDown){const i=this.context.menu;i.spatialMenuIsVisible?i.setSpatialMenuVisible(!1):this.context.menu.setSpatialMenuVisible(!0)}}}if(this.hand){const e=this.handObject;if(e){const t=e.joints["index-finger-tip"],i=e.joints["thumb-tip"];if(t&&i){const n=t.position.distanceTo(i.position);this._pinchPosition.lerpVectors(t.position,i.position,.5);const s=this.xr.context.mainCamera?.parent;if(s&&this._pinchPosition.applyMatrix4(s.matrixWorld),n!==0){const r=this.states.pinch||new r_,a=(.02+.01)*1.5;r.value=1-(n-.02)/a;const l=n<.02-.01,c=n>.02+.01;l&&!r.pressed?(Td&&console.log("pinch start",n),r.isDown=!0,r.isUp=!1,r.pressed=!0):c&&r.pressed?(r.isDown=!1,r.isUp=!0,r.pressed=!1):(r.isDown=!1,r.isUp=!1),this.states.pinch=r}}}}}_didMoveLastFrame=!1;_lastPointerMovePosition=new b;_lastPointerMoveQuaternion=new U;onUpdateMove(){if(!this.emitPointerMoveEvent)return;let e=!1;if(this._lastPointerMovePosition.distanceTo(this.gripWorldPosition)>this.pointerMoveDistanceThreshold*this.xr.rigScale&&(e=!0),e||this._lastPointerMoveQuaternion.angleTo(this.gripWorldQuaternion)>this.pointerMoveAngleThreshold&&(e=!0),e){this._didMoveLastFrame=!0,this._lastPointerMovePosition.copy(this.gripWorldPosition),this._lastPointerMoveQuaternion.copy(this.gripWorldQuaternion),wo&&F.DrawLabel(this.rayWorldPosition.add(this.object.worldForward.multiplyScalar(.1)),"move",.01);let t=this.xr.context.input.getFirstPressedButtonForPointer(this.index);t===void 0&&(t=0);const i=this.gamepad?.buttons[t]?.value;this.emitPointerEvent("pointermove",t,"none",!1,null,i)}else this._didMoveLastFrame=!1}pointerInit;emitPointerEvent(e,t,i,n,s=null,r){if(!this.emitEvents){wo&&e!==Ee.PointerMove&&console.warn("Pointer events are disabled for this controller",this.index,e,t);return}if(this.xr.mode==="immersive-vr"||this.xr.isPassThrough){this.pointerInit.origin=this,this.pointerInit.pointerId=this.getPointerId(t),this.pointerInit.pointerType=this.hand?"hand":"controller",this.pointerInit.button=t,this.pointerInit.buttonName=i,this.pointerInit.isPrimary=n,this.pointerInit.mode=this.inputSource.targetRayMode,this.pointerInit.ray=this.ray,this.pointerInit.device=this.object,this.pointerInit.pressure=r,this.pointerInit.clientX=this._rayPosition.x/this.xr.rigScale,this.pointerInit.clientY=this._rayPosition.y/this.xr.rigScale,this.pointerInit.clientZ=this._rayPosition.z/this.xr.rigScale;const a=z.Current;z.Current=this.xr.context,wo&&e!=="pointermove"&&console.warn("Pointer event",e,t,i,{...this.pointerInit}),this.xr.context.input.createInputEvent(new vo(e,s,this.pointerInit)),z.Current=a}}}class r_{isDown=!1;isUp=!1;pressed=!1;value=0}class a_{index;name;touched=!1;pressed=!1;value=0;isDown=!1;isUp=!1;constructor(e,t){this.index=e,this.name=t}}var Ym=(o=>(o.Visible="application-visible",o.Hidden="application-hidden",o.MuteChanged="application-mutechanged",o))(Ym||{});let Ed=!1;const Oa=[];function dr(){if(Ed)return;E()&&console.debug("User interaction registered: audio can now be played"),Ed=!0;const o=[...Oa];Oa.length=0,o.forEach(e=>e())}document.addEventListener("mousedown",dr),document.addEventListener("pointerup",dr),document.addEventListener("click",dr),document.addEventListener("dragstart",dr),document.addEventListener("touchend",dr),document.addEventListener("keydown",dr);class Tn extends EventTarget{static get userInteractionRegistered(){return Ed}static registerWaitForAllowAudio=Tn.registerWaitForInteraction;static registerWaitForInteraction(e){if(e!==null){if(Ed){e();return}Oa.indexOf(e)===-1&&Oa.push(e)}}static unregisterWaitForInteraction(e){const t=Oa.indexOf(e);t!==-1&&Oa.splice(t,1)}_mute=!1;get muted(){return this._mute}set muted(e){e!==this._mute&&(this._mute=e,this.dispatchEvent(new Event("application-mutechanged")))}context;get hasFocus(){return document.hasFocus()}get isVisible(){return this._isVisible}_isVisible=!0;constructor(e){super(),this.context=e,window.addEventListener("visibilitychange",this.onVisiblityChanged.bind(this),!1)}onVisiblityChanged(e){switch(e.target.visibilityState){case"hidden":this._isVisible=!1,this.dispatchEvent(new Event("application-hidden"));break;case"visible":this._isVisible=!0,this.dispatchEvent(new Event("application-visible"));break}}}const ka=new Map,Ma=new Map;let l_=0;function xo(o,e,t){if(ka.has(e)||ka.set(e,new Array),ka.get(e).push({method:o,options:{once:!1,...t}}),l_<30){const i=Ma.get(e);i&&i?.length>100&&(l_+=1,console.warn(`You have ${i.length} methods registered for Event ${e}.
153
153
 
154
154
  This might be a performance issue!
155
155
  Consider unregistering the methods when they are not needed anymore!
@@ -161,8 +161,8 @@ or by using the once option like onStart(()=>{}, { once:true }).
161
161
  See https://engine.needle.tools/docs/scripting.html#special-lifecycle-hooks for more information.`))}}function ds(o,e){const t=Ma.get(e);if(t){for(let n=0;n<t.length;n++)if(t[n].method===o){t.splice(n,1);return}}const i=ka.get(e);if(i){for(let n=0;n<i.length;n++)if(i[n].method===o){i.splice(n,1);return}}}function Fn(o,e){e===he.ContextCreated&&Km.delete(o),c_(o,e)}function c_(o,e){e===we.Start&&ka.get(he.ContextCreated)&&c_(o,he.ContextCreated);const t=e===we.Start||e===he.ContextCreated,i=Ma.get(e);i&&i.length>0&&d_(o,i,t);const n=ka.get(e);if(n&&n.length>0){const s=[...n];n.length=0,d_(o,s,t),s.length>0&&(Ma.has(e)||Ma.set(e,new Array),Ma.get(e).push(...s))}}const Ad=new Array,h_={context:null};function d_(o,e,t){Ad.length=0;for(let n=0;n<e.length;n++)Ad.push(e[n]);let i=Km.get(o);for(let n=0;n<Ad.length;n++){const s=Ad[n];let r=!0;if(i&&i.has(s)&&(r=!1),r)try{h_.context=o,s.method?.call(h_,o)}catch(a){console.error("Error in lifecycle method",a)}if(s.options?.once){for(let a=0;a<e.length;a++)if(e[a]===s){e.splice(a,1);break}}else t&&(i||(i=new Set,Km.set(o,i)),i.add(s))}}const Km=new WeakMap,Zm={};function Jm(o,e){Zm[o]=e}function u_(o){const e=o.getBufferIdentifier(),t=Zm[e];return t(o)}function p_(o){return typeof o.guid=="function"?o.guid():null}let eg;function MO(){return eg}function RO(o){eg=o}function m_(o,e){return e||(e={}),e={...eg,...e},o?new eb(o,e):new eb(e)}async function g_(){const o=await import("./vendor-XJ9xiwrv.min.js").then(e=>e.bundler);return console.log(o),o.default===void 0?o:o.default}class f_{get isHost(){return this._host!==void 0}_host;_client;_clientData;constructor(){this.onEnable()}onEnable(){this.trySetupHost("HOST-5980e65c-8438-453e-8b35-f13c736dcd81")}async trySetupHost(e){const t=await g_(),i=new t(e);i.on("error",n=>{console.error(n),this._host=void 0,this.trySetupClient(e)}),i.on("open",n=>{this._host=new EO(i)})}async trySetupClient(e){const t=await g_();this._client=new t,this._client.on("error",i=>{console.error("Client error",i)}),this._client.on("open",i=>{console.log("client connected",i),this._clientData=this._client.connect(e,{metadata:{id:i}}),this._clientData.on("open",()=>{console.log("Connected to host")}),this._clientData.on("data",n=>{console.log("<<",n)})})}}class TO{_peer;constructor(e){this._peer=e}}class EO extends TO{get isHost(){return!0}_connections=[];constructor(e){super(e),console.log("I AM THE HOST"),this._peer?.on("connection",this.onConnection.bind(this)),this._peer.on("close",()=>{this.broadcast("BYE")}),setInterval(()=>{this.broadcast("HELLO")},2e3)}onConnection(e){console.log("host connection",e),e.on("open",()=>{this._connections.push(e),this.broadcastConnection(e)})}broadcastConnection(e){const t=this._connections.map(i=>i.metadata?.id).filter(i=>i!==void 0);this.broadcast({type:"connection-list",connections:t})}broadcast(e){if(e!=null){console.log(">>",e);for(const t in this._peer.connections){const i=this._peer.connections[t];if(i)if(Array.isArray(i))for(const n of i)n&&n.send(e);else console.warn(i)}}}}var fn=(o=>(o[o.OnConnection=0]="OnConnection",o[o.OnRoomJoin=1]="OnRoomJoin",o[o.Queued=2]="Queued",o[o.Immediate=3]="Immediate",o))(fn||{});const y_="https://urls.needle.tools/default-networking-backend/index";let Hi="wss://networking.needle.tools/socket";const ni=!!w("debugnet"),Zl=!!(ni||w("debugowner")),Id=w("debugnetbin");var b_=(o=>(o.ConnectionInfo="connection-start-info",o))(b_||{}),te=(o=>(o.Join="join-room",o.Leave="leave-room",o.JoinedRoom="joined-room",o.LeftRoom="left-room",o.UserJoinedRoom="user-joined-room",o.UserLeftRoom="user-left-room",o.RoomStateSent="room-state-sent",o))(te||{});class AO{room;viewId;allowEditing;inRoom}class IO{room}class LO{userId}var __=(o=>(o.RequestHasOwner="request-has-owner",o.ResponseHasOwner="response-has-owner",o.RequestIsOwner="request-is-owner",o.ResponseIsOwner="response-is-owner",o.RequestOwnership="request-ownership",o.GainedOwnership="gained-ownership",o.RemoveOwnership="remove-ownership",o.LostOwnership="lost-ownership",o.GainedOwnershipBroadcast="gained-ownership-broadcast",o.LostOwnershipBroadcast="lost-ownership-broadcast",o))(__||{});class tg{guid;connection;get hasOwnership(){return this._hasOwnership}get isOwned(){return this._isOwned}get isConnected(){return this.connection.isConnected}_hasOwnership=!1;_isOwned=void 0;_gainSubscription;_lostSubscription;_hasOwnerResponse;constructor(e,t){this.connection=e,this.guid=t,this._gainSubscription=this.onGainedOwnership.bind(this),this._lostSubscription=this.onLostOwnership.bind(this),e.beginListen("lost-ownership",this._lostSubscription),e.beginListen("gained-ownership-broadcast",this._gainSubscription),this._hasOwnerResponse=this.onHasOwnerResponse.bind(this),e.beginListen("response-has-owner",this._hasOwnerResponse)}_isWaitingForOwnershipResponseCallback=null;updateIsOwned(){this.connection.send("request-has-owner",{guid:this.guid})}onHasOwnerResponse(e){e.guid===this.guid&&(this._isOwned=e.value)}requestOwnershipIfNotOwned(){return this._isWaitingForOwnershipResponseCallback!==null?this:(this._isWaitingForOwnershipResponseCallback=this.waitForHasOwnershipRequestResponse.bind(this),this.connection.beginListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this.connection.send("request-has-owner",{guid:this.guid}),this)}waitForHasOwnershipRequestResponse(e){e.guid===this.guid&&(this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this._isOwned=e.value,e.value||(Zl&&console.log("request ownership",this.guid),this.requestOwnership()))}requestOwnershipAsync(){return new Promise((e,t)=>{this.requestOwnership();let i=0;const n=()=>{if(i++>10)return t("Timeout");setTimeout(()=>{this.hasOwnership?e(this):n()},100)};n()})}requestOwnership(){return Zl&&console.log("Request ownership",this.guid),this.connection.send("request-ownership",{guid:this.guid}),this}freeOwnership(){return this.connection.send("remove-ownership",{guid:this.guid}),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this}destroy(){this.connection.stopListen("gained-ownership",this._gainSubscription),this.connection.stopListen("lost-ownership",this._lostSubscription),this.connection.stopListen("response-has-owner",this._hasOwnerResponse),this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null)}onGainedOwnership(e){e.guid===this.guid&&(this._isOwned=!0,this.connection.connectionId===e.owner?(Zl&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(Zl&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}}class v_{context;_peer=null;constructor(e){this.context=e}get peer(){return this._peer||(this._peer=new f_),this._peer}tryGetState(e){return e==="invalid"?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return ni}get isConnected(){return this.connected}get currentRoomName(){return this._currentRoomName}get allowEditing(){return this._currentRoomAllowEditing}get currentRoomViewId(){return this._currentRoomViewId}getViewOnlyUrl(){if(this.currentRoomViewId===null)return null;const e=new URL(window.location.href);return e.searchParams.set("view",this.currentRoomViewId),e.href}get isInRoom(){return this._isInRoom}get currentLatency(){return this._currentDelay}get currentServerUrl(){return this._ws?.url??null}sendPing(){this.send("ping",{time:this.context.time.time})}userIsInRoom(e){return this._currentInRoom.indexOf(e)!==-1}_usersInRoomCopy=[];usersInRoom(e=null){e||(e=this._usersInRoomCopy),e.length=0;for(const t of this._currentInRoom)e.push(t);return e}joinRoom(e,t=!1){return e?e.length>1024?(console.error('Room name too long, can not join: "'+e+'". Max length is 1024 characters.'),!1):(this.isInRoom&&this.currentRoomName!==e&&console.warn("Needle Engine is already connected to a networking room. Connecting to multiple rooms is not supported"),this.connect(),ni&&console.log("join: "+e),this.send("join-room",{room:e,viewOnly:t},fn.OnConnection),!0):(console.error('Missing room name, can not join: "'+e+'"'),!1)}leaveRoom(e=null){return e||(e=this.currentRoomName),e?(this.send("leave-room",{room:e}),!0):(console.error('Missing room name, can not join: "'+e+'"'),!1)}send(e,t=null,i=fn.Queued){if(t===null&&(t={}),i===fn.Queued){this._defaultMessagesBuffer.push({key:e,value:t});return}return this.sendWithWebsocket(e,t,i)}sendDeleteRemoteState(e){this.send("delete-state",{guid:e,dontSave:!0}),delete this._state[e]}sendDeleteRemoteStateAll(){this.send("delete-all-state"),this._state={}}sendBinary(e){Id&&console.log("<< send binary",this.context.time.frame,e.length/1024+" KB"),this._ws?.send(e)}_defaultMessagesBuffer=[];_defaultMessagesBufferArray=[];sendBufferedMessagesNow(){if(!this._ws)return;this._defaultMessagesBufferArray.length=0;const e=Object.keys(this._defaultMessagesBuffer).length;for(const i in this._defaultMessagesBuffer){const n=this._defaultMessagesBuffer[i];if(e<=1){this.sendWithWebsocket(n.key,n.value,fn.Immediate);break}const s=this.toMessage(n.key,n.value);this._defaultMessagesBufferArray.push(s)}if(this._defaultMessagesBuffer.length=0,this._defaultMessagesBufferArray.length>0&&ni&&console.log("SEND BUFFERED",this._defaultMessagesBufferArray.length),this._defaultMessagesBufferArray.length<=0)return;const t=JSON.stringify(this._defaultMessagesBufferArray);this._ws?.send(t)}beginListen(e,t){return this._listeners[e]||(this._listeners[e]=[]),this._listeners[e].push(t),t}stopListening(e,t){return this.stopListen(e,t)}stopListen(e,t){if(!t||!this._listeners[e])return;const i=this._listeners[e].indexOf(t);i>=0&&this._listeners[e].splice(i,1)}beginListenBinary(e,t){return this._listenersBinary[e]||(this._listenersBinary[e]=[]),this._listenersBinary[e].push(t),t}stopListenBinary(e,t){if(!this._listenersBinary[e])return;const i=this._listenersBinary[e].indexOf(t);i>=0&&this._listenersBinary[e].splice(i,1)}netWebSocketUrlProvider;registerProvider(e){this.netWebSocketUrlProvider=e}async connect(e){if(this.connected&&e&&e!==Hi)return Promise.reject("Can not connect to different server url. Please disconnect first.");if(this.connected)return Promise.resolve(!0);e&&console.debug("Connecting to user provided url "+e);const t=e||this.netWebSocketUrlProvider?.getWebsocketUrl();return t?Hi=t:cb()&&(Hi="wss://"+window.location.host+"/socket"),this.connectWebsocket()}disconnect(){this._ws?.close(),this._ws=void 0,Hi=void 0,this._currentRoomAllowEditing=!0,this._currentRoomName=null,this._currentRoomViewId=null,this._isInRoom=!1,this._currentInRoom.length=0,this._state={},this._currentDelay=-1}_listeners={};_listenersBinary={};connected=!1;channelId;_connectionId=null;_ws;_waitingForSocket={};_isInRoom=!1;_currentRoomName=null;_currentRoomViewId=null;_currentRoomAllowEditing=!0;_currentInRoom=[];_state={};_currentDelay=-1;_connectingToWebsocketPromise=null;connectWebsocket(){return this._connectingToWebsocketPromise?this._connectingToWebsocketPromise:this._connectingToWebsocketPromise=new Promise(async(e,t)=>{let i=!1;const n=c=>{i||(i=!0,e(c))};if(Hi===void 0&&(console.log("Fetch default backend url: "+y_),Hi=await(await fetch(y_)).text()),Hi===void 0){n(!1);return}console.debug(`\u22A1 Connecting to networking backend on
162
162
  `+Hi);const s=await import("./vendor-XJ9xiwrv.min.js").then(c=>c.index),r=s.default?.WebsocketBuilder??s.WebsocketBuilder,a=s.default?.ExponentialBackoff??s.ExponentialBackoff,l=new r(Hi).withMaxRetries(10).withBackoff(new a(2e3,4)).onOpen(()=>{this._connectingToWebsocketPromise=null,this._ws=l,this.connected=!0,E()||ni?console.log(`\u229E Connected to networking backend
163
163
  `+Hi):console.debug("\u229E Connected to networking backend",Hi),n(!0),this.onSendQueued(fn.OnConnection)}).onClose(c=>{this._connectingToWebsocketPromise=null,this.connected=!1,this._isInRoom=!1,n(!1);let h="Websocket connection closed...";Hi?.includes("/socket")||(h+=' Do you perhaps mean to connect to "/socket"?'),console.error(h)}).onError(c=>{console.error("\u22A0 Websocket connection failed..."),n(!1)}).onRetry(()=>{console.log("\u2192 Retry connecting to networking websocket")}).build();l.addEventListener(s.WebsocketEvent.message,(c,h)=>{this.onMessage(c,h)})})}onMessage(e,t){const i=t.data;try{if(typeof i!="string"){i.size&&this.handleIncomingBinaryMessage(i);return}const n=JSON.parse(i);if(Array.isArray(n))for(const s of n)this.handleIncomingStringMessage(s);else this.handleIncomingStringMessage(n);return}catch(n){ni&&i==="pong"?console.log("<<",i):E()&&console.error("Failed to parse message",n)}}async handleIncomingBinaryMessage(e){Id&&console.log("<< bin",this.context.time.frame);const t=await e.arrayBuffer();var i=new Uint8Array(t);const n=new BC(i),s=n.getBufferIdentifier(),r=this._listenersBinary[s],a=u_(n),l=p_(a);if(l&&typeof l=="string"&&(this._state[l]=a),!r)return;const c=a??n;for(const h of r)h(c)}handleIncomingStringMessage(e){if(ni&&console.log("<<",e.key??e),e.key)switch(e.key){case"connection-start-info":if(e.data){const r=e.data;r&&(console.assert(r.id!==void 0&&r.id!==null&&r.id.length>0,"server did not send connection id",r.id),console.debug("Your id is: "+r.id,this.context.alias??""),this._connectionId=r.id)}else console.warn("Expected connection id in "+e.key);break;case"joined-room":if(ni&&console.log(e),e){this._isInRoom=!0;const r=e;this._currentRoomName=r.room,this._currentRoomViewId=r.viewId,this._currentRoomAllowEditing=r.allowEditing??!0,this._currentInRoom.length=0,this._currentInRoom.push(...r.inRoom),(Id||E())&&console.debug("Joined Needle Engine Room: "+r.room);const a=new URL(window.location.href);a.searchParams.has("room")&&a.searchParams.delete("room"),a.searchParams.set("view",this._currentRoomViewId),console.debug(`Room view id: ${this._currentRoomViewId}
164
- ${a.href}`)}this.onSendQueued(fn.OnRoomJoin);break;case"left-room":const n=e;n.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentRoomAllowEditing=!0,this._currentInRoom.length=0,(Id||E())&&console.debug("Left Needle Engine Room: "+n.room));break;case"user-joined-room":if(e.data){const r=e.data;this._currentInRoom.push(r.userId),ni&&console.log(r.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(e.data){const r=e.data,a=this._currentInRoom.indexOf(r.userId);a>=0&&(ni&&console.log(r.userId+" left","now in room:",this._currentInRoom),this._currentInRoom.splice(a,1)),r.userId===this.connectionId&&console.log("you left the room")}break;case"all-room-state-deleted":ni&&console.log("RECEIVED all-room-state-deleted"),this._state={};break;case"ping":case"pong":const s=e.data?.time;s&&(this._currentDelay=this.context.time.time-s),ni&&console.log(`Current latency: ${(this._currentDelay*1e3).toFixed()} ms`,"Clients in room: "+this._currentInRoom?.length);break}const t=e.data;t&&(this._state[t.guid]=t);let i=this._listeners[e.key];if(i){i=[...i];for(const n of i)try{n(e.data)}catch(s){console.error('Error invoking callback for "'+e.key+'"',s)}}}toMessage(e,t){return{key:e,data:t}}sendWithWebsocket(e,t,i=fn.OnRoomJoin){if(!this._ws){const s=this._waitingForSocket[i]||[];s.push(()=>this.sendWithWebsocket(e,t,i)),this._waitingForSocket[i]=s;return}const n=JSON.stringify(this.toMessage(e,t));ni&&console.log(">>",e),this._ws.send(n)}onSendQueued(e){const t=this._waitingForSocket[e];if(t){for(const i of t)i();t.length=0}}}const Jl=w("debugwebxr");class ig{controllerStates=[];userId;context;userStateEvtName;constructor(e,t){this.userId=e,this.context=t,this.userStateEvtName="xr-sync-user-state-"+e,this.context.connection.beginListen(this.userStateEvtName,this.onReceivedControllerState)}dispose(){this.context.connection.stopListen(this.userStateEvtName,this.onReceivedControllerState)}onReceivedControllerState=e=>{Jl&&console.log(`XRSync: Received change for ${this.userId}: ${e.type} ${e.handedness}; tracked=${e.isTracking}`);let t=!1;for(let i=0;i<this.controllerStates.length;i++)if(this.controllerStates[i].index===e.index){this.controllerStates[i]=e,t=!0;break}t||this.controllerStates.push(e)};update(e){if(this.context.connection.isConnected!=!1){for(let t=this.controllerStates.length-1;t>=0;t--){const i=this.controllerStates[t];let n=!1;for(let s=0;s<e.controllers.length;s++)e.controllers[s].index===i.index&&(n=!0);n||(Jl&&console.log(`XRSync: ${i.type} ${i.handedness} removed`,i.index),this.controllerStates.splice(t,1),this.sendControllerRemoved(i))}for(const t of e.controllers)this.updateControllerStates(t)}}onExitXR(e){for(const t of this.controllerStates)this.sendControllerRemoved(t);this.controllerStates.length=0}sendControllerRemoved(e){e.isTracking=!1,e.guid="",this.context.connection.send(this.userStateEvtName,e),this.context.connection.sendDeleteRemoteState(e.guid)}updateControllerStates(e){const t=this.controllerStates.find(i=>i.index===e.index);if(t){let i=!1;i||=t.isTracking!=e.isTracking,i&&(t.isTracking=e.isTracking,this.context.connection.send(this.userStateEvtName,t))}else{const i={guid:this.userId+"-"+e.index,isTracking:e.isTracking,handedness:e.side,index:e.index,type:e.hand?"hand":"controller"};this.controllerStates.push(i),this.context.connection.send(this.userStateEvtName,i),Jl&&console.log(`XRSync: ${i.type} ${i.handedness} added`,i.index)}}}class w_{hasState(e){return e?this._states.has(e):!1}isTracking(e,t){if(!e)return;const i=this._states.get(e);return i?i.controllerStates.find(n=>n.handedness===t)?.isTracking||!1:void 0}getDeviceType(e,t){if(!e)return;const i=this._states.get(e);return i?i.controllerStates.find(n=>n.handedness===t)?.type||"unknown":void 0}context;constructor(e){this.context=e,this.context.connection.beginListen(te.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(te.LeftRoom,this.onLeftRoom),this.context.connection.beginListen(te.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.beginListen(te.UserLeftRoom,this.onOtherUserLeftRoom)}destroy(){this.context.connection.stopListen(te.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(te.LeftRoom,this.onLeftRoom),this.context.connection.stopListen(te.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.stopListen(te.UserLeftRoom,this.onOtherUserLeftRoom)}onJoinedRoom=()=>{if(this.context.connection.connectionId){this._states.has(this.context.connection.connectionId)||(Jl&&console.log("XRSync: Local user joined room",this.context.connection.connectionId),this._states.set(this.context.connection.connectionId,new ig(this.context.connection.connectionId,this.context)));for(const e of this.context.connection.usersInRoom())this._states.has(e)||this._states.set(e,new ig(e,this.context))}};onLeftRoom=()=>{this.context.connection.connectionId&&(this._states.has(this.context.connection.connectionId)||(this._states.get(this.context.connection.connectionId)?.dispose(),this._states.delete(this.context.connection.connectionId)))};onOtherUserJoinedRoom=e=>{const t=e.userId;this._states.has(t)||(Jl&&console.log("XRSync: Remote user joined room",t),this._states.set(t,new ig(t,this.context)))};onOtherUserLeftRoom=e=>{const t=e.userId;this._states.has(t)||(this._states.get(t)?.dispose(),this._states.delete(t))};_states=new Map;onUpdate(e){this.context.connection.isConnected&&this.context.connection.connectionId&&this._states.get(this.context.connection.connectionId)?.update(e)}onExitXR(e){this.context.connection.isConnected&&this.context.connection.connectionId&&this._states.get(this.context.connection.connectionId)?.onExitXR(e)}}class x_{_fadeToColorQuad;_fadeToColorMaterial;constructor(){this._fadeToColorMaterial=new xe({color:0,transparent:!0,depthTest:!1,fog:!1,side:vi}),this._fadeToColorQuad=new H(new In(10,10),this._fadeToColorMaterial)}dispose(){this._fadeToColorQuad.geometry.dispose(),this._fadeToColorMaterial.dispose()}update(e,t){const i=this._fadeToColorQuad,n=this._fadeToColorMaterial;i.parent!==e&&n.opacity>0?e.add(i):n.opacity===0&&i.removeFromParent(),i.layers.set(2),i.material=this._fadeToColorMaterial,i.position.z=-1,i.renderOrder=1/0;const s=this._requestedFadeValue;n.opacity=D.lerp(n.opacity,s,t/.03),Math.abs(n.opacity-s)<=.01&&this._transitionResolve&&(this._transitionResolve(),this._transitionResolve=null,this._transitionPromise=null,this._requestedFadeValue=0)}remove(){this._fadeToColorQuad.removeFromParent()}fadeTransition(){if(this._transitionPromise)return this._transitionPromise;this._requestedFadeValue=1;const e=new Promise(t=>{this._transitionResolve=t});return this._transitionPromise=e,e}_requestedFadeValue=0;_transitionPromise=null;_transitionResolve=null}var ur=(o=>(o[o.Quad=0]="Quad",o[o.Cube=1]="Cube",o[o.Sphere=2]="Sphere",o[o.Cylinder=3]="Cylinder",o[o.RoundedCube=10]="RoundedCube",o))(ur||{});class pr{static createText(e,t){let i=null;const n=t?.font||DO(t?.familyFamily||null);n instanceof fC?i=this.#t(e,n,t):i==null&&(i=new un);const s=t?.color||16777215,r=new H(i,t?.material??new ut({color:s}));return this.applyDefaultObjectOptions(r,t),n instanceof Promise?n.then(a=>{r.geometry=this.#t(e,a,t),t?.onGeometry&&t.onGeometry(r)}):t?.onGeometry&&t.onGeometry(r),r}static#t(e,t,i){const n=i?.depth||.1;return new yC(e,{font:t,size:1,depth:n,height:n,bevelEnabled:i?.bevel||!1,bevelThickness:.01,bevelOffset:.01,bevelSize:.01})}static createOccluder(e){const t=new xe({colorWrite:!1,depthWrite:!0,side:vi});return this.createPrimitive(e,{material:t})}static createPrimitive(e,t){let i;const n=t?.color||16777215;switch(e){case"Quad":case 0:{const s=new In(1,1,1,1),r=t?.material??new ut({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new H(s,r),i.name="Quad"}break;case"Cube":case 1:{const s=new ma(1,1,1),r=t?.material??new ut({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new H(s,r),i.name="Cube"}break;case 10:case"RoundedCube":{const s=jO(1,1,1,.1,2),r=t?.material??new ut({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new H(s,r),i.name="RoundedCube"}break;case"Sphere":case 2:{const s=new od(.5,16,16),r=t?.material??new ut({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new H(s,r),i.name="Sphere"}break;case"Cylinder":case 3:{const s=new L0(.5,.5,1,32),r=t?.material??new ut({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new H(s,r),i.name="Cylinder"}break;case"ShaderBall":i=new os,i.name="ShaderBall",BO(i,t);break}return this.applyDefaultObjectOptions(i,t),i}static createSprite(e){const t=new Z1({color:16777215});e?.texture&&"map"in t&&(t.map=e.texture);const i=new J1(t);return this.applyDefaultObjectOptions(i,e),i}static applyDefaultObjectOptions(e,t){e.receiveShadow=!0,e.castShadow=!0,t?.name&&(e.name=t.name),t?.position&&(Array.isArray(t.position)?e.position.set(t.position[0],t.position[1],t.position[2]):e.position.set(t.position.x||0,t.position.y||0,t.position.z||0)),t?.rotation&&(Array.isArray(t.rotation)?e.rotation.set(t.rotation[0],t.rotation[1],t.rotation[2]):e.rotation.set(t.rotation.x||0,t.rotation.y||0,t.rotation.z||0)),t?.scale&&(typeof t.scale=="number"?e.scale.set(t.scale,t.scale,t.scale):Array.isArray(t.scale)?e.scale.set(t.scale[0],t.scale[1],t.scale[2]):e.scale.set(t.scale.x||1,t.scale.y||1,t.scale.z||1)),t?.receiveShadow!=null&&(e.receiveShadow=t.receiveShadow),t?.castShadow!=null&&(e.castShadow=t.castShadow),t?.parent&&t.parent.add(e)}}function jO(o,e,t,i,n){const s=new eS,r=1e-5,a=i-r;s.absarc(r,r,r,-Math.PI/2,-Math.PI,!0),s.absarc(r,e-a*2,r,Math.PI,Math.PI/2,!0),s.absarc(o-a*2,e-a*2,r,Math.PI/2,0,!0),s.absarc(o-a*2,r,r,0,-Math.PI/2,!0);const l=new tS(s,{bevelEnabled:!0,bevelSegments:n*2,steps:1,bevelSize:a,bevelThickness:i,curveSegments:n,UVGenerator:{generateTopUV:(c,h)=>{const d=[];for(let p=0;p<h.length;p+=3)d.push(new J(h[p]/o,h[p+1]/e));return d},generateSideWallUV:(c,h,d,p,g,f)=>{const m=[];return m.push(new J(h[d]/o,h[d+1]/e)),m.push(new J(h[p]/o,h[p+1]/e)),m.push(new J(h[g]/o,h[g+1]/e)),m.push(new J(h[f]/o,h[f+1]/e)),m}}});return l.scale(1,1,1-i),l.center(),l.index||l.setIndex(Array.from({length:l.attributes.position.count},(c,h)=>h)),l.computeVertexNormals(),l}const Ld=new Map;function DO(o){let e="";switch(o){default:case"OpenSans":e="https://cdn.needle.tools/static/fonts/facetype/Open Sans_Regular_ascii.json";break;case"Helvetiker":e="https://raw.githubusercontent.com/mrdoob/three.js/master/examples/fonts/helvetiker_regular.typeface.json";break}if(Ld.has(e)){const n=Ld.get(e);if(n)return n}const t=new bC,i=new Promise((n,s)=>{t.load(e,r=>{Ld.set(e,r),n(r)},void 0,s)});return Ld.set(e,i),i}let ng=!1,og=null;function BO(o,e){if(og===null){const t="https://cdn.needle.tools/static/models/shaderball.glb",i=new fo,n=pm(null);i.setDRACOLoader(n.dracoLoader),i.setKTX2Loader(n.ktx2Loader),ng=!0,og=i.loadAsync(t).then(s=>{const r=s.scene;return r.position.y-=.5,r}).catch(s=>(console.warn("Failed to load shaderball mesh: "+s.message),C_())).finally(()=>{ng=!1})}if(ng){const t=C_();t.name="ShaderBall-Placeholder";const i=t.children[0];i?.type==="Mesh"&&S_(i,e),o.add(t)}og.then(t=>{o.children.forEach(s=>{s.name==="ShaderBall-Placeholder"&&o.remove(s)});const i=t.clone(),n=i.children[0];n?.type==="Mesh"&&(n.geometry.attributes.tangent||n.geometry.computeTangents(),S_(n,e)),o.add(i)})}function S_(o,e){if(e?.color||e?.material||e?.texture){const t=e?.material??o.material?.clone()??new ut;e.color&&"color"in t&&t.color instanceof ne&&t.color.set(e.color),e?.texture&&"map"in t&&(t.map=e.texture),o.material=t}}function C_(){return new os().add(pr.createPrimitive("Sphere",{material:new xe({transparent:!0,opacity:.1})}))}class Tl{static _active=null;static get active(){return this._active}static _requestInFlight=!1;static async start(e,t){if(this._active)return console.error("Cannot start a new XR session while one is already active"),null;if(this._requestInFlight)return console.error("Cannot start a new XR session while a request is already in flight"),null;if("xr"in navigator&&navigator.xr){if(!t)return console.error("XRSessionInit must be provided"),null;this._requestInFlight=!0;const i=await navigator.xr.requestSession(e,t);return i.addEventListener("end",()=>{this._active=null}),this._requestInFlight?(this._requestInFlight=!1,this._active=new Tl(e,t,i),this._active):(i.end(),null)}return null}static async handoff(){return this._active?this._active.handoff():null}static async stop(){this._requestInFlight=!1,this._active&&(await this._active.end(),await Dn(100)),this._active=null}_session;_mode;_init;get isAR(){return this._mode==="immersive-ar"}_renderer;_camera;_scene;constructor(e,t,i){this._mode=e,this._init=t,this._session=i,this._session.addEventListener("end",this.onEnd),this._renderer=new er({alpha:!0}),this._renderer.setAnimationLoop(this.onFrame),this._renderer.xr.setSession(i),this._renderer.xr.enabled=!0,this._camera=new de,this._scene=new yi,this._scene.fog=new j0(4473924,10,250),this._scene.add(this._camera),this.setupScene()}end(){return this._session?this._session.end():Promise.resolve()}async handoff(){if(!this._session)throw new Error("Cannot handoff a session that has already ended");const e={session:this._session,mode:this._mode,init:this._init};return await this.onBeforeHandoff(),this.onEnd(),this._session=null,e}onEnd=()=>{this._session?.removeEventListener("end",this.onEnd),this._renderer.setAnimationLoop(null),this._renderer.dispose(),this._scene.clear()};_lastTime=0;onFrame=(e,t)=>{const i=e-this._lastTime;this.update(e,i),this._camera.parent!==this._scene&&this._scene.add(this._camera),this._renderer.render(this._scene,this._camera)};async onBeforeHandoff(){await Dn(1e3),this._scene.clear()}_objects=[];setupScene(){this._scene.background=new ne(0),this._scene.add(new Jp(5,10,1118481,1118481));const e=new em(16777215,1);e.position.set(0,20,0),e.castShadow=!1,this._scene.add(e);const t=new em(16777215,1);t.position.set(0,-1,0),t.castShadow=!1,this._scene.add(t);const i=new tm(16777215,1,100,1);i.position.set(0,2,0),i.castShadow=!1,i.distance=200,this._scene.add(i);const n=50;for(let s=0;s<100;s++){const r=new ut({color:2236962,metalness:1,roughness:.8});this.isAR&&(r.emissive=new ne(Math.random(),Math.random(),Math.random()),r.emissiveIntensity=Math.random());const a=D.random(0,1)>.5?ur.Sphere:ur.Cube,l=pr.createPrimitive(a,{material:r});l.position.x=D.random(-n,n),l.position.y=D.random(-2,n),l.position.z=D.random(-n,n),l.rotation.x=D.random(0,Math.PI*2),l.rotation.y=D.random(0,Math.PI*2),l.rotation.z=D.random(0,Math.PI*2),l.scale.multiplyScalar(.5+Math.random()*10);const c=l.position.distanceTo(this._camera.position)-l.scale.x;c<1&&l.position.multiplyScalar(1+1/c),this._objects.push(l),this._scene.add(l)}}update(e,t){const i=e*4e-4;for(let n=0;n<this._objects.length;n++){const s=this._objects[n];s.position.y+=Math.sin(i+n*.5)*.005,s.rotateY(.002)}}}var ec;(o=>{const e=[];function t(){if(!e?.length)return!1;for(const s of e)s.exportAndOpen();return!0}o.exportAndOpen=t;function i(s){e.push(s)}o.registerExporter=i;function n(s){if(!e)return;const r=e.indexOf(s);r>=0&&e.splice(r,1)}o.unregisterExporter=n})(ec||(ec={}));const He=w("debugwebxr"),P_=w("stats");let sg=0;function FO(o){let e=null;const t=o;return t.getAROverlayContainer?e=t.getAROverlayContainer():e=o,e}UO();async function UO(){if(w("debugasap")){let o=globalThis["needle:XRSession"];if(o instanceof Promise){delete globalThis["needle:XRSession"],ue.addContextCreatedCallback(async e=>{if(!o)return;ar(!0);const t=await o;if(t){const i=K.getDefaultSessionInit("immersive-vr");K.setSession("immersive-vr",t,i,e.context)}else console.error("NeedleXRSession: ASAP session was rejected");o=void 0});return}}if("xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent)){console.warn("WebXRViewer does not support addEventListener");return}navigator.xr?.addEventListener("sessiongranted",async()=>{ar(!0),console.log("Received Session Granted..."),await Dn(100);const o=sessionStorage.getItem("needle_xr_session_mode"),e=sessionStorage.getItem("needle_xr_session_init")??null,t=e?JSON.parse(e):null;let i=null;if(O_()&&(await Tl.start(o||"immersive-vr",t||K.getDefaultSessionInit("immersive-vr")),await WO(),i=await Tl.handoff()),i)K.setSession(i.mode,i.session,i.init,z.Current);else if(o&&e){console.log("Session Granted: Restore last session");const n=JSON.parse(e);K.start(o,n).catch(s=>console.warn(s))}else K.start("immersive-vr").catch(n=>console.warn("Session Granted failed:",n))},{once:!0})}}function zO(o,e){sessionStorage.setItem("needle_xr_session_mode",o),sessionStorage.setItem("needle_xr_session_init",JSON.stringify(e))}function NO(){sessionStorage.removeItem("needle_xr_session_mode"),sessionStorage.removeItem("needle_xr_session_init")}const rg=new Set;ue.registerCallback(he.ContextCreationStart,async o=>{rg.add(o.context)}),ue.registerCallback(he.ContextCreated,async o=>{rg.delete(o.context);const e=o.context?.domElement.getAttribute("autostart")||null;VO(e)});function O_(){return rg.size>0}function WO(){return new Promise(o=>{const e=Date.now(),t=setInterval(()=>{(!O_()||Date.now()-e>6e4)&&(clearInterval(t),o())},100)})}G.isDesktop()&&E()&&window.addEventListener("keydown",o=>{(o.key==="x"||o.key==="Escape")&&K.active&&K.stop()});function VO(o){if(o)switch(o?.toLowerCase()){case"ar":Tn.registerWaitForInteraction(()=>{K.start("ar")});break}}const jd=Symbol("initial-fov");class K{static _sync=null;static getXRSync(e){return this._sync||(this._sync=new w_(e)),this._sync}static get currentSessionRequest(){return this._currentSessionRequestMode}static _currentSessionRequestMode=null;static get active(){return this._activeSession}static get activeMode(){return this._activeSession?.mode??null}static get xrSystem(){return"xr"in navigator?navigator.xr:void 0}static isXRSupported(){return Promise.all([this.isVRSupported(),this.isARSupported()]).then(e=>e.some(t=>t)).catch(()=>!1)}static isVRSupported(){return this.isSessionSupported("immersive-vr")}static isARSupported(){return this.isSessionSupported("immersive-ar")}static isSessionSupported(e){return this.xrSystem?.isSessionSupported(e).catch(t=>(He&&console.error(t),!1))??Promise.resolve(!1)}static _currentSessionRequest;static _activeSession;static onSessionRequestStart(e){this._sessionRequestStartListeners.push(e)}static offSessionRequestStart(e){const t=this._sessionRequestStartListeners.indexOf(e);t>=0&&this._sessionRequestStartListeners.splice(t,1)}static _sessionRequestStartListeners=[];static onSessionRequestEnd(e){this._sessionRequestEndListeners.push(e)}static offSessionRequestEnd(e){const t=this._sessionRequestEndListeners.indexOf(e);t>=0&&this._sessionRequestEndListeners.splice(t,1)}static _sessionRequestEndListeners=[];static onXRSessionStart(e){this._xrStartListeners.push(e)}static offXRSessionStart(e){const t=this._xrStartListeners.indexOf(e);t>=0&&this._xrStartListeners.splice(t,1)}static _xrStartListeners=[];static onXRSessionEnd(e){this._xrEndListeners.push(e)}static offXRSessionEnd(e){const t=this._xrEndListeners.indexOf(e);t>=0&&this._xrEndListeners.splice(t,1)}static _xrEndListeners=[];static onControllerAdded(e){this._controllerAddedListeners.push(e)}static offControllerAdded(e){const t=this._controllerAddedListeners.indexOf(e);t>=0&&this._controllerAddedListeners.splice(t,1)}static _controllerAddedListeners=[];static onControllerRemoved(e){this._controllerRemovedListeners.push(e)}static offControllerRemoved(e){const t=this._controllerRemovedListeners.indexOf(e);t>=0&&this._controllerRemovedListeners.splice(t,1)}static _controllerRemovedListeners=[];static offerSession(e,t,i){return"xr"in navigator&&navigator.xr&&"offerSession"in navigator.xr?(typeof navigator.xr.offerSession=="function"&&(console.log("WebXR offerSession is available - requesting mode: "+e),t=="default"&&(t=this.getDefaultSessionInit(e)),navigator.xr.offerSession(e,{...t}).then(n=>K.setSession(e,n,t,i)).catch(n=>{console.log("XRSession offer rejected (perhaps because another call to offerSession was made or a call to requestSession was made)")})),!0):!1}static getDefaultSessionInit(e){switch(e){case"immersive-ar":const t=["anchors","local-floor","layers","dom-overlay","hit-test","unbounded"];return G.isVisionOS()||t.push("hand-tracking"),{optionalFeatures:t};case"immersive-vr":const i=["local-floor","bounded-floor","high-fixed-foveation-level","layers"];return G.isVisionOS()||i.push("hand-tracking"),{optionalFeatures:i};default:return console.warn("No default session init for mode",e),{}}}static async start(e,t,i){if(G.isiOS()){if(e==="ar")if(await this.isARSupported())e="immersive-ar";else return ec.exportAndOpen(),null}else e=="ar"&&(e="immersive-ar");if(E()&&w("debugxrpreroom"))return console.warn("Debug: Starting temporary XR session"),await Tl.start(e,t||K.getDefaultSessionInit(e)),null;if(this._currentSessionRequest)return console.warn("A XRSession is already being requested"),(He||E())&&ge("A XRSession is already being requested"),this._currentSessionRequest.then(()=>this._activeSession);if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;if(i||(i=z.Current),i||(i=ue.All[0]),!i)throw new Error("No Needle Engine Context found");switch(t||(t={}),e){case"immersive-ar":{if(await this.xrSystem?.isSessionSupported("immersive-ar")!==!0)return console.error(e+" is not supported by this browser."),null;const r=this.getDefaultSessionInit(e),a=FO(i.domElement);a&&!G.isQuest()&&(r.domOverlay={root:a},r.optionalFeatures.push("dom-overlay")),t={...r,...t}}break;case"immersive-vr":{if(await this.xrSystem?.isSessionSupported("immersive-vr")!==!0)return console.error(e+" is not supported by this browser."),null;t={...this.getDefaultSessionInit(e),...t}}break;default:console.warn("No default session init for mode",e);break}t.optionalFeatures??=[],t.requiredFeatures??=[],await Tl.stop();const n=e=="immersive-ar"?i.scripts_immersive_ar:i.scripts_immersive_vr;He?console.log(`%cRequesting ${e} session`,"font-weight:bold;",t,n):console.log(`%cRequesting ${e} session`,"font-weight:bold;");for(const r of n)r.onBeforeXR&&r.onBeforeXR(e,t);for(const r of this._sessionRequestStartListeners)r({mode:e,init:t});He&&Te("Requesting "+e+" session ("+Date.now()+")"),this._currentSessionRequest=navigator?.xr?.requestSession(e,t),this._currentSessionRequestMode=e;const s=await this._currentSessionRequest?.catch(r=>{console.error(r,"Code: "+r.code),r.code===9&&ge("Make sure your device has the required permissions (e.g. camera access)"),console.log("If the specified XR configuration is not supported (e.g. entering AR doesnt work) - make sure you access the website on a secure connection (HTTPS) and your device has the required permissions (e.g. camera access)"),location.protocol==="http:"&&ge("XR requires a secure connection (HTTPS)")});this._currentSessionRequest=void 0,this._currentSessionRequestMode=null;for(const r of this._sessionRequestEndListeners)r({mode:e,init:t,newSession:s||null});return s?this.setSession(e,s,t,i):(console.warn("XR Session request was rejected"),null)}static setSession(e,t,i,n){if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;const s=e=="immersive-ar"?n.scripts_immersive_ar:n.scripts_immersive_vr;return this._activeSession=new K(e,t,n,{scripts:s,controller_added:this._controllerAddedListeners,controller_removed:this._controllerRemovedListeners,init:i}),t.addEventListener("end",this.onEnd),He?console.log(`%cStarted ${e} session`,"font-weight:bold;",s):console.log(`%cStarted ${e} session`,"font-weight:bold;"),this._activeSession}static $_stop_request=Symbol();static stop(){const e=this._activeSession;e&&(e[this.$_stop_request]===void 0?(He&&console.log("[NeedleXRSession] Stopping XR Session... (new)"),e[this.$_stop_request]=setTimeout(()=>{e.end()})):He&&console.warn("[NeedleXRSession] XR Session stop already requested"))}static onEnd=()=>{He&&console.log("XR Session ended"),this._activeSession=null};context;get sync(){return K._sync}get running(){return!this._ended&&this.session!=null}session;mode;get interactionMode(){return this.session.interactionMode}get visibilityState(){return this.session.visibilityState}get isVisibleBlurred(){return this.session.visibilityState==="visible-blurred"}get isSystemKeyboardSupported(){return this.session.isSystemKeyboardSupported}get environmentBlendMode(){return this.session.environmentBlendMode}get frame(){return this.context.xrFrame}controllers=[];get leftController(){return this.controllers.find(e=>e.side==="left")}get rightController(){return this.controllers.find(e=>e.side==="right")}getController(e){return typeof e=="number"?this.controllers[e]||null:this.controllers.find(t=>t.side===e)||null}get isPassThrough(){return!!(this.environmentBlendMode!=="opaque"&&this.interactionMode==="world-space"||this.mode==="immersive-ar"&&this.environmentBlendMode!=="opaque"&&this.controllers.some(e=>e.inputSource.targetRayMode==="tracked-pointer")||E()&&G.isDesktop()&&this.mode==="immersive-ar")}get isAR(){return this.mode==="immersive-ar"}get isVR(){return this.mode==="immersive-vr"}get isScreenBasedAR(){return this.isAR&&!this.isPassThrough}get posePosition(){return this._transformPosition}get poseOrientation(){return this._transformOrientation}get referenceSpace(){return this.context.renderer.xr.getReferenceSpace()}get viewerPose(){return this._viewerPose}get isTrackingImages(){if(this.frame&&"getImageTrackingResults"in this.frame&&typeof this.frame.getImageTrackingResults=="function")try{const e=this.frame.getImageTrackingResults();for(const t of e)if(t.trackingState==="tracked")return!0}catch{return!1}return!1}get rig(){const e=this._rigs[0]??null;return e?.gameObject&&vr(e.gameObject)||e?.isActive===!1?(this.updateActiveXRRig(),this._rigs[0]??null):e}_rigScale=1;_lastRigScaleUpdate=-1;get rigScale(){return this._rigs[0]?(this._lastRigScaleUpdate!==this.context.time.frame&&(this._lastRigScaleUpdate=this.context.time.frame,this._rigScale=this._rigs[0].gameObject.worldScale.x),this._rigScale):1}addRig(e){this._rigs.indexOf(e)>=0||(e.priority===void 0&&(e.priority=0),this._rigs.push(e),this.updateActiveXRRig())}removeRig(e){const t=this._rigs.indexOf(e);t!==-1&&(this._rigs.splice(t,1),this.updateActiveXRRig())}setRigActive(e){const t=this._rigs.indexOf(e),i=this._rigs[0];this._rigs.splice(t,1),this._rigs.unshift(e),e.priority=i?.priority??0,this.updateActiveXRRig()}getUserOffsetInRig(){const e=this.context.mainCamera?.position;if(!e||!this.rig)return $(0,0,0);const t=$(e);return t.x*=-1,t.z*=-1,t.applyQuaternion(ti(this.rig.gameObject.quaternion)),t}updateActiveXRRig(){const e=this._rigs[0]??null;this._defaultRig.gameObject.parent!==this.context.scene&&this.context.scene.add(this._defaultRig.gameObject),this._defaultRig.gameObject.visible=!0,this._rigs.includes(this._defaultRig)||this._rigs.push(this._defaultRig);let t=this._rigs[0];t&&t.priority===void 0&&(t.priority=0);for(let i=1;i<this._rigs.length;i++){const n=this._rigs[i];if(n.isActive){if(vr(n.gameObject)){this._rigs.splice(i,1),i--;continue}(!t||t.isActive===!1||n.priority!==void 0&&n.priority>t.priority)&&(t=n)}}if(e!==t){const i=this._rigs.indexOf(t);i>=0&&this._rigs.splice(i,1),this._rigs.unshift(t)}He&&(e===t?console.log("Updated Active XR Rig:",t,"prev:",e):console.log("Updated Active XRRig:",t," (the same as before)"))}_rigs=[];_viewerHitTestSource=null;getHitTest(e){if(e)return this.getControllerHitTest(e);if(!this._viewerHitTestSource)return null;const t=this._viewerHitTestSource,i=this.frame.getHitTestResults(t);if(i.length>0){const n=i[0];return this.convertHitTestResult(n)}return null}getControllerHitTest(e){const t=e.getHitTestSource();if(!t)return null;const i=this.frame.getHitTestResultsForTransientInput(t);for(const n of i)if(n.inputSource===e.inputSource)for(const s of n.results)return this.convertHitTestResult(s);return null}convertHitTestResult(e){const t=this.context.renderer.xr.getReferenceSpace(),i=t&&e.getPose(t);if(i){const n=$(i.transform.position),s=ti(i.transform.orientation),r=this.context.mainCamera;if(r?.parent!==this._cameraRenderParent&&n.applyMatrix4(Pa),r?.parent){n.applyMatrix4(r.parent.matrixWorld),s.multiply($i);const a=be(r.parent);a.premultiply($i),s.premultiply(a)}return{hit:e,position:n,quaternion:s}}return null}convertSpace(e){const t=$(e.position);t.applyMatrix4(Pa);const i=ti(e.orientation);return i.premultiply($i),{position:t,quaternion:i}}_defaultRig;_xr_scripts;_xr_update_scripts=[];_inactive_scripts=[];_controllerAdded;_controllerRemoved;_originalCameraWorldPosition;_originalCameraWorldRotation;_originalCameraWorldScale;_originalCameraParent;_mainCamera=null;constructor(e,t,i,n){zO(e,n.init),this.session=t,this.mode=e,this.context=i,(He||w("console"))&&ar(!0),this._xr_scripts=[...n.scripts],this._xr_update_scripts=this._xr_scripts.filter(s=>typeof s.onUpdateXR=="function"),this._controllerAdded=n.controller_added,this._controllerRemoved=n.controller_removed,xo(this.onBefore,we.LateUpdate),this.context.pre_render_callbacks.push(this.onBeforeRender),this.context.post_render_callbacks.push(this.onAfterRender),(n.init.optionalFeatures?.includes("hit-test")||n.init.requiredFeatures?.includes("hit-test"))&&t.requestReferenceSpace("viewer").then(s=>t.requestHitTestSource?.call(t,{space:s})?.then(r=>this._viewerHitTestSource=r).catch(r=>console.error(r))).catch(s=>console.error(s)),this.context.mainCamera&&(this._originalCameraWorldPosition=Z(this.context.mainCamera,new b),this._originalCameraWorldRotation=be(this.context.mainCamera,new U),this._originalCameraWorldScale=$e(this.context.mainCamera,new b),this._originalCameraParent=this.context.mainCamera.parent,this.context.mainCamera instanceof de&&(this.context.mainCamera[jd]=this.context.mainCamera.fov)),this._defaultRig=new SO,this.context.scene.add(this._defaultRig.gameObject),this.addRig(this._defaultRig);for(let s=0;s<t.inputSources.length;s++){const r=t.inputSources[s];if(!r.handedness){console.warn("Input source in xr session has no handedness - ignoring",s);continue}this.onInputSourceAdded(r)}this.session.addEventListener("end",this.onEnd),this.session.addEventListener("inputsourceschange",s=>{for(const r of s.removed)this.disconnectInputSource(r);for(const r of s.added)this.onInputSourceAdded(r)}),this.context.xr=this,this.context.renderer.xr.setSession(this.session).then(this.onRendererSessionSet),"controllerAutoUpdate"in this.context.renderer.xr?(console.debug("Disabling three.js controllerAutoUpdate"),this.context.renderer.xr.controllerAutoUpdate=!1):He&&console.warn("controllerAutoUpdate is not available in three.js - cannot disable it")}onRendererSessionSet=()=>{this.running&&(this.context.renderer.xr.enabled=!0,this.context.renderer.xr.updateCamera(this.context.mainCamera),this.context.mainCameraComponent?.applyClearFlags())};onInputSourceAdded=e=>{if(e.targetRayMode==="screen")return;let t=0;for(let n=0;n<this.session.inputSources.length;n++)if(this.session.inputSources[n]===e){t=n;break}if(this.controllers.find(n=>n.inputSource===e)){console.debug("Controller already exists for input source",t);return}else if(this._newControllers.find(n=>n.inputSource===e)){console.debug("Controller already registered for input source",t);return}const i=new Qm(this,e,t);this._newControllers.push(i)};disconnectInputSource(e){const t=(s,r)=>{if(s.inputSource===e){He&&console.log("Disconnecting controller",s.index);const a=r.indexOf(s);a>=0&&r.splice(a,1),this.invokeControllerEvent(s,this._controllerRemoved,"removed");const l={xr:this,controller:s,change:"removed"};for(const c of this._xr_scripts)c.onXRControllerRemoved&&c.onXRControllerRemoved(l);s.onDisconnected()}},i=[...this.controllers];for(let s=i.length-1;s>=0;s--){const r=i[s];t(r,this.controllers)}const n=[...this._newControllers];for(let s=n.length-1;s>=0;s--){const r=n[s];t(r,this._newControllers)}}end(){this._ended||this.session.end().catch(e=>console.warn(e))}_ended=!1;_newControllers=[];onEnd=e=>{if(this._ended)return;this._ended=!0,console.debug("XR Session ended"),NO(),this.onAfterRender(),this.revertCustomForward(),this._didStart=!1,this._previousCameraParent=null,this.requestedCameraNearPlane=null,ds(this.onBefore,we.LateUpdate);const t=this.context.pre_render_callbacks.indexOf(this.onBeforeRender);t>=0&&this.context.pre_render_callbacks.splice(t,1);const i=this.context.post_render_callbacks.indexOf(this.onAfterRender);i>=0&&this.context.post_render_callbacks.splice(i,1),this.context.xr=null,this.context.renderer.xr.enabled=!1,this.context.pre_update_oneshot_callbacks.push(()=>{this.context.mainCameraComponent?.applyClearFlags(),this.context.mainCameraComponent?.applyClippingPlane()}),o_({session:this});for(const s of K._xrEndListeners)s({xr:this});const n=[...this.controllers];for(let s=0;s<n.length;s++)this.disconnectInputSource(n[s].inputSource);this.controllers.length=0,this._newControllers.length=0;for(const s of this._xr_scripts)s?.onLeaveXR?.({xr:this});this.sync?.onExitXR(this),this.context.mainCamera&&(this._originalCameraParent?.add(this.context.mainCamera),this._originalCameraWorldPosition&&mt(this.context.mainCamera,this._originalCameraWorldPosition),this._originalCameraWorldRotation&&pn(this.context.mainCamera,this._originalCameraWorldRotation),this._originalCameraWorldScale&&wa(this.context.mainCamera,this._originalCameraWorldScale),this.context.mainCamera instanceof de&&this.context.mainCamera[jd]&&(this.context.mainCamera.fov=this.context.mainCamera[jd],this.context.mainCamera[jd]=0)),this.context.requestSizeUpdate(),this._defaultRig.gameObject.removeFromParent(),ar(!1)};_didStart=!1;onBefore=e=>{const t=e.xrFrame;if(!t)return;this.context.xr=this,this.context.mainCameraComponent&&this.context.mainCameraComponent!==this._mainCamera&&(this._mainCamera=this.context.mainCameraComponent),this.rig?.isActive==!1&&(He&&console.warn("Latest rig is not active - trying to activate a different rig",this.rig),this.updateActiveXRRig()),this.rig&&this._mainCamera?.gameObject&&this._mainCamera?.gameObject?.parent!==this.rig.gameObject&&this.rig.gameObject.add(this._mainCamera?.gameObject),this.internalUpdateState(),this.applyCustomForward();const i={xr:this};if(this._didStart){if(this.context.new_scripts_xr.length>0){const n=[...this.context.new_scripts_xr];for(let s=0;s<n.length;s++){const r=this.context.new_scripts_xr[s];if(!r||r.destroyed||r.supportsXR?.(this.mode)==!1){this.context.new_scripts_xr.splice(s,1);continue}if(!r.activeAndEnabled){this.context.new_scripts_xr.splice(s,1),this.markInactive(r);continue}if(this.addScript(r)){this.invokeCallback_EnterXR(r);for(const a of this.controllers)this.invokeCallback_ControllerAdded(r,a)}}}}else{if(this._didStart=!0,this.mode==="immersive-vr"){const s=Wt(this.context.scene.children);if(s){const r=s.getSize($());if(r.length()>0){const a=this._defaultRig.gameObject;a.position.set(s.min.x+r.x*.5,s.min.y,s.max.z+r.z*.5+1.5);const l=s.getCenter($());l.y=a.position.y,a.lookAt(l)}}}n_({session:this}),dr();for(const s of K._xrStartListeners)s(i);const n=[...this._xr_scripts];He&&console.log("NeedleXRSession start, handle scripts:",n);for(const s of n){if(s.destroyed){this._script_to_remove.push(s);continue}if(!s.activeAndEnabled){this.markInactive(s);continue}this.invokeCallback_EnterXR(s);for(const r of this.controllers)this.invokeCallback_ControllerAdded(s,r)}}this.syncCameraCullingMask();for(const n of this.controllers)n.onUpdate(t);if(this._newControllers.length>0){const n=[...this._newControllers];this._newControllers.length=0;for(const s of n){if(!s.connected){console.warn("New controller is not connected",s);continue}this.controllers.push(s);for(const r of this._xr_scripts){if(r.destroyed){this._script_to_remove.push(r);continue}r.activeAndEnabled!==!1&&this.invokeCallback_ControllerAdded(r,s)}}this.controllers.sort((s,r)=>s.index-r.index)}He&&this.context.time.frame%30===0&&this.controllers.length<=0&&this.session.inputSources.length>0&&(ar(!0),console.error("XRControllers are not added but inputSources are present"));for(const n of this._xr_update_scripts){if(n.destroyed===!0){this._script_to_remove.push(n);continue}if(n.activeAndEnabled===!1){this.markInactive(n);continue}n.onUpdateXR&&n.onUpdateXR(i)}if(this.handleInactiveScripts(),this._script_to_remove.length>0){const n=[...new Set(this._script_to_remove)];this._script_to_remove.length=0;for(const s of n)!s.destroyed&&this.running&&s.onLeaveXR?.(i),this.removeScript(s)}this.sync?.onUpdate(this),this.onRenderDebug()};onRenderDebug(){if(He)for(const e of this.controllers)e.onRenderDebug();if((He||P_)&&this.rig&&(sg++,sg>=20)){const e=this.rig.gameObject.worldPosition,t=this.rig.gameObject.worldForward;e.add(t.multiplyScalar(1.5));const i=this.rig.gameObject.worldUp;e.add(i.multiplyScalar(2.5));let n="";if(n+=`${this.context.time.smoothedFps.toFixed(0)} FPS`,n+=`, calls: ${this.context.renderer.info.render.calls}, tris: ${this.context.renderer.info.render.triangles.toLocaleString()}`,He||P_)for(const s of this.controllers)n+=`
165
- ${s.hand?"hand":"ctrl"} ${s.inputSource.handedness}[${s.index}] con:${s.connected} tr:${s.isTracking} hts:${s.hasHitTestSource?"yes":"no"}`;sg=0,F.DrawLabel(e,n,void 0,1/60*20)}}onBeforeRender=()=>{this.context.mainCamera&&(this.updateFade(this.context.mainCamera),this.requestedCameraNearPlane!==null&&this.context.mainCamera instanceof de&&(this.context.mainCamera.near=this.requestedCameraNearPlane,this.requestedCameraNearPlane=null))};onAfterRender=()=>{if(this.onUpdateFade_PostRender(),G.isDesktop()||!this._renderOnceOnDevice){const e=this.context.renderer;if(e.xr.isPresenting&&this.context.mainCamera){this._renderOnceOnDevice=!0;const t=e.xr.enabled,i=e.getRenderTarget(),n=this.context.scene.background;e.xr.enabled=!1,e.setRenderTarget(null),this.isPassThrough&&(this.context.scene.background=null),this.context.composer?this.context.composer.render(this.context.time.deltaTime):e.render(this.context.scene,this.context.mainCamera),e.xr.enabled=t,e.setRenderTarget(i),this.context.scene.background=n}}};addScript(e){return this._xr_scripts.includes(e)?!1:(He&&console.log("Register new XRScript",e),this._xr_scripts.push(e),typeof e.onUpdateXR=="function"&&this._xr_update_scripts.push(e),!0)}markInactive(e){if(!(this._inactive_scripts.indexOf(e)>=0)){this.removeScript(e,!1),this._inactive_scripts.push(e);for(const t of this.controllers)this.invokeCallback_ControllerRemoved(e,t);this.invokeCallback_LeaveXR(e)}}handleInactiveScripts(){if(this._inactive_scripts.length>0)for(let e=this._inactive_scripts.length-1;e>=0;e--){const t=this._inactive_scripts[e];if(t.activeAndEnabled){this._inactive_scripts.splice(e,1),this.addScript(t),this.invokeCallback_EnterXR(t);for(const i of this.controllers)this.invokeCallback_ControllerAdded(t,i)}}}_script_to_remove=[];removeScript(e,t=!0){He&&console.log("Remove XRScript",e);const i=this._xr_scripts.indexOf(e);i>=0&&this._xr_scripts.splice(i,1);const n=this._xr_update_scripts.indexOf(e);if(n>=0&&this._xr_update_scripts.splice(n,1),t){const s=this._inactive_scripts.indexOf(e);s>=0&&this._inactive_scripts.splice(s,1)}}invokeCallback_EnterXR(e){e.onEnterXR&&e.onEnterXR({xr:this})}invokeCallback_ControllerAdded(e,t){e.onXRControllerAdded&&e.onXRControllerAdded({xr:this,controller:t,change:"added"})}invokeCallback_ControllerRemoved(e,t){e.onXRControllerRemoved&&e.onXRControllerRemoved({xr:this,controller:t,change:"removed"})}invokeCallback_LeaveXR(e){e.onLeaveXR&&!e.destroyed&&e.onLeaveXR({xr:this})}syncCameraCullingMask(){const e=this.context.xrCamera,t=this.context.mainCameraComponent?.cullingMask;if(e&&t!==void 0){for(const i of e.cameras)i.layers.mask=t;e.layers.mask=t}else if(e){for(const i of e.cameras)i.layers.enableAll();e.layers.enableAll()}}invokeControllerEvent(e,t,i){for(let n=t.length-1;n>=0;n--){const s=t[n];if(s)try{s({xr:this,controller:e,change:i})}catch(r){console.error(r)}}}_camera;_cameraRenderParent=new O().rotateY(Math.PI);_previousCameraParent;_customforward=!0;originalCameraNearPlane;requestedCameraNearPlane=null;applyCustomForward(){if(this.context.mainCamera&&this._customforward){this._camera=this.context.mainCamera,this._camera.parent!==this._cameraRenderParent&&(this._previousCameraParent=this._camera.parent,this._previousCameraParent?.add(this._cameraRenderParent)),this._cameraRenderParent.name="XR Camera Render Parent",this._cameraRenderParent.add(this._camera);{let e=.02;const t=.001;if(this.rig){const i=$e(this.rig.gameObject);e*=i.x}this._camera instanceof de&&Math.abs(this._camera.near-e)>t&&(this.isAR?this.originalCameraNearPlane=this._camera.near:this._camera.near=e,He&&console.debug(`Setting camera near plane to ${e} (was ${this.originalCameraNearPlane}) to account for XR rendering scale`))}}}revertCustomForward(){this._camera&&this._previousCameraParent&&this._previousCameraParent.add(this._camera),this._previousCameraParent=null,this._camera instanceof de&&this.originalCameraNearPlane!=null&&(this._camera.near=this.originalCameraNearPlane,this.originalCameraNearPlane=void 0)}_viewerPose;_transformOrientation=new U;_transformPosition=new b;internalUpdateState(){const e=this.context.renderer.xr.getReferenceSpace();if(!e){this._viewerPose=void 0;return}if(this._viewerPose=this.frame.getViewerPose(e),this._viewerPose){const t=this._viewerPose.transform;this._transformPosition.set(t.position.x,t.position.y,t.position.z),this._transformOrientation.set(t.orientation.x,t.orientation.y,t.orientation.z,t.orientation.w)}}_transition;get transition(){return this._transition||(this._transition=new x_),this._transition}fadeTransition(){return this._transition||(this._transition=new x_),this._transition.fadeTransition()}updateFade(e){this._transition&&e instanceof de&&this._transition.update(e,this.context.time.deltaTime)}onUpdateFade_PostRender(){this._transition?.remove()}}const ag=w("debugwebxr");class k_{static tryFindAvatarObjects(e,t,i){if(i.head&&i.leftHand&&i.rightHand)return;const n=e.name.toLocaleLowerCase();!i.head&&n.includes("head")&&(ag&&console.log("FOUND AVATAR HEAD",e.name),i.head=new ie("",t,e)),n.includes("hand")&&(!i.leftHand&&n.includes("left")&&(ag&&console.log("FOUND AVATAR LEFT HAND",e.name),i.leftHand=new ie("",t,e)),!i.rightHand&&n.includes("right")&&(ag&&console.log("FOUND AVATAR RIGHT HAND",e.name),i.rightHand=new ie("",t,e)));for(let s=0;s<e.children.length;s++){if(i.head&&i.leftHand&&i.rightHand)return;const r=e.children[s];this.tryFindAvatarObjects(r,t,i)}}}const It=new b,M_=new b,R_=new U,$O=w("debuggizmos"),yn=8947848,lg=32;class F{constructor(){}static enabled=!0;static isGizmo(e){return e[hg]!==void 0}static setVisible(e){for(const t of Gi.timedObjectsBuffer)t.visible=e}static DrawLabel(e,t,i=.05,n=0,s,r,a){if(!F.enabled)return null;s||(s=yn);const l=K.active?.rigScale??1,c=Gi.getTextLabel(n,t,i*l,s,r);return a instanceof O&&a.add(c),c.position.x=e.x,c.position.y=e.y,c.position.z=e.z,c}static DrawRay(e,t,i=yn,n=0,s=!0){if(!F.enabled)return;const r=Gi.getLine(n),a=r.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),It.set(t.x,t.y,t.z).multiplyScalar(999999999),a.setXYZ(1,e.x+It.x,e.y+It.y,e.z+It.z),a.needsUpdate=!0,r.material.color.set(i),r.material.depthTest=s,r.material.depthWrite=!1}static DrawDirection(e,t,i=yn,n=0,s=!0,r=1){if(!F.enabled)return;const a=Gi.getLine(n),l=a.geometry.getAttribute("position");l.setXYZ(0,e.x,e.y,e.z),t.w!==void 0?(It.set(0,0,-r),R_.set(t.x,t.y,t.z,t.w),It.applyQuaternion(R_)):(It.set(t.x,t.y,t.z),It.multiplyScalar(r)),l.setXYZ(1,e.x+It.x,e.y+It.y,e.z+It.z),l.needsUpdate=!0,a.material.color.set(i),a.material.depthTest=s,a.material.depthWrite=!1}static DrawLine(e,t,i=yn,n=0,s=!0){if(!F.enabled)return;const r=Gi.getLine(n),a=r.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),a.setXYZ(1,t.x,t.y,t.z),a.needsUpdate=!0,r.material.color.set(i),r.material.depthTest=s,r.material.depthWrite=!1,r.material.fog=!1}static DrawCircle(e,t,i,n=yn,s=0,r=!0){if(!F.enabled)return;const a=Gi.getCircle(s);a.position.set(e.x,e.y,e.z),a.scale.set(i,i,i),a.quaternion.setFromUnitVectors(this._up,It.set(t.x,t.y,t.z).normalize()),a.material.color.set(n),a.material.depthTest=r,a.material.depthWrite=!1,a.material.fog=!1}static DrawWireSphere(e,t,i=yn,n=0,s=!0){if(!F.enabled)return;const r=Gi.getSphere(t,n,!0);sr(r,e.x,e.y,e.z),r.material.color.set(i),r.material.depthTest=s,r.material.depthWrite=!1,r.material.fog=!1}static DrawSphere(e,t,i=yn,n=0,s=!0){if(!F.enabled)return;const r=Gi.getSphere(t,n,!1);sr(r,e.x,e.y,e.z),r.material.color.set(i),r.material.depthTest=s,r.material.depthWrite=!1}static DrawWireBox(e,t,i=yn,n=0,s=!0,r=void 0){if(!F.enabled)return;const a=Gi.getBox(n);a.position.set(e.x,e.y,e.z),a.scale.set(t.x,t.y,t.z),r?a.quaternion.copy(r):a.quaternion.identity(),a.material.color.set(i),a.material.depthTest=s,a.material.wireframe=!0,a.material.depthWrite=!1,a.material.fog=!1}static DrawWireBox3(e,t=yn,i=0,n=!0){if(!F.enabled)return;const s=Gi.getBox(i);s.position.copy(e.getCenter(It)),s.scale.copy(e.getSize(It)),s.material.color.set(t),s.material.depthTest=n,s.material.wireframe=!0,s.material.depthWrite=!1,s.material.fog=!1}static _up=new b(0,1,0);static DrawArrow(e,t,i=yn,n=0,s=!0,r=!1){if(!F.enabled)return;const a=Gi.getArrowHead(n);a.position.set(t.x,t.y,t.z),a.quaternion.setFromUnitVectors(this._up.set(0,1,0),It.set(t.x,t.y,t.z).sub(M_.set(e.x,e.y,e.z)).normalize());const l=It.set(t.x,t.y,t.z).sub(M_.set(e.x,e.y,e.z)).length()*.1;a.scale.set(l,l,l),a.material.color.set(i),a.material.depthTest=s,a.material.wireframe=r,this.DrawLine(e,t,i,n,s)}static DrawWireMesh(e){const t=Gi.getMesh(e.duration??0);"mesh"in e?(t.geometry=e.mesh.geometry,t.matrix.copy(e.mesh.matrixWorld)):(t.geometry=e.geometry,t.matrix.copy(e.matrix)),t.matrixAutoUpdate=!1,t.matrixWorldAutoUpdate=!1,t.material.color.set(e.color??yn),t.material.depthTest=e.depthTest??!0,t.material.wireframe=!0}}const HO=new ma(1,1,1);function cg(o=null){const e=new ne(o??14540253),t=new iS(HO);return new D0(t,new im({color:e}))}const hg=Symbol("GizmoCache");class Gi{static familyName="needle-gizmos";static ensureFont(){let e=Ce.FontLibrary.getFontFamily(this.familyName);e||(e=Ce.FontLibrary.addFontFamily(this.familyName),e.addVariant("normal","normal","https://uploads.needle.tools/include/font-msdf.json","https://uploads.needle.tools/include/font.png")?.addEventListener("ready",()=>{Ce.update()}))}static getTextLabel(e,t,i,n,s){this.ensureFont();let r=this.textLabelCache.pop(),a=1;s&&typeof s=="string"&&s?.length>=8&&s.startsWith("#")?(a=parseInt(s.substring(7),16)/255,s=s.substring(0,7),$O&&console.log(s,a)):typeof s=="object"&&s.a!==void 0&&(a=s.a);const l={boxSizing:"border-box",fontFamily:this.familyName,width:"auto",fontSize:i,color:n,lineHeight:1,backgroundColor:s??void 0,backgroundOpacity:a,textContent:t,borderRadius:.5*i,padding:.8*i,whiteSpace:"pre",offset:.05*i};if(r)r.set(l);else{r=new sb(l);const c=this,h=r;h.setText=function(d){this.set({textContent:d}),c.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(z.Current,r,e,this.textLabelCache),r}static getBox(e){let t=this.boxesCache.pop();if(!t){const i=new ma(1,1,1);t=new H(i)}return this.registerTimedObject(z.Current,t,e,this.boxesCache),t}static getLine(e){let t=this.linesCache.pop();if(!t){t=new ga;let i=t.geometry.getAttribute("position");i||(i=new pt(new Float32Array(6),3),t.geometry.setAttribute("position",i))}return t.frustumCulled=!1,this.registerTimedObject(z.Current,t,e,this.linesCache),t}static getCircle(e){let t=this.circlesCache.pop();if(!t){t=new ga;let i=t.geometry.getAttribute("position");if(!i){i=new pt(new Float32Array(lg*3),3),t.geometry.setAttribute("position",i);const n=$(0,1,0),s=$(0,0,1),r=$(s);r.cross(n).normalize();const a=$(r),l=Math.PI*2/(lg-1);for(let c=0;c<lg+1;c++){const h=l*c;n.copy(a).multiplyScalar(Math.cos(h)*1),r.copy(s).multiplyScalar(Math.sin(h)*1);const d=n.add(r);i.setXYZ(c,d.x,d.y,d.z)}}}return t.frustumCulled=!1,this.registerTimedObject(z.Current,t,e,this.circlesCache),t}static getSphere(e,t,i){let n=this.spheresCache.pop();return n||(n=new H(new od(1,8,8))),n.scale.set(e,e,e),n.material.wireframe=i,this.registerTimedObject(z.Current,n,t,this.spheresCache),n}static getArrowHead(e){let t=this.arrowHeadsCache.pop();return t||(t=new H(new L0(0,.5,1,8))),this.registerTimedObject(z.Current,t,e,this.arrowHeadsCache),t}static getMesh(e){let t=this.mesh.pop();return t||(t=new H,t.material=new xe),this.registerTimedObject(z.Current,t,e,this.mesh),t}static linesCache=[];static circlesCache=[];static spheresCache=[];static boxesCache=[];static arrowHeadsCache=[];static mesh=[];static textLabelCache=[];static registerTimedObject(e,t,i,n){if(!e){console.error("No Needle Engine context available. Did you call a Gizmos function in global scope?");return}const s=this.contextBeforeRenderCallbacks.get(e),r=this.contextPostRenderCallbacks.get(e);if(s){if(e.pre_render_callbacks[e.pre_render_callbacks.length-1]!==s){const a=e.pre_render_callbacks.indexOf(s);a>=0&&e.pre_render_callbacks.splice(a,1),e.pre_render_callbacks.push(s)}}else{const a=()=>{this.onBeforeRender(e,this.timedObjectsBuffer)};this.contextBeforeRenderCallbacks.set(e,a),e.pre_render_callbacks.push(a)}if(r){if(e.post_render_callbacks[e.post_render_callbacks.length-1]!==r){const a=e.post_render_callbacks.indexOf(r);a>=0&&e.post_render_callbacks.splice(a,1),e.post_render_callbacks.push(r)}}else{const a=()=>{this.onPostRender(e,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(e,a),e.post_render_callbacks.push(a)}t.traverse(a=>{a.layers.disableAll(),a.layers.enable(2)}),t.renderOrder=999999,t[hg]=n,t.castShadow=!1,t.receiveShadow=!1,t.isGizmo=!0,this.timedObjectsBuffer.push(t),this.timesBuffer.push(z.Current.time.realtimeSinceStartup+i),e.scene.add(t)}static timedObjectsBuffer=new Array;static timesBuffer=new Array;static contextPostRenderCallbacks=new Map;static contextBeforeRenderCallbacks=new Map;static tmuiNeedsUpdate=!1;static onBeforeRender(e,t){this.tmuiNeedsUpdate&&(this.tmuiNeedsUpdate=!1,Ce.update());for(let i=0;i<t.length;i++){const n=t[i];if(e.mainCamera&&n instanceof Ce.MeshUIBaseElement){if(vr(n))continue;const s=e.isInVR,r=!1,a=!s;$l(n,e.mainCamera,r,a)}}}static onPostRender(e,t,i){const n=e.time.realtimeSinceStartup;for(let s=t.length-1;s>=0;s--){const r=t[s];n>=i[s]-1e-6&&(t.splice(s,1),i.splice(s,1),r.removeFromParent(),vr(r)!=!0&&r[hg].push(r))}}}const Vt=w("debugphysics"),T_=new is;class us{static AllLayers=4294967295;ray;cam;screenPoint;raycaster;results;targets;recursive=!0;minDistance;maxDistance;lineThreshold;layerMask;ignore;testObject;useAcceleratedRaycast;allowSlowRaycastFallback=!0;screenPointFromOffset(e,t){this.screenPoint===void 0&&(this.screenPoint=new J),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setLayer(e){T_.set(e),this.layerMask=T_}setMask(e){this.layerMask||(this.layerMask=new is);const t=this.layerMask;t?t.mask=e:this.layerMask=e}}class dg{distance;point;object;constructor(e,t,i){this.object=e,this.distance=t,this.point=i}}class El{static _raycasting=0;static get raycasting(){return this._raycasting>0}raycastPhysicsFast(e,t=void 0,i=1/0,n=!0){return this.context.physics.engine?.raycast(e,t,{maxDistance:i,solid:n})??null}raycastPhysicsFastAndGetNormal(e,t=void 0,i=1/0,n=!0){return this.context.physics.engine?.raycastAndGetNormal(e,t,{maxDistance:i,solid:n})??null}sphereOverlapPhysics(e,t){return this.context.physics.engine?.sphereOverlap(e,t)??null}context;engine;constructor(e){this.context=e}raycaster=new sd;defaultRaycastOptions=new us;targetBuffer=new Array(1);defaultThresholds={Mesh:{},Line:{threshold:-1},LOD:{},Points:{threshold:0},Sprite:{}};sphereResults=new Array;sphereMask=new is;sphere=new rd;sphereOverlap(e,t,i=!0,n=!1,s=null){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;const r=this.sphereMask;r.enableAll(),r.disable(2);for(const a of this.context.scene.children)this.intersectSphere(a,e,t,r,this.sphereResults,i,n,s);return this.sphereResults.sort((a,l)=>a.distance-l.distance)}raycastFromRay(e,t=null){const i=t??this.defaultRaycastOptions;i.ray=e;const n=this.raycast(i);return i===this.defaultRaycastOptions&&(i.ray=void 0),n}raycast(e=null){Vt&&performance.mark("raycast.start"),e||(e=this.defaultRaycastOptions);const t=e.screenPoint??this.context.input.mousePositionRC,i=e.raycaster??this.raycaster;if(i.near=e.minDistance??0,i.far=e.maxDistance??1/0,i.params=this.defaultThresholds,e.lineThreshold===void 0&&(e.lineThreshold=-1),i.params.Line={threshold:e.lineThreshold},e.ray)i.ray.copy(e.ray);else{const a=e.cam??this.context.mainCamera;if(!a)return Vt&&console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];const l=this.context.xrCamera;this.context.isInXR&&l instanceof nS&&l.cameras.length>0?i.setFromCamera(t,l.cameras[0]):i.setFromCamera(t,a)}let n=e.targets;n||(n=this.targetBuffer,n.length=1,n[0]=this.context.scene);let s=e.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),s||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),s=this.defaultRaycastOptions.results),e.layerMask!==void 0?e.layerMask instanceof is?i.layers.mask=e.layerMask.mask:i.layers.mask=e.layerMask:(i.layers.enableAll(),i.layers.disable(2)),Vt&&console.time("raycast"),s.length=0,El._raycasting++,this.intersect(this.raycaster,n,s,e),s.sort((a,l)=>a.distance-l.distance);const r=e.ignore;return r!==void 0&&r.length>0&&(s=s.filter(a=>!r.includes(a.object))),El._raycasting--,Vt&&(console.timeEnd("raycast"),console.warn("#"+this.context.time.frame+", hits:",s?.length?[...s]:"nothing"),performance.mark("raycast.end"),performance.measure("raycast","raycast.start","raycast.end")),s}intersect(e,t,i,n){for(const s of t){if(!s||s.visible===!1||F.isGizmo(s)||n.lineThreshold!==void 0&&n.lineThreshold<0&&s instanceof ga)continue;let r=!0;const a=s,l=a.geometry;if(n.testObject){const c=n.testObject?.(s);if(c===!1)continue;c==="continue in children"&&(r=!1)}if(r&&(l&&E_(l)||(r=!1)),r){const c=q0(s);c&&(a.geometry=c);const h=i.length;let d=!0;if(n.precise===!1&&(d=!1),d||=l.getAttribute("position")?.array?.length<64,a instanceof ba&&(d=!1),!d&&qO(a,e,i)||(n.useAcceleratedRaycast!==!1?Bd.runMeshBVHRaycast(e,a,i,this.context,n):e.intersectObject(a,!1,i)),Vt&&i.length!=h){const p=i[i.length-1],g=c?8969557:7798784;F.DrawWireSphere(p.point,.1,g,1,!1),F.DrawWireMesh({mesh:s,depthTest:!1,duration:.2,color:g})}a.geometry=l}n.recursive!==!1&&this.intersect(e,s.children,i,n)}return i}tempBoundingBox=new bi;intersectSphere(e,t,i,n,s,r,a,l){let c=e&&e.isMesh&&e.layers.test(n)&&!F.isGizmo(e);c&&=e.visible,c&&=!(e instanceof ga),c&&=!(e instanceof ba);const h=e,d=h.geometry;if(c&&l){const p=l(e);if(p===!1)return;p==="continue in children"&&(c=!1)}if(d&&E_(d)||(c=!1),c){if(a){const p=this.sphere;p.center.copy(t),p.radius=i;const g=s.length;if(Bd.runMeshBVHRaycast(this.sphere,h,s,this.context,{}),g!=s.length&&!r)return}else if(d.boundingBox||d.computeBoundingBox(),d.boundingBox){h.matrixWorldNeedsUpdate&&h.updateWorldMatrix(!1,!1);const p=this.tempBoundingBox.copy(d.boundingBox).applyMatrix4(h.matrixWorld),g=this.sphere;if(g.center.copy(t),g.radius=i,g.intersectsBox(p)){const f=Z(e),m=f.distanceTo(g.center),y=new dg(e,m,f);if(s.push(y),!r)return}}}if(e.children)for(const p of e.children){const g=s.length;if(this.intersectSphere(p,t,i,n,s,r,a,l),g!=s.length&&!r)return}}}function E_(o){return!(o.index&&o.index.array.length<3)}const mr=new rd,Dd=new tr,GO=new I0;function qO(o,e,t){const i=o._computeIntersections;if(!i)return!1;let n=o["_computeIntersections:Needle"];return n||(n=o["_computeIntersections:Needle"]=function(s,r,a){const l=this,c=l.geometry.boundingSphere;if(c){if(l instanceof ba){Dd.setFromNormalAndCoplanarPoint($(0,1,0),$(0,-l.position.y,0)),Dd.applyMatrix4(l.matrixWorld,GO);const d=s.ray.intersectPlane(Dd,$());if(d){mr.copy(c),mr.applyMatrix4(l.matrixWorld);const p=$(d).sub(s.ray.origin).length(),g=mr.radius*.5;p<g&&r.push({distance:p,point:d,object:l,normal:Dd.normal.clone()})}return}mr.copy(c),mr.applyMatrix4(l.matrixWorld);const h=s.ray.intersectSphere(mr,$());if(h){const d=$(h).sub(s.ray.origin),p=d.length();if(p>mr.radius){const g=d.clone().normalize();r.push({distance:p,point:h,object:l,normal:g})}}}}),o._computeIntersections=n,e.intersectObject(o,!1,t),o._computeIntersections=i,!0}var Bd;(o=>{function e(_,v,P,R,k){if(!v.geometry||!v.geometry.hasAttribute("position"))return!1;const A=v.geometry;if(v?.isSkinnedMesh){const L=v,N=L.bvhNeedsUpdate;if(!L.staticGenerator)a(),s&&(L.staticGenerator=new s(v),L.staticGenerator.applyWorldTransforms=!1,L.staticGeometry=L.staticGenerator.generate(),A.boundsTree=r?.call(L.staticGeometry),L.staticGeometryLastUpdate=performance.now()+Math.random()*200,L.bvhNeedsUpdate=!0);else if(A.boundsTree&&(L.autoUpdateMeshBvhInterval!==void 0&&L.autoUpdateMeshBvhInterval>=0||N===!0)){const j=performance.now(),q=j-L.staticGeometryLastUpdate,Y=L.autoUpdateMeshBvhInterval??100;(N||q>Y)&&(Vt&&console.warn(`Physics: updating skinned mesh bvh for ${v.name} after ${q.toFixed(2)}ms`),L.bvhNeedsUpdate=!1,L.staticGeometryLastUpdate=j,L.staticGenerator?.generate(L.staticGeometry),A.boundsTree.refit())}}else if(!A.boundsTree){c||y();let L=!0;if((R.xr||A[g]===!1||A.getAttribute("position")?.isInterleavedBufferAttribute||A.index&&A.index?.isInterleavedBufferAttribute)&&(L=!1),L&&d){if(A[p]===void 0){let N=null;if(m.length>0){const j=m.shift();j&&!j.running&&(N=j)}if(!N&&f.length<3&&(N=new d,f.push(N)),N!=null&&!N.running){const j=v.name;Vt&&console.log("<<<< worker start",j,N),A[p]="queued",performance.mark("bvh.create.start");const q=A.clone();try{N.generate(q).then(Y=>{A[p]="done",A.boundsTree=Y}).catch(Y=>{A[p]="failed - "+Y?.message,A[g]=!1,Vt&&console.error("Failed to generate mesh bvh on worker",Y)}).finally(()=>{Vt&&console.log(">>>>> worker done",j,{hasBoundsTre:A.boundsTree!=null}),m.push(N),q.dispose(),performance.mark("bvh.create.end"),performance.measure("bvh.create (worker)","bvh.create.start","bvh.create.end")})}catch(Y){console.error("Failed to generate mesh bvh on worker",Y)}}else Vt&&console.warn("No worker available")}}else(!h||!L)&&(a(),n&&(performance.mark("bvh.create.start"),A.boundsTree=new n(A),performance.mark("bvh.create.end"),performance.measure("bvh.create","bvh.create.start","bvh.create.end")))}if(_ instanceof sd){const L=_,N=v.raycast;if(A.boundsTree)a(),i&&(v.acceleratedRaycast||(v.acceleratedRaycast=i.bind(v),Vt&&console.debug(`Physics: bind acceleratedRaycast fn to "${v.name}"`)),v.raycast=v.acceleratedRaycast);else if(Vt&&console.warn("No bounds tree found for mesh",v.name,{workerTask:A[p],hasAcceleratedRaycast:i!=null}),k.allowSlowRaycastFallback===!1)return Vt&&console.warn("Skipping raycast because no bounds tree is available and allowSlowRaycastFallback is false"),!1;const j=L.firstHitOnly;return L.firstHitOnly=!1,L.intersectObject(v,!1,P),L.firstHitOnly=j,v.raycast=N,!0}else if(_ instanceof rd){const L=A.boundsTree;if(L){const N=_;if(l.copy(v.matrixWorld).invert(),N.applyMatrix4(l),L.intersectsSphere(N)){const j=Z(v),q=j.distanceTo(N.center),Y=new dg(v,q,j);P.push(Y)}}return!0}return!1}o.runMeshBVHRaycast=e;let t=!1,i=null,n=null,s=null,r=null;function a(){t||(t=!0,import("./vendor-XJ9xiwrv.min.js").then(_=>_.index$1).then(_=>{i=_.acceleratedRaycast,n=_.MeshBVH,s=_.StaticGeometryGenerator,r=_.computeBoundsTree}).catch(_=>{(Vt||E())&&console.error("Failed to load BVH library...",_.message)}))}const l=new ee;let c=!1,h=!1,d=null;const p=Symbol("Needle:MeshBVH-Worker"),g=Symbol("Needle:MeshBVH-CanUseWorker"),f=[],m=[];function y(){c=!0,h=!0,Promise.resolve().then(()=>EI).then(_=>{d=_.GenerateMeshBVHWorker}).catch(_=>{(Vt||E())&&console.warn("Failed to setup mesh bvh worker")}).finally(()=>{h=!1})}})(Bd||(Bd={}));const A_=Symbol("gltf-loader-internal-usage-tracker"),XO=w("debugusers");class Al{get name(){return"NEEDLE_internal_usage_tracker"}static isLoading(e){return Al._loadingProcesses>0}static _loadingProcesses=0;parser;_getDependency;_loadingId;_loadedObjects=new Set;constructor(e){this.parser=e,this._getDependency=this.parser.getDependency,this._loadingId=Date.now().toString()}beforeRoot(){Al._loadingProcesses++;const e=this,t=this._getDependency;return this.parser.getDependency=function(i,n){const s=t.call(this,i,n);return s.then(r=>(r&&(e._loadedObjects.add(r),r[A_]=e._loadingId),r)),s},null}afterRoot(e){Al._loadingProcesses--,this.parser.getDependency=this._getDependency;for(const t of this._loadedObjects)delete t[A_],t instanceof O&&(t.parent||t instanceof H&&setTimeout(()=>{XO&&console.warn("> GLTF LOADER: Mesh not used in scene!",t),t.material=null,t.geometry=null},1e3));return null}}class I_{constructor(){window.addEventListener("unhandledrejection",e=>{if(e.defaultPrevented)return;const t=e?.reason?.path;if(t){const i=t[0];i&&i.tagName==="IMG"&&(console.warn(`Could not load image:
164
+ ${a.href}`)}this.onSendQueued(fn.OnRoomJoin);break;case"left-room":const n=e;n.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentRoomAllowEditing=!0,this._currentInRoom.length=0,(Id||E())&&console.debug("Left Needle Engine Room: "+n.room));break;case"user-joined-room":if(e.data){const r=e.data;this._currentInRoom.push(r.userId),ni&&console.log(r.userId+" joined","now in room:",this._currentInRoom)}break;case"user-left-room":if(e.data){const r=e.data,a=this._currentInRoom.indexOf(r.userId);a>=0&&(ni&&console.log(r.userId+" left","now in room:",this._currentInRoom),this._currentInRoom.splice(a,1)),r.userId===this.connectionId&&console.log("you left the room")}break;case"all-room-state-deleted":ni&&console.log("RECEIVED all-room-state-deleted"),this._state={};break;case"ping":case"pong":const s=e.data?.time;s&&(this._currentDelay=this.context.time.time-s),ni&&console.log(`Current latency: ${(this._currentDelay*1e3).toFixed()} ms`,"Clients in room: "+this._currentInRoom?.length);break}const t=e.data;t&&(this._state[t.guid]=t);let i=this._listeners[e.key];if(i){i=[...i];for(const n of i)try{n(e.data)}catch(s){console.error('Error invoking callback for "'+e.key+'"',s)}}}toMessage(e,t){return{key:e,data:t}}sendWithWebsocket(e,t,i=fn.OnRoomJoin){if(!this._ws){const s=this._waitingForSocket[i]||[];s.push(()=>this.sendWithWebsocket(e,t,i)),this._waitingForSocket[i]=s;return}const n=JSON.stringify(this.toMessage(e,t));ni&&console.log(">>",e),this._ws.send(n)}onSendQueued(e){const t=this._waitingForSocket[e];if(t){for(const i of t)i();t.length=0}}}const Jl=w("debugwebxr");class ig{controllerStates=[];userId;context;userStateEvtName;constructor(e,t){this.userId=e,this.context=t,this.userStateEvtName="xr-sync-user-state-"+e,this.context.connection.beginListen(this.userStateEvtName,this.onReceivedControllerState)}dispose(){this.context.connection.stopListen(this.userStateEvtName,this.onReceivedControllerState)}onReceivedControllerState=e=>{Jl&&console.log(`XRSync: Received change for ${this.userId}: ${e.type} ${e.handedness}; tracked=${e.isTracking}`);let t=!1;for(let i=0;i<this.controllerStates.length;i++)if(this.controllerStates[i].index===e.index){this.controllerStates[i]=e,t=!0;break}t||this.controllerStates.push(e)};update(e){if(this.context.connection.isConnected!=!1){for(let t=this.controllerStates.length-1;t>=0;t--){const i=this.controllerStates[t];let n=!1;for(let s=0;s<e.controllers.length;s++)e.controllers[s].index===i.index&&(n=!0);n||(Jl&&console.log(`XRSync: ${i.type} ${i.handedness} removed`,i.index),this.controllerStates.splice(t,1),this.sendControllerRemoved(i))}for(const t of e.controllers)this.updateControllerStates(t)}}onExitXR(e){for(const t of this.controllerStates)this.sendControllerRemoved(t);this.controllerStates.length=0}sendControllerRemoved(e){e.isTracking=!1,e.guid="",this.context.connection.send(this.userStateEvtName,e),this.context.connection.sendDeleteRemoteState(e.guid)}updateControllerStates(e){const t=this.controllerStates.find(i=>i.index===e.index);if(t){let i=!1;i||=t.isTracking!=e.isTracking,i&&(t.isTracking=e.isTracking,this.context.connection.send(this.userStateEvtName,t))}else{const i={guid:this.userId+"-"+e.index,isTracking:e.isTracking,handedness:e.side,index:e.index,type:e.hand?"hand":"controller"};this.controllerStates.push(i),this.context.connection.send(this.userStateEvtName,i),Jl&&console.log(`XRSync: ${i.type} ${i.handedness} added`,i.index)}}}class w_{hasState(e){return e?this._states.has(e):!1}isTracking(e,t){if(!e)return;const i=this._states.get(e);return i?i.controllerStates.find(n=>n.handedness===t)?.isTracking||!1:void 0}getDeviceType(e,t){if(!e)return;const i=this._states.get(e);return i?i.controllerStates.find(n=>n.handedness===t)?.type||"unknown":void 0}context;constructor(e){this.context=e,this.context.connection.beginListen(te.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(te.LeftRoom,this.onLeftRoom),this.context.connection.beginListen(te.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.beginListen(te.UserLeftRoom,this.onOtherUserLeftRoom)}destroy(){this.context.connection.stopListen(te.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(te.LeftRoom,this.onLeftRoom),this.context.connection.stopListen(te.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.stopListen(te.UserLeftRoom,this.onOtherUserLeftRoom)}onJoinedRoom=()=>{if(this.context.connection.connectionId){this._states.has(this.context.connection.connectionId)||(Jl&&console.log("XRSync: Local user joined room",this.context.connection.connectionId),this._states.set(this.context.connection.connectionId,new ig(this.context.connection.connectionId,this.context)));for(const e of this.context.connection.usersInRoom())this._states.has(e)||this._states.set(e,new ig(e,this.context))}};onLeftRoom=()=>{this.context.connection.connectionId&&(this._states.has(this.context.connection.connectionId)||(this._states.get(this.context.connection.connectionId)?.dispose(),this._states.delete(this.context.connection.connectionId)))};onOtherUserJoinedRoom=e=>{const t=e.userId;this._states.has(t)||(Jl&&console.log("XRSync: Remote user joined room",t),this._states.set(t,new ig(t,this.context)))};onOtherUserLeftRoom=e=>{const t=e.userId;this._states.has(t)||(this._states.get(t)?.dispose(),this._states.delete(t))};_states=new Map;onUpdate(e){this.context.connection.isConnected&&this.context.connection.connectionId&&this._states.get(this.context.connection.connectionId)?.update(e)}onExitXR(e){this.context.connection.isConnected&&this.context.connection.connectionId&&this._states.get(this.context.connection.connectionId)?.onExitXR(e)}}class x_{_fadeToColorQuad;_fadeToColorMaterial;constructor(){this._fadeToColorMaterial=new xe({color:0,transparent:!0,depthTest:!1,fog:!1,side:vi}),this._fadeToColorQuad=new H(new In(10,10),this._fadeToColorMaterial)}dispose(){this._fadeToColorQuad.geometry.dispose(),this._fadeToColorMaterial.dispose()}update(e,t){const i=this._fadeToColorQuad,n=this._fadeToColorMaterial;i.parent!==e&&n.opacity>0?e.add(i):n.opacity===0&&i.removeFromParent(),i.layers.set(2),i.material=this._fadeToColorMaterial,i.position.z=-1,i.renderOrder=1/0;const s=this._requestedFadeValue;n.opacity=D.lerp(n.opacity,s,t/.03),Math.abs(n.opacity-s)<=.01&&this._transitionResolve&&(this._transitionResolve(),this._transitionResolve=null,this._transitionPromise=null,this._requestedFadeValue=0)}remove(){this._fadeToColorQuad.removeFromParent()}fadeTransition(){if(this._transitionPromise)return this._transitionPromise;this._requestedFadeValue=1;const e=new Promise(t=>{this._transitionResolve=t});return this._transitionPromise=e,e}_requestedFadeValue=0;_transitionPromise=null;_transitionResolve=null}var ur=(o=>(o[o.Quad=0]="Quad",o[o.Cube=1]="Cube",o[o.Sphere=2]="Sphere",o[o.Cylinder=3]="Cylinder",o[o.RoundedCube=10]="RoundedCube",o))(ur||{});class pr{static createText(e,t){let i=null;const n=t?.font||DO(t?.familyFamily||null);n instanceof fC?i=this.#t(e,n,t):i==null&&(i=new un);const s=t?.color||16777215,r=new H(i,t?.material??new ut({color:s}));return this.applyDefaultObjectOptions(r,t),n instanceof Promise?n.then(a=>{r.geometry=this.#t(e,a,t),t?.onGeometry&&t.onGeometry(r)}):t?.onGeometry&&t.onGeometry(r),r}static#t(e,t,i){const n=i?.depth||.1;return new yC(e,{font:t,size:1,depth:n,height:n,bevelEnabled:i?.bevel||!1,bevelThickness:.01,bevelOffset:.01,bevelSize:.01})}static createOccluder(e){const t=new xe({colorWrite:!1,depthWrite:!0,side:vi});return this.createPrimitive(e,{material:t})}static createPrimitive(e,t){let i;const n=t?.color||16777215;switch(e){case"Quad":case 0:{const s=new In(1,1,1,1),r=t?.material??new ut({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new H(s,r),i.name="Quad"}break;case"Cube":case 1:{const s=new ma(1,1,1),r=t?.material??new ut({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new H(s,r),i.name="Cube"}break;case 10:case"RoundedCube":{const s=jO(1,1,1,.1,2),r=t?.material??new ut({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new H(s,r),i.name="RoundedCube"}break;case"Sphere":case 2:{const s=new od(.5,16,16),r=t?.material??new ut({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new H(s,r),i.name="Sphere"}break;case"Cylinder":case 3:{const s=new L0(.5,.5,1,32),r=t?.material??new ut({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new H(s,r),i.name="Cylinder"}break;case"ShaderBall":i=new os,i.name="ShaderBall",BO(i,t);break}return this.applyDefaultObjectOptions(i,t),i}static createSprite(e){const t=new Z1({color:16777215});e?.texture&&"map"in t&&(t.map=e.texture);const i=new J1(t);return this.applyDefaultObjectOptions(i,e),i}static applyDefaultObjectOptions(e,t){e.receiveShadow=!0,e.castShadow=!0,t?.name&&(e.name=t.name),t?.position&&(Array.isArray(t.position)?e.position.set(t.position[0],t.position[1],t.position[2]):e.position.set(t.position.x||0,t.position.y||0,t.position.z||0)),t?.rotation&&(Array.isArray(t.rotation)?e.rotation.set(t.rotation[0],t.rotation[1],t.rotation[2]):e.rotation.set(t.rotation.x||0,t.rotation.y||0,t.rotation.z||0)),t?.scale&&(typeof t.scale=="number"?e.scale.set(t.scale,t.scale,t.scale):Array.isArray(t.scale)?e.scale.set(t.scale[0],t.scale[1],t.scale[2]):e.scale.set(t.scale.x||1,t.scale.y||1,t.scale.z||1)),t?.receiveShadow!=null&&(e.receiveShadow=t.receiveShadow),t?.castShadow!=null&&(e.castShadow=t.castShadow),t?.parent&&t.parent.add(e)}}function jO(o,e,t,i,n){const s=new eS,r=1e-5,a=i-r;s.absarc(r,r,r,-Math.PI/2,-Math.PI,!0),s.absarc(r,e-a*2,r,Math.PI,Math.PI/2,!0),s.absarc(o-a*2,e-a*2,r,Math.PI/2,0,!0),s.absarc(o-a*2,r,r,0,-Math.PI/2,!0);const l=new tS(s,{bevelEnabled:!0,bevelSegments:n*2,steps:1,bevelSize:a,bevelThickness:i,curveSegments:n,UVGenerator:{generateTopUV:(c,h)=>{const d=[];for(let p=0;p<h.length;p+=3)d.push(new J(h[p]/o,h[p+1]/e));return d},generateSideWallUV:(c,h,d,p,m,f)=>{const g=[];return g.push(new J(h[d]/o,h[d+1]/e)),g.push(new J(h[p]/o,h[p+1]/e)),g.push(new J(h[m]/o,h[m+1]/e)),g.push(new J(h[f]/o,h[f+1]/e)),g}}});return l.scale(1,1,1-i),l.center(),l.index||l.setIndex(Array.from({length:l.attributes.position.count},(c,h)=>h)),l.computeVertexNormals(),l}const Ld=new Map;function DO(o){let e="";switch(o){default:case"OpenSans":e="https://cdn.needle.tools/static/fonts/facetype/Open Sans_Regular_ascii.json";break;case"Helvetiker":e="https://raw.githubusercontent.com/mrdoob/three.js/master/examples/fonts/helvetiker_regular.typeface.json";break}if(Ld.has(e)){const n=Ld.get(e);if(n)return n}const t=new bC,i=new Promise((n,s)=>{t.load(e,r=>{Ld.set(e,r),n(r)},void 0,s)});return Ld.set(e,i),i}let ng=!1,og=null;function BO(o,e){if(og===null){const t="https://cdn.needle.tools/static/models/shaderball.glb",i=new fo,n=pm(null);i.setDRACOLoader(n.dracoLoader),i.setKTX2Loader(n.ktx2Loader),ng=!0,og=i.loadAsync(t).then(s=>{const r=s.scene;return r.position.y-=.5,r}).catch(s=>(console.warn("Failed to load shaderball mesh: "+s.message),C_())).finally(()=>{ng=!1})}if(ng){const t=C_();t.name="ShaderBall-Placeholder";const i=t.children[0];i?.type==="Mesh"&&S_(i,e),o.add(t)}og.then(t=>{o.children.forEach(s=>{s.name==="ShaderBall-Placeholder"&&o.remove(s)});const i=t.clone(),n=i.children[0];n?.type==="Mesh"&&(n.geometry.attributes.tangent||n.geometry.computeTangents(),S_(n,e)),o.add(i)})}function S_(o,e){if(e?.color||e?.material||e?.texture){const t=e?.material??o.material?.clone()??new ut;e.color&&"color"in t&&t.color instanceof ne&&t.color.set(e.color),e?.texture&&"map"in t&&(t.map=e.texture),o.material=t}}function C_(){return new os().add(pr.createPrimitive("Sphere",{material:new xe({transparent:!0,opacity:.1})}))}class Tl{static _active=null;static get active(){return this._active}static _requestInFlight=!1;static async start(e,t){if(this._active)return console.error("Cannot start a new XR session while one is already active"),null;if(this._requestInFlight)return console.error("Cannot start a new XR session while a request is already in flight"),null;if("xr"in navigator&&navigator.xr){if(!t)return console.error("XRSessionInit must be provided"),null;this._requestInFlight=!0;const i=await navigator.xr.requestSession(e,t);return i.addEventListener("end",()=>{this._active=null}),this._requestInFlight?(this._requestInFlight=!1,this._active=new Tl(e,t,i),this._active):(i.end(),null)}return null}static async handoff(){return this._active?this._active.handoff():null}static async stop(){this._requestInFlight=!1,this._active&&(await this._active.end(),await Dn(100)),this._active=null}_session;_mode;_init;get isAR(){return this._mode==="immersive-ar"}_renderer;_camera;_scene;constructor(e,t,i){this._mode=e,this._init=t,this._session=i,this._session.addEventListener("end",this.onEnd),this._renderer=new er({alpha:!0}),this._renderer.setAnimationLoop(this.onFrame),this._renderer.xr.setSession(i),this._renderer.xr.enabled=!0,this._camera=new de,this._scene=new yi,this._scene.fog=new j0(4473924,10,250),this._scene.add(this._camera),this.setupScene()}end(){return this._session?this._session.end():Promise.resolve()}async handoff(){if(!this._session)throw new Error("Cannot handoff a session that has already ended");const e={session:this._session,mode:this._mode,init:this._init};return await this.onBeforeHandoff(),this.onEnd(),this._session=null,e}onEnd=()=>{this._session?.removeEventListener("end",this.onEnd),this._renderer.setAnimationLoop(null),this._renderer.dispose(),this._scene.clear()};_lastTime=0;onFrame=(e,t)=>{const i=e-this._lastTime;this.update(e,i),this._camera.parent!==this._scene&&this._scene.add(this._camera),this._renderer.render(this._scene,this._camera)};async onBeforeHandoff(){await Dn(1e3),this._scene.clear()}_objects=[];setupScene(){this._scene.background=new ne(0),this._scene.add(new Jp(5,10,1118481,1118481));const e=new em(16777215,1);e.position.set(0,20,0),e.castShadow=!1,this._scene.add(e);const t=new em(16777215,1);t.position.set(0,-1,0),t.castShadow=!1,this._scene.add(t);const i=new tm(16777215,1,100,1);i.position.set(0,2,0),i.castShadow=!1,i.distance=200,this._scene.add(i);const n=50;for(let s=0;s<100;s++){const r=new ut({color:2236962,metalness:1,roughness:.8});this.isAR&&(r.emissive=new ne(Math.random(),Math.random(),Math.random()),r.emissiveIntensity=Math.random());const a=D.random(0,1)>.5?ur.Sphere:ur.Cube,l=pr.createPrimitive(a,{material:r});l.position.x=D.random(-n,n),l.position.y=D.random(-2,n),l.position.z=D.random(-n,n),l.rotation.x=D.random(0,Math.PI*2),l.rotation.y=D.random(0,Math.PI*2),l.rotation.z=D.random(0,Math.PI*2),l.scale.multiplyScalar(.5+Math.random()*10);const c=l.position.distanceTo(this._camera.position)-l.scale.x;c<1&&l.position.multiplyScalar(1+1/c),this._objects.push(l),this._scene.add(l)}}update(e,t){const i=e*4e-4;for(let n=0;n<this._objects.length;n++){const s=this._objects[n];s.position.y+=Math.sin(i+n*.5)*.005,s.rotateY(.002)}}}var ec;(o=>{const e=[];function t(){if(!e?.length)return!1;for(const s of e)s.exportAndOpen();return!0}o.exportAndOpen=t;function i(s){e.push(s)}o.registerExporter=i;function n(s){if(!e)return;const r=e.indexOf(s);r>=0&&e.splice(r,1)}o.unregisterExporter=n})(ec||(ec={}));const He=w("debugwebxr"),P_=w("stats");let sg=0;function FO(o){let e=null;const t=o;return t.getAROverlayContainer?e=t.getAROverlayContainer():e=o,e}UO();async function UO(){if(w("debugasap")){let o=globalThis["needle:XRSession"];if(o instanceof Promise){delete globalThis["needle:XRSession"],ue.addContextCreatedCallback(async e=>{if(!o)return;ar(!0);const t=await o;if(t){const i=K.getDefaultSessionInit("immersive-vr");K.setSession("immersive-vr",t,i,e.context)}else console.error("NeedleXRSession: ASAP session was rejected");o=void 0});return}}if("xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent)){console.warn("WebXRViewer does not support addEventListener");return}navigator.xr?.addEventListener("sessiongranted",async()=>{ar(!0),console.log("Received Session Granted..."),await Dn(100);const o=sessionStorage.getItem("needle_xr_session_mode"),e=sessionStorage.getItem("needle_xr_session_init")??null,t=e?JSON.parse(e):null;let i=null;if(O_()&&(await Tl.start(o||"immersive-vr",t||K.getDefaultSessionInit("immersive-vr")),await WO(),i=await Tl.handoff()),i)K.setSession(i.mode,i.session,i.init,z.Current);else if(o&&e){console.log("Session Granted: Restore last session");const n=JSON.parse(e);K.start(o,n).catch(s=>console.warn(s))}else K.start("immersive-vr").catch(n=>console.warn("Session Granted failed:",n))},{once:!0})}}function zO(o,e){sessionStorage.setItem("needle_xr_session_mode",o),sessionStorage.setItem("needle_xr_session_init",JSON.stringify(e))}function NO(){sessionStorage.removeItem("needle_xr_session_mode"),sessionStorage.removeItem("needle_xr_session_init")}const rg=new Set;ue.registerCallback(he.ContextCreationStart,async o=>{rg.add(o.context)}),ue.registerCallback(he.ContextCreated,async o=>{rg.delete(o.context);const e=o.context?.domElement.getAttribute("autostart")||null;VO(e)});function O_(){return rg.size>0}function WO(){return new Promise(o=>{const e=Date.now(),t=setInterval(()=>{(!O_()||Date.now()-e>6e4)&&(clearInterval(t),o())},100)})}G.isDesktop()&&E()&&window.addEventListener("keydown",o=>{(o.key==="x"||o.key==="Escape")&&K.active&&K.stop()});function VO(o){if(o)switch(o?.toLowerCase()){case"ar":Tn.registerWaitForInteraction(()=>{K.start("ar")});break}}const jd=Symbol("initial-fov");class K{static _sync=null;static getXRSync(e){return this._sync||(this._sync=new w_(e)),this._sync}static get currentSessionRequest(){return this._currentSessionRequestMode}static _currentSessionRequestMode=null;static get active(){return this._activeSession}static get activeMode(){return this._activeSession?.mode??null}static get xrSystem(){return"xr"in navigator?navigator.xr:void 0}static isXRSupported(){return Promise.all([this.isVRSupported(),this.isARSupported()]).then(e=>e.some(t=>t)).catch(()=>!1)}static isVRSupported(){return this.isSessionSupported("immersive-vr")}static isARSupported(){return this.isSessionSupported("immersive-ar")}static isSessionSupported(e){return this.xrSystem?.isSessionSupported(e).catch(t=>(He&&console.error(t),!1))??Promise.resolve(!1)}static _currentSessionRequest;static _activeSession;static onSessionRequestStart(e){this._sessionRequestStartListeners.push(e)}static offSessionRequestStart(e){const t=this._sessionRequestStartListeners.indexOf(e);t>=0&&this._sessionRequestStartListeners.splice(t,1)}static _sessionRequestStartListeners=[];static onSessionRequestEnd(e){this._sessionRequestEndListeners.push(e)}static offSessionRequestEnd(e){const t=this._sessionRequestEndListeners.indexOf(e);t>=0&&this._sessionRequestEndListeners.splice(t,1)}static _sessionRequestEndListeners=[];static onXRSessionStart(e){this._xrStartListeners.push(e)}static offXRSessionStart(e){const t=this._xrStartListeners.indexOf(e);t>=0&&this._xrStartListeners.splice(t,1)}static _xrStartListeners=[];static onXRSessionEnd(e){this._xrEndListeners.push(e)}static offXRSessionEnd(e){const t=this._xrEndListeners.indexOf(e);t>=0&&this._xrEndListeners.splice(t,1)}static _xrEndListeners=[];static onControllerAdded(e){this._controllerAddedListeners.push(e)}static offControllerAdded(e){const t=this._controllerAddedListeners.indexOf(e);t>=0&&this._controllerAddedListeners.splice(t,1)}static _controllerAddedListeners=[];static onControllerRemoved(e){this._controllerRemovedListeners.push(e)}static offControllerRemoved(e){const t=this._controllerRemovedListeners.indexOf(e);t>=0&&this._controllerRemovedListeners.splice(t,1)}static _controllerRemovedListeners=[];static offerSession(e,t,i){return"xr"in navigator&&navigator.xr&&"offerSession"in navigator.xr?(typeof navigator.xr.offerSession=="function"&&(console.log("WebXR offerSession is available - requesting mode: "+e),t=="default"&&(t=this.getDefaultSessionInit(e)),navigator.xr.offerSession(e,{...t}).then(n=>K.setSession(e,n,t,i)).catch(n=>{console.log("XRSession offer rejected (perhaps because another call to offerSession was made or a call to requestSession was made)")})),!0):!1}static getDefaultSessionInit(e){switch(e){case"immersive-ar":const t=["anchors","local-floor","layers","dom-overlay","hit-test","unbounded"];return G.isVisionOS()||t.push("hand-tracking"),{optionalFeatures:t};case"immersive-vr":const i=["local-floor","bounded-floor","high-fixed-foveation-level","layers"];return G.isVisionOS()||i.push("hand-tracking"),{optionalFeatures:i};default:return console.warn("No default session init for mode",e),{}}}static async start(e,t,i){if(G.isiOS()){if(e==="ar")if(await this.isARSupported())e="immersive-ar";else return ec.exportAndOpen(),null}else e=="ar"&&(e="immersive-ar");if(E()&&w("debugxrpreroom"))return console.warn("Debug: Starting temporary XR session"),await Tl.start(e,t||K.getDefaultSessionInit(e)),null;if(this._currentSessionRequest)return console.warn("A XRSession is already being requested"),(He||E())&&ge("A XRSession is already being requested"),this._currentSessionRequest.then(()=>this._activeSession);if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;if(i||(i=z.Current),i||(i=ue.All[0]),!i)throw new Error("No Needle Engine Context found");switch(t||(t={}),e){case"immersive-ar":{if(await this.xrSystem?.isSessionSupported("immersive-ar")!==!0)return console.error(e+" is not supported by this browser."),null;const r=this.getDefaultSessionInit(e),a=FO(i.domElement);a&&!G.isQuest()&&(r.domOverlay={root:a},r.optionalFeatures.push("dom-overlay")),t={...r,...t}}break;case"immersive-vr":{if(await this.xrSystem?.isSessionSupported("immersive-vr")!==!0)return console.error(e+" is not supported by this browser."),null;t={...this.getDefaultSessionInit(e),...t}}break;default:console.warn("No default session init for mode",e);break}t.optionalFeatures??=[],t.requiredFeatures??=[],await Tl.stop();const n=e=="immersive-ar"?i.scripts_immersive_ar:i.scripts_immersive_vr;He?console.log(`%cRequesting ${e} session`,"font-weight:bold;",t,n):console.log(`%cRequesting ${e} session`,"font-weight:bold;");for(const r of n)r.onBeforeXR&&r.onBeforeXR(e,t);for(const r of this._sessionRequestStartListeners)r({mode:e,init:t});He&&Te("Requesting "+e+" session ("+Date.now()+")"),this._currentSessionRequest=navigator?.xr?.requestSession(e,t),this._currentSessionRequestMode=e;const s=await this._currentSessionRequest?.catch(r=>{console.error(r,"Code: "+r.code),r.code===9&&ge("Make sure your device has the required permissions (e.g. camera access)"),console.log("If the specified XR configuration is not supported (e.g. entering AR doesnt work) - make sure you access the website on a secure connection (HTTPS) and your device has the required permissions (e.g. camera access)"),location.protocol==="http:"&&ge("XR requires a secure connection (HTTPS)")});this._currentSessionRequest=void 0,this._currentSessionRequestMode=null;for(const r of this._sessionRequestEndListeners)r({mode:e,init:t,newSession:s||null});return s?this.setSession(e,s,t,i):(console.warn("XR Session request was rejected"),null)}static setSession(e,t,i,n){if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;const s=e=="immersive-ar"?n.scripts_immersive_ar:n.scripts_immersive_vr;return this._activeSession=new K(e,t,n,{scripts:s,controller_added:this._controllerAddedListeners,controller_removed:this._controllerRemovedListeners,init:i}),t.addEventListener("end",this.onEnd),He?console.log(`%cStarted ${e} session`,"font-weight:bold;",s):console.log(`%cStarted ${e} session`,"font-weight:bold;"),this._activeSession}static $_stop_request=Symbol();static stop(){const e=this._activeSession;e&&(e[this.$_stop_request]===void 0?(He&&console.log("[NeedleXRSession] Stopping XR Session... (new)"),e[this.$_stop_request]=setTimeout(()=>{e.end()})):He&&console.warn("[NeedleXRSession] XR Session stop already requested"))}static onEnd=()=>{He&&console.log("XR Session ended"),this._activeSession=null};context;get sync(){return K._sync}get running(){return!this._ended&&this.session!=null}session;mode;get interactionMode(){return this.session.interactionMode}get visibilityState(){return this.session.visibilityState}get isVisibleBlurred(){return this.session.visibilityState==="visible-blurred"}get isSystemKeyboardSupported(){return this.session.isSystemKeyboardSupported}get environmentBlendMode(){return this.session.environmentBlendMode}get frame(){return this.context.xrFrame}controllers=[];get leftController(){return this.controllers.find(e=>e.side==="left")}get rightController(){return this.controllers.find(e=>e.side==="right")}getController(e){return typeof e=="number"?this.controllers[e]||null:this.controllers.find(t=>t.side===e)||null}get isPassThrough(){return!!(this.environmentBlendMode!=="opaque"&&this.interactionMode==="world-space"||this.mode==="immersive-ar"&&this.environmentBlendMode!=="opaque"&&this.controllers.some(e=>e.inputSource.targetRayMode==="tracked-pointer")||E()&&G.isDesktop()&&this.mode==="immersive-ar")}get isAR(){return this.mode==="immersive-ar"}get isVR(){return this.mode==="immersive-vr"}get isScreenBasedAR(){return this.isAR&&!this.isPassThrough}get posePosition(){return this._transformPosition}get poseOrientation(){return this._transformOrientation}get referenceSpace(){return this.context.renderer.xr.getReferenceSpace()}get viewerPose(){return this._viewerPose}get isTrackingImages(){if(this.frame&&"getImageTrackingResults"in this.frame&&typeof this.frame.getImageTrackingResults=="function")try{const e=this.frame.getImageTrackingResults();for(const t of e)if(t.trackingState==="tracked")return!0}catch{return!1}return!1}get rig(){const e=this._rigs[0]??null;return e?.gameObject&&vr(e.gameObject)||e?.isActive===!1?(this.updateActiveXRRig(),this._rigs[0]??null):e}_rigScale=1;_lastRigScaleUpdate=-1;get rigScale(){return this._rigs[0]?(this._lastRigScaleUpdate!==this.context.time.frame&&(this._lastRigScaleUpdate=this.context.time.frame,this._rigScale=this._rigs[0].gameObject.worldScale.x),this._rigScale):1}addRig(e){this._rigs.indexOf(e)>=0||(e.priority===void 0&&(e.priority=0),this._rigs.push(e),this.updateActiveXRRig())}removeRig(e){const t=this._rigs.indexOf(e);t!==-1&&(this._rigs.splice(t,1),this.updateActiveXRRig())}setRigActive(e){const t=this._rigs.indexOf(e),i=this._rigs[0];this._rigs.splice(t,1),this._rigs.unshift(e),e.priority=i?.priority??0,this.updateActiveXRRig()}getUserOffsetInRig(){const e=this.context.mainCamera?.position;if(!e||!this.rig)return $(0,0,0);const t=$(e);return t.x*=-1,t.z*=-1,t.applyQuaternion(ti(this.rig.gameObject.quaternion)),t}updateActiveXRRig(){const e=this._rigs[0]??null;this._defaultRig.gameObject.parent!==this.context.scene&&this.context.scene.add(this._defaultRig.gameObject),this._defaultRig.gameObject.visible=!0,this._rigs.includes(this._defaultRig)||this._rigs.push(this._defaultRig);let t=this._rigs[0];t&&t.priority===void 0&&(t.priority=0);for(let i=1;i<this._rigs.length;i++){const n=this._rigs[i];if(n.isActive){if(vr(n.gameObject)){this._rigs.splice(i,1),i--;continue}(!t||t.isActive===!1||n.priority!==void 0&&n.priority>t.priority)&&(t=n)}}if(e!==t){const i=this._rigs.indexOf(t);i>=0&&this._rigs.splice(i,1),this._rigs.unshift(t)}He&&(e===t?console.log("Updated Active XR Rig:",t,"prev:",e):console.log("Updated Active XRRig:",t," (the same as before)"))}_rigs=[];_viewerHitTestSource=null;getHitTest(e){if(e)return this.getControllerHitTest(e);if(!this._viewerHitTestSource)return null;const t=this._viewerHitTestSource,i=this.frame.getHitTestResults(t);if(i.length>0){const n=i[0];return this.convertHitTestResult(n)}return null}getControllerHitTest(e){const t=e.getHitTestSource();if(!t)return null;const i=this.frame.getHitTestResultsForTransientInput(t);for(const n of i)if(n.inputSource===e.inputSource)for(const s of n.results)return this.convertHitTestResult(s);return null}convertHitTestResult(e){const t=this.context.renderer.xr.getReferenceSpace(),i=t&&e.getPose(t);if(i){const n=$(i.transform.position),s=ti(i.transform.orientation),r=this.context.mainCamera;if(r?.parent!==this._cameraRenderParent&&n.applyMatrix4(Pa),r?.parent){n.applyMatrix4(r.parent.matrixWorld),s.multiply($i);const a=be(r.parent);a.premultiply($i),s.premultiply(a)}return{hit:e,position:n,quaternion:s}}return null}convertSpace(e){const t=$(e.position);t.applyMatrix4(Pa);const i=ti(e.orientation);return i.premultiply($i),{position:t,quaternion:i}}_defaultRig;_xr_scripts;_xr_update_scripts=[];_inactive_scripts=[];_controllerAdded;_controllerRemoved;_originalCameraWorldPosition;_originalCameraWorldRotation;_originalCameraWorldScale;_originalCameraParent;_mainCamera=null;constructor(e,t,i,n){zO(e,n.init),this.session=t,this.mode=e,this.context=i,(He||w("console"))&&ar(!0),this._xr_scripts=[...n.scripts],this._xr_update_scripts=this._xr_scripts.filter(s=>typeof s.onUpdateXR=="function"),this._controllerAdded=n.controller_added,this._controllerRemoved=n.controller_removed,xo(this.onBefore,we.LateUpdate),this.context.pre_render_callbacks.push(this.onBeforeRender),this.context.post_render_callbacks.push(this.onAfterRender),(n.init.optionalFeatures?.includes("hit-test")||n.init.requiredFeatures?.includes("hit-test"))&&t.requestReferenceSpace("viewer").then(s=>t.requestHitTestSource?.call(t,{space:s})?.then(r=>this._viewerHitTestSource=r).catch(r=>console.error(r))).catch(s=>console.error(s)),this.context.mainCamera&&(this._originalCameraWorldPosition=Z(this.context.mainCamera,new b),this._originalCameraWorldRotation=be(this.context.mainCamera,new U),this._originalCameraWorldScale=$e(this.context.mainCamera,new b),this._originalCameraParent=this.context.mainCamera.parent,this.context.mainCamera instanceof de&&(this.context.mainCamera[jd]=this.context.mainCamera.fov)),this._defaultRig=new SO,this.context.scene.add(this._defaultRig.gameObject),this.addRig(this._defaultRig);for(let s=0;s<t.inputSources.length;s++){const r=t.inputSources[s];if(!r.handedness){console.warn("Input source in xr session has no handedness - ignoring",s);continue}this.onInputSourceAdded(r)}this.session.addEventListener("end",this.onEnd),this.session.addEventListener("inputsourceschange",s=>{for(const r of s.removed)this.disconnectInputSource(r);for(const r of s.added)this.onInputSourceAdded(r)}),this.context.xr=this,this.context.renderer.xr.setSession(this.session).then(this.onRendererSessionSet),"controllerAutoUpdate"in this.context.renderer.xr?(console.debug("Disabling three.js controllerAutoUpdate"),this.context.renderer.xr.controllerAutoUpdate=!1):He&&console.warn("controllerAutoUpdate is not available in three.js - cannot disable it")}onRendererSessionSet=()=>{this.running&&(this.context.renderer.xr.enabled=!0,this.context.renderer.xr.updateCamera(this.context.mainCamera),this.context.mainCameraComponent?.applyClearFlags())};onInputSourceAdded=e=>{if(e.targetRayMode==="screen")return;let t=0;for(let n=0;n<this.session.inputSources.length;n++)if(this.session.inputSources[n]===e){t=n;break}if(this.controllers.find(n=>n.inputSource===e)){console.debug("Controller already exists for input source",t);return}else if(this._newControllers.find(n=>n.inputSource===e)){console.debug("Controller already registered for input source",t);return}const i=new Qm(this,e,t);this._newControllers.push(i)};disconnectInputSource(e){const t=(s,r)=>{if(s.inputSource===e){He&&console.log("Disconnecting controller",s.index);const a=r.indexOf(s);a>=0&&r.splice(a,1),this.invokeControllerEvent(s,this._controllerRemoved,"removed");const l={xr:this,controller:s,change:"removed"};for(const c of this._xr_scripts)c.onXRControllerRemoved&&c.onXRControllerRemoved(l);s.onDisconnected()}},i=[...this.controllers];for(let s=i.length-1;s>=0;s--){const r=i[s];t(r,this.controllers)}const n=[...this._newControllers];for(let s=n.length-1;s>=0;s--){const r=n[s];t(r,this._newControllers)}}end(){this._ended||this.session.end().catch(e=>console.warn(e))}_ended=!1;_newControllers=[];onEnd=e=>{if(this._ended)return;this._ended=!0,console.debug("XR Session ended"),NO(),this.onAfterRender(),this.revertCustomForward(),this._didStart=!1,this._previousCameraParent=null,this.requestedCameraNearPlane=null,ds(this.onBefore,we.LateUpdate);const t=this.context.pre_render_callbacks.indexOf(this.onBeforeRender);t>=0&&this.context.pre_render_callbacks.splice(t,1);const i=this.context.post_render_callbacks.indexOf(this.onAfterRender);i>=0&&this.context.post_render_callbacks.splice(i,1),this.context.xr=null,this.context.renderer.xr.enabled=!1,this.context.pre_update_oneshot_callbacks.push(()=>{this.context.mainCameraComponent?.applyClearFlags(),this.context.mainCameraComponent?.applyClippingPlane()}),o_({session:this});for(const s of K._xrEndListeners)s({xr:this});const n=[...this.controllers];for(let s=0;s<n.length;s++)this.disconnectInputSource(n[s].inputSource);this.controllers.length=0,this._newControllers.length=0;for(const s of this._xr_scripts)s?.onLeaveXR?.({xr:this});this.sync?.onExitXR(this),this.context.mainCamera&&(this._originalCameraParent?.add(this.context.mainCamera),this._originalCameraWorldPosition&&mt(this.context.mainCamera,this._originalCameraWorldPosition),this._originalCameraWorldRotation&&pn(this.context.mainCamera,this._originalCameraWorldRotation),this._originalCameraWorldScale&&wa(this.context.mainCamera,this._originalCameraWorldScale),this.context.mainCamera instanceof de&&this.context.mainCamera[jd]&&(this.context.mainCamera.fov=this.context.mainCamera[jd],this.context.mainCamera[jd]=0)),this.context.requestSizeUpdate(),this._defaultRig.gameObject.removeFromParent(),ar(!1)};_didStart=!1;onBefore=e=>{const t=e.xrFrame;if(!t)return;this.context.xr=this,this.context.mainCameraComponent&&this.context.mainCameraComponent!==this._mainCamera&&(this._mainCamera=this.context.mainCameraComponent),this.rig?.isActive==!1&&(He&&console.warn("Latest rig is not active - trying to activate a different rig",this.rig),this.updateActiveXRRig()),this.rig&&this._mainCamera?.gameObject&&this._mainCamera?.gameObject?.parent!==this.rig.gameObject&&this.rig.gameObject.add(this._mainCamera?.gameObject),this.internalUpdateState(),this.applyCustomForward();const i={xr:this};if(this._didStart){if(this.context.new_scripts_xr.length>0){const n=[...this.context.new_scripts_xr];for(let s=0;s<n.length;s++){const r=this.context.new_scripts_xr[s];if(!r||r.destroyed||r.supportsXR?.(this.mode)==!1){this.context.new_scripts_xr.splice(s,1);continue}if(!r.activeAndEnabled){this.context.new_scripts_xr.splice(s,1),this.markInactive(r);continue}if(this.addScript(r)){this.invokeCallback_EnterXR(r);for(const a of this.controllers)this.invokeCallback_ControllerAdded(r,a)}}}}else{if(this._didStart=!0,this.mode==="immersive-vr"){const s=Wt(this.context.scene.children);if(s){const r=s.getSize($());if(r.length()>0){const a=this._defaultRig.gameObject;a.position.set(s.min.x+r.x*.5,s.min.y,s.max.z+r.z*.5+1.5);const l=s.getCenter($());l.y=a.position.y,a.lookAt(l)}}}n_({session:this}),dr();for(const s of K._xrStartListeners)s(i);const n=[...this._xr_scripts];He&&console.log("NeedleXRSession start, handle scripts:",n);for(const s of n){if(s.destroyed){this._script_to_remove.push(s);continue}if(!s.activeAndEnabled){this.markInactive(s);continue}this.invokeCallback_EnterXR(s);for(const r of this.controllers)this.invokeCallback_ControllerAdded(s,r)}}this.syncCameraCullingMask();for(const n of this.controllers)n.onUpdate(t);if(this._newControllers.length>0){const n=[...this._newControllers];this._newControllers.length=0;for(const s of n){if(!s.connected){console.warn("New controller is not connected",s);continue}this.controllers.push(s);for(const r of this._xr_scripts){if(r.destroyed){this._script_to_remove.push(r);continue}r.activeAndEnabled!==!1&&this.invokeCallback_ControllerAdded(r,s)}}this.controllers.sort((s,r)=>s.index-r.index)}He&&this.context.time.frame%30===0&&this.controllers.length<=0&&this.session.inputSources.length>0&&(ar(!0),console.error("XRControllers are not added but inputSources are present"));for(const n of this._xr_update_scripts){if(n.destroyed===!0){this._script_to_remove.push(n);continue}if(n.activeAndEnabled===!1){this.markInactive(n);continue}n.onUpdateXR&&n.onUpdateXR(i)}if(this.handleInactiveScripts(),this._script_to_remove.length>0){const n=[...new Set(this._script_to_remove)];this._script_to_remove.length=0;for(const s of n)!s.destroyed&&this.running&&s.onLeaveXR?.(i),this.removeScript(s)}this.sync?.onUpdate(this),this.onRenderDebug()};onRenderDebug(){if(He)for(const e of this.controllers)e.onRenderDebug();if((He||P_)&&this.rig&&(sg++,sg>=20)){const e=this.rig.gameObject.worldPosition,t=this.rig.gameObject.worldForward;e.add(t.multiplyScalar(1.5));const i=this.rig.gameObject.worldUp;e.add(i.multiplyScalar(2.5));let n="";if(n+=`${this.context.time.smoothedFps.toFixed(0)} FPS`,n+=`, calls: ${this.context.renderer.info.render.calls}, tris: ${this.context.renderer.info.render.triangles.toLocaleString()}`,He||P_)for(const s of this.controllers)n+=`
165
+ ${s.hand?"hand":"ctrl"} ${s.inputSource.handedness}[${s.index}] con:${s.connected} tr:${s.isTracking} hts:${s.hasHitTestSource?"yes":"no"}`;sg=0,F.DrawLabel(e,n,void 0,1/60*20)}}onBeforeRender=()=>{this.context.mainCamera&&(this.updateFade(this.context.mainCamera),this.requestedCameraNearPlane!==null&&this.context.mainCamera instanceof de&&(this.context.mainCamera.near=this.requestedCameraNearPlane,this.requestedCameraNearPlane=null))};onAfterRender=()=>{if(this.onUpdateFade_PostRender(),G.isDesktop()||!this._renderOnceOnDevice){const e=this.context.renderer;if(e.xr.isPresenting&&this.context.mainCamera){this._renderOnceOnDevice=!0;const t=e.xr.enabled,i=e.getRenderTarget(),n=this.context.scene.background;e.xr.enabled=!1,e.setRenderTarget(null),this.isPassThrough&&(this.context.scene.background=null),this.context.composer?this.context.composer.render(this.context.time.deltaTime):e.render(this.context.scene,this.context.mainCamera),e.xr.enabled=t,e.setRenderTarget(i),this.context.scene.background=n}}};addScript(e){return this._xr_scripts.includes(e)?!1:(He&&console.log("Register new XRScript",e),this._xr_scripts.push(e),typeof e.onUpdateXR=="function"&&this._xr_update_scripts.push(e),!0)}markInactive(e){if(!(this._inactive_scripts.indexOf(e)>=0)){this.removeScript(e,!1),this._inactive_scripts.push(e);for(const t of this.controllers)this.invokeCallback_ControllerRemoved(e,t);this.invokeCallback_LeaveXR(e)}}handleInactiveScripts(){if(this._inactive_scripts.length>0)for(let e=this._inactive_scripts.length-1;e>=0;e--){const t=this._inactive_scripts[e];if(t.activeAndEnabled){this._inactive_scripts.splice(e,1),this.addScript(t),this.invokeCallback_EnterXR(t);for(const i of this.controllers)this.invokeCallback_ControllerAdded(t,i)}}}_script_to_remove=[];removeScript(e,t=!0){He&&console.log("Remove XRScript",e);const i=this._xr_scripts.indexOf(e);i>=0&&this._xr_scripts.splice(i,1);const n=this._xr_update_scripts.indexOf(e);if(n>=0&&this._xr_update_scripts.splice(n,1),t){const s=this._inactive_scripts.indexOf(e);s>=0&&this._inactive_scripts.splice(s,1)}}invokeCallback_EnterXR(e){e.onEnterXR&&e.onEnterXR({xr:this})}invokeCallback_ControllerAdded(e,t){e.onXRControllerAdded&&e.onXRControllerAdded({xr:this,controller:t,change:"added"})}invokeCallback_ControllerRemoved(e,t){e.onXRControllerRemoved&&e.onXRControllerRemoved({xr:this,controller:t,change:"removed"})}invokeCallback_LeaveXR(e){e.onLeaveXR&&!e.destroyed&&e.onLeaveXR({xr:this})}syncCameraCullingMask(){const e=this.context.xrCamera,t=this.context.mainCameraComponent?.cullingMask;if(e&&t!==void 0){for(const i of e.cameras)i.layers.mask=t;e.layers.mask=t}else if(e){for(const i of e.cameras)i.layers.enableAll();e.layers.enableAll()}}invokeControllerEvent(e,t,i){for(let n=t.length-1;n>=0;n--){const s=t[n];if(s)try{s({xr:this,controller:e,change:i})}catch(r){console.error(r)}}}_camera;_cameraRenderParent=new O().rotateY(Math.PI);_previousCameraParent;_customforward=!0;originalCameraNearPlane;requestedCameraNearPlane=null;applyCustomForward(){if(this.context.mainCamera&&this._customforward){this._camera=this.context.mainCamera,this._camera.parent!==this._cameraRenderParent&&(this._previousCameraParent=this._camera.parent,this._previousCameraParent?.add(this._cameraRenderParent)),this._cameraRenderParent.name="XR Camera Render Parent",this._cameraRenderParent.add(this._camera);{let e=.02;const t=.001;if(this.rig){const i=$e(this.rig.gameObject);e*=i.x}this._camera instanceof de&&Math.abs(this._camera.near-e)>t&&(this.isAR?this.originalCameraNearPlane=this._camera.near:this._camera.near=e,He&&console.debug(`Setting camera near plane to ${e} (was ${this.originalCameraNearPlane}) to account for XR rendering scale`))}}}revertCustomForward(){this._camera&&this._previousCameraParent&&this._previousCameraParent.add(this._camera),this._previousCameraParent=null,this._camera instanceof de&&this.originalCameraNearPlane!=null&&(this._camera.near=this.originalCameraNearPlane,this.originalCameraNearPlane=void 0)}_viewerPose;_transformOrientation=new U;_transformPosition=new b;internalUpdateState(){const e=this.context.renderer.xr.getReferenceSpace();if(!e){this._viewerPose=void 0;return}if(this._viewerPose=this.frame.getViewerPose(e),this._viewerPose){const t=this._viewerPose.transform;this._transformPosition.set(t.position.x,t.position.y,t.position.z),this._transformOrientation.set(t.orientation.x,t.orientation.y,t.orientation.z,t.orientation.w)}}_transition;get transition(){return this._transition||(this._transition=new x_),this._transition}fadeTransition(){return this._transition||(this._transition=new x_),this._transition.fadeTransition()}updateFade(e){this._transition&&e instanceof de&&this._transition.update(e,this.context.time.deltaTime)}onUpdateFade_PostRender(){this._transition?.remove()}}const ag=w("debugwebxr");class k_{static tryFindAvatarObjects(e,t,i){if(i.head&&i.leftHand&&i.rightHand)return;const n=e.name.toLocaleLowerCase();!i.head&&n.includes("head")&&(ag&&console.log("FOUND AVATAR HEAD",e.name),i.head=new ie("",t,e)),n.includes("hand")&&(!i.leftHand&&n.includes("left")&&(ag&&console.log("FOUND AVATAR LEFT HAND",e.name),i.leftHand=new ie("",t,e)),!i.rightHand&&n.includes("right")&&(ag&&console.log("FOUND AVATAR RIGHT HAND",e.name),i.rightHand=new ie("",t,e)));for(let s=0;s<e.children.length;s++){if(i.head&&i.leftHand&&i.rightHand)return;const r=e.children[s];this.tryFindAvatarObjects(r,t,i)}}}const It=new b,M_=new b,R_=new U,$O=w("debuggizmos"),yn=8947848,lg=32;class F{constructor(){}static enabled=!0;static isGizmo(e){return e[hg]!==void 0}static setVisible(e){for(const t of Gi.timedObjectsBuffer)t.visible=e}static DrawLabel(e,t,i=.05,n=0,s,r,a){if(!F.enabled)return null;s||(s=yn);const l=K.active?.rigScale??1,c=Gi.getTextLabel(n,t,i*l,s,r);return a instanceof O&&a.add(c),c.position.x=e.x,c.position.y=e.y,c.position.z=e.z,c}static DrawRay(e,t,i=yn,n=0,s=!0){if(!F.enabled)return;const r=Gi.getLine(n),a=r.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),It.set(t.x,t.y,t.z).multiplyScalar(999999999),a.setXYZ(1,e.x+It.x,e.y+It.y,e.z+It.z),a.needsUpdate=!0,r.material.color.set(i),r.material.depthTest=s,r.material.depthWrite=!1}static DrawDirection(e,t,i=yn,n=0,s=!0,r=1){if(!F.enabled)return;const a=Gi.getLine(n),l=a.geometry.getAttribute("position");l.setXYZ(0,e.x,e.y,e.z),t.w!==void 0?(It.set(0,0,-r),R_.set(t.x,t.y,t.z,t.w),It.applyQuaternion(R_)):(It.set(t.x,t.y,t.z),It.multiplyScalar(r)),l.setXYZ(1,e.x+It.x,e.y+It.y,e.z+It.z),l.needsUpdate=!0,a.material.color.set(i),a.material.depthTest=s,a.material.depthWrite=!1}static DrawLine(e,t,i=yn,n=0,s=!0){if(!F.enabled)return;const r=Gi.getLine(n),a=r.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),a.setXYZ(1,t.x,t.y,t.z),a.needsUpdate=!0,r.material.color.set(i),r.material.depthTest=s,r.material.depthWrite=!1,r.material.fog=!1}static DrawCircle(e,t,i,n=yn,s=0,r=!0){if(!F.enabled)return;const a=Gi.getCircle(s);a.position.set(e.x,e.y,e.z),a.scale.set(i,i,i),a.quaternion.setFromUnitVectors(this._up,It.set(t.x,t.y,t.z).normalize()),a.material.color.set(n),a.material.depthTest=r,a.material.depthWrite=!1,a.material.fog=!1}static DrawWireSphere(e,t,i=yn,n=0,s=!0){if(!F.enabled)return;const r=Gi.getSphere(t,n,!0);sr(r,e.x,e.y,e.z),r.material.color.set(i),r.material.depthTest=s,r.material.depthWrite=!1,r.material.fog=!1}static DrawSphere(e,t,i=yn,n=0,s=!0){if(!F.enabled)return;const r=Gi.getSphere(t,n,!1);sr(r,e.x,e.y,e.z),r.material.color.set(i),r.material.depthTest=s,r.material.depthWrite=!1}static DrawWireBox(e,t,i=yn,n=0,s=!0,r=void 0){if(!F.enabled)return;const a=Gi.getBox(n);a.position.set(e.x,e.y,e.z),a.scale.set(t.x,t.y,t.z),r?a.quaternion.copy(r):a.quaternion.identity(),a.material.color.set(i),a.material.depthTest=s,a.material.wireframe=!0,a.material.depthWrite=!1,a.material.fog=!1}static DrawWireBox3(e,t=yn,i=0,n=!0){if(!F.enabled)return;const s=Gi.getBox(i);s.position.copy(e.getCenter(It)),s.scale.copy(e.getSize(It)),s.material.color.set(t),s.material.depthTest=n,s.material.wireframe=!0,s.material.depthWrite=!1,s.material.fog=!1}static _up=new b(0,1,0);static DrawArrow(e,t,i=yn,n=0,s=!0,r=!1){if(!F.enabled)return;const a=Gi.getArrowHead(n);a.position.set(t.x,t.y,t.z),a.quaternion.setFromUnitVectors(this._up.set(0,1,0),It.set(t.x,t.y,t.z).sub(M_.set(e.x,e.y,e.z)).normalize());const l=It.set(t.x,t.y,t.z).sub(M_.set(e.x,e.y,e.z)).length()*.1;a.scale.set(l,l,l),a.material.color.set(i),a.material.depthTest=s,a.material.wireframe=r,this.DrawLine(e,t,i,n,s)}static DrawWireMesh(e){const t=Gi.getMesh(e.duration??0);"mesh"in e?(t.geometry=e.mesh.geometry,t.matrix.copy(e.mesh.matrixWorld)):(t.geometry=e.geometry,t.matrix.copy(e.matrix)),t.matrixAutoUpdate=!1,t.matrixWorldAutoUpdate=!1,t.material.color.set(e.color??yn),t.material.depthTest=e.depthTest??!0,t.material.wireframe=!0}}const HO=new ma(1,1,1);function cg(o=null){const e=new ne(o??14540253),t=new iS(HO);return new D0(t,new im({color:e}))}const hg=Symbol("GizmoCache");class Gi{static familyName="needle-gizmos";static ensureFont(){let e=Ce.FontLibrary.getFontFamily(this.familyName);e||(e=Ce.FontLibrary.addFontFamily(this.familyName),e.addVariant("normal","normal","https://uploads.needle.tools/include/font-msdf.json","https://uploads.needle.tools/include/font.png")?.addEventListener("ready",()=>{Ce.update()}))}static getTextLabel(e,t,i,n,s){this.ensureFont();let r=this.textLabelCache.pop(),a=1;s&&typeof s=="string"&&s?.length>=8&&s.startsWith("#")?(a=parseInt(s.substring(7),16)/255,s=s.substring(0,7),$O&&console.log(s,a)):typeof s=="object"&&s.a!==void 0&&(a=s.a);const l={boxSizing:"border-box",fontFamily:this.familyName,width:"auto",fontSize:i,color:n,lineHeight:1,backgroundColor:s??void 0,backgroundOpacity:a,textContent:t,borderRadius:.5*i,padding:.8*i,whiteSpace:"pre",offset:.05*i};if(r)r.set(l);else{r=new sb(l);const c=this,h=r;h.setText=function(d){this.set({textContent:d}),c.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(z.Current,r,e,this.textLabelCache),r}static getBox(e){let t=this.boxesCache.pop();if(!t){const i=new ma(1,1,1);t=new H(i)}return this.registerTimedObject(z.Current,t,e,this.boxesCache),t}static getLine(e){let t=this.linesCache.pop();if(!t){t=new ga;let i=t.geometry.getAttribute("position");i||(i=new pt(new Float32Array(6),3),t.geometry.setAttribute("position",i))}return t.frustumCulled=!1,this.registerTimedObject(z.Current,t,e,this.linesCache),t}static getCircle(e){let t=this.circlesCache.pop();if(!t){t=new ga;let i=t.geometry.getAttribute("position");if(!i){i=new pt(new Float32Array(lg*3),3),t.geometry.setAttribute("position",i);const n=$(0,1,0),s=$(0,0,1),r=$(s);r.cross(n).normalize();const a=$(r),l=Math.PI*2/(lg-1);for(let c=0;c<lg+1;c++){const h=l*c;n.copy(a).multiplyScalar(Math.cos(h)*1),r.copy(s).multiplyScalar(Math.sin(h)*1);const d=n.add(r);i.setXYZ(c,d.x,d.y,d.z)}}}return t.frustumCulled=!1,this.registerTimedObject(z.Current,t,e,this.circlesCache),t}static getSphere(e,t,i){let n=this.spheresCache.pop();return n||(n=new H(new od(1,8,8))),n.scale.set(e,e,e),n.material.wireframe=i,this.registerTimedObject(z.Current,n,t,this.spheresCache),n}static getArrowHead(e){let t=this.arrowHeadsCache.pop();return t||(t=new H(new L0(0,.5,1,8))),this.registerTimedObject(z.Current,t,e,this.arrowHeadsCache),t}static getMesh(e){let t=this.mesh.pop();return t||(t=new H,t.material=new xe),this.registerTimedObject(z.Current,t,e,this.mesh),t}static linesCache=[];static circlesCache=[];static spheresCache=[];static boxesCache=[];static arrowHeadsCache=[];static mesh=[];static textLabelCache=[];static registerTimedObject(e,t,i,n){if(!e){console.error("No Needle Engine context available. Did you call a Gizmos function in global scope?");return}const s=this.contextBeforeRenderCallbacks.get(e),r=this.contextPostRenderCallbacks.get(e);if(s){if(e.pre_render_callbacks[e.pre_render_callbacks.length-1]!==s){const a=e.pre_render_callbacks.indexOf(s);a>=0&&e.pre_render_callbacks.splice(a,1),e.pre_render_callbacks.push(s)}}else{const a=()=>{this.onBeforeRender(e,this.timedObjectsBuffer)};this.contextBeforeRenderCallbacks.set(e,a),e.pre_render_callbacks.push(a)}if(r){if(e.post_render_callbacks[e.post_render_callbacks.length-1]!==r){const a=e.post_render_callbacks.indexOf(r);a>=0&&e.post_render_callbacks.splice(a,1),e.post_render_callbacks.push(r)}}else{const a=()=>{this.onPostRender(e,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(e,a),e.post_render_callbacks.push(a)}t.traverse(a=>{a.layers.disableAll(),a.layers.enable(2)}),t.renderOrder=999999,t[hg]=n,t.castShadow=!1,t.receiveShadow=!1,t.isGizmo=!0,this.timedObjectsBuffer.push(t),this.timesBuffer.push(z.Current.time.realtimeSinceStartup+i),e.scene.add(t)}static timedObjectsBuffer=new Array;static timesBuffer=new Array;static contextPostRenderCallbacks=new Map;static contextBeforeRenderCallbacks=new Map;static tmuiNeedsUpdate=!1;static onBeforeRender(e,t){this.tmuiNeedsUpdate&&(this.tmuiNeedsUpdate=!1,Ce.update());for(let i=0;i<t.length;i++){const n=t[i];if(e.mainCamera&&n instanceof Ce.MeshUIBaseElement){if(vr(n))continue;const s=e.isInVR,r=!1,a=!s;$l(n,e.mainCamera,r,a)}}}static onPostRender(e,t,i){const n=e.time.realtimeSinceStartup;for(let s=t.length-1;s>=0;s--){const r=t[s];n>=i[s]-1e-6&&(t.splice(s,1),i.splice(s,1),r.removeFromParent(),vr(r)!=!0&&r[hg].push(r))}}}const Vt=w("debugphysics"),T_=new is;class us{static AllLayers=4294967295;ray;cam;screenPoint;raycaster;results;targets;recursive=!0;minDistance;maxDistance;lineThreshold;layerMask;ignore;testObject;useAcceleratedRaycast;allowSlowRaycastFallback=!0;screenPointFromOffset(e,t){this.screenPoint===void 0&&(this.screenPoint=new J),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setLayer(e){T_.set(e),this.layerMask=T_}setMask(e){this.layerMask||(this.layerMask=new is);const t=this.layerMask;t?t.mask=e:this.layerMask=e}}class dg{distance;point;object;constructor(e,t,i){this.object=e,this.distance=t,this.point=i}}class El{static _raycasting=0;static get raycasting(){return this._raycasting>0}raycastPhysicsFast(e,t=void 0,i=1/0,n=!0){return this.context.physics.engine?.raycast(e,t,{maxDistance:i,solid:n})??null}raycastPhysicsFastAndGetNormal(e,t=void 0,i=1/0,n=!0){return this.context.physics.engine?.raycastAndGetNormal(e,t,{maxDistance:i,solid:n})??null}sphereOverlapPhysics(e,t){return this.context.physics.engine?.sphereOverlap(e,t)??null}context;engine;constructor(e){this.context=e}raycaster=new sd;defaultRaycastOptions=new us;targetBuffer=new Array(1);defaultThresholds={Mesh:{},Line:{threshold:-1},LOD:{},Points:{threshold:0},Sprite:{}};sphereResults=new Array;sphereMask=new is;sphere=new rd;sphereOverlap(e,t,i=!0,n=!1,s=null){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;const r=this.sphereMask;r.enableAll(),r.disable(2);for(const a of this.context.scene.children)this.intersectSphere(a,e,t,r,this.sphereResults,i,n,s);return this.sphereResults.sort((a,l)=>a.distance-l.distance)}raycastFromRay(e,t=null){const i=t??this.defaultRaycastOptions;i.ray=e;const n=this.raycast(i);return i===this.defaultRaycastOptions&&(i.ray=void 0),n}raycast(e=null){Vt&&performance.mark("raycast.start"),e||(e=this.defaultRaycastOptions);const t=e.screenPoint??this.context.input.mousePositionRC,i=e.raycaster??this.raycaster;if(i.near=e.minDistance??0,i.far=e.maxDistance??1/0,i.params=this.defaultThresholds,e.lineThreshold===void 0&&(e.lineThreshold=-1),i.params.Line={threshold:e.lineThreshold},e.ray)i.ray.copy(e.ray);else{const a=e.cam??this.context.mainCamera;if(!a)return Vt&&console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];const l=this.context.xrCamera;this.context.isInXR&&l instanceof nS&&l.cameras.length>0?i.setFromCamera(t,l.cameras[0]):i.setFromCamera(t,a)}let n=e.targets;n||(n=this.targetBuffer,n.length=1,n[0]=this.context.scene);let s=e.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),s||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),s=this.defaultRaycastOptions.results),e.layerMask!==void 0?e.layerMask instanceof is?i.layers.mask=e.layerMask.mask:i.layers.mask=e.layerMask:(i.layers.enableAll(),i.layers.disable(2)),Vt&&console.time("raycast"),s.length=0,El._raycasting++,this.intersect(this.raycaster,n,s,e),s.sort((a,l)=>a.distance-l.distance);const r=e.ignore;return r!==void 0&&r.length>0&&(s=s.filter(a=>!r.includes(a.object))),El._raycasting--,Vt&&(console.timeEnd("raycast"),console.warn("#"+this.context.time.frame+", hits:",s?.length?[...s]:"nothing"),performance.mark("raycast.end"),performance.measure("raycast","raycast.start","raycast.end")),s}intersect(e,t,i,n){for(const s of t){if(!s||s.visible===!1||F.isGizmo(s)||n.lineThreshold!==void 0&&n.lineThreshold<0&&s instanceof ga)continue;let r=!0;const a=s,l=a.geometry;if(n.testObject){const c=n.testObject?.(s);if(c===!1)continue;c==="continue in children"&&(r=!1)}if(r&&(l&&E_(l)||(r=!1)),r){const c=q0(s);c&&(a.geometry=c);const h=i.length;let d=!0;if(n.precise===!1&&(d=!1),d||=l.getAttribute("position")?.array?.length<64,a instanceof ba&&(d=!1),!d&&qO(a,e,i)||(n.useAcceleratedRaycast!==!1?Bd.runMeshBVHRaycast(e,a,i,this.context,n):e.intersectObject(a,!1,i)),Vt&&i.length!=h){const p=i[i.length-1],m=c?8969557:7798784;F.DrawWireSphere(p.point,.1,m,1,!1),F.DrawWireMesh({mesh:s,depthTest:!1,duration:.2,color:m})}a.geometry=l}n.recursive!==!1&&this.intersect(e,s.children,i,n)}return i}tempBoundingBox=new bi;intersectSphere(e,t,i,n,s,r,a,l){let c=e&&e.isMesh&&e.layers.test(n)&&!F.isGizmo(e);c&&=e.visible,c&&=!(e instanceof ga),c&&=!(e instanceof ba);const h=e,d=h.geometry;if(c&&l){const p=l(e);if(p===!1)return;p==="continue in children"&&(c=!1)}if(d&&E_(d)||(c=!1),c){if(a){const p=this.sphere;p.center.copy(t),p.radius=i;const m=s.length;if(Bd.runMeshBVHRaycast(this.sphere,h,s,this.context,{}),m!=s.length&&!r)return}else if(d.boundingBox||d.computeBoundingBox(),d.boundingBox){h.matrixWorldNeedsUpdate&&h.updateWorldMatrix(!1,!1);const p=this.tempBoundingBox.copy(d.boundingBox).applyMatrix4(h.matrixWorld),m=this.sphere;if(m.center.copy(t),m.radius=i,m.intersectsBox(p)){const f=Z(e),g=f.distanceTo(m.center),y=new dg(e,g,f);if(s.push(y),!r)return}}}if(e.children)for(const p of e.children){const m=s.length;if(this.intersectSphere(p,t,i,n,s,r,a,l),m!=s.length&&!r)return}}}function E_(o){return!(o.index&&o.index.array.length<3)}const mr=new rd,Dd=new tr,GO=new I0;function qO(o,e,t){const i=o._computeIntersections;if(!i)return!1;let n=o["_computeIntersections:Needle"];return n||(n=o["_computeIntersections:Needle"]=function(s,r,a){const l=this,c=l.geometry.boundingSphere;if(c){if(l instanceof ba){Dd.setFromNormalAndCoplanarPoint($(0,1,0),$(0,-l.position.y,0)),Dd.applyMatrix4(l.matrixWorld,GO);const d=s.ray.intersectPlane(Dd,$());if(d){mr.copy(c),mr.applyMatrix4(l.matrixWorld);const p=$(d).sub(s.ray.origin).length(),m=mr.radius*.5;p<m&&r.push({distance:p,point:d,object:l,normal:Dd.normal.clone()})}return}mr.copy(c),mr.applyMatrix4(l.matrixWorld);const h=s.ray.intersectSphere(mr,$());if(h){const d=$(h).sub(s.ray.origin),p=d.length();if(p>mr.radius){const m=d.clone().normalize();r.push({distance:p,point:h,object:l,normal:m})}}}}),o._computeIntersections=n,e.intersectObject(o,!1,t),o._computeIntersections=i,!0}var Bd;(o=>{function e(_,v,P,R,k){if(!v.geometry||!v.geometry.hasAttribute("position"))return!1;const A=v.geometry;if(v?.isSkinnedMesh){const L=v,N=L.bvhNeedsUpdate;if(!L.staticGenerator)a(),s&&(L.staticGenerator=new s(v),L.staticGenerator.applyWorldTransforms=!1,L.staticGeometry=L.staticGenerator.generate(),A.boundsTree=r?.call(L.staticGeometry),L.staticGeometryLastUpdate=performance.now()+Math.random()*200,L.bvhNeedsUpdate=!0);else if(A.boundsTree&&(L.autoUpdateMeshBvhInterval!==void 0&&L.autoUpdateMeshBvhInterval>=0||N===!0)){const j=performance.now(),q=j-L.staticGeometryLastUpdate,Y=L.autoUpdateMeshBvhInterval??100;(N||q>Y)&&(Vt&&console.warn(`Physics: updating skinned mesh bvh for ${v.name} after ${q.toFixed(2)}ms`),L.bvhNeedsUpdate=!1,L.staticGeometryLastUpdate=j,L.staticGenerator?.generate(L.staticGeometry),A.boundsTree.refit())}}else if(!A.boundsTree){c||y();let L=!0;if((R.xr||A[m]===!1||A.getAttribute("position")?.isInterleavedBufferAttribute||A.index&&A.index?.isInterleavedBufferAttribute)&&(L=!1),L&&d){if(A[p]===void 0){let N=null;if(g.length>0){const j=g.shift();j&&!j.running&&(N=j)}if(!N&&f.length<3&&(N=new d,f.push(N)),N!=null&&!N.running){const j=v.name;Vt&&console.log("<<<< worker start",j,N),A[p]="queued",performance.mark("bvh.create.start");const q=A.clone();try{N.generate(q).then(Y=>{A[p]="done",A.boundsTree=Y}).catch(Y=>{A[p]="failed - "+Y?.message,A[m]=!1,Vt&&console.error("Failed to generate mesh bvh on worker",Y)}).finally(()=>{Vt&&console.log(">>>>> worker done",j,{hasBoundsTre:A.boundsTree!=null}),g.push(N),q.dispose(),performance.mark("bvh.create.end"),performance.measure("bvh.create (worker)","bvh.create.start","bvh.create.end")})}catch(Y){console.error("Failed to generate mesh bvh on worker",Y)}}else Vt&&console.warn("No worker available")}}else(!h||!L)&&(a(),n&&(performance.mark("bvh.create.start"),A.boundsTree=new n(A),performance.mark("bvh.create.end"),performance.measure("bvh.create","bvh.create.start","bvh.create.end")))}if(_ instanceof sd){const L=_,N=v.raycast;if(A.boundsTree)a(),i&&(v.acceleratedRaycast||(v.acceleratedRaycast=i.bind(v),Vt&&console.debug(`Physics: bind acceleratedRaycast fn to "${v.name}"`)),v.raycast=v.acceleratedRaycast);else if(Vt&&console.warn("No bounds tree found for mesh",v.name,{workerTask:A[p],hasAcceleratedRaycast:i!=null}),k.allowSlowRaycastFallback===!1)return Vt&&console.warn("Skipping raycast because no bounds tree is available and allowSlowRaycastFallback is false"),!1;const j=L.firstHitOnly;return L.firstHitOnly=!1,L.intersectObject(v,!1,P),L.firstHitOnly=j,v.raycast=N,!0}else if(_ instanceof rd){const L=A.boundsTree;if(L){const N=_;if(l.copy(v.matrixWorld).invert(),N.applyMatrix4(l),L.intersectsSphere(N)){const j=Z(v),q=j.distanceTo(N.center),Y=new dg(v,q,j);P.push(Y)}}return!0}return!1}o.runMeshBVHRaycast=e;let t=!1,i=null,n=null,s=null,r=null;function a(){t||(t=!0,import("./vendor-XJ9xiwrv.min.js").then(_=>_.index$1).then(_=>{i=_.acceleratedRaycast,n=_.MeshBVH,s=_.StaticGeometryGenerator,r=_.computeBoundsTree}).catch(_=>{(Vt||E())&&console.error("Failed to load BVH library...",_.message)}))}const l=new ee;let c=!1,h=!1,d=null;const p=Symbol("Needle:MeshBVH-Worker"),m=Symbol("Needle:MeshBVH-CanUseWorker"),f=[],g=[];function y(){c=!0,h=!0,Promise.resolve().then(()=>EI).then(_=>{d=_.GenerateMeshBVHWorker}).catch(_=>{(Vt||E())&&console.warn("Failed to setup mesh bvh worker")}).finally(()=>{h=!1})}})(Bd||(Bd={}));const A_=Symbol("gltf-loader-internal-usage-tracker"),XO=w("debugusers");class Al{get name(){return"NEEDLE_internal_usage_tracker"}static isLoading(e){return Al._loadingProcesses>0}static _loadingProcesses=0;parser;_getDependency;_loadingId;_loadedObjects=new Set;constructor(e){this.parser=e,this._getDependency=this.parser.getDependency,this._loadingId=Date.now().toString()}beforeRoot(){Al._loadingProcesses++;const e=this,t=this._getDependency;return this.parser.getDependency=function(i,n){const s=t.call(this,i,n);return s.then(r=>(r&&(e._loadedObjects.add(r),r[A_]=e._loadingId),r)),s},null}afterRoot(e){Al._loadingProcesses--,this.parser.getDependency=this._getDependency;for(const t of this._loadedObjects)delete t[A_],t instanceof O&&(t.parent||t instanceof H&&setTimeout(()=>{XO&&console.warn("> GLTF LOADER: Mesh not used in scene!",t),t.material=null,t.geometry=null},1e3));return null}}class I_{constructor(){window.addEventListener("unhandledrejection",e=>{if(e.defaultPrevented)return;const t=e?.reason?.path;if(t){const i=t[0];i&&i.tagName==="IMG"&&(console.warn(`Could not load image:
166
166
  `+i.src),e.preventDefault())}})}}const Fd=w("trackresources");function L_(){return Fd==="dispose"}let gr=!0;Fd===0&&(gr=!1);function QO(o){gr=o}function j_(){return gr}const D_=Symbol("disposable");function B_(o,e){o&&(o[D_]=e,fr&&console.warn("Set disposable",e,o))}const F_=Symbol("disposed");function YO(o){return o[F_]===!0}function Pe(o){if(o){if(o[D_]===!1){fr&&console.warn("Object is marked as not disposable",o);return}if(typeof o=="object"&&(o[F_]=!0),o instanceof yi)Pe(o.environment),Pe(o.background),Pe(o.customDepthMaterial),Pe(o.customDistanceMaterial);else if(o instanceof ss)Pe(o.geometry),Pe(o.material),Pe(o.skeleton),Pe(o.bindMatrix),Pe(o.bindMatrixInverse),Pe(o.customDepthMaterial),Pe(o.customDistanceMaterial),o.visible=!1;else if(o instanceof H)Pe(o.geometry),Pe(o.material),Pe(o.customDepthMaterial),Pe(o.customDistanceMaterial),o.visible=!1;else if(o instanceof O)o.visible=!1;else if(o instanceof un){Ra(o);for(const e of Object.keys(o.attributes)){const t=o.attributes[e];Pe(t)}}else if(o instanceof pt||o instanceof B0)fr&&console.warn("BufferAttribute dispose not supported",o.count);else if(o instanceof Array)for(const e of o)e instanceof ve&&Pe(e);else if(o instanceof ve){Ra(o);for(const t of Object.keys(o)){const i=o[t];i instanceof Re&&Pe(i)}const e=o.uniforms;if(e)for(const t of Object.keys(e)){const i=e[t];i instanceof Re?Pe(i):i instanceof Ni&&Pe(i.value)}}else o instanceof Re?(Ra(o),Ra(o.source),o.source?.data instanceof ImageBitmap&&Ra(o.source.data)):o instanceof oS?(Ra(o.boneTexture),o.boneTexture=null):o instanceof sS||!(o instanceof O)&&fr&&console.warn("Unknown object type",o)}}function Ra(o){o&&((fr||L_()||Fd)&&console.warn("\u{1F9E8} FREE",o),o instanceof ImageBitmap||"dispose"in o&&typeof o.dispose=="function"&&o.dispose())}function KO(o){}const ZO=new Set;function ug(o,e,t=null,i){if(i||(i=ZO,i.clear()),!o)return i;const n=o[tc];if(n)for(const s of n)i.has(s)||t?.call(null,s)!==!1&&(i.add(s),e&&ug(s,!0,t,i));return i}function JO(o){return o[ic]}const fr=w("debugresourceusers")||w("debugmemory"),tc=Symbol("needle-resource-users"),ic=Symbol("needle-resource-users-count");function $t(o,e){Od(o,e,function(t,i){gr&&!El.raycasting&&(Ud(tc,this,t,!1),Ud(tc,this,i,!0))})}gr&&($t(H.prototype,"material"),$t(H.prototype,"geometry"),$t(ve.prototype,"map"),$t(ve.prototype,"bumpMap"),$t(ve.prototype,"alphaMap"),$t(ve.prototype,"normalMap"),$t(ve.prototype,"displacementMap"),$t(ve.prototype,"roughnessMap"),$t(ve.prototype,"metalnessMap"),$t(ve.prototype,"emissiveMap"),$t(ve.prototype,"specularMap"),$t(ve.prototype,"envMap"),$t(ve.prototype,"lightMap"),$t(ve.prototype,"aoMap"),$t(ve.prototype,"gradientMap"));function ek(o){if(gr===!1)return;const e=o[tc];if(e)for(const t of e)Ud(tc,t,o,!1)}gr&&Od(ve.prototype,"dispose",function(){ek(this)});let pg=0;function Ud(o,e,t,i){if(pg>0)return;if(Array.isArray(t)){for(const s of t)Ud(o,e,s,i);return}if(!t)return;let n=t[o];if(n||(n=new Set),i){if(e&&!n.has(e)){n.add(e);let s=t[ic]||0;s+=1,t[ic]=s,fr&&console.warn(`\u{1F7E2} Added user of "${t.type}"`,e,t,s,"users:",n)}}else if(e&&n.has(e)){n.delete(e);let s=t[ic]||0;s>0&&(s-=1,t[ic]=s),fr&&console.warn(`\u{1F534} Removed user of "${t.type}"`,e,t,s,"users:",n),s<=0&&(Al.isLoading(t)||(Fd&&console.warn(`\u{1F534} Removed all user of "${t.type}"`,t),L_()&&Pe(t)))}t[o]=n}try{Od(er.prototype,"render",function(){pg++},function(){pg--})}catch(o){console.warn("Could not wrap WebGLRenderer.render",o)}const U_=w("debugcomponentevents");class zd{static eventListeners=new Map;static addComponentLifecylceEventListener(e,t){this.eventListeners.has(e)&&this.eventListeners.set(e,[]);let i=this.eventListeners.get(e);i||(i=[]),i.push(t),this.eventListeners.set(e,i),U_&&console.log("Added event listener for "+e,this.eventListeners)}static removeComponentLifecylceEventListener(e,t){const i=this.eventListeners.get(e);if(!i)return;const n=i.indexOf(t);n<0||i.splice(n,1)}static dispatchComponentLifecycleEvent(e,t){const i=this.eventListeners.get(e);if(U_&&console.log("Dispatching event "+e,i),!!i)for(const n of i)n(t)}}const nc=Symbol("NEEDLE_NEED_UPDATE_INSTANCE"),z_=Symbol("isUsingInstancing"),N_=Symbol("instancingRenderer"),oc=Symbol("instancingAutoUpdateBounds");class an{static isUsingInstancing(e){return e[z_]===!0}static getRenderer(e){return e[N_]||null}setAutoUpdateBounds(e,t){const i=an.getRenderer(e);i&&(i[oc]=t)}static markDirty(e,t=!0){if(e&&(this.isUsingInstancing(e)&&(e[nc]=!0,e.matrixWorldNeedsUpdate=!0),t))for(const i of e.children)an.markDirty(i,!0)}}var sc;(o=>{o.experimentalSmartHierarchyUpdate=!1})(sc||(sc={}));function Ta(o,e){try{e||o()}catch(t){return console.error(t),!1}return!0}const mg=w("debugnewscripts"),tk=w("debughierarchy"),Ae=[];function ik(){return Ae.length>0}function Nd(o){if(mg&&console.log("Register new components",o.new_scripts.length,[...o.new_scripts],o.alias?"element: "+o.alias:o.hash,o),o.new_scripts_pre_setup_callbacks.length>0){for(const e of o.new_scripts_pre_setup_callbacks)e&&e();o.new_scripts_pre_setup_callbacks.length=0}if(!(o.new_scripts.length<=0)){Ae.length=0,o.new_scripts.length>0&&Ae.push(...o.new_scripts),o.new_scripts.length=0;for(let e=0;e<Ae.length;e++)try{const t=Ae[e];if(t.isComponent!==!0){(E()||mg)&&console.error(`Registered script is not a Needle Engine component.
167
167
  The script will be ignored. Please make sure your component extends "Behaviour" imported from "@needle-tools/engine"
168
168
  `,t),Ae.splice(e,1),e--;continue}if(t.destroyed)continue;if(!t.gameObject){console.warn(`Component can not be initialized: no GameObject assigned.
@@ -182,12 +182,12 @@ Please change to:
182
182
  ${s}? : AssetReference;
183
183
 
184
184
  in script ${i}.ts
185
- <a href="https://docs.needle.tools/serializable" target="_blank">documentation</a>`),console.warn(i,s,o[s],o);continue}}}}function Sk(o,e){for(const t of Object.keys(e)){const i=e[t];if(typeof i=="object"&&i!==null&&i!==void 0){const n=o[t];if(!n){Un&&console.log(t,"is undefined on",o);continue}for(const s of Object.keys(i))if(n[s]===void 0&&lv(i[s])&&!lv(n)){const r=Ck(n,s);if(r&&(r?.writable===void 0||r?.writable===!1)&&r.set===void 0){Un&&console.warn('Property is not writable "'+s+'"',n,r,i[s],n[s]);continue}n[s]=i[s]}}}}function Ck(o,e){for(;o;){const t=Object.getOwnPropertyDescriptor(o,e);if(t)return t;o=Object.getPrototypeOf(o)}}function lv(o){switch(typeof o){case"number":case"string":case"boolean":return!0}return!1}function Rg(o,e,t,i,n){let s=typeof e=="function"&&e.prototype===void 0,r=e;if(s)try{if(r=e?.call(e,n),s=!1,r==null)return}catch(h){console.error("Error in callback",h,o)}if(t.type=r,!s&&n&&(n instanceof ve||n instanceof H||n instanceof un||n instanceof rs))return n;if(i||(i={serializer:Hd.getSerializerForConstructor(r)}),n&&typeof n=="object"&&yk(n)){if(n.__concreteInstance)return n.__concreteInstance;const h=n;if(!h.$serializedTypes&&r.prototype.$serializedTypes&&(h.$serializedTypes=r.prototype.$serializedTypes),h.$serializedTypes&&qd(h,o,t),n&&r!==void 0)try{let d=null;i.serializer&&(d=i.serializer.onDeserialize(o,t)),d||(d=new r,gt&&console.log("Create concrete instance for persistent asset",n,"instance:",d),Aa(d,n)),n.__concreteInstance=d,n=d}catch(d){console.error("Error creating instance or creating values on instance",d,n,r)}return n}if(Array.isArray(o)){const h=[];for(let d=0;d<o.length;d++){const p=o[d],g=Rg(p,e,t,i,p);h.push(g)}return h}const a=i?.serializer;if(a)return a.onDeserialize(o,t);if(n instanceof Re)return n;let l;if(o&&(o.isMaterial||o.isTexture||o.isObject3D||o instanceof rs))l=o;else{if(o===void 0)return;if(o===null&&(r===ve||r===Re||r===H||r===rs))return null;try{l=new r(...Pk(o))}catch(h){console.error("Error creating "+t.path,t.target,h);return}}const c=l;return c.$serializedTypes&&qd(c,o,t),l}function Pk(o){if(Gd.length=0,typeof o=="object"&&o!==null&&o!==void 0)for(const e of Object.keys(o))Gd.push(o[e]);return Gd}const Tg=Symbol("assigned component properties");function Aa(o,e,t,i){if(e==null||o==null)return;o[Tg]=!0;const n=o.constructor?.name??"unknown";t?.registerDefinedKeys(n,o);for(const s of Object.keys(e)){const r=Ok(o,s);if(typeof r?.value!="function"&&(!r||r.writable===!0||r.set!==void 0)){const a=e[s],l=o[s];o[s]=a,i?.onAssigned&&i.onAssigned(o,s,l,a)}}delete o[Tg]}function Ok(o,e){let t;do t=Object.getOwnPropertyDescriptor(o,e);while(!t&&(o=Object.getPrototypeOf(o)));return t}const cv=Symbol("customVisibilityFlag");function Co(o,e){o.layers[cv]=e}const hv=Symbol("DidPatchLayers");function kk(){const o=is.prototype;if(o[hv])return;o[hv]=!0;const e=o.test;o.test=function(t){return this[cv]===!1?!1:e.call(this,t)}}kk(),Object.defineProperty(de.prototype,"fov",{get:function(){return this._fov},set:function(o){const e=o!==this._fov;this._fov=o,e&&this.view!==void 0&&this.updateProjectionMatrix()},configurable:!0}),Object.defineProperty(de.prototype,"near",{get:function(){return this._near},set:function(o){const e=o!==this._near;this._near=o,e&&this.view!==void 0&&this.updateProjectionMatrix()},configurable:!0}),Object.defineProperty(de.prototype,"far",{get:function(){return this._far},set:function(o){const e=o!==this._far;this._far=o,e&&this.view!==void 0&&this.updateProjectionMatrix()},configurable:!0});const dv=new Map;function uv(o,e){if(!o)return;if(!e){console.warn("No prototype found",o,o.prototype,o.constructor);return}const t=dv.get(e);t&&t.apply(o)}function pv(o){const e=Mk(o.prototype);dv.set(o,e)}function Mk(o){return new Rk(o)}class Rk{$symbol;extensions;descriptors;constructor(e){this.$symbol=Symbol("prototype-extension"),this.extensions=Object.keys(e),this.descriptors=new Array;for(let t=0;t<this.extensions.length;t++){const i=this.extensions[t],n=Object.getOwnPropertyDescriptor(e,i);n&&this.descriptors.push(n)}}apply(e){if(!e[this.$symbol]){e[this.$symbol]=!0;for(let t=0;t<this.extensions.length;t++){const i=this.extensions[t],n=this.descriptors[t];n&&Object.defineProperty(e,i,n)}}}}const Tk=w("debuggetcomponent"),mv=()=>Tk||globalThis.NEEDLE_DEBUG_GETCOMPONENT===!0;function Ek(o){return o==null||o.isObject3D?o:o.object&&o.object.isObject3D?o.object:o}function Eg(o,e){if(!o||!o.userData.components)return e;const t=o.userData.components.indexOf(e);return t<0||(zd.dispatchComponentLifecycleEvent("removing-component",e),e.gameObject=null,o.userData.components.splice(t,1)),e}function cc(o,e,t){return br(o,e)||bn(o,e,t)}const gv=new At("addComponentIdProvider");function yr(o,e,t=!0){o.userData||(o.userData={}),o.userData.components||(o.userData.components=[]),o.userData.components.push(e),e.gameObject=o,(e.guid===void 0||e.guid==="invalid")&&(e.guid=gv.generateUUID()),Qd(o),lu(e,e.context);try{t&&e.__internalAwake&&(rc(o),e.activeAndEnabled&&e.__internalAwake()),zd.dispatchComponentLifecycleEvent("component-added",e)}catch(i){console.error(i)}return e}function bn(o,e,t,i){if(typeof e=="function"){const n=new e;t&&n.__internalNewInstanceCreated(t);let s=!0;return i?.callAwake!=null&&(s=i.callAwake),yr(o,n,s)}if(e.destroyed)return console.warn("Can not move/add a destroyed component",e),e;if(e.gameObject===o)return e;if(e.gameObject&&e.gameObject.userData?.components){const n=e.gameObject.userData.components.indexOf(e);e.gameObject.userData.components.splice(n,1)}if(o.userData||(o.userData={}),!o.userData.components)o.userData.components=[];else if(o.userData.components.includes(e))return e;return o.userData.components.push(e),e.gameObject=o,(e.guid===void 0||e.guid==="invalid")&&(e.guid=gv.generateUUID()),t&&e._internalInit(t),lu(e,e.context),e}function fv(o){if(o.gameObject&&o.gameObject.userData.components){const e=o.gameObject.userData.components.indexOf(o);o.gameObject.userData.components.splice(e,1)}o.__internalDisable&&o.__internalDisable(),So(o,o.context??z.Current),o.destroy(),o.gameObject=null}let yv=!1;function bv(o,e,t){if(o==null)return null;if(!o.isObject3D)return console.error("Object is not object3D"),null;if(!o?.userData?.components||(typeof e=="string"&&(yv||(yv=!0,console.warn(`Accessing components by name is not supported.
185
+ <a href="https://docs.needle.tools/serializable" target="_blank">documentation</a>`),console.warn(i,s,o[s],o);continue}}}}function Sk(o,e){for(const t of Object.keys(e)){const i=e[t];if(typeof i=="object"&&i!==null&&i!==void 0){const n=o[t];if(!n){Un&&console.log(t,"is undefined on",o);continue}for(const s of Object.keys(i))if(n[s]===void 0&&lv(i[s])&&!lv(n)){const r=Ck(n,s);if(r&&(r?.writable===void 0||r?.writable===!1)&&r.set===void 0){Un&&console.warn('Property is not writable "'+s+'"',n,r,i[s],n[s]);continue}n[s]=i[s]}}}}function Ck(o,e){for(;o;){const t=Object.getOwnPropertyDescriptor(o,e);if(t)return t;o=Object.getPrototypeOf(o)}}function lv(o){switch(typeof o){case"number":case"string":case"boolean":return!0}return!1}function Rg(o,e,t,i,n){let s=typeof e=="function"&&e.prototype===void 0,r=e;if(s)try{if(r=e?.call(e,n),s=!1,r==null)return}catch(h){console.error("Error in callback",h,o)}if(t.type=r,!s&&n&&(n instanceof ve||n instanceof H||n instanceof un||n instanceof rs))return n;if(i||(i={serializer:Hd.getSerializerForConstructor(r)}),n&&typeof n=="object"&&yk(n)){if(n.__concreteInstance)return n.__concreteInstance;const h=n;if(!h.$serializedTypes&&r.prototype.$serializedTypes&&(h.$serializedTypes=r.prototype.$serializedTypes),h.$serializedTypes&&qd(h,o,t),n&&r!==void 0)try{let d=null;i.serializer&&(d=i.serializer.onDeserialize(o,t)),d||(d=new r,gt&&console.log("Create concrete instance for persistent asset",n,"instance:",d),Aa(d,n)),n.__concreteInstance=d,n=d}catch(d){console.error("Error creating instance or creating values on instance",d,n,r)}return n}if(Array.isArray(o)){const h=[];for(let d=0;d<o.length;d++){const p=o[d],m=Rg(p,e,t,i,p);h.push(m)}return h}const a=i?.serializer;if(a)return a.onDeserialize(o,t);if(n instanceof Re)return n;let l;if(o&&(o.isMaterial||o.isTexture||o.isObject3D||o instanceof rs))l=o;else{if(o===void 0)return;if(o===null&&(r===ve||r===Re||r===H||r===rs))return null;try{l=new r(...Pk(o))}catch(h){console.error("Error creating "+t.path,t.target,h);return}}const c=l;return c.$serializedTypes&&qd(c,o,t),l}function Pk(o){if(Gd.length=0,typeof o=="object"&&o!==null&&o!==void 0)for(const e of Object.keys(o))Gd.push(o[e]);return Gd}const Tg=Symbol("assigned component properties");function Aa(o,e,t,i){if(e==null||o==null)return;o[Tg]=!0;const n=o.constructor?.name??"unknown";t?.registerDefinedKeys(n,o);for(const s of Object.keys(e)){const r=Ok(o,s);if(typeof r?.value!="function"&&(!r||r.writable===!0||r.set!==void 0)){const a=e[s],l=o[s];o[s]=a,i?.onAssigned&&i.onAssigned(o,s,l,a)}}delete o[Tg]}function Ok(o,e){let t;do t=Object.getOwnPropertyDescriptor(o,e);while(!t&&(o=Object.getPrototypeOf(o)));return t}const cv=Symbol("customVisibilityFlag");function Co(o,e){o.layers[cv]=e}const hv=Symbol("DidPatchLayers");function kk(){const o=is.prototype;if(o[hv])return;o[hv]=!0;const e=o.test;o.test=function(t){return this[cv]===!1?!1:e.call(this,t)}}kk(),Object.defineProperty(de.prototype,"fov",{get:function(){return this._fov},set:function(o){const e=o!==this._fov;this._fov=o,e&&this.view!==void 0&&this.updateProjectionMatrix()},configurable:!0}),Object.defineProperty(de.prototype,"near",{get:function(){return this._near},set:function(o){const e=o!==this._near;this._near=o,e&&this.view!==void 0&&this.updateProjectionMatrix()},configurable:!0}),Object.defineProperty(de.prototype,"far",{get:function(){return this._far},set:function(o){const e=o!==this._far;this._far=o,e&&this.view!==void 0&&this.updateProjectionMatrix()},configurable:!0});const dv=new Map;function uv(o,e){if(!o)return;if(!e){console.warn("No prototype found",o,o.prototype,o.constructor);return}const t=dv.get(e);t&&t.apply(o)}function pv(o){const e=Mk(o.prototype);dv.set(o,e)}function Mk(o){return new Rk(o)}class Rk{$symbol;extensions;descriptors;constructor(e){this.$symbol=Symbol("prototype-extension"),this.extensions=Object.keys(e),this.descriptors=new Array;for(let t=0;t<this.extensions.length;t++){const i=this.extensions[t],n=Object.getOwnPropertyDescriptor(e,i);n&&this.descriptors.push(n)}}apply(e){if(!e[this.$symbol]){e[this.$symbol]=!0;for(let t=0;t<this.extensions.length;t++){const i=this.extensions[t],n=this.descriptors[t];n&&Object.defineProperty(e,i,n)}}}}const Tk=w("debuggetcomponent"),mv=()=>Tk||globalThis.NEEDLE_DEBUG_GETCOMPONENT===!0;function Ek(o){return o==null||o.isObject3D?o:o.object&&o.object.isObject3D?o.object:o}function Eg(o,e){if(!o||!o.userData.components)return e;const t=o.userData.components.indexOf(e);return t<0||(zd.dispatchComponentLifecycleEvent("removing-component",e),e.gameObject=null,o.userData.components.splice(t,1)),e}function cc(o,e,t){return br(o,e)||bn(o,e,t)}const gv=new At("addComponentIdProvider");function yr(o,e,t=!0){o.userData||(o.userData={}),o.userData.components||(o.userData.components=[]),o.userData.components.push(e),e.gameObject=o,(e.guid===void 0||e.guid==="invalid")&&(e.guid=gv.generateUUID()),Qd(o),lu(e,e.context);try{t&&e.__internalAwake&&(rc(o),e.activeAndEnabled&&e.__internalAwake()),zd.dispatchComponentLifecycleEvent("component-added",e)}catch(i){console.error(i)}return e}function bn(o,e,t,i){if(typeof e=="function"){const n=new e;t&&n.__internalNewInstanceCreated(t);let s=!0;return i?.callAwake!=null&&(s=i.callAwake),yr(o,n,s)}if(e.destroyed)return console.warn("Can not move/add a destroyed component",e),e;if(e.gameObject===o)return e;if(e.gameObject&&e.gameObject.userData?.components){const n=e.gameObject.userData.components.indexOf(e);e.gameObject.userData.components.splice(n,1)}if(o.userData||(o.userData={}),!o.userData.components)o.userData.components=[];else if(o.userData.components.includes(e))return e;return o.userData.components.push(e),e.gameObject=o,(e.guid===void 0||e.guid==="invalid")&&(e.guid=gv.generateUUID()),t&&e._internalInit(t),lu(e,e.context),e}function fv(o){if(o.gameObject&&o.gameObject.userData.components){const e=o.gameObject.userData.components.indexOf(o);o.gameObject.userData.components.splice(e,1)}o.__internalDisable&&o.__internalDisable(),So(o,o.context??z.Current),o.destroy(),o.gameObject=null}let yv=!1;function bv(o,e,t){if(o==null)return null;if(!o.isObject3D)return console.error("Object is not object3D"),null;if(!o?.userData?.components||(typeof e=="string"&&(yv||(yv=!0,console.warn(`Accessing components by name is not supported.
186
186
  Please use the component type instead. This may keep working in local development but it will fail when bundling your application.
187
187
 
188
188
  You can import other modules your main module to get access to types
189
189
  or if you use npmdefs you can make types available globally using globalThis:
190
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis`,e))),mv()&&console.log("[onGetComponent] FIND",e),e==null))return null;for(let i=0;i<o.userData.components.length;i++){const n=o.userData.components[i];let s=Object.getPrototypeOf(n);for(;s;){if(s===e.prototype)if(mv()&&console.log("[onGetComponent] MATCH BY PROTOYPE",s),t)t.push(n);else return n;s=Object.getPrototypeOf(s)}}return t||null}function br(o,e){const t=bv(o,e);return t?Array.isArray(t)?t[0]:t:null}function hc(o,e,t,i=!0){return t||(t=[]),i&&(t.length=0),bv(o,e,t),t}function dc(o,e,t){if(t===!1&&o[_o]===!1)return null;const i=br(o,e);if(t===!1&&i?.enabled===!1)return null;if(i)return i;for(let n=0;n<o?.children?.length;n++){const s=dc(o.children[n],e);if(s)return s}return null}function Ia(o,e,t,i=!0){t||(t=[]),i&&(t.length=0),hc(o,e,t,!1);for(let n=0;n<o?.children?.length;n++)Ia(o.children[n],e,t,!1);return t}function uc(o,e){if(!o)return null;if(Array.isArray(o)){for(let i=0;i<o.length;i++){const n=Ek(o[i]),s=uc(n,e);if(s)return s}return null}return br(o,e)||(o.parent?uc(o.parent,e):null)}function Xd(o,e,t,i=!0){return t||(t=[]),i&&(t.length=0),o?(hc(o,e,t,!1),o.parent?Xd(o.parent,e,t,!1):t):t}function pc(o,e=void 0,t=!0){if(!o)return null;if(!e&&(e=z.Current,!e))return console.error("Can not search object without any needle context or scene!!!"),null;let i=e;return i.isScene||(i=e?.scene),i&&dc(i,o,t)||null}function _v(o,e,t=void 0){if(!o)return e??[];if(e||(e=[]),e.length=0,!t&&(t=z.Current,!t))return console.error("Can not search object without any needle context or scene!!!"),e;"scene"in t&&(t=t.scene);const i=t;return i&&Ia(i,o,e,!1),e}function Qd(o){o&&o.isObject3D===!0&&uv(o,O)}if(sc.experimentalSmartHierarchyUpdate){const o=O.prototype.add;O.prototype.add=function(...i){return bg(),o.apply(this,i)};const e=O.prototype.attach;O.prototype.attach=function(...i){return bg(),e.apply(this,i)};const t=O.prototype.remove;O.prototype.remove=function(...i){return bg(),t.apply(this,i)}}O.prototype.SetActive=function(o){this.visible=o},O.prototype.setActive=function(o){this.visible=o},O.prototype.destroy=function(){Ci(this)},O.prototype.addComponent=function(o,e){return bn(this,o,e)},O.prototype.addNewComponent=function(o,e){return bn(this,o,e)},O.prototype.removeComponent=function(o){return Eg(this,o)},O.prototype.getOrAddComponent=function(o,e){return cc(this,o,e)},O.prototype.getComponent=function(o){return br(this,o)},O.prototype.getComponents=function(o,e){return hc(this,o,e)},O.prototype.getComponentInChildren=function(o){return dc(this,o)},O.prototype.getComponentsInChildren=function(o,e){return Ia(this,o,e)},O.prototype.getComponentInParent=function(o){return uc(this,o)},O.prototype.getComponentsInParent=function(o,e){return Xd(this,o,e)},Object.getOwnPropertyDescriptor(O.prototype,"activeSelf")||Object.defineProperty(O.prototype,"activeSelf",{get:function(){return La(this)},set:function(o){mc(this,o)}}),Object.getOwnPropertyDescriptor(O.prototype,"worldPosition")||Object.defineProperty(O.prototype,"worldPosition",{get:function(){return this instanceof X0?Z(this.object):Z(this)},set:function(o){mt(this,o)}}),Object.getOwnPropertyDescriptor(O.prototype,"worldQuaternion")||Object.defineProperty(O.prototype,"worldQuaternion",{get:function(){return this instanceof X0?be(this.object):be(this)},set:function(o){pn(this,o)}}),Object.getOwnPropertyDescriptor(O.prototype,"worldRotation")||Object.defineProperty(O.prototype,"worldRotation",{get:function(){return xd(this)},set:function(o){Ub(this,o)}}),Object.getOwnPropertyDescriptor(O.prototype,"worldScale")||Object.defineProperty(O.prototype,"worldScale",{get:function(){return $e(this)},set:function(o){wa(this,o)}});const Ak=new ee,Ik=new b(0,0,0),Lk=new b(0,1,0);Object.getOwnPropertyDescriptor(O.prototype,"worldForward")||Object.defineProperty(O.prototype,"worldForward",{get:function(){return $().set(0,0,1).applyQuaternion(be(this))},set:function(o){const e=ti().setFromRotationMatrix(Ak.lookAt(Ik.set(0,0,0),o,Lk.set(0,1,0)));this.worldQuaternion=e}}),Object.getOwnPropertyDescriptor(O.prototype,"worldRight")||Object.defineProperty(O.prototype,"worldRight",{get:function(){return $().set(1,0,0).applyQuaternion(be(this))}}),Object.getOwnPropertyDescriptor(O.prototype,"worldUp")||Object.defineProperty(O.prototype,"worldUp",{get:function(){return $().set(0,1,0).applyQuaternion(be(this))}}),pv(O);class se extends ne{alpha=1;get isRGBAColor(){return!0}set a(e){this.alpha=e}get a(){return this.alpha}constructor(e,t,i,n){super(),typeof e=="number"&&typeof t=="number"&&typeof i=="number"?(this.set(e,t,i),this.alpha=typeof n=="number"?n:1):e!==void 0&&(this.set(e),this.alpha=1)}clone(){const e=super.clone();return e.alpha=this.alpha,e}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,"alpha"in e&&typeof e.alpha=="number"?this.alpha=e.alpha:typeof e.a=="number"&&(this.alpha=e.a),this}lerp(e,t){const i=e;return i.alpha!=null&&(this.alpha=D.lerp(this.alpha,i.alpha,t)),super.lerp(e,t)}lerpColors(e,t,i){const n=e,s=t;return n.alpha!=null&&s.alpha!=null&&(this.alpha=D.lerp(n.alpha,s.alpha,i)),super.lerpColors(e,t,i)}multiply(e){const t=e;return t.alpha!=null&&(this.alpha=this.alpha*t.alpha),super.multiply(e)}fromArray(e,t=0){return this.alpha=e[t+3],super.fromArray(e,t)}static fromColorRepresentation(e){if(typeof e=="string"){if(e.trim()==="transparent")return new se(0,0,0,0);if(e.startsWith("#")&&e.length===9){const t=parseInt(e.slice(1,9),16),i=t>>24&255,n=t>>16&255,s=t>>8&255,r=t>>0&255;return new se(i/255,n/255,s/255,r/255)}else if(e.startsWith("#")){const t=parseInt(e.slice(1),16),i=t>>16&255,n=t>>8&255,s=t>>0&255;return new se(i/255,n/255,s/255,1)}else if(e.startsWith("rgba")){const t=e.slice(5,-1).split(",").map(Number);return new se(t[0]/255,t[1]/255,t[2]/255,t[3])}else if(e.startsWith("rgb")){const t=e.slice(4,-1).split(",").map(Number);return new se(t[0]/255,t[1]/255,t[2]/255,1)}}else if(Array.isArray(e)){if(e.length===4)return new se(e[0],e[1],e[2],e[3]);if(e.length===3)return new se(e[0],e[1],e[2],1);console.error("Invalid color array length. Expected 3 or 4, got "+e.length)}return new se(e)}}const Yd=w("debuggetcomponent"),_r=w("debuginstantiate");class En{idProvider;parent;keepWorldPosition;position;rotation;scale;visible;context;components;clone(){const e=new En;return e.idProvider=this.idProvider,e.parent=this.parent,e.keepWorldPosition=this.keepWorldPosition,e.position=Array.isArray(this.position)?[...this.position]:this.position?.clone(),e.rotation=Array.isArray(this.rotation)?[...this.rotation]:this.rotation?.clone(),e.scale=Array.isArray(this.scale)?[...this.scale]:this.scale?.clone(),e.visible=this.visible,e.context=this.context,e.components=this.components,e}cloneAssign(e){this.idProvider=e.idProvider,this.parent=e.parent,this.keepWorldPosition=e.keepWorldPosition,this.position=Array.isArray(e.position)?[...e.position]:e.position?.clone(),this.rotation=Array.isArray(e.rotation)?[...e.rotation]:e.rotation?.clone(),this.scale=Array.isArray(e.scale)?[...e.scale]:e.scale?.clone(),this.visible=e.visible,this.context=e.context,this.components=e.components}}function La(o){return o.visible}function mc(o,e){return typeof e=="number"&&(e=e>.5),o.visible=e,o.visible}function vv(o){return o[_o]||Kd(o)}function wv(o,e){o[z_]=e}function Kd(o){return an.isUsingInstancing(o)}function Ag(o,e){return _a(o,e,!0,!0)}const xv=Symbol("isDestroyed");function vr(o){return o[xv]}function Sv(o,e){o[xv]=e}const Ig=Symbol("isDontDestroy");function ja(o,e=!0){o[Ig]=e}const Zd=[],Jd=[];function Ci(o,e=!0,t=!1){Zd.length=0,Jd.length=0,Lg(o,e,!0);for(const i of Zd)i.gameObject=null,i.context=null;for(const i of Jd)Sv(i,!0),t&&Pe(i);Jd.length=0,Zd.length=0}function Lg(o,e=!0,t=!0){if(o==null)return;const i=o;if(i.isComponent){if(i[Ig])return;Zd.push(i);const r=i.gameObject;i.__internalDisable(),i.__internalDestroy(),i.gameObject=r;return}if(o[Ig])return;const n=o;Yd&&console.log(n),Jd.push(n);const s=n.userData?.components;if(s!=null&&Array.isArray(s)){let r=s.length;for(let a=0;a<s.length;a++){const l=s[a];Lg(l,e,!1),s.length<r&&(r=s.length,a--)}}if(e&&n.children)for(const r of n.children)Lg(r,e,!1);t&&n.removeFromParent()}function wr(o,e,t=!0){return Cv(o,e,t)}function*eu(o,e,t=!1,i=999,n=0){if(o?.userData.components&&!(n>i)){for(const s of o.userData.components)e&&s?.isComponent===!0&&s instanceof e?yield s:yield s;if(t===!0)for(const s of o.children)yield*eu(s,e,!0,i,n+1)}}function Cv(o,e,t,i=0){if(o){if(o.isObject3D,i>1e3){console.warn("Failed to iterate components: too many levels");return}if(o.userData?.components)for(let n=0;n<o.userData.components.length;n++){const s=o.userData.components[n];if(s?.isComponent===!0){const r=e(s);if(r!==void 0)return r}}if(t&&o.children){const n=i+1;for(let s=0;s<o.children.length;s++){const r=o.children[s];if(!r)continue;const a=Cv(r,e,t,n);if(a!==void 0)return a}}}}function Da(o,e){if("isAssetReference"in o)return o.instantiate(e??void 0);let t=null;e!=null&&(e.x!==void 0?(t=new En,t.position=e):t=e);let i=z.Current;t?.context&&(i=t.context),Yd&&i.alias&&console.log("context",i.alias),t&&!t.idProvider&&(t.idProvider=new At(Date.now()));const n=[],s={},r={},a=Pv(i,o,t,n,s,r);a&&(Bk(a,s),Dk(r,s)),Yd&&(Sd(o,!0),Sd(a,!0));const l={};if(t?.components!==!1){for(const c in n){const h=n[c],d=h.guid;t&&t.idProvider&&(h.guid=t.idProvider.generateUUID(),l[d]=h.guid,Yd&&console.log(h.name,h.guid)),lu(h,i),h.__internalNewInstanceCreated&&h.__internalNewInstanceCreated()}for(const c in n){const h=n[c];h.resolveGuids&&h.resolveGuids(l),h.enabled!==!1&&(h.enabled=!0)}Nd(i)}return a}function Pv(o,e,t,i,n,s){if(!e||e[Si])return null;const r=e.userData;e.userData={};const a=e.children;e.children=[];const l=e.clone(!1);if(Qd(l),e.userData=r,e.children=a,n[e.uuid]={original:e,clone:l},_r&&console.log("ADD",e,l),e.type==="SkinnedMesh"&&(s[e.uuid]={original:e,clone:l}),t?.visible!==void 0&&(l.visible=t.visible),t?.idProvider){l.uuid=t.idProvider.generateUUID();const h=l;h&&(h.guid=l.uuid)}e.animations&&e.animations.length>0&&(l.animations=[...e.animations]);const c=e.parent;if(c&&c.add(l),t?.position)if(Array.isArray(t.position)){const h=new b;h.fromArray(t.position),l.worldPosition=h}else l.worldPosition=t.position;else l.position.copy(e.position);if(t?.rotation){if(t.rotation instanceof U)l.worldQuaternion=t.rotation;else if(t.rotation instanceof nt)l.worldQuaternion=ti().setFromEuler(t.rotation);else if(Array.isArray(t.rotation)){const h=new nt;h.fromArray(t.rotation),l.worldQuaternion=ti().setFromEuler(h)}}else l.quaternion.copy(e.quaternion);if(t?.scale)if(Array.isArray(t.scale)){const h=new b;h.fromArray(t.scale),t.scale=h}else l.scale.copy(t.scale);else l.scale.copy(e.scale);if(t?.parent&&t.parent!=="scene"){let h=null;if(typeof t.parent=="string"?h=_a(t.parent,o.scene,!0):h=t.parent,h){const d=t.keepWorldPosition===!0?h.attach:h.add;d?d.call(h,l):console.error("Invalid parent object",h,"received when instantiating:",e)}else console.warn("could not find parent:",t.parent)}for(const[h,d]of Object.entries(e.userData))h!=="components"&&(l.userData[h]=d);if(e.userData?.components){const h=e.userData.components,d=[];l.userData.components=d;for(let p=0;p<h.length;p++){const g=h[p],f=new g.constructor;jk(g,f),g[Yl]!==void 0&&(f[Yl]=g[Yl]),d.push(f),f.gameObject=l,i.push(f),n[g.guid]={original:g,clone:f},zd.dispatchComponentLifecycleEvent("component-added",f)}}t&&(t.position=void 0,t.rotation=void 0,t.scale=void 0,t.parent=void 0,t.visible=void 0);for(const h in e.children){const d=e.children[h],p=Pv(o,d,t,i,n,s);p&&(n[p.uuid]={original:d,clone:p},l.add(p))}return l}function jk(o,e,t){Aa(e,o,void 0,{})}function Dk(o,e){for(const t in o){const i=o[t],n=i.original,s=n.skeleton,r=i.clone;if(!s){console.warn("Skinned mesh has no skeleton?",i);continue}const a=s.bones,l=r.skeleton.clone();r.skeleton=l,r.bindMatrix.clone().copy(n.bindMatrix),r.bindMatrixInverse.copy(n.bindMatrixInverse);const c=[];l.bones=c;for(let h=0;h<a.length;h++){const d=a[h],p=e[d.uuid].clone;c.push(p)}}for(const t in o){const i=o[t].clone;i.skeleton.update(),i.bind(i.skeleton,i.bindMatrix),i.updateMatrixWorld(!0)}}function Bk(o,e){for(const t in e){const i=e[t].clone;if(i?.isObject3D&&i?.userData?.components)for(let n=0;n<i.userData.components.length;n++){const s=i.userData.components[n],r=Object.entries(s);for(const[a,l]of r)if(Array.isArray(l)){const c=[];s[a]=c;for(let h=0;h<l.length;h++){const d=l[h];if(typeof d!="object"){c.push(d);continue}const p=Ov(s,a,d,e);p!==void 0?(_r&&console.log("Found new instance for",a,d,"->",p),c.push(p)):(_r&&console.warn("Could not find new instance for",a,d),c.push(d))}}else if(typeof l=="object"){const c=Ov(s,a,l,e);c!==void 0?s[a]=c:_r&&console.warn("Could not find new instance for",a,l)}}}}function Ov(o,e,t,i){if(t!=null)if(t.isComponent===!0){const n=t.gameObject;if(n){const s=n.uuid,r=i[s]?.clone;if(!r){_r&&console.log("reference did not change",e,o,t);return}const a=n.userData.components.indexOf(t);if(a>=0&&r.isObject3D)return _r&&console.log(e,s),r.userData.components[a];console.warn("could not find component",e,t)}}else if(t.isObject3D===!0){if(e==="gameObject")return;const n=t;if(n){const s=n.uuid,r=i[s]?.clone;if(r)return _r&&console.log(e,"old",t,"new",r),r}}else{if(t.isVector4||t.isVector3||t.isVector2||t.isQuaternion||t.isEuler||t.isColor===!0)return t.clone();if(t.isEventList===!0)return t.__internalOnInstantiate(i)}}var xr;(o=>{o.baseUrl="https://networking.needle.tools";function e(l){return ib(new Uint8Array(l))}o.hashMD5=e;function t(l){const c=ib(new Uint8Array(l),{encoding:"binary",asBytes:!0});return btoa(String.fromCharCode(...c))}o.hashMD5_Base64=t;function i(l){const c=new Uint8Array(l);return crypto.subtle.digest("SHA-256",c).then(h=>btoa(String.fromCharCode(...new Uint8Array(h))))}o.hashSha256=i;function n(l){const c=l.filesize/1024/1024;return Vn()?c<50:c<5}o.canUpload=n;async function s(l,c){const h=o.baseUrl;if(h){if(!l.name)return console.error("Upload: file name is missing"),null}else return console.error("Blob storage base url is not set"),null;let d=null;l instanceof File?d=await l.arrayBuffer():d=l.data;const p=d.byteLength,g=p/1024/1024;if(g>50)return c?.silent!==!0&&ge(`File (${g.toFixed(1)}MB) is too large for uploading (see console for details)`),console.warn(`Your file is too large for uploading (${g.toFixed(1)}MB). Max allowed size is 50MB`),null;if(!Vn()&&g>5)return c?.silent!==!0&&ge('File is too large for uploading. Please get a <a href="https://needle.tools/pricing" target="_blank">commercial license</a> to upload files larger than 5MB'),console.warn(`Your file is too large for uploading (${g.toFixed(1)}MB). Max size is 5MB for non-commercial users. Please get a commercial license at https://needle.tools/pricing for larger files (up to 50MB)`),null;if(p<1)return console.warn(`Your file is too small for uploading (${g.toFixed(1)}MB). Min size is 1 byte`),null;const f=t(d),m={filename:l.name,"Content-Md5":f,"Content-Type":l.type||"application/octet-stream",FileSize:p.toString(),"Content-Disposition":`attachment; filename="${l.name}"`,"x-amz-server-side-encryption":"AES256"},y=await fetch(h+"/api/needle/blob",{method:"POST",headers:m,signal:c?.abort}).then(_=>_.json()).catch(_=>(console.error(_),null));if(y==null)return console.warn("Upload failed..."),null;if("error"in y)return console.error(y.error),null;if("upload"in y&&y.upload){let _=function(R){return c?.onProgress?.call(null,{progress01:0,state:"inprogress"}),fetch(R,{method:"PUT",headers:m,body:d,signal:c?.abort}).then(k=>(c?.onProgress?.call(null,{progress01:1,state:"finished"}),k)).catch(k=>k)};console.debug("Uploading file",y.upload);let v=!1,P=null;for(let R=0;R<3;R++)try{if(v)break;if(c?.abort?.aborted)return console.debug("Aborted upload"),null;const k=await _(y.upload);k instanceof Error?(P=k,await Dn(1e3*R)):k.ok&&(console.debug("File uploaded successfully"),v=!0)}catch(k){console.error(k)}if(!v)return console.error(P?.message||"Failed to upload file"),null}if("download"in y){const _=h+y.download;return console.debug("File found in blob storage",_),{key:y.key,success:!0,download_url:_}}return null}o.upload=s;function r(l){return`${o.baseUrl}/api/needle/blob/${l}`}o.getBlobUrlForKey=r;async function a(l,c){const h=new nm;h.setResponseType("arraybuffer");const d=await h.loadAsync(l,p=>{c&&c.call(null,p)});return d instanceof ArrayBuffer?new Uint8Array(d):(console.error("Download failed, no arraybuffer returned"),null)}o.download=a})(xr||(xr={}));const ps=w("debugaddressables");class kv{_context;_assetReferences={};constructor(e){this._context=e,this._context.pre_update_callbacks.push(this.preUpdate)}dispose(){const e=this._context.pre_update_callbacks.indexOf(this.preUpdate);e>=0&&this._context.pre_update_callbacks.splice(e,1);for(const t in this._assetReferences)this._assetReferences[t]?.unload();this._assetReferences={}}preUpdate=()=>{};findAssetReference(e){return this._assetReferences[e]||null}registerAssetReference(e){return e.url&&(this._assetReferences[e.url]?console.warn("Asset reference already registered",e):this._assetReferences[e.url]=e),e}unregisterAssetReference(e){e.url&&delete this._assetReferences[e.url]}}const jg=Symbol("assetReference");class ie{static getOrCreateFromUrl(e,t){if(!t&&(t=z.Current,!t))throw new Error('Context is required when sourceId is a string. When you call this method from a component you can call it with "getOrCreate(this, url)" where "this" is the component.');const i=t.addressables,n=i.findAssetReference(e);if(n)return n;const s=new ie(e,t.hash);return i.registerAssetReference(s),s}static getOrCreate(e,t,i){if(typeof e=="string"){if(!i&&(i=z.Current,!i))throw new Error('Context is required when sourceId is a string. When you call this method from a component you can call it with "getOrCreate(this, url)" where "this" is the component.')}else i=e.context,e=e.sourceId;const n=ls(e,t);ps&&console.log("GetOrCreate Addressable from",e,t,"FinalPath=",n);const s=i.addressables,r=s.findAssetReference(n);if(r)return r;const a=new ie(n,i.hash);return s.registerAssetReference(a),a}isAssetReference=!0;get rawAsset(){return this._rawAsset}get asset(){return this._glbRoot??(this._rawAsset?.scene||null)}set asset(e){e?this._rawAsset={animations:e.animations,scene:e,scenes:[e]}:this._rawAsset=null}get uri(){return this._url}get url(){return this._url}get urlName(){return this._urlName}get hasUrl(){return this._url!==void 0&&(this._url.startsWith("http")||this._url.startsWith("blob:")||this._url.startsWith("www.")||this._url.includes("/"))}_rawAsset=null;_glbRoot;_url;_urlName;_progressListeners=[];_isLoadingRawBinary=!1;_rawBinary;constructor(...e){typeof e[0]=="object"?"url"in e[0]?this._url=e[0].url:(this._url="",e[0].asset&&(this.asset=e[0].asset)):(this._url=e[0],e[2]instanceof O&&(this.asset=e[2]));const t=this._url.lastIndexOf("/");if(t>=0){this._urlName=this._url.substring(t+1);const i=this._urlName.lastIndexOf(".");i>=0&&(this._urlName=this._urlName.substring(0,i))}else this._urlName=this._url;ev(this._url,this.onResolvePrefab.bind(this))}async onResolvePrefab(e){return e===this.url&&(this.mustLoad&&await this.loadAssetAsync(),this.asset)?this.asset:null}get mustLoad(){return!this.asset||this.asset.__destroyed===!0||vr(this.asset)===!0}_loadingPromise=null;isLoaded(){return this._rawBinary||this.asset!==void 0}unload(){this.asset&&(ps&&console.log("Unload",this.asset),"scene"in this.asset&&this.asset.scene&&Ci(this.asset.scene,!0,!0),Ci(this.asset,!0,!0)),this.asset=null,this._rawBinary=void 0,this._glbRoot=null,this._loadingPromise=null,z.Current&&z.Current.addressables.unregisterAssetReference(this)}async preload(){if(!this.mustLoad||this._isLoadingRawBinary)return null;if(this._rawBinary!==void 0)return this._rawBinary;this._isLoadingRawBinary=!0,ps&&console.log("Preload",this.url);const e=await xr.download(this.url,t=>{this.raiseProgressEvent(t)});return this._rawBinary=e?.buffer??null,this._isLoadingRawBinary=!1,this._rawBinary}async loadAssetAsync(e){if(ps&&console.log("[AssetReference] loadAssetAsync",this.url),!this.mustLoad)return this.asset;if(e&&this._progressListeners.push(e),this._loadingPromise!==null)return this._loadingPromise.then(n=>this.asset);const t=z.Current;if(this._rawBinary){if(!(this._rawBinary instanceof ArrayBuffer))return console.error("[AssetReference] Failed loading \u2013 Invalid data. Must be of type ArrayBuffer. "+typeof this._rawBinary),null;this._loadingPromise=gn().parseSync(t,this._rawBinary,this.url,null),this.raiseProgressEvent(new ProgressEvent("progress",{loaded:this._rawBinary.byteLength,total:this._rawBinary.byteLength}))}else ps&&console.log("Load async",this.url),this._loadingPromise=gn().loadSync(t,this.url,this.url,null,n=>{this.raiseProgressEvent(n)});this._loadingPromise.finally(()=>this._loadingPromise=null);const i=await this._loadingPromise;return this._progressListeners.length=0,this._glbRoot=this.tryGetActualGameObjectRoot(i),i?(i[jg]=this,this._glbRoot&&(this._glbRoot[jg]=this),this.asset&&(this.asset[jg]=this),Nd(t),i.scene!==void 0&&(this._rawAsset=i),this.asset):null}instantiate(e){return this.onInstantiate(e,!1)}instantiateSynced(e,t=!0){return this.onInstantiate(e,!0,t)}beginListenDownload(e){this._progressListeners.indexOf(e)<0&&this._progressListeners.push(e)}endListenDownload(e){const t=this._progressListeners.indexOf(e);t>=0&&this._progressListeners.splice(t,1)}raiseProgressEvent(e){for(const t of this._progressListeners)t(this,e)}static currentlyInstantiating=new Map;async onInstantiate(e,t=!1,i){const n=z.Current,s=new En;if(e instanceof O?s.parent=e:e&&(Object.assign(s,e),s.cloneAssign(e)),s.parent===void 0&&(s.parent=n.scene),this.mustLoad&&await this.loadAssetAsync(),ps&&console.log("Instantiate",this.url,"parent:",e),this.asset){ps&&console.log("Add to scene",this.asset);let r=ie.currentlyInstantiating.get(this.url);if(r!==void 0&&r>=1e4)return console.error("Recursive or too many instantiations of "+this.url+" in the same frame ("+r+")"),null;try{if(r===void 0&&(r=0),r+=1,ie.currentlyInstantiating.set(this.url,r),t){s.context=n;const a=this.asset;a.guid=this.url;const l=xg(a,s,void 0,i);if(l)return l}else{const a=Da(this.asset,s);if(a)return a}}finally{n.post_render_callbacks.push(()=>{r===void 0||r<0?r=0:r-=1,ie.currentlyInstantiating.set(this.url,r)})}}else ps&&console.warn("Failed to load asset",this.url);return null}tryGetActualGameObjectRoot(e){if(e&&e.scene){const t=e.scene;if(t.isGroup&&t.children.length===1&&t.children[0].name+"glb"===t.name){const i=t.children[0];return i.animations=t.animations,i}else return t}return null}}class Fk extends Xi{constructor(){super([ie],"AssetReferenceSerializer")}onSerialize(e,t){if(e&&e.uri!==void 0&&typeof e.uri=="string")return e.uri}onDeserialize(e,t){if(typeof e=="string")return t.context?t.gltfId?ie.getOrCreate(t.gltfId,e,t.context):(console.error("Missing source id"),null):(console.error("Missing context"),null);if(e instanceof O){if(!t.context)return console.error("Missing context"),null;if(!t.gltfId)return console.error("Missing source id"),null;const i=e,n=t.context,s=i.guid??i.uuid,r=n.addressables.findAssetReference(s);if(r)return r;const a=new ie(s,void 0,i);return n.addressables.registerAssetReference(a),a}return null}}new Fk;const Uk=Promise.resolve(null);class ha{static imageReferences=new Map;static getOrCreate(e){let t=ha.imageReferences.get(e);return t||(t=new ha(e),ha.imageReferences.set(e,t)),t}constructor(e){this.url=e}url;_bitmap;_bitmapObject;dispose(){this._bitmapObject&&this._bitmapObject.close(),this._bitmap=void 0}createHTMLImage(){const e=new Image;return e.src=this.url,e}loader=null;createTexture(){return this.url?(this.loader||(this.loader=new Fl),this.loader.setCrossOrigin("anonymous"),this.loader.loadAsync(this.url).then(e=>(e&&!e.name?.length&&(e.name=this.url.split("/").pop()??this.url),e))):(console.error("Can not load texture without url"),Uk)}getBitmap(){return this._bitmap?this._bitmap:(this._bitmap=new Promise((e,t)=>{const i=document.createElement("img");i.addEventListener("load",()=>{this._bitmap=createImageBitmap(i).then(n=>(this._bitmapObject=n,e(n),n))}),i.addEventListener("error",n=>{console.error("Failed to load image:"+this.url,n),e(null)}),i.src=this.url}),this._bitmap)}}class Mv extends Xi{constructor(){super([ha],"ImageReferenceSerializer")}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"){const i=ls(t.gltfId,e);return ha.getOrCreate(i)}}}new Mv;class da{static cache=new Map;static getOrCreate(e){let t=da.cache.get(e);return t||(t=new da(e),da.cache.set(e,t)),t}async loadRaw(){return this.res||(this.res=fetch(this.url)),this.res.then(e=>e.blob())}async loadText(){return this.res||(this.res=fetch(this.url)),this.res.then(e=>e.text())}url;res;constructor(e){this.url=e}}class Rv extends Xi{constructor(){super([da],"FileReferenceSerializer")}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"){const i=ls(t.gltfId,e);return da.getOrCreate(i)}}}new Rv;class zk{context;mixers=[];constructor(e){this.context=e}onDestroy(){this.mixers.forEach(e=>e.stopAllAction()),this.mixers.length=0}registerAnimationMixer(e){if(!e){console.warn("AnimationsRegistry.registerAnimationMixer called with null or undefined mixer");return}this.mixers.includes(e)||this.mixers.push(e)}unregisterAnimationMixer(e){if(!e){console.warn("AnimationsRegistry.unregisterAnimationMixer called with null or undefined mixer");return}const t=this.mixers.indexOf(e);t!==-1&&this.mixers.splice(t,1)}}class Ba{static tryGetActionsFromMixer(e){return e._actions||null}static tryGetAnimationClipsFromObjectHierarchy(e,t){if(t||(t=new Array),e)e.animations&&t.push(...e.animations);else return t;if(e.children)for(const i of e.children)this.tryGetAnimationClipsFromObjectHierarchy(i,t);return t}static autoplayAnimations(e){if(!e||!e.animations)return console.debug("No animations found in file"),null;const t="scene"in e?e.scene:e,i=new Array;for(let s=0;s<e.animations.length;s++){const r=e.animations[s];if(!r.tracks||r.tracks.length<=0){console.warn("Animation has no tracks");continue}for(const a in r.tracks){const l=r.tracks[a],c=fa.parseTrackName(l.name);let h=fa.findNode(t,c.nodeName);if(!h){const p=l.__objectName??l.name.substring(0,l.name.indexOf("."));if(h=t.getObjectByProperty("uuid",p),!h)continue}let d=n(h)||n(t);if(!d){const p=C.get("Animation");if(d=t.addComponent(p),!d){console.error("Failed creating Animation component: No 'Animation' component found in TypeStore");break}}i.push(d),d.addClip&&d.addClip(r)}}return i;function n(s){if(!s)return null;const r=s.userData?.components;if(r&&r.length>0)for(let a=0;a<r.length;a++){const l=r[a];if(l.isAnimationComponent===!0)return l}return n(s.parent)}}}function*Dg(o,e=null){const t=e?e.time:z.Current.time,i=t.time;for(;t.time-i<o;)yield}function*Nk(o){for(let e=0;e<o;e++)yield}function*Tv(o){let e=!0;for(o.then(()=>e=!1),o.catch(()=>e=!1);e;)yield}const Ev="NEEDLE_lightmaps",gc=w("debuglightmapsextension")||w("debuglightmaps");var zn=(o=>(o[o.Lightmap=0]="Lightmap",o[o.Skybox=1]="Skybox",o[o.Reflection=2]="Reflection",o))(zn||{});class Wk{get name(){return Ev}parser;registry;source;constructor(e,t,i){this.parser=e,this.registry=t,this.source=i}afterRoot(e){const t=this.parser.json.extensions;if(t){const i=t[Ev];if(i){const n=i.textures;return n?.length?(gc&&console.log(i),new Promise(async(s,r)=>{const a=[];for(const c of n)if(c.pointer){gc&&console.log(c);let h=null;if(c.pointer.startsWith("/textures/")||c.pointer.startsWith("textures/"))gc&&console.log("Load texture from gltf",c.pointer),h=Pg(this.parser,c.pointer).then(d=>this.resolveTexture(c,d));else if(typeof c.pointer=="string"){gc&&console.log("Load texture from path",c.pointer);const d=ls(this.source,c.pointer);let p;d.endsWith(".exr")?p=new mm(this.parser.options.manager):d.endsWith(".hdr")?p=new Q0(this.parser.options.manager):p=new Fl(this.parser.options.manager),h=p.loadAsync(d,void 0).then(g=>this.resolveTexture(c,g))}else c.pointer;h&&a.push(h)}const l=await Pm(a);l?.anyFailed&&E()&&console.error("Failed to load lightmap extension",l),s()})):null}}return null}resolveTexture(e,t){const i=t;gc&&console.log("Lightmap loaded:",i),i?.isTexture&&(this.registry?(i.colorSpace=po,this.registry.registerTexture(this.source,e.type,i,e.index)):console.log(zn[e.type],e.pointer,i))}}const Fa=!!w("debuglightmaps");class Vk{_context;_lightmaps=new Map;clear(){this._lightmaps.clear()}constructor(e){this._context=e}registerTexture(e,t,i,n){Fa&&console.log("Registering ",zn[t]+' "'+e+'"',i),this._lightmaps.has(e)||this._lightmaps.set(e,new Map);const s=this._lightmaps.get(e),r=s?.get(t)??[];r.length<n&&(r.length=n+1),B_(i,!1),r[n]=i,s?.set(t,r)}tryGetLightmap(e,t=0){return this.tryGet(e,zn.Lightmap,t)}tryGetSkybox(e){return Fa&&console.log("[Get Skybox]",e,this._lightmaps),this.tryGet(e,zn.Skybox,0)}tryGetReflection(e){return Fa&&console.log("[Get Reflection]",e,this._lightmaps),this.tryGet(e,zn.Reflection,0)}tryGet(e,t,i){if(!e)return Fa&&console.warn("Missing source id"),null;const n=this._lightmaps.get(e);if(!n)return Fa&&console.warn(`[Lighting] No ${zn[t]} texture entry for`,e),null;const s=n.get(t);return s===void 0?(Fa&&console.warn(`[Lighting] No ${zn[t]} texture for`,e,"index",i),null):!s?.length||s.length<=i?null:s[i]}}Nt.lights_fragment_maps=Nt.lights_fragment_maps.replace("vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );",`
190
+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis`,e))),mv()&&console.log("[onGetComponent] FIND",e),e==null))return null;for(let i=0;i<o.userData.components.length;i++){const n=o.userData.components[i];let s=Object.getPrototypeOf(n);for(;s;){if(s===e.prototype)if(mv()&&console.log("[onGetComponent] MATCH BY PROTOYPE",s),t)t.push(n);else return n;s=Object.getPrototypeOf(s)}}return t||null}function br(o,e){const t=bv(o,e);return t?Array.isArray(t)?t[0]:t:null}function hc(o,e,t,i=!0){return t||(t=[]),i&&(t.length=0),bv(o,e,t),t}function dc(o,e,t){if(t===!1&&o[_o]===!1)return null;const i=br(o,e);if(t===!1&&i?.enabled===!1)return null;if(i)return i;for(let n=0;n<o?.children?.length;n++){const s=dc(o.children[n],e);if(s)return s}return null}function Ia(o,e,t,i=!0){t||(t=[]),i&&(t.length=0),hc(o,e,t,!1);for(let n=0;n<o?.children?.length;n++)Ia(o.children[n],e,t,!1);return t}function uc(o,e){if(!o)return null;if(Array.isArray(o)){for(let i=0;i<o.length;i++){const n=Ek(o[i]),s=uc(n,e);if(s)return s}return null}return br(o,e)||(o.parent?uc(o.parent,e):null)}function Xd(o,e,t,i=!0){return t||(t=[]),i&&(t.length=0),o?(hc(o,e,t,!1),o.parent?Xd(o.parent,e,t,!1):t):t}function pc(o,e=void 0,t=!0){if(!o)return null;if(!e&&(e=z.Current,!e))return console.error("Can not search object without any needle context or scene!!!"),null;let i=e;return i.isScene||(i=e?.scene),i&&dc(i,o,t)||null}function _v(o,e,t=void 0){if(!o)return e??[];if(e||(e=[]),e.length=0,!t&&(t=z.Current,!t))return console.error("Can not search object without any needle context or scene!!!"),e;"scene"in t&&(t=t.scene);const i=t;return i&&Ia(i,o,e,!1),e}function Qd(o){o&&o.isObject3D===!0&&uv(o,O)}if(sc.experimentalSmartHierarchyUpdate){const o=O.prototype.add;O.prototype.add=function(...i){return bg(),o.apply(this,i)};const e=O.prototype.attach;O.prototype.attach=function(...i){return bg(),e.apply(this,i)};const t=O.prototype.remove;O.prototype.remove=function(...i){return bg(),t.apply(this,i)}}O.prototype.SetActive=function(o){this.visible=o},O.prototype.setActive=function(o){this.visible=o},O.prototype.destroy=function(){Ci(this)},O.prototype.addComponent=function(o,e){return bn(this,o,e)},O.prototype.addNewComponent=function(o,e){return bn(this,o,e)},O.prototype.removeComponent=function(o){return Eg(this,o)},O.prototype.getOrAddComponent=function(o,e){return cc(this,o,e)},O.prototype.getComponent=function(o){return br(this,o)},O.prototype.getComponents=function(o,e){return hc(this,o,e)},O.prototype.getComponentInChildren=function(o){return dc(this,o)},O.prototype.getComponentsInChildren=function(o,e){return Ia(this,o,e)},O.prototype.getComponentInParent=function(o){return uc(this,o)},O.prototype.getComponentsInParent=function(o,e){return Xd(this,o,e)},Object.getOwnPropertyDescriptor(O.prototype,"activeSelf")||Object.defineProperty(O.prototype,"activeSelf",{get:function(){return La(this)},set:function(o){mc(this,o)}}),Object.getOwnPropertyDescriptor(O.prototype,"worldPosition")||Object.defineProperty(O.prototype,"worldPosition",{get:function(){return this instanceof X0?Z(this.object):Z(this)},set:function(o){mt(this,o)}}),Object.getOwnPropertyDescriptor(O.prototype,"worldQuaternion")||Object.defineProperty(O.prototype,"worldQuaternion",{get:function(){return this instanceof X0?be(this.object):be(this)},set:function(o){pn(this,o)}}),Object.getOwnPropertyDescriptor(O.prototype,"worldRotation")||Object.defineProperty(O.prototype,"worldRotation",{get:function(){return xd(this)},set:function(o){Ub(this,o)}}),Object.getOwnPropertyDescriptor(O.prototype,"worldScale")||Object.defineProperty(O.prototype,"worldScale",{get:function(){return $e(this)},set:function(o){wa(this,o)}});const Ak=new ee,Ik=new b(0,0,0),Lk=new b(0,1,0);Object.getOwnPropertyDescriptor(O.prototype,"worldForward")||Object.defineProperty(O.prototype,"worldForward",{get:function(){return $().set(0,0,1).applyQuaternion(be(this))},set:function(o){const e=ti().setFromRotationMatrix(Ak.lookAt(Ik.set(0,0,0),o,Lk.set(0,1,0)));this.worldQuaternion=e}}),Object.getOwnPropertyDescriptor(O.prototype,"worldRight")||Object.defineProperty(O.prototype,"worldRight",{get:function(){return $().set(1,0,0).applyQuaternion(be(this))}}),Object.getOwnPropertyDescriptor(O.prototype,"worldUp")||Object.defineProperty(O.prototype,"worldUp",{get:function(){return $().set(0,1,0).applyQuaternion(be(this))}}),pv(O);class se extends ne{alpha=1;get isRGBAColor(){return!0}set a(e){this.alpha=e}get a(){return this.alpha}constructor(e,t,i,n){super(),typeof e=="number"&&typeof t=="number"&&typeof i=="number"?(this.set(e,t,i),this.alpha=typeof n=="number"?n:1):e!==void 0&&(this.set(e),this.alpha=1)}clone(){const e=super.clone();return e.alpha=this.alpha,e}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,"alpha"in e&&typeof e.alpha=="number"?this.alpha=e.alpha:typeof e.a=="number"&&(this.alpha=e.a),this}lerp(e,t){const i=e;return i.alpha!=null&&(this.alpha=D.lerp(this.alpha,i.alpha,t)),super.lerp(e,t)}lerpColors(e,t,i){const n=e,s=t;return n.alpha!=null&&s.alpha!=null&&(this.alpha=D.lerp(n.alpha,s.alpha,i)),super.lerpColors(e,t,i)}multiply(e){const t=e;return t.alpha!=null&&(this.alpha=this.alpha*t.alpha),super.multiply(e)}fromArray(e,t=0){return this.alpha=e[t+3],super.fromArray(e,t)}static fromColorRepresentation(e){if(typeof e=="string"){if(e.trim()==="transparent")return new se(0,0,0,0);if(e.startsWith("#")&&e.length===9){const t=parseInt(e.slice(1,9),16),i=t>>24&255,n=t>>16&255,s=t>>8&255,r=t>>0&255;return new se(i/255,n/255,s/255,r/255)}else if(e.startsWith("#")){const t=parseInt(e.slice(1),16),i=t>>16&255,n=t>>8&255,s=t>>0&255;return new se(i/255,n/255,s/255,1)}else if(e.startsWith("rgba")){const t=e.slice(5,-1).split(",").map(Number);return new se(t[0]/255,t[1]/255,t[2]/255,t[3])}else if(e.startsWith("rgb")){const t=e.slice(4,-1).split(",").map(Number);return new se(t[0]/255,t[1]/255,t[2]/255,1)}}else if(Array.isArray(e)){if(e.length===4)return new se(e[0],e[1],e[2],e[3]);if(e.length===3)return new se(e[0],e[1],e[2],1);console.error("Invalid color array length. Expected 3 or 4, got "+e.length)}return new se(e)}}const Yd=w("debuggetcomponent"),_r=w("debuginstantiate");class En{idProvider;parent;keepWorldPosition;position;rotation;scale;visible;context;components;clone(){const e=new En;return e.idProvider=this.idProvider,e.parent=this.parent,e.keepWorldPosition=this.keepWorldPosition,e.position=Array.isArray(this.position)?[...this.position]:this.position?.clone(),e.rotation=Array.isArray(this.rotation)?[...this.rotation]:this.rotation?.clone(),e.scale=Array.isArray(this.scale)?[...this.scale]:this.scale?.clone(),e.visible=this.visible,e.context=this.context,e.components=this.components,e}cloneAssign(e){this.idProvider=e.idProvider,this.parent=e.parent,this.keepWorldPosition=e.keepWorldPosition,this.position=Array.isArray(e.position)?[...e.position]:e.position?.clone(),this.rotation=Array.isArray(e.rotation)?[...e.rotation]:e.rotation?.clone(),this.scale=Array.isArray(e.scale)?[...e.scale]:e.scale?.clone(),this.visible=e.visible,this.context=e.context,this.components=e.components}}function La(o){return o.visible}function mc(o,e){return typeof e=="number"&&(e=e>.5),o.visible=e,o.visible}function vv(o){return o[_o]||Kd(o)}function wv(o,e){o[z_]=e}function Kd(o){return an.isUsingInstancing(o)}function Ag(o,e){return _a(o,e,!0,!0)}const xv=Symbol("isDestroyed");function vr(o){return o[xv]}function Sv(o,e){o[xv]=e}const Ig=Symbol("isDontDestroy");function ja(o,e=!0){o[Ig]=e}const Zd=[],Jd=[];function Ci(o,e=!0,t=!1){Zd.length=0,Jd.length=0,Lg(o,e,!0);for(const i of Zd)i.gameObject=null,i.context=null;for(const i of Jd)Sv(i,!0),t&&Pe(i);Jd.length=0,Zd.length=0}function Lg(o,e=!0,t=!0){if(o==null)return;const i=o;if(i.isComponent){if(i[Ig])return;Zd.push(i);const r=i.gameObject;i.__internalDisable(),i.__internalDestroy(),i.gameObject=r;return}if(o[Ig])return;const n=o;Yd&&console.log(n),Jd.push(n);const s=n.userData?.components;if(s!=null&&Array.isArray(s)){let r=s.length;for(let a=0;a<s.length;a++){const l=s[a];Lg(l,e,!1),s.length<r&&(r=s.length,a--)}}if(e&&n.children)for(const r of n.children)Lg(r,e,!1);t&&n.removeFromParent()}function wr(o,e,t=!0){return Cv(o,e,t)}function*eu(o,e,t=!1,i=999,n=0){if(o?.userData.components&&!(n>i)){for(const s of o.userData.components)e&&s?.isComponent===!0&&s instanceof e?yield s:yield s;if(t===!0)for(const s of o.children)yield*eu(s,e,!0,i,n+1)}}function Cv(o,e,t,i=0){if(o){if(o.isObject3D,i>1e3){console.warn("Failed to iterate components: too many levels");return}if(o.userData?.components)for(let n=0;n<o.userData.components.length;n++){const s=o.userData.components[n];if(s?.isComponent===!0){const r=e(s);if(r!==void 0)return r}}if(t&&o.children){const n=i+1;for(let s=0;s<o.children.length;s++){const r=o.children[s];if(!r)continue;const a=Cv(r,e,t,n);if(a!==void 0)return a}}}}function Da(o,e){if("isAssetReference"in o)return o.instantiate(e??void 0);let t=null;e!=null&&(e.x!==void 0?(t=new En,t.position=e):t=e);let i=z.Current;t?.context&&(i=t.context),Yd&&i.alias&&console.log("context",i.alias),t&&!t.idProvider&&(t.idProvider=new At(Date.now()));const n=[],s={},r={},a=Pv(i,o,t,n,s,r);a&&(Bk(a,s),Dk(r,s)),Yd&&(Sd(o,!0),Sd(a,!0));const l={};if(t?.components!==!1){for(const c in n){const h=n[c],d=h.guid;t&&t.idProvider&&(h.guid=t.idProvider.generateUUID(),l[d]=h.guid,Yd&&console.log(h.name,h.guid)),lu(h,i),h.__internalNewInstanceCreated&&h.__internalNewInstanceCreated()}for(const c in n){const h=n[c];h.resolveGuids&&h.resolveGuids(l),h.enabled!==!1&&(h.enabled=!0)}Nd(i)}return a}function Pv(o,e,t,i,n,s){if(!e||e[Si])return null;const r=e.userData;e.userData={};const a=e.children;e.children=[];const l=e.clone(!1);if(Qd(l),e.userData=r,e.children=a,n[e.uuid]={original:e,clone:l},_r&&console.log("ADD",e,l),e.type==="SkinnedMesh"&&(s[e.uuid]={original:e,clone:l}),t?.visible!==void 0&&(l.visible=t.visible),t?.idProvider){l.uuid=t.idProvider.generateUUID();const h=l;h&&(h.guid=l.uuid)}e.animations&&e.animations.length>0&&(l.animations=[...e.animations]);const c=e.parent;if(c&&c.add(l),t?.position)if(Array.isArray(t.position)){const h=new b;h.fromArray(t.position),l.worldPosition=h}else l.worldPosition=t.position;else l.position.copy(e.position);if(t?.rotation){if(t.rotation instanceof U)l.worldQuaternion=t.rotation;else if(t.rotation instanceof nt)l.worldQuaternion=ti().setFromEuler(t.rotation);else if(Array.isArray(t.rotation)){const h=new nt;h.fromArray(t.rotation),l.worldQuaternion=ti().setFromEuler(h)}}else l.quaternion.copy(e.quaternion);if(t?.scale)if(Array.isArray(t.scale)){const h=new b;h.fromArray(t.scale),t.scale=h}else l.scale.copy(t.scale);else l.scale.copy(e.scale);if(t?.parent&&t.parent!=="scene"){let h=null;if(typeof t.parent=="string"?h=_a(t.parent,o.scene,!0):h=t.parent,h){const d=t.keepWorldPosition===!0?h.attach:h.add;d?d.call(h,l):console.error("Invalid parent object",h,"received when instantiating:",e)}else console.warn("could not find parent:",t.parent)}for(const[h,d]of Object.entries(e.userData))h!=="components"&&(l.userData[h]=d);if(e.userData?.components){const h=e.userData.components,d=[];l.userData.components=d;for(let p=0;p<h.length;p++){const m=h[p],f=new m.constructor;jk(m,f),m[Yl]!==void 0&&(f[Yl]=m[Yl]),d.push(f),f.gameObject=l,i.push(f),n[m.guid]={original:m,clone:f},zd.dispatchComponentLifecycleEvent("component-added",f)}}t&&(t.position=void 0,t.rotation=void 0,t.scale=void 0,t.parent=void 0,t.visible=void 0);for(const h in e.children){const d=e.children[h],p=Pv(o,d,t,i,n,s);p&&(n[p.uuid]={original:d,clone:p},l.add(p))}return l}function jk(o,e,t){Aa(e,o,void 0,{})}function Dk(o,e){for(const t in o){const i=o[t],n=i.original,s=n.skeleton,r=i.clone;if(!s){console.warn("Skinned mesh has no skeleton?",i);continue}const a=s.bones,l=r.skeleton.clone();r.skeleton=l,r.bindMatrix.clone().copy(n.bindMatrix),r.bindMatrixInverse.copy(n.bindMatrixInverse);const c=[];l.bones=c;for(let h=0;h<a.length;h++){const d=a[h],p=e[d.uuid].clone;c.push(p)}}for(const t in o){const i=o[t].clone;i.skeleton.update(),i.bind(i.skeleton,i.bindMatrix),i.updateMatrixWorld(!0)}}function Bk(o,e){for(const t in e){const i=e[t].clone;if(i?.isObject3D&&i?.userData?.components)for(let n=0;n<i.userData.components.length;n++){const s=i.userData.components[n],r=Object.entries(s);for(const[a,l]of r)if(Array.isArray(l)){const c=[];s[a]=c;for(let h=0;h<l.length;h++){const d=l[h];if(typeof d!="object"){c.push(d);continue}const p=Ov(s,a,d,e);p!==void 0?(_r&&console.log("Found new instance for",a,d,"->",p),c.push(p)):(_r&&console.warn("Could not find new instance for",a,d),c.push(d))}}else if(typeof l=="object"){const c=Ov(s,a,l,e);c!==void 0?s[a]=c:_r&&console.warn("Could not find new instance for",a,l)}}}}function Ov(o,e,t,i){if(t!=null)if(t.isComponent===!0){const n=t.gameObject;if(n){const s=n.uuid,r=i[s]?.clone;if(!r){_r&&console.log("reference did not change",e,o,t);return}const a=n.userData.components.indexOf(t);if(a>=0&&r.isObject3D)return _r&&console.log(e,s),r.userData.components[a];console.warn("could not find component",e,t)}}else if(t.isObject3D===!0){if(e==="gameObject")return;const n=t;if(n){const s=n.uuid,r=i[s]?.clone;if(r)return _r&&console.log(e,"old",t,"new",r),r}}else{if(t.isVector4||t.isVector3||t.isVector2||t.isQuaternion||t.isEuler||t.isColor===!0)return t.clone();if(t.isEventList===!0)return t.__internalOnInstantiate(i)}}var xr;(o=>{o.baseUrl="https://networking.needle.tools";function e(l){return ib(new Uint8Array(l))}o.hashMD5=e;function t(l){const c=ib(new Uint8Array(l),{encoding:"binary",asBytes:!0});return btoa(String.fromCharCode(...c))}o.hashMD5_Base64=t;function i(l){const c=new Uint8Array(l);return crypto.subtle.digest("SHA-256",c).then(h=>btoa(String.fromCharCode(...new Uint8Array(h))))}o.hashSha256=i;function n(l){const c=l.filesize/1024/1024;return Vn()?c<50:c<5}o.canUpload=n;async function s(l,c){const h=o.baseUrl;if(h){if(!l.name)return console.error("Upload: file name is missing"),null}else return console.error("Blob storage base url is not set"),null;let d=null;l instanceof File?d=await l.arrayBuffer():d=l.data;const p=d.byteLength,m=p/1024/1024;if(m>50)return c?.silent!==!0&&ge(`File (${m.toFixed(1)}MB) is too large for uploading (see console for details)`),console.warn(`Your file is too large for uploading (${m.toFixed(1)}MB). Max allowed size is 50MB`),null;if(!Vn()&&m>5)return c?.silent!==!0&&ge('File is too large for uploading. Please get a <a href="https://needle.tools/pricing" target="_blank">commercial license</a> to upload files larger than 5MB'),console.warn(`Your file is too large for uploading (${m.toFixed(1)}MB). Max size is 5MB for non-commercial users. Please get a commercial license at https://needle.tools/pricing for larger files (up to 50MB)`),null;if(p<1)return console.warn(`Your file is too small for uploading (${m.toFixed(1)}MB). Min size is 1 byte`),null;const f=t(d),g={filename:l.name,"Content-Md5":f,"Content-Type":l.type||"application/octet-stream",FileSize:p.toString(),"Content-Disposition":`attachment; filename="${l.name}"`,"x-amz-server-side-encryption":"AES256"},y=await fetch(h+"/api/needle/blob",{method:"POST",headers:g,signal:c?.abort}).then(_=>_.json()).catch(_=>(console.error(_),null));if(y==null)return console.warn("Upload failed..."),null;if("error"in y)return console.error(y.error),null;if("upload"in y&&y.upload){let _=function(R){return c?.onProgress?.call(null,{progress01:0,state:"inprogress"}),fetch(R,{method:"PUT",headers:g,body:d,signal:c?.abort}).then(k=>(c?.onProgress?.call(null,{progress01:1,state:"finished"}),k)).catch(k=>k)};console.debug("Uploading file",y.upload);let v=!1,P=null;for(let R=0;R<3;R++)try{if(v)break;if(c?.abort?.aborted)return console.debug("Aborted upload"),null;const k=await _(y.upload);k instanceof Error?(P=k,await Dn(1e3*R)):k.ok&&(console.debug("File uploaded successfully"),v=!0)}catch(k){console.error(k)}if(!v)return console.error(P?.message||"Failed to upload file"),null}if("download"in y){const _=h+y.download;return console.debug("File found in blob storage",_),{key:y.key,success:!0,download_url:_}}return null}o.upload=s;function r(l){return`${o.baseUrl}/api/needle/blob/${l}`}o.getBlobUrlForKey=r;async function a(l,c){const h=new nm;h.setResponseType("arraybuffer");const d=await h.loadAsync(l,p=>{c&&c.call(null,p)});return d instanceof ArrayBuffer?new Uint8Array(d):(console.error("Download failed, no arraybuffer returned"),null)}o.download=a})(xr||(xr={}));const ps=w("debugaddressables");class kv{_context;_assetReferences={};constructor(e){this._context=e,this._context.pre_update_callbacks.push(this.preUpdate)}dispose(){const e=this._context.pre_update_callbacks.indexOf(this.preUpdate);e>=0&&this._context.pre_update_callbacks.splice(e,1);for(const t in this._assetReferences)this._assetReferences[t]?.unload();this._assetReferences={}}preUpdate=()=>{};findAssetReference(e){return this._assetReferences[e]||null}registerAssetReference(e){return e.url&&(this._assetReferences[e.url]?console.warn("Asset reference already registered",e):this._assetReferences[e.url]=e),e}unregisterAssetReference(e){e.url&&delete this._assetReferences[e.url]}}const jg=Symbol("assetReference");class ie{static getOrCreateFromUrl(e,t){if(!t&&(t=z.Current,!t))throw new Error('Context is required when sourceId is a string. When you call this method from a component you can call it with "getOrCreate(this, url)" where "this" is the component.');const i=t.addressables,n=i.findAssetReference(e);if(n)return n;const s=new ie(e,t.hash);return i.registerAssetReference(s),s}static getOrCreate(e,t,i){if(typeof e=="string"){if(!i&&(i=z.Current,!i))throw new Error('Context is required when sourceId is a string. When you call this method from a component you can call it with "getOrCreate(this, url)" where "this" is the component.')}else i=e.context,e=e.sourceId;const n=ls(e,t);ps&&console.log("GetOrCreate Addressable from",e,t,"FinalPath=",n);const s=i.addressables,r=s.findAssetReference(n);if(r)return r;const a=new ie(n,i.hash);return s.registerAssetReference(a),a}isAssetReference=!0;get rawAsset(){return this._rawAsset}get asset(){return this._glbRoot??(this._rawAsset?.scene||null)}set asset(e){e?this._rawAsset={animations:e.animations,scene:e,scenes:[e]}:this._rawAsset=null}get uri(){return this._url}get url(){return this._url}get urlName(){return this._urlName}get hasUrl(){return this._url!==void 0&&(this._url.startsWith("http")||this._url.startsWith("blob:")||this._url.startsWith("www.")||this._url.includes("/"))}_rawAsset=null;_glbRoot;_url;_urlName;_progressListeners=[];_isLoadingRawBinary=!1;_rawBinary;constructor(...e){typeof e[0]=="object"?"url"in e[0]?this._url=e[0].url:(this._url="",e[0].asset&&(this.asset=e[0].asset)):(this._url=e[0],e[2]instanceof O&&(this.asset=e[2]));const t=this._url.lastIndexOf("/");if(t>=0){this._urlName=this._url.substring(t+1);const i=this._urlName.lastIndexOf(".");i>=0&&(this._urlName=this._urlName.substring(0,i))}else this._urlName=this._url;ev(this._url,this.onResolvePrefab.bind(this))}async onResolvePrefab(e){return e===this.url&&(this.mustLoad&&await this.loadAssetAsync(),this.asset)?this.asset:null}get mustLoad(){return!this.asset||this.asset.__destroyed===!0||vr(this.asset)===!0}_loadingPromise=null;isLoaded(){return this._rawBinary||this.asset!==void 0}unload(){this.asset&&(ps&&console.log("Unload",this.asset),"scene"in this.asset&&this.asset.scene&&Ci(this.asset.scene,!0,!0),Ci(this.asset,!0,!0)),this.asset=null,this._rawBinary=void 0,this._glbRoot=null,this._loadingPromise=null,z.Current&&z.Current.addressables.unregisterAssetReference(this)}async preload(){if(!this.mustLoad||this._isLoadingRawBinary)return null;if(this._rawBinary!==void 0)return this._rawBinary;this._isLoadingRawBinary=!0,ps&&console.log("Preload",this.url);const e=await xr.download(this.url,t=>{this.raiseProgressEvent(t)});return this._rawBinary=e?.buffer??null,this._isLoadingRawBinary=!1,this._rawBinary}async loadAssetAsync(e){if(ps&&console.log("[AssetReference] loadAssetAsync",this.url),!this.mustLoad)return this.asset;if(e&&this._progressListeners.push(e),this._loadingPromise!==null)return this._loadingPromise.then(n=>this.asset);const t=z.Current;if(this._rawBinary){if(!(this._rawBinary instanceof ArrayBuffer))return console.error("[AssetReference] Failed loading \u2013 Invalid data. Must be of type ArrayBuffer. "+typeof this._rawBinary),null;this._loadingPromise=gn().parseSync(t,this._rawBinary,this.url,null),this.raiseProgressEvent(new ProgressEvent("progress",{loaded:this._rawBinary.byteLength,total:this._rawBinary.byteLength}))}else ps&&console.log("Load async",this.url),this._loadingPromise=gn().loadSync(t,this.url,this.url,null,n=>{this.raiseProgressEvent(n)});this._loadingPromise.finally(()=>this._loadingPromise=null);const i=await this._loadingPromise;return this._progressListeners.length=0,this._glbRoot=this.tryGetActualGameObjectRoot(i),i?(i[jg]=this,this._glbRoot&&(this._glbRoot[jg]=this),this.asset&&(this.asset[jg]=this),Nd(t),i.scene!==void 0&&(this._rawAsset=i),this.asset):null}instantiate(e){return this.onInstantiate(e,!1)}instantiateSynced(e,t=!0){return this.onInstantiate(e,!0,t)}beginListenDownload(e){this._progressListeners.indexOf(e)<0&&this._progressListeners.push(e)}endListenDownload(e){const t=this._progressListeners.indexOf(e);t>=0&&this._progressListeners.splice(t,1)}raiseProgressEvent(e){for(const t of this._progressListeners)t(this,e)}static currentlyInstantiating=new Map;async onInstantiate(e,t=!1,i){const n=z.Current,s=new En;if(e instanceof O?s.parent=e:e&&(Object.assign(s,e),s.cloneAssign(e)),s.parent===void 0&&(s.parent=n.scene),this.mustLoad&&await this.loadAssetAsync(),ps&&console.log("Instantiate",this.url,"parent:",e),this.asset){ps&&console.log("Add to scene",this.asset);let r=ie.currentlyInstantiating.get(this.url);if(r!==void 0&&r>=1e4)return console.error("Recursive or too many instantiations of "+this.url+" in the same frame ("+r+")"),null;try{if(r===void 0&&(r=0),r+=1,ie.currentlyInstantiating.set(this.url,r),t){s.context=n;const a=this.asset;a.guid=this.url;const l=xg(a,s,void 0,i);if(l)return l}else{const a=Da(this.asset,s);if(a)return a}}finally{n.post_render_callbacks.push(()=>{r===void 0||r<0?r=0:r-=1,ie.currentlyInstantiating.set(this.url,r)})}}else ps&&console.warn("Failed to load asset",this.url);return null}tryGetActualGameObjectRoot(e){if(e&&e.scene){const t=e.scene;if(t.isGroup&&t.children.length===1&&t.children[0].name+"glb"===t.name){const i=t.children[0];return i.animations=t.animations,i}else return t}return null}}class Fk extends Xi{constructor(){super([ie],"AssetReferenceSerializer")}onSerialize(e,t){if(e&&e.uri!==void 0&&typeof e.uri=="string")return e.uri}onDeserialize(e,t){if(typeof e=="string")return t.context?t.gltfId?ie.getOrCreate(t.gltfId,e,t.context):(console.error("Missing source id"),null):(console.error("Missing context"),null);if(e instanceof O){if(!t.context)return console.error("Missing context"),null;if(!t.gltfId)return console.error("Missing source id"),null;const i=e,n=t.context,s=i.guid??i.uuid,r=n.addressables.findAssetReference(s);if(r)return r;const a=new ie(s,void 0,i);return n.addressables.registerAssetReference(a),a}return null}}new Fk;const Uk=Promise.resolve(null);class ha{static imageReferences=new Map;static getOrCreate(e){let t=ha.imageReferences.get(e);return t||(t=new ha(e),ha.imageReferences.set(e,t)),t}constructor(e){this.url=e}url;_bitmap;_bitmapObject;dispose(){this._bitmapObject&&this._bitmapObject.close(),this._bitmap=void 0}createHTMLImage(){const e=new Image;return e.src=this.url,e}loader=null;createTexture(){return this.url?(this.loader||(this.loader=new Fl),this.loader.setCrossOrigin("anonymous"),this.loader.loadAsync(this.url).then(e=>(e&&!e.name?.length&&(e.name=this.url.split("/").pop()??this.url),e))):(console.error("Can not load texture without url"),Uk)}getBitmap(){return this._bitmap?this._bitmap:(this._bitmap=new Promise((e,t)=>{const i=document.createElement("img");i.addEventListener("load",()=>{this._bitmap=createImageBitmap(i).then(n=>(this._bitmapObject=n,e(n),n))}),i.addEventListener("error",n=>{console.error("Failed to load image:"+this.url,n),e(null)}),i.src=this.url}),this._bitmap)}}class Mv extends Xi{constructor(){super([ha],"ImageReferenceSerializer")}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"){const i=ls(t.gltfId,e);return ha.getOrCreate(i)}}}new Mv;class da{static cache=new Map;static getOrCreate(e){let t=da.cache.get(e);return t||(t=new da(e),da.cache.set(e,t)),t}async loadRaw(){return this.res||(this.res=fetch(this.url)),this.res.then(e=>e.blob())}async loadText(){return this.res||(this.res=fetch(this.url)),this.res.then(e=>e.text())}url;res;constructor(e){this.url=e}}class Rv extends Xi{constructor(){super([da],"FileReferenceSerializer")}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"){const i=ls(t.gltfId,e);return da.getOrCreate(i)}}}new Rv;class zk{context;mixers=[];constructor(e){this.context=e}onDestroy(){this.mixers.forEach(e=>e.stopAllAction()),this.mixers.length=0}registerAnimationMixer(e){if(!e){console.warn("AnimationsRegistry.registerAnimationMixer called with null or undefined mixer");return}this.mixers.includes(e)||this.mixers.push(e)}unregisterAnimationMixer(e){if(!e){console.warn("AnimationsRegistry.unregisterAnimationMixer called with null or undefined mixer");return}const t=this.mixers.indexOf(e);t!==-1&&this.mixers.splice(t,1)}}class Ba{static tryGetActionsFromMixer(e){return e._actions||null}static tryGetAnimationClipsFromObjectHierarchy(e,t){if(t||(t=new Array),e)e.animations&&t.push(...e.animations);else return t;if(e.children)for(const i of e.children)this.tryGetAnimationClipsFromObjectHierarchy(i,t);return t}static autoplayAnimations(e){if(!e||!e.animations)return console.debug("No animations found in file"),null;const t="scene"in e?e.scene:e,i=new Array;for(let s=0;s<e.animations.length;s++){const r=e.animations[s];if(!r.tracks||r.tracks.length<=0){console.warn("Animation has no tracks");continue}for(const a in r.tracks){const l=r.tracks[a],c=fa.parseTrackName(l.name);let h=fa.findNode(t,c.nodeName);if(!h){const p=l.__objectName??l.name.substring(0,l.name.indexOf("."));if(h=t.getObjectByProperty("uuid",p),!h)continue}let d=n(h)||n(t);if(!d){const p=C.get("Animation");if(d=t.addComponent(p),!d){console.error("Failed creating Animation component: No 'Animation' component found in TypeStore");break}}i.push(d),d.addClip&&d.addClip(r)}}return i;function n(s){if(!s)return null;const r=s.userData?.components;if(r&&r.length>0)for(let a=0;a<r.length;a++){const l=r[a];if(l.isAnimationComponent===!0)return l}return n(s.parent)}}}function*Dg(o,e=null){const t=e?e.time:z.Current.time,i=t.time;for(;t.time-i<o;)yield}function*Nk(o){for(let e=0;e<o;e++)yield}function*Tv(o){let e=!0;for(o.then(()=>e=!1),o.catch(()=>e=!1);e;)yield}const Ev="NEEDLE_lightmaps",gc=w("debuglightmapsextension")||w("debuglightmaps");var zn=(o=>(o[o.Lightmap=0]="Lightmap",o[o.Skybox=1]="Skybox",o[o.Reflection=2]="Reflection",o))(zn||{});class Wk{get name(){return Ev}parser;registry;source;constructor(e,t,i){this.parser=e,this.registry=t,this.source=i}afterRoot(e){const t=this.parser.json.extensions;if(t){const i=t[Ev];if(i){const n=i.textures;return n?.length?(gc&&console.log(i),new Promise(async(s,r)=>{const a=[];for(const c of n)if(c.pointer){gc&&console.log(c);let h=null;if(c.pointer.startsWith("/textures/")||c.pointer.startsWith("textures/"))gc&&console.log("Load texture from gltf",c.pointer),h=Pg(this.parser,c.pointer).then(d=>this.resolveTexture(c,d));else if(typeof c.pointer=="string"){gc&&console.log("Load texture from path",c.pointer);const d=ls(this.source,c.pointer);let p;d.endsWith(".exr")?p=new mm(this.parser.options.manager):d.endsWith(".hdr")?p=new Q0(this.parser.options.manager):p=new Fl(this.parser.options.manager),h=p.loadAsync(d,void 0).then(m=>this.resolveTexture(c,m))}else c.pointer;h&&a.push(h)}const l=await Pm(a);l?.anyFailed&&E()&&console.error("Failed to load lightmap extension",l),s()})):null}}return null}resolveTexture(e,t){const i=t;gc&&console.log("Lightmap loaded:",i),i?.isTexture&&(this.registry?(i.colorSpace=po,this.registry.registerTexture(this.source,e.type,i,e.index)):console.log(zn[e.type],e.pointer,i))}}const Fa=!!w("debuglightmaps");class Vk{_context;_lightmaps=new Map;clear(){this._lightmaps.clear()}constructor(e){this._context=e}registerTexture(e,t,i,n){Fa&&console.log("Registering ",zn[t]+' "'+e+'"',i),this._lightmaps.has(e)||this._lightmaps.set(e,new Map);const s=this._lightmaps.get(e),r=s?.get(t)??[];r.length<n&&(r.length=n+1),B_(i,!1),r[n]=i,s?.set(t,r)}tryGetLightmap(e,t=0){return this.tryGet(e,zn.Lightmap,t)}tryGetSkybox(e){return Fa&&console.log("[Get Skybox]",e,this._lightmaps),this.tryGet(e,zn.Skybox,0)}tryGetReflection(e){return Fa&&console.log("[Get Reflection]",e,this._lightmaps),this.tryGet(e,zn.Reflection,0)}tryGet(e,t,i){if(!e)return Fa&&console.warn("Missing source id"),null;const n=this._lightmaps.get(e);if(!n)return Fa&&console.warn(`[Lighting] No ${zn[t]} texture entry for`,e),null;const s=n.get(t);return s===void 0?(Fa&&console.warn(`[Lighting] No ${zn[t]} texture for`,e,"index",i),null):!s?.length||s.length<=i?null:s[i]}}Nt.lights_fragment_maps=Nt.lights_fragment_maps.replace("vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );",`
191
191
  vec2 lUv = vLightMapUv.xy * lightmapScaleOffset.xy + vec2(lightmapScaleOffset.z, (1. - (lightmapScaleOffset.y + lightmapScaleOffset.w)));
192
192
  vec4 lightMapTexel = texture2D( lightMap, lUv);
193
193
  // The range of RGBM lightmaps goes from 0 to 34.49 (5^2.2) in linear space, and from 0 to 5 in gamma space.
@@ -210,13 +210,13 @@ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects
210
210
  irradiance += 0.;
211
211
  #else
212
212
  irradiance += getLightProbeIrradiance( lightProbe, geometry.normal );
213
- #endif`),lS.lightmap.lightmapScaleOffset={value:new pe(1,1,0,0)};const Bg=w("debugprogressive"),tu=new bi,iu=new rd;class $k{static GLTF_PROGRESSIVE_LODSMANAGER_TYPE=ir;context;_lodsManager;_settings={};get manager(){return this._lodsManager}get skinnedMeshAutoUpdateBoundsInterval(){return this._lodsManager?.skinnedMeshAutoUpdateBoundsInterval||this._settings.skinnedMeshAutoUpdateBoundsInterval||0}set skinnedMeshAutoUpdateBoundsInterval(e){this._settings.skinnedMeshAutoUpdateBoundsInterval=e,this.applySettings()}get targetTriangleDensity(){return this._lodsManager?.targetTriangleDensity||this._settings.targetTriangleDensity||2e5}set targetTriangleDensity(e){this._settings.targetTriangleDensity=e,this.applySettings()}constructor(e){this.context=e}applySettings(){if(this._lodsManager)for(const e in this._settings)this._lodsManager[e]=this._settings[e]}setRenderer(e){this._lodsManager?.disable(),ir.removePlugin(this),ir.addPlugin(this),ir.debugDrawLine=F.DrawLine,this._lodsManager=ir.get(e,{engine:"needle-engine"}),this.applySettings(),this._lodsManager.enable()}disable(){this._lodsManager?.disable(),ir.removePlugin(this)}onAfterUpdatedLOD(e,t,i,n,s){Bg&&this.onRenderDebug(i,n,s)}onRenderDebug(e,t,i){if(!t.geometry||!Ve.hasLODLevelAvailable(t.geometry)&&!Ve.hasLODLevelAvailable(t.material))return;const n=ir.getObjectLODState(t);if(!n)return;let s=i.mesh_lod;const r=i.mesh_lod!=n.lastLodLevel_Mesh||i.texture_lod!=n.lastLodLevel_Texture;if(Bg&&t.geometry.boundingSphere){const a=t.geometry.boundingSphere;iu.copy(a),iu.applyMatrix4(t.matrixWorld);const l=iu.center,c=iu.radius,h=["#76c43e","#bcc43e","#c4ac3e","#c4673e","#ff3e3e"];if(r)F.DrawWireSphere(l,c,h[s],.1);else{const d=t.geometry.index?.count??0,p=Ve.getMeshLODExtension(t.geometry)?.lods;s=p?Math.min(p?.length-1,s):0;let g="";if(p&&n.lastScreenCoverage>0)for(let y=0;y<p.length;y++){const _=p[y].density,v=y==p.length-1;g+=_.toFixed(0)+">"+(_/n.lastScreenCoverage).toFixed(0)+(v?"":",")}const f=p?p[s]?.density:-1;let m="LOD "+i.mesh_lod+`
214
- TEX `+i.texture_lod;if(Bg=="density"&&(m+=`
213
+ #endif`),lS.lightmap.lightmapScaleOffset={value:new pe(1,1,0,0)};const Bg=w("debugprogressive"),tu=new bi,iu=new rd;class $k{static GLTF_PROGRESSIVE_LODSMANAGER_TYPE=ir;context;_lodsManager;_settings={};get manager(){return this._lodsManager}get skinnedMeshAutoUpdateBoundsInterval(){return this._lodsManager?.skinnedMeshAutoUpdateBoundsInterval||this._settings.skinnedMeshAutoUpdateBoundsInterval||0}set skinnedMeshAutoUpdateBoundsInterval(e){this._settings.skinnedMeshAutoUpdateBoundsInterval=e,this.applySettings()}get targetTriangleDensity(){return this._lodsManager?.targetTriangleDensity||this._settings.targetTriangleDensity||2e5}set targetTriangleDensity(e){this._settings.targetTriangleDensity=e,this.applySettings()}constructor(e){this.context=e}applySettings(){if(this._lodsManager)for(const e in this._settings)this._lodsManager[e]=this._settings[e]}setRenderer(e){this._lodsManager?.disable(),ir.removePlugin(this),ir.addPlugin(this),ir.debugDrawLine=F.DrawLine,this._lodsManager=ir.get(e,{engine:"needle-engine"}),this.applySettings(),this._lodsManager.enable()}disable(){this._lodsManager?.disable(),ir.removePlugin(this)}onAfterUpdatedLOD(e,t,i,n,s){Bg&&this.onRenderDebug(i,n,s)}onRenderDebug(e,t,i){if(!t.geometry||!Ve.hasLODLevelAvailable(t.geometry)&&!Ve.hasLODLevelAvailable(t.material))return;const n=ir.getObjectLODState(t);if(!n)return;let s=i.mesh_lod;const r=i.mesh_lod!=n.lastLodLevel_Mesh||i.texture_lod!=n.lastLodLevel_Texture;if(Bg&&t.geometry.boundingSphere){const a=t.geometry.boundingSphere;iu.copy(a),iu.applyMatrix4(t.matrixWorld);const l=iu.center,c=iu.radius,h=["#76c43e","#bcc43e","#c4ac3e","#c4673e","#ff3e3e"];if(r)F.DrawWireSphere(l,c,h[s],.1);else{const d=t.geometry.index?.count??0,p=Ve.getMeshLODExtension(t.geometry)?.lods;s=p?Math.min(p?.length-1,s):0;let m="";if(p&&n.lastScreenCoverage>0)for(let y=0;y<p.length;y++){const _=p[y].density,v=y==p.length-1;m+=_.toFixed(0)+">"+(_/n.lastScreenCoverage).toFixed(0)+(v?"":",")}const f=p?p[s]?.density:-1;let g="LOD "+i.mesh_lod+`
214
+ TEX `+i.texture_lod;if(Bg=="density"&&(g+=`
215
215
  `+d+` tris
216
216
  `+(f/n.lastScreenCoverage).toFixed(0)+` dens
217
217
  `+(n.lastScreenCoverage*100).toFixed(1)+`% cov
218
218
  `+(n.lastCentrality*100).toFixed(1)+`% centr
219
- `+(tu.min.x.toFixed(2)+"-"+tu.max.x.toFixed(2)+"x"+tu.min.y.toFixed(2)+"-"+tu.max.y.toFixed(2))+" scr"),n.lastScreenCoverage>.1){const y=e,_=y.worldForward,v=y.worldPosition,P=$(_).multiplyScalar(c*.7).add(l),R=P.distanceTo(v),k=h[Math.min(h.length-1,Math.max(0,s))]+"88",A=this.context.domHeight>0?screen.height/this.context.domHeight:1,L=e.isPerspectiveCamera?Math.tan(e.fov*Math.PI/180/2):1;F.DrawLabel(P,m,R*.012*A*L,void 0,16777215,k)}}}}}const Hk=w("debugplayerview");var ms=(o=>(o.Browser="browser",o.Headset="headset",o.Handheld="handheld",o))(ms||{});class Av{userId;context;viewDevice="browser";get currentObject(){return this._object}set currentObject(e){this._object=e}get isConnected(){return this.context.connection.userIsInRoom(this.userId)}removed=!1;_object;constructor(e,t){this.userId=e,this.context=t}}class Iv{context;playerViews=new Map;constructor(e){this.context=e}setPlayerView(e,t,i){let n=this.playerViews.get(e);n||(n=new Av(e,this.context),this.playerViews.set(e,n)),n.viewDevice=i,n.currentObject=t,n.removed=!1}getPlayerView(e){if(!!e){if(!this.context.connection.userIsInRoom(e)){this.playerViews.delete(e);return}return this.playerViews.get(e)}}removePlayerView(e,t){const i=this.playerViews.get(e);i?.viewDevice===t&&(Hk&&console.log("REMOVE",e),i.removed=!0,this.playerViews.delete(e))}}new nm;const fc=new Uint8Array(4);fc[0]=255,fc[1]=255,fc[2]=255,fc[3]=255;const Gk=new om(fc,1,1,ad);function Fg(o,e=1){const t="alpha"in o,i=e*e,n=new Uint8Array(4*i),s=Math.floor(o.r*255),r=Math.floor(o.g*255),a=Math.floor(o.b*255);for(let c=0;c<i;c++){const h=c*4;n[h+0]=s,n[h+1]=r,n[h+2]=a,t?n[h+3]=Math.floor(o.alpha*255):n[h+3]=255}const l=new om(n,e,e);return l.needsUpdate=!0,l}function qk(o,e,t,i=1,n=3){const s=i*n,r=[o,e,t],a=r.length,l=new Uint8Array(4*a*s),c=new ne;for(let d=0;d<n;d++){const p=Math.floor(d/n*a),g=D.clamp(p+1,0,a-1),f=r[p],m=r[g],y=d/n*a%1;c.lerpColors(f,m,y);const _=Math.floor(c.r*255),v=Math.floor(c.g*255),P=Math.floor(c.b*255);for(let R=0;R<i;R++){const k=(d*i+R)*4;l[k+0]=_,l[k+1]=v,l[k+2]=P,l[k+3]=255}}const h=new om(l,i,n);return h.needsUpdate=!0,h}function nu(o,e){const t=o.elements;e||(e=[]),e.length=0;for(let i=0;i<16;i+=4){const n=t[i],s=t[i+1],r=t[i+2],a=t[i+3],l=new pe(n,s,r,a);e.push(l)}return e}const Ug=[],Lv=[];function Xk(o,e){if(Ug.length===0)for(let t=0;t<27;t++)Ug.push(0);e||(e=Ug);for(let t=0;t<27;t++)Lv[t]=e[t];e=Lv,o.unity_SHAr={value:new pe(e[9],e[3],e[6],e[0])},o.unity_SHBr={value:new pe(e[12],e[15],e[18],e[21])},o.unity_SHAg={value:new pe(e[10],e[4],e[7],e[1])},o.unity_SHBg={value:new pe(e[13],e[16],e[19],e[22])},o.unity_SHAb={value:new pe(e[11],e[5],e[8],e[2])},o.unity_SHBb={value:new pe(e[14],e[17],e[20],e[23])},o.unity_SHC={value:new pe(e[24],e[25],e[26],1)}}class Qk{vertexShader;fragmentShader;technique;constructor(e,t,i){this.vertexShader=e,this.fragmentShader=t,this.technique=i}}async function Yk(o,e){if(!o)return console.error("Can not find technique: no shader data"),null;const t=o.programs[e],i=t.vertexShader,n=t.fragmentShader;if(i!==void 0&&n!==void 0){const s=o.shaders[i],r=o.shaders[n];if(s.uri&&r.uri||s.code&&r.code){if(!s.code&&s.uri&&await jv(s),!r.code&&r.uri&&await jv(r),!s.code||!r.code)return null;const a=o.techniques[e];return new Qk(s.code,r.code,a)}}return console.error("Shader technique not found",e),null}async function jv(o){const e=o.uri;if(e)if(e.endsWith(".glsl")){const t=await new nm().loadAsync(e);o.code=t.toString()}else o.code=Kk(o.uri)}function Kk(o){return decodeURIComponent(Array.prototype.map.call(atob(o),function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)}).join(""))}const _n=w("debugenvlight");var Ua=(o=>(o[o.Skybox=0]="Skybox",o[o.Trilight=1]="Trilight",o[o.Flat=3]="Flat",o[o.Custom=4]="Custom",o))(Ua||{}),ou=(o=>(o[o.Skybox=0]="Skybox",o[o.Custom=1]="Custom",o))(ou||{});class Dv{context;constructor(e){this.context=e,this.context.pre_update_callbacks.push(this.preUpdate.bind(this))}_currentLightSettingsId;_sceneLightSettings;preUpdate(){const e=this.context.time;this._timevec4.x=e.time,this._timevec4.y=Math.sin(e.time),this._timevec4.z=Math.cos(e.time),this._timevec4.w=e.deltaTime}_timevec4=new pe;get timeVec4(){return this._timevec4}get environmentIntensity(){if(!this._sceneLightSettings||!this._currentLightSettingsId)return 1;const e=this._sceneLightSettings.get(this._currentLightSettingsId);return e?e.ambientIntensity:1}get sceneLightSettings(){return this._sceneLightSettings?.values()}enable(e){e instanceof ie&&(e=e.url);const t=this._sceneLightSettings?.get(e);return t?(_n&&console.log("Enable scene light settings",e,t),e!==this._currentLightSettingsId&&this._currentLightSettingsId&&this.disable(this._currentLightSettingsId),this._currentLightSettingsId=e,t.enabled=!0,!0):(_n&&console.warn("No light settings found for",e),!1)}disable(e){if(e instanceof ie&&(e=e.url),e==null)return!1;const t=this._sceneLightSettings?.get(e);return t?(_n&&console.log("Disable scene light settings",e,t),t.enabled=!1,!0):!1}disableCurrent(){if(this._currentLightSettingsId){const e=this._currentLightSettingsId;return this.disable(this._currentLightSettingsId),e}return null}internalRegisterSceneLightSettings(e){const t=e.sourceId;if(!t){console.error("Missing source id for scene light settings, can not register:",e);return}_n&&console.log("Register "+e?.sourceId+" lighting",e),this._sceneLightSettings||(this._sceneLightSettings=new Map),this._sceneLightSettings.set(t,e)}internalUnregisterSceneLightSettings(e){const t=e.sourceId;if(!t){console.error("Missing source id for scene light settings, can not unregister:",e);return}_n&&console.log("Unregister "+e?.sourceId+" lighting",e),this._sceneLightSettings&&this._sceneLightSettings.delete(t)}internalRegisterReflection(e,t){_n&&console.log("Register reflection",e,t);const i=new Bv(this.context,t,1);this._lighting[e]=i}internalGetReflection(e){return this._lighting[e]}__currentReflectionId=null;internalEnableReflection(e){this.__currentReflectionId=e;const t=this._sceneLightSettings?.get(e);switch(_n&&console.log("Enable reflection",e,t?Ua[t.ambientMode]:"Unknown ambient mode",t),t?.ambientMode){case 0:case 4:const i=this.internalGetReflection(e);if(i&&i.Source){_n&&console.log("Setting environment reflection",i);const n=this.context.scene,s=i.Source;s.mapping=mo,n.environment=s;return}else _n&&console.warn("Could not find reflection for source",e);break}if(t?.environmentReflectionSource===1)switch(t?.ambientMode){case 1:if(t.ambientTrilight){const i=t.ambientTrilight,n=qk(i[0],i[1],i[2],64,64);n.colorSpace=go,n.mapping=mo,this.context.scene.environment=n}else console.error("Missing ambient trilight",t.sourceId);return;case 3:if(t.ambientLight){const i=Fg(t.ambientLight,64);i.colorSpace=go,i.mapping=mo,this.context.scene.environment=i}else console.error("Missing ambientlight",t.sourceId);return;default:return}}internalDisableReflection(e){if(e&&e!==this.__currentReflectionId){_n&&console.log("Not disabling reflection for",e,"because it is not the current light settings id",this.__currentReflectionId);return}_n&&console.log("Disable reflection",e);const t=this.context.scene;t.environment=null}_lighting={}}class Bv{get Source(){return this._source}_source;constructor(e,t,i=1){this._source=t,t.mapping=mo}}const Fv=w("timescale");let zg=1;typeof Fv=="number"&&(zg=Fv);class Uv{get time(){return this._time}set time(e){this._time=e}_time=0;get deltaTime(){return this._deltaTime}set deltaTime(e){this._deltaTime=e}_deltaTime=0;get deltaTimeUnscaled(){return this._deltaTimeUnscaled}_deltaTimeUnscaled=0;timeScale=1;get frame(){return this._frame}set frame(e){this._frame=e}_frame=0;get frameCount(){return this.frame}get realtimeSinceStartup(){return this.clock.elapsedTime}get fps(){return 1/this.deltaTime}get smoothedFps(){return this._smoothedFps}get smoothedDeltaTime(){return 1/this._smoothedFps}clock=new cS;_smoothedFps=0;_smoothedDeltaTime=0;_fpsSamples=[];_fpsSampleIndex=0;constructor(){typeof zg=="number"&&(this.timeScale=zg)}update(){this.deltaTime=this.clock.getDelta(),this.deltaTime=Math.min(.1,this.deltaTime),this._deltaTimeUnscaled=this.deltaTime,this.deltaTime<=0&&(this.deltaTime=1e-12),this.deltaTime*=this.timeScale,this.frame+=1,this.time+=this.deltaTime,this._fpsSamples.length<60?this._fpsSamples.push(this.deltaTime):this._fpsSamples[this._fpsSampleIndex++%60]=this.deltaTime;let e=0;for(let t=0;t<this._fpsSamples.length;t++)e+=this._fpsSamples[t];this._smoothedDeltaTime=e/this._fpsSamples.length,this._smoothedFps=1/this._smoothedDeltaTime}}let zv=!1;function Nv(o){zv||(zv=!0,Zk(),Jk())}Nv();function Zk(){const o=`
219
+ `+(tu.min.x.toFixed(2)+"-"+tu.max.x.toFixed(2)+"x"+tu.min.y.toFixed(2)+"-"+tu.max.y.toFixed(2))+" scr"),n.lastScreenCoverage>.1){const y=e,_=y.worldForward,v=y.worldPosition,P=$(_).multiplyScalar(c*.7).add(l),R=P.distanceTo(v),k=h[Math.min(h.length-1,Math.max(0,s))]+"88",A=this.context.domHeight>0?screen.height/this.context.domHeight:1,L=e.isPerspectiveCamera?Math.tan(e.fov*Math.PI/180/2):1;F.DrawLabel(P,g,R*.012*A*L,void 0,16777215,k)}}}}}const Hk=w("debugplayerview");var ms=(o=>(o.Browser="browser",o.Headset="headset",o.Handheld="handheld",o))(ms||{});class Av{userId;context;viewDevice="browser";get currentObject(){return this._object}set currentObject(e){this._object=e}get isConnected(){return this.context.connection.userIsInRoom(this.userId)}removed=!1;_object;constructor(e,t){this.userId=e,this.context=t}}class Iv{context;playerViews=new Map;constructor(e){this.context=e}setPlayerView(e,t,i){let n=this.playerViews.get(e);n||(n=new Av(e,this.context),this.playerViews.set(e,n)),n.viewDevice=i,n.currentObject=t,n.removed=!1}getPlayerView(e){if(!!e){if(!this.context.connection.userIsInRoom(e)){this.playerViews.delete(e);return}return this.playerViews.get(e)}}removePlayerView(e,t){const i=this.playerViews.get(e);i?.viewDevice===t&&(Hk&&console.log("REMOVE",e),i.removed=!0,this.playerViews.delete(e))}}new nm;const fc=new Uint8Array(4);fc[0]=255,fc[1]=255,fc[2]=255,fc[3]=255;const Gk=new om(fc,1,1,ad);function Fg(o,e=1){const t="alpha"in o,i=e*e,n=new Uint8Array(4*i),s=Math.floor(o.r*255),r=Math.floor(o.g*255),a=Math.floor(o.b*255);for(let c=0;c<i;c++){const h=c*4;n[h+0]=s,n[h+1]=r,n[h+2]=a,t?n[h+3]=Math.floor(o.alpha*255):n[h+3]=255}const l=new om(n,e,e);return l.needsUpdate=!0,l}function qk(o,e,t,i=1,n=3){const s=i*n,r=[o,e,t],a=r.length,l=new Uint8Array(4*a*s),c=new ne;for(let d=0;d<n;d++){const p=Math.floor(d/n*a),m=D.clamp(p+1,0,a-1),f=r[p],g=r[m],y=d/n*a%1;c.lerpColors(f,g,y);const _=Math.floor(c.r*255),v=Math.floor(c.g*255),P=Math.floor(c.b*255);for(let R=0;R<i;R++){const k=(d*i+R)*4;l[k+0]=_,l[k+1]=v,l[k+2]=P,l[k+3]=255}}const h=new om(l,i,n);return h.needsUpdate=!0,h}function nu(o,e){const t=o.elements;e||(e=[]),e.length=0;for(let i=0;i<16;i+=4){const n=t[i],s=t[i+1],r=t[i+2],a=t[i+3],l=new pe(n,s,r,a);e.push(l)}return e}const Ug=[],Lv=[];function Xk(o,e){if(Ug.length===0)for(let t=0;t<27;t++)Ug.push(0);e||(e=Ug);for(let t=0;t<27;t++)Lv[t]=e[t];e=Lv,o.unity_SHAr={value:new pe(e[9],e[3],e[6],e[0])},o.unity_SHBr={value:new pe(e[12],e[15],e[18],e[21])},o.unity_SHAg={value:new pe(e[10],e[4],e[7],e[1])},o.unity_SHBg={value:new pe(e[13],e[16],e[19],e[22])},o.unity_SHAb={value:new pe(e[11],e[5],e[8],e[2])},o.unity_SHBb={value:new pe(e[14],e[17],e[20],e[23])},o.unity_SHC={value:new pe(e[24],e[25],e[26],1)}}class Qk{vertexShader;fragmentShader;technique;constructor(e,t,i){this.vertexShader=e,this.fragmentShader=t,this.technique=i}}async function Yk(o,e){if(!o)return console.error("Can not find technique: no shader data"),null;const t=o.programs[e],i=t.vertexShader,n=t.fragmentShader;if(i!==void 0&&n!==void 0){const s=o.shaders[i],r=o.shaders[n];if(s.uri&&r.uri||s.code&&r.code){if(!s.code&&s.uri&&await jv(s),!r.code&&r.uri&&await jv(r),!s.code||!r.code)return null;const a=o.techniques[e];return new Qk(s.code,r.code,a)}}return console.error("Shader technique not found",e),null}async function jv(o){const e=o.uri;if(e)if(e.endsWith(".glsl")){const t=await new nm().loadAsync(e);o.code=t.toString()}else o.code=Kk(o.uri)}function Kk(o){return decodeURIComponent(Array.prototype.map.call(atob(o),function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)}).join(""))}const _n=w("debugenvlight");var Ua=(o=>(o[o.Skybox=0]="Skybox",o[o.Trilight=1]="Trilight",o[o.Flat=3]="Flat",o[o.Custom=4]="Custom",o))(Ua||{}),ou=(o=>(o[o.Skybox=0]="Skybox",o[o.Custom=1]="Custom",o))(ou||{});class Dv{context;constructor(e){this.context=e,this.context.pre_update_callbacks.push(this.preUpdate.bind(this))}_currentLightSettingsId;_sceneLightSettings;preUpdate(){const e=this.context.time;this._timevec4.x=e.time,this._timevec4.y=Math.sin(e.time),this._timevec4.z=Math.cos(e.time),this._timevec4.w=e.deltaTime}_timevec4=new pe;get timeVec4(){return this._timevec4}get environmentIntensity(){if(!this._sceneLightSettings||!this._currentLightSettingsId)return 1;const e=this._sceneLightSettings.get(this._currentLightSettingsId);return e?e.ambientIntensity:1}get sceneLightSettings(){return this._sceneLightSettings?.values()}enable(e){e instanceof ie&&(e=e.url);const t=this._sceneLightSettings?.get(e);return t?(_n&&console.log("Enable scene light settings",e,t),e!==this._currentLightSettingsId&&this._currentLightSettingsId&&this.disable(this._currentLightSettingsId),this._currentLightSettingsId=e,t.enabled=!0,!0):(_n&&console.warn("No light settings found for",e),!1)}disable(e){if(e instanceof ie&&(e=e.url),e==null)return!1;const t=this._sceneLightSettings?.get(e);return t?(_n&&console.log("Disable scene light settings",e,t),t.enabled=!1,!0):!1}disableCurrent(){if(this._currentLightSettingsId){const e=this._currentLightSettingsId;return this.disable(this._currentLightSettingsId),e}return null}internalRegisterSceneLightSettings(e){const t=e.sourceId;if(!t){console.error("Missing source id for scene light settings, can not register:",e);return}_n&&console.log("Register "+e?.sourceId+" lighting",e),this._sceneLightSettings||(this._sceneLightSettings=new Map),this._sceneLightSettings.set(t,e)}internalUnregisterSceneLightSettings(e){const t=e.sourceId;if(!t){console.error("Missing source id for scene light settings, can not unregister:",e);return}_n&&console.log("Unregister "+e?.sourceId+" lighting",e),this._sceneLightSettings&&this._sceneLightSettings.delete(t)}internalRegisterReflection(e,t){_n&&console.log("Register reflection",e,t);const i=new Bv(this.context,t,1);this._lighting[e]=i}internalGetReflection(e){return this._lighting[e]}__currentReflectionId=null;internalEnableReflection(e){this.__currentReflectionId=e;const t=this._sceneLightSettings?.get(e);switch(_n&&console.log("Enable reflection",e,t?Ua[t.ambientMode]:"Unknown ambient mode",t),t?.ambientMode){case 0:case 4:const i=this.internalGetReflection(e);if(i&&i.Source){_n&&console.log("Setting environment reflection",i);const n=this.context.scene,s=i.Source;s.mapping=mo,n.environment=s;return}else _n&&console.warn("Could not find reflection for source",e);break}if(t?.environmentReflectionSource===1)switch(t?.ambientMode){case 1:if(t.ambientTrilight){const i=t.ambientTrilight,n=qk(i[0],i[1],i[2],64,64);n.colorSpace=go,n.mapping=mo,this.context.scene.environment=n}else console.error("Missing ambient trilight",t.sourceId);return;case 3:if(t.ambientLight){const i=Fg(t.ambientLight,64);i.colorSpace=go,i.mapping=mo,this.context.scene.environment=i}else console.error("Missing ambientlight",t.sourceId);return;default:return}}internalDisableReflection(e){if(e&&e!==this.__currentReflectionId){_n&&console.log("Not disabling reflection for",e,"because it is not the current light settings id",this.__currentReflectionId);return}_n&&console.log("Disable reflection",e);const t=this.context.scene;t.environment=null}_lighting={}}class Bv{get Source(){return this._source}_source;constructor(e,t,i=1){this._source=t,t.mapping=mo}}const Fv=w("timescale");let zg=1;typeof Fv=="number"&&(zg=Fv);class Uv{get time(){return this._time}set time(e){this._time=e}_time=0;get deltaTime(){return this._deltaTime}set deltaTime(e){this._deltaTime=e}_deltaTime=0;get deltaTimeUnscaled(){return this._deltaTimeUnscaled}_deltaTimeUnscaled=0;timeScale=1;get frame(){return this._frame}set frame(e){this._frame=e}_frame=0;get frameCount(){return this.frame}get realtimeSinceStartup(){return this.clock.elapsedTime}get fps(){return 1/this.deltaTime}get smoothedFps(){return this._smoothedFps}get smoothedDeltaTime(){return 1/this._smoothedFps}clock=new cS;_smoothedFps=0;_smoothedDeltaTime=0;_fpsSamples=[];_fpsSampleIndex=0;constructor(){typeof zg=="number"&&(this.timeScale=zg)}update(){this.deltaTime=this.clock.getDelta(),this.deltaTime=Math.min(.1,this.deltaTime),this._deltaTimeUnscaled=this.deltaTime,this.deltaTime<=0&&(this.deltaTime=1e-12),this.deltaTime*=this.timeScale,this.frame+=1,this.time+=this.deltaTime,this._fpsSamples.length<60?this._fpsSamples.push(this.deltaTime):this._fpsSamples[this._fpsSampleIndex++%60]=this.deltaTime;let e=0;for(let t=0;t<this._fpsSamples.length;t++)e+=this._fpsSamples[t];this._smoothedDeltaTime=e/this._fpsSamples.length,this._smoothedFps=1/this._smoothedDeltaTime}}let zv=!1;function Nv(o){zv||(zv=!0,Zk(),Jk())}Nv();function Zk(){const o=`
220
220
  float startCompression = 0.8;
221
221
  float desaturation = 0.5;
222
222
  // Patched tonemapping function
@@ -779,7 +779,7 @@ vec3 AgXToneMapping( vec3 color ) {
779
779
  The script will be ignored. Please make sure your component extends "Behaviour" imported from "@needle-tools/engine"
780
780
  `,o);return}e||(e=z.Current,Xe&&console.warn("> Registering component without context"));const t=e?.new_scripts;t.includes(o)||t.push(o)}class z{static _defaultTargetFramerate={value:90,toString(){return this.value}};static get DefaultTargetFrameRate(){return z._defaultTargetFramerate.value}static set DefaultTargetFrameRate(e){z._defaultTargetFramerate.value=e}static _defaultWebglRendererParameters={antialias:!0,alpha:!1,powerPreference:G.isiOS()||G.isMacOS()?"default":"high-performance",stencil:!0};static get DefaultWebGLRendererParameters(){return z._defaultWebglRendererParameters}get version(){return mn}static get Current(){return ue.Current}static set Current(e){ue.Current=e}static get All(){return ue.All}name;alias;isManagedExternally=!1;isPaused=!1;runInBackground=!1;targetFrameRate;physicsSteps=1;hash;domElement;appendHTMLElement(e){return this.domElement.shadowRoot?this.domElement.shadowRoot.appendChild(e):this.domElement.appendChild(e)}get resolutionScaleFactor(){return this._resolutionScaleFactor}set resolutionScaleFactor(e){if(e!==this._resolutionScaleFactor&&typeof e=="number"){if(e<=0){console.error("Invalid resolution scale factor",e);return}this._resolutionScaleFactor=e,this.updateSize()}}_resolutionScaleFactor=1;_boundingClientRectFrame=-1;_boundingClientRect=null;_domX;_domY;calculateBoundingClientRect(){if(this.xr){this._domX=0,this._domY=0;return}this._boundingClientRectFrame!==this.time.frame&&(this._boundingClientRectFrame=this.time.frame,this._boundingClientRect=this.domElement.getBoundingClientRect(),this._domX=this._boundingClientRect.x,this._domY=this._boundingClientRect.y)}get domWidth(){return this.isInAR?window.innerWidth:this.domElement.clientWidth}get domHeight(){return this.isInAR?window.innerHeight:this.domElement.clientHeight}get domX(){return this.calculateBoundingClientRect(),this._domX}get domY(){return this.calculateBoundingClientRect(),this._domY}get isInXR(){return this.renderer?.xr?.isPresenting||!1}xr=null;get xrSessionMode(){return this.xr?.mode}get isInVR(){return this.xrSessionMode==="immersive-vr"}get isInAR(){return this.xrSessionMode==="immersive-ar"}get isInPassThrough(){return this.xr?this.xr.isPassThrough:!1}get xrSession(){return this.renderer?.xr?.getSession()}get xrFrame(){return this._xrFrame}get xrCamera(){return this.renderer.xr.isPresenting?this.renderer?.xr?.getCamera():void 0}_xrFrame=null;get arOverlayElement(){const e=this.domElement;return typeof e.getAROverlayContainer=="function"?e.getAROverlayContainer():this.domElement}get currentFrameEvent(){return this._currentFrameEvent}_currentFrameEvent=-1;scene;renderer;composer=null;scripts=[];scripts_pausedChanged=[];scripts_earlyUpdate=[];scripts_update=[];scripts_lateUpdate=[];scripts_onBeforeRender=[];scripts_onAfterRender=[];scripts_WithCorroutines=[];scripts_immersive_vr=[];scripts_immersive_ar=[];coroutines={};post_setup_callbacks=[];pre_update_callbacks=[];pre_render_callbacks=[];post_render_callbacks=[];pre_update_oneshot_callbacks=[];new_scripts=[];new_script_start=[];new_scripts_pre_setup_callbacks=[];new_scripts_post_setup_callbacks=[];new_scripts_xr=[];mainCameraComponent=void 0;get mainCamera(){if(this._mainCamera)return this._mainCamera;if(this.mainCameraComponent){const e=this.mainCameraComponent;return e.threeCamera||e.buildCamera(),e.threeCamera}return this._fallbackCamera||(this._fallbackCamera=new de(75,this.domWidth/this.domHeight,.1,1e3)),this._fallbackCamera}set mainCamera(e){this._mainCamera=e}_mainCamera=null;_fallbackCamera=null;application;animations;time;input;physics;connection;assets;mainLight=null;get rendererData(){return this.sceneLighting}sceneLighting;addressables;lightmaps;players;lodsManager;menu;get isCreated(){return this._isCreated}_needsUpdateSize=!1;_isCreated=!1;_isCreating=!1;_isVisible=!1;_stats=nM?new _C:null;constructor(e){this.name=e?.name||"",this.alias=e?.alias,this.domElement=e?.domElement||document.body,this.hash=e?.hash,e?.renderer&&(this.renderer=e.renderer,this.isManagedExternally=!0),e?.runInBackground!==void 0&&(this.runInBackground=e.runInBackground),e?.scene?this.scene=e.scene:this.scene=new yi,e?.camera&&(this._mainCamera=e.camera),this.application=new Tn(this),this.time=new Uv,this.input=new s_(this),this.physics=new El(this),this.connection=new v_(this),this.assets=new I_,this.sceneLighting=new Dv(this),this.addressables=new kv(this),this.lightmaps=new Vk(this),this.players=new Iv(this),this.menu=new iM(this),this.lodsManager=new $k(this),this.animations=new zk(this);const t=()=>this._needsUpdateSize=!0;window.addEventListener("resize",t),this._disposeCallbacks.push(()=>window.removeEventListener("resize",t));const i=new ResizeObserver(n=>this._needsUpdateSize=!0);i.observe(this.domElement),this._disposeCallbacks.push(()=>i.disconnect()),this._intersectionObserver=new IntersectionObserver(n=>{this._isVisible=n[0].isIntersecting}),this._disposeCallbacks.push(()=>this._intersectionObserver?.disconnect()),ue.register(this)}createNewRenderer(e){if(this.renderer?.dispose(),e={...z.DefaultWebGLRendererParameters,...e},!e.canvas){const t=this.domElement?.shadowRoot?.querySelector("canvas");t&&(e.canvas=t,Xe&&console.log("Using canvas from shadow root",t))}return Xe&&console.log("Using Renderer Parameters:",e,this.domElement),this.renderer=new er(e),this.renderer.debug.checkShaderErrors=E()||w("checkshadererrors")===!0,this.renderer.toneMappingExposure=1,this.renderer.toneMapping=hd,this.renderer.setClearColor(new ne("lightgrey"),0),this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=hS,this.renderer.setSize(this.domWidth,this.domHeight),this.renderer.outputColorSpace=go,this.renderer.nodes={library:new dS,modelViewMatrix:null,modelNormalViewMatrix:null},this.lodsManager.setRenderer(this.renderer),this.input.bindEvents(),this.renderer}_intersectionObserver=null;internalOnUpdateVisible(){this._intersectionObserver?.disconnect(),this._intersectionObserver?.observe(this.domElement)}_disposeCallbacks=[];requestSizeUpdate(){this._needsUpdateSize=!0}maxRenderResolution;get devicePixelRatio(){return this._devicePixelRatio}set devicePixelRatio(e){e!==this._devicePixelRatio&&(this._devicePixelRatio=e,this._needsUpdateSize=!0)}_devicePixelRatio="auto";updateSize(e=!1){if(e||!this.isManagedExternally&&this.renderer.xr?.isPresenting===!1){this._needsUpdateSize=!1;const t=this.resolutionScaleFactor;let i=this.domWidth*t,n=this.domHeight*t;this.maxRenderResolution&&(this.maxRenderResolution.x=Math.max(1,this.maxRenderResolution.x),i=Math.min(this.maxRenderResolution.x,i),this.maxRenderResolution.y=Math.max(1,this.maxRenderResolution.y),n=Math.min(this.maxRenderResolution.y,n));const s=this.mainCamera;this.updateAspect(s),this.renderer.setSize(i,n,!0),this.renderer.domElement.style.width="100%",this.renderer.domElement.style.height="100%";const r=typeof this.devicePixelRatio=="number"?this.devicePixelRatio:this.devicePixelRatio==="auto"?Math.min(2,window.devicePixelRatio):void 0;r!==void 0&&this.renderer.setPixelRatio(r),this.composer&&(this.composer.setSize?.call(this.composer,i,n),r!==void 0&&"setPixelRatio"in this.composer&&typeof this.composer.setPixelRatio=="function"&&this.composer.setPixelRatio?.call(this.composer,window.devicePixelRatio))}}updateAspect(e,t,i){if(!e)return;t===void 0&&(t=this.domWidth),i===void 0&&(i=this.domHeight);const n=t/i;if(e.isPerspectiveCamera){const s=e,r=s.aspect;s.aspect=n,r!==s.aspect&&e.updateProjectionMatrix()}else if(e.isOrthographicCamera){const s=e,r=s.top-s.bottom,a=r*n/2,l=r/2;(s.left!=-a||s.top!=l)&&(s.left=-a,s.right=a,s.top=l,s.bottom=-l,e.updateProjectionMatrix())}}recreate(){this.clear(),this.create(this._originalCreationArgs)}_originalCreationArgs;async onCreate(e){return this.create(e)}async create(e){try{this._isCreating=!0,e!==this._originalCreationArgs&&(this._originalCreationArgs=Nl(e)),window.addEventListener("unhandledrejection",this.onUnhandledRejection);const t=await this.internalOnCreate(e);return this._isCreated=t,t}finally{window.removeEventListener("unhandledrejection",this.onUnhandledRejection),this._isCreating=!1}}onUnhandledRejection=e=>{this.onError(e.reason)};onError(e){this.domElement.dispatchEvent(new CustomEvent("error",{detail:e}))}clear(){ue.dispatchCallback(he.ContextClearing,this),Fn(this,he.ContextClearing),Ci(this.scene,!0,!0),this.scene=new yi,this.addressables?.dispose(),this.lightmaps?.clear(),this.physics?.engine?.clearCaches(),this.lodsManager.disable(),this._onBeforeRenderListeners.clear(),this._onAfterRenderListeners.clear(),this.isManagedExternally||this.renderer&&(this.renderer.renderLists.dispose(),this.renderer.state.reset(),this.renderer.resetState()),ue.dispatchCallback(he.ContextCleared,this)}dispose(){this.internalOnDestroy()}onDestroy(){this.internalOnDestroy()}internalOnDestroy(){z.Current=this,ue.dispatchCallback(he.ContextDestroying,this),Fn(this,he.ContextDestroying),this.clear(),this.renderer?.setAnimationLoop(null),this.renderer&&(this.renderer.setClearAlpha(0),this.renderer.clear(),this.isManagedExternally||(Xe&&console.log("Disposing renderer"),this.renderer.dispose())),this.scene=null,this.renderer=null,this.input.dispose(),this.menu.onDestroy(),this.animations.onDestroy();for(const e of this._disposeCallbacks)try{e()}catch(t){console.error("Error in on dispose callback:",t,e)}this.domElement?.parentElement&&this.domElement.parentElement.removeChild(this.domElement),this._isCreated=!1,ue.dispatchCallback(he.ContextDestroyed,this),Fn(this,he.ContextDestroyed),ue.unregister(this),z.Current===this&&(z.Current=null)}registerCoroutineUpdate(e,t,i){return typeof t?.next!="function"?(console.error("Registered invalid coroutine function from "+e.name+`
781
781
  Coroutine functions must be generators: "*myCoroutine() {...}"
782
- Start a coroutine from a component by calling "this.startCoroutine(myCoroutine())"`),t):(this.coroutines[i]||(this.coroutines[i]=[]),this.coroutines[i].push({comp:e,main:t}),t)}unregisterCoroutineUpdate(e,t){if(!this.coroutines[t])return;const i=this.coroutines[t].findIndex(n=>n.main===e);i>=0&&this.coroutines[t].splice(i,1)}stopAllCoroutinesFrom(e){for(const t in this.coroutines){const i=this.coroutines[t];for(let n=i.length-1;n>=0;n--)i[n].comp===e&&i.splice(n,1)}}_cameraStack=[];setCurrentCamera(e){if(!e)return;if(e.threeCamera||e.buildCamera(),!e.threeCamera){console.warn("Camera component is missing camera",e);return}const t=this._cameraStack.indexOf(e);t>=0&&this._cameraStack.splice(t,1),this._cameraStack.push(e),this.mainCameraComponent=e;const i=e.threeCamera;i.isPerspectiveCamera&&this.updateAspect(i),this.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}removeCamera(e){if(!e)return;const t=this._cameraStack.indexOf(e);if(t>=0&&this._cameraStack.splice(t,1),this.mainCameraComponent===e&&(this.mainCameraComponent=void 0,this._cameraStack.length>0)){const i=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(i)}}_onBeforeRenderListeners=new Map;_onAfterRenderListeners=new Map;addBeforeRenderListener(e,t){if(!this._onBeforeRenderListeners.has(e.uuid)){const i=[];this._onBeforeRenderListeners.set(e.uuid,i),e.onBeforeRender=this._createRenderCallbackWrapper(i)}this._onBeforeRenderListeners.get(e.uuid).push(t)}removeBeforeRenderListener(e,t){if(this._onBeforeRenderListeners.has(e.uuid)){const i=this._onBeforeRenderListeners.get(e.uuid),n=i.indexOf(t);n>=0&&i.splice(n,1)}}addAfterRenderListener(e,t){if(!this._onAfterRenderListeners.has(e.uuid)){const i=[];this._onAfterRenderListeners.set(e.uuid,i),e.onAfterRender=this._createRenderCallbackWrapper(i)}this._onAfterRenderListeners.get(e.uuid)?.push(t)}removeAfterRenderListener(e,t){if(this._onAfterRenderListeners.has(e.uuid)){const i=this._onAfterRenderListeners.get(e.uuid),n=i.indexOf(t);n>=0&&i.splice(n,1)}}_createRenderCallbackWrapper(e){return(t,i,n,s,r,a)=>{for(let l=0;l<e.length;l++){const c=e[l];c(t,i,n,s,r,a)}}}_requireDepthTexture=!1;_requireColorTexture=!1;_renderTarget;_isRendering=!1;get isRendering(){return this._isRendering}setRequireDepth(e){this._requireDepthTexture=e}setRequireColor(e){this._requireColorTexture=e}get depthTexture(){return this._renderTarget?.depthTexture||null}get opaqueColorTexture(){return this._renderTarget?.texture||null}get isVisibleToUser(){if(this.isInXR)return!0;if(!this._isVisible)return!1;if(!this._needsVisibleUpdate&&this._lastStyleComputedResult!==void 0)return this._lastStyleComputedResult;this._needsVisibleUpdate=!1;const e=getComputedStyle(this.domElement);return this._lastStyleComputedResult=e.visibility!=="hidden"&&e.display!=="none"&&e.opacity!=="0",this._lastStyleComputedResult}_needsVisibleUpdate=!0;_lastStyleComputedResult=void 0;_createId=0;async internalOnCreate(e){const t=++this._createId;Xe&&console.log("Creating context",this.name,e);const i=globalThis["needle:dependencies:ready"];i instanceof Promise&&(Xe&&console.log("Waiting for dependencies to be ready"),await i.catch(c=>{if(Xe||E()){if(Xl("Needle Engine dependencies failed to load. Please check the console for more details"),c instanceof ReferenceError){let h="YourComponentName";const d=c.message.indexOf("'");if(d>0){const p=c.message.indexOf("'",d+1);if(p>0){const g=c.message.substring(d+1,p);g.length>3&&(h=g)}}console.error(`Needle Engine dependencies failed to load:
782
+ Start a coroutine from a component by calling "this.startCoroutine(myCoroutine())"`),t):(this.coroutines[i]||(this.coroutines[i]=[]),this.coroutines[i].push({comp:e,main:t}),t)}unregisterCoroutineUpdate(e,t){if(!this.coroutines[t])return;const i=this.coroutines[t].findIndex(n=>n.main===e);i>=0&&this.coroutines[t].splice(i,1)}stopAllCoroutinesFrom(e){for(const t in this.coroutines){const i=this.coroutines[t];for(let n=i.length-1;n>=0;n--)i[n].comp===e&&i.splice(n,1)}}_cameraStack=[];setCurrentCamera(e){if(!e)return;if(e.threeCamera||e.buildCamera(),!e.threeCamera){console.warn("Camera component is missing camera",e);return}const t=this._cameraStack.indexOf(e);t>=0&&this._cameraStack.splice(t,1),this._cameraStack.push(e),this.mainCameraComponent=e;const i=e.threeCamera;i.isPerspectiveCamera&&this.updateAspect(i),this.mainCameraComponent?.applyClearFlagsIfIsActiveCamera()}removeCamera(e){if(!e)return;const t=this._cameraStack.indexOf(e);if(t>=0&&this._cameraStack.splice(t,1),this.mainCameraComponent===e&&(this.mainCameraComponent=void 0,this._cameraStack.length>0)){const i=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(i)}}_onBeforeRenderListeners=new Map;_onAfterRenderListeners=new Map;addBeforeRenderListener(e,t){if(!this._onBeforeRenderListeners.has(e.uuid)){const i=[];this._onBeforeRenderListeners.set(e.uuid,i),e.onBeforeRender=this._createRenderCallbackWrapper(i)}this._onBeforeRenderListeners.get(e.uuid).push(t)}removeBeforeRenderListener(e,t){if(this._onBeforeRenderListeners.has(e.uuid)){const i=this._onBeforeRenderListeners.get(e.uuid),n=i.indexOf(t);n>=0&&i.splice(n,1)}}addAfterRenderListener(e,t){if(!this._onAfterRenderListeners.has(e.uuid)){const i=[];this._onAfterRenderListeners.set(e.uuid,i),e.onAfterRender=this._createRenderCallbackWrapper(i)}this._onAfterRenderListeners.get(e.uuid)?.push(t)}removeAfterRenderListener(e,t){if(this._onAfterRenderListeners.has(e.uuid)){const i=this._onAfterRenderListeners.get(e.uuid),n=i.indexOf(t);n>=0&&i.splice(n,1)}}_createRenderCallbackWrapper(e){return(t,i,n,s,r,a)=>{for(let l=0;l<e.length;l++){const c=e[l];c(t,i,n,s,r,a)}}}_requireDepthTexture=!1;_requireColorTexture=!1;_renderTarget;_isRendering=!1;get isRendering(){return this._isRendering}setRequireDepth(e){this._requireDepthTexture=e}setRequireColor(e){this._requireColorTexture=e}get depthTexture(){return this._renderTarget?.depthTexture||null}get opaqueColorTexture(){return this._renderTarget?.texture||null}get isVisibleToUser(){if(this.isInXR)return!0;if(!this._isVisible)return!1;if(!this._needsVisibleUpdate&&this._lastStyleComputedResult!==void 0)return this._lastStyleComputedResult;this._needsVisibleUpdate=!1;const e=getComputedStyle(this.domElement);return this._lastStyleComputedResult=e.visibility!=="hidden"&&e.display!=="none"&&e.opacity!=="0",this._lastStyleComputedResult}_needsVisibleUpdate=!0;_lastStyleComputedResult=void 0;_createId=0;async internalOnCreate(e){const t=++this._createId;Xe&&console.log("Creating context",this.name,e);const i=globalThis["needle:dependencies:ready"];i instanceof Promise&&(Xe&&console.log("Waiting for dependencies to be ready"),await i.catch(c=>{if(Xe||E()){if(Xl("Needle Engine dependencies failed to load. Please check the console for more details"),c instanceof ReferenceError){let h="YourComponentName";const d=c.message.indexOf("'");if(d>0){const p=c.message.indexOf("'",d+1);if(p>0){const m=c.message.substring(d+1,p);m.length>3&&(h=m)}}console.error(`Needle Engine dependencies failed to load:
783
783
 
784
784
  # Make sure you don't have circular imports in your scripts!
785
785
 
@@ -787,7 +787,7 @@ Possible solutions:
787
787
  \u2192 Replace @serializable(${h}) in your script with @serializable(Behaviour)
788
788
  \u2192 If you only need type information try importing the type only, e.g: import { type ${h} }
789
789
 
790
- ---`,c);return}console.error("Needle Engine dependencies failed to load",c)}}).then(()=>{Xe&&console.log("Needle Engine dependencies are ready")})),this.clear();const n=this.renderer,s=!n||n.isDisposed===!0;this.isManagedExternally===!1&&s?this.createNewRenderer():this.lodsManager.setRenderer(this.renderer),this.renderer?.setAnimationLoop(null),z.Current=this,await ue.dispatchCallback(he.ContextCreationStart,this);let r=!0,a;try{z.Current=this,e?a=await this.internalLoadInitialContent(t,e):a=[]}catch(c){console.error(c),r=!1}if(!r)return this.onError("Failed to load initial content"),!1;if(t!==this._createId||e?.abortSignal?.aborted)return!1;if(this.internalOnUpdateVisible(),!this.renderer)return Xe&&console.warn("Context has no renderer (perhaps it was disconnected?",this.domElement.isConnected),!1;!this.isManagedExternally&&!this.domElement.shadowRoot&&this.domElement.prepend(this.renderer.domElement),z.Current=this,z.Current=this;for(let c=0;c<this.new_scripts.length;c++){const h=this.new_scripts[c];if(h.gameObject!==void 0&&h.gameObject!==null){h.gameObject.userData===void 0&&(h.gameObject.userData={}),h.gameObject.userData.components===void 0&&(h.gameObject.userData.components=[]);const d=h.gameObject.userData.components;d.includes(h)||d.push(h)}}if(this.post_setup_callbacks)for(let c=0;c<this.post_setup_callbacks.length;c++)z.Current=this,await this.post_setup_callbacks[c](this);if(!this._mainCamera){z.Current=this;let c=null;wr(this.scene,h=>{const d=h;if(d?.isCamera){if(rc(d.gameObject),!d.activeAndEnabled)return;if(d.tag==="MainCamera")return c=d,!0;c=d}}),c?this.setCurrentCamera(c):!ue.dispatchCallback(he.MissingCamera,this,{files:a})&&!this.mainCamera&&!this.isManagedExternally&&console.warn("Missing camera in main scene",this)}this.input.bindEvents(),z.Current=this,Nd(this),this.physics.engine&&(this.physics.engine?.step(0),this.physics.engine?.postStep()),!this.isManagedExternally&&this.composer&&this.mainCamera,this._needsUpdateSize=!0,this._stats&&(this._stats.showPanel(0),this._stats.dom.style.position="absolute",this.domElement.shadowRoot?.appendChild(this._stats.dom)),Xe&&Sd(this.scene,!0),this.targetFrameRate===void 0?(Xe&&console.warn("No target framerate set, using default",z.DefaultTargetFrameRate),this.targetFrameRate=z._defaultTargetFramerate):Xe&&console.log("Target framerate set to",this.targetFrameRate),this._dispatchReadyAfterFrame=!0;const l=ue.dispatchCallback(he.ContextCreated,this,{files:a});if(l){const c=this.domElement;"internalSetLoadingMessage"in c&&typeof c.internalSetLoadingMessage=="function"&&c?.internalSetLoadingMessage("finish loading"),await l}return e?.abortSignal?.aborted?!1:(Fn(this,he.ContextCreated),Xe&&console.log("Context Created...",this.renderer,this.renderer.domElement),this._isCreating=!1,!this.isManagedExternally&&!e?.abortSignal?.aborted&&this.restartRenderLoop(),!0)}async internalLoadInitialContent(e,t){const i=new Array;if(t.files.length===0)return i;const n=[...t.files],s={name:"",progress:null,index:0,count:n.length},r=gn(),a=0;for(let l=0;l<n.length;l++){if(t.abortSignal?.aborted){Xe&&console.log("Aborting loading because of abort signal");break}if(e!==this._createId){Xe&&console.log("Aborting loading because create id changed",e,this._createId);break}const c=n[l];t?.onLoadingStart?.call(this,l,c),Xe&&console.log("Context Load "+c);const h=await r.loadSync(this,c,c,a,d=>{t.abortSignal?.aborted||(s.name=c,s.progress=d,s.index=l,s.count=n.length,t.onLoadingProgress?.call(this,s))});t?.onLoadingFinished?.call(this,l,c,h??null),h?i.push({src:c,file:h}):console.warn("Could not load file: "+c)}if(e!==this._createId||t.abortSignal?.aborted){Xe&&console.log("Aborting loading because create id changed or abort signal was set",e,this._createId);for(const l of i)if(l&&l.file)for(const c of l.file.scenes)Ci(c,!0,!0)}else{let l=!1;for(const c of i)c&&c.file&&(c.file.scene?(l=!0,this.scene.add(c.file.scene)):console.warn("No scene found in loaded file"));if(!l){for(const c of i)if(c&&c.file&&"parser"in c.file){let h=0;if(!Array.isArray(c.file.parser.json.materials))continue;for(let d=0;d<c.file.parser.json.materials.length;d++){const p=await c.file.parser.getDependency("material",d),g=new O;g.position.x=d*1.1,g.position.y=h,this.scene.add(g),pr.createPrimitive("ShaderBall",{parent:g,material:p})}h+=1}}}return i}restartRenderLoop(){return this.renderer?this._isCreating?(console.warn("Can not start render loop while creating context"),!1):(this.renderer.setAnimationLoop((e,t)=>{this.isManagedExternally||this.update(e,t)}),!0):(console.error("Can not start render loop without renderer"),!1)}_renderlooperrors=0;update(e,t){if(t===void 0&&(t=null),E()||Xe||ik())try{this.internalStep(e,t),this._renderlooperrors=0}catch(i){this._renderlooperrors+=1,(E()||Xe)&&(i instanceof Error||i instanceof TypeError)&&Te("Caught unhandled exception during render-loop - see console for details.",xi.Error),console.error("Frame #"+this.time.frame+`
790
+ ---`,c);return}console.error("Needle Engine dependencies failed to load",c)}}).then(()=>{Xe&&console.log("Needle Engine dependencies are ready")})),this.clear();const n=this.renderer,s=!n||n.isDisposed===!0;this.isManagedExternally===!1&&s?this.createNewRenderer():this.lodsManager.setRenderer(this.renderer),this.renderer?.setAnimationLoop(null),z.Current=this,await ue.dispatchCallback(he.ContextCreationStart,this);let r=!0,a;try{z.Current=this,e?a=await this.internalLoadInitialContent(t,e):a=[]}catch(c){console.error(c),r=!1}if(!r)return this.onError("Failed to load initial content"),!1;if(t!==this._createId||e?.abortSignal?.aborted)return!1;if(this.internalOnUpdateVisible(),!this.renderer)return Xe&&console.warn("Context has no renderer (perhaps it was disconnected?",this.domElement.isConnected),!1;!this.isManagedExternally&&!this.domElement.shadowRoot&&this.domElement.prepend(this.renderer.domElement),z.Current=this,z.Current=this;for(let c=0;c<this.new_scripts.length;c++){const h=this.new_scripts[c];if(h.gameObject!==void 0&&h.gameObject!==null){h.gameObject.userData===void 0&&(h.gameObject.userData={}),h.gameObject.userData.components===void 0&&(h.gameObject.userData.components=[]);const d=h.gameObject.userData.components;d.includes(h)||d.push(h)}}if(this.post_setup_callbacks)for(let c=0;c<this.post_setup_callbacks.length;c++)z.Current=this,await this.post_setup_callbacks[c](this);if(!this._mainCamera){z.Current=this;let c=null;wr(this.scene,h=>{const d=h;if(d?.isCamera){if(rc(d.gameObject),!d.activeAndEnabled)return;if(d.tag==="MainCamera")return c=d,!0;c=d}}),c?this.setCurrentCamera(c):!ue.dispatchCallback(he.MissingCamera,this,{files:a})&&!this.mainCamera&&!this.isManagedExternally&&console.warn("Missing camera in main scene",this)}this.input.bindEvents(),z.Current=this,Nd(this),this.physics.engine&&(this.physics.engine?.step(0),this.physics.engine?.postStep()),!this.isManagedExternally&&this.composer&&this.mainCamera,this._needsUpdateSize=!0,this._stats&&(this._stats.showPanel(0),this._stats.dom.style.position="absolute",this.domElement.shadowRoot?.appendChild(this._stats.dom)),Xe&&Sd(this.scene,!0),this.targetFrameRate===void 0?(Xe&&console.warn("No target framerate set, using default",z.DefaultTargetFrameRate),this.targetFrameRate=z._defaultTargetFramerate):Xe&&console.log("Target framerate set to",this.targetFrameRate),this._dispatchReadyAfterFrame=!0;const l=ue.dispatchCallback(he.ContextCreated,this,{files:a});if(l){const c=this.domElement;"internalSetLoadingMessage"in c&&typeof c.internalSetLoadingMessage=="function"&&c?.internalSetLoadingMessage("finish loading"),await l}return e?.abortSignal?.aborted?!1:(Fn(this,he.ContextCreated),Xe&&console.log("Context Created...",this.renderer,this.renderer.domElement),this._isCreating=!1,!this.isManagedExternally&&!e?.abortSignal?.aborted&&this.restartRenderLoop(),!0)}async internalLoadInitialContent(e,t){const i=new Array;if(t.files.length===0)return i;const n=[...t.files],s={name:"",progress:null,index:0,count:n.length},r=gn(),a=0;for(let l=0;l<n.length;l++){if(t.abortSignal?.aborted){Xe&&console.log("Aborting loading because of abort signal");break}if(e!==this._createId){Xe&&console.log("Aborting loading because create id changed",e,this._createId);break}const c=n[l];t?.onLoadingStart?.call(this,l,c),Xe&&console.log("Context Load "+c);const h=await r.loadSync(this,c,c,a,d=>{t.abortSignal?.aborted||(s.name=c,s.progress=d,s.index=l,s.count=n.length,t.onLoadingProgress?.call(this,s))});t?.onLoadingFinished?.call(this,l,c,h??null),h?i.push({src:c,file:h}):console.warn("Could not load file: "+c)}if(e!==this._createId||t.abortSignal?.aborted){Xe&&console.log("Aborting loading because create id changed or abort signal was set",e,this._createId);for(const l of i)if(l&&l.file)for(const c of l.file.scenes)Ci(c,!0,!0)}else{let l=!1;for(const c of i)c&&c.file&&(c.file.scene?(l=!0,this.scene.add(c.file.scene)):console.warn("No scene found in loaded file"));if(!l){for(const c of i)if(c&&c.file&&"parser"in c.file){let h=0;if(!Array.isArray(c.file.parser.json.materials))continue;for(let d=0;d<c.file.parser.json.materials.length;d++){const p=await c.file.parser.getDependency("material",d),m=new O;m.position.x=d*1.1,m.position.y=h,this.scene.add(m),pr.createPrimitive("ShaderBall",{parent:m,material:p})}h+=1}}}return i}restartRenderLoop(){return this.renderer?this._isCreating?(console.warn("Can not start render loop while creating context"),!1):(this.renderer.setAnimationLoop((e,t)=>{this.isManagedExternally||this.update(e,t)}),!0):(console.error("Can not start render loop without renderer"),!1)}_renderlooperrors=0;update(e,t){if(t===void 0&&(t=null),E()||Xe||ik())try{this.internalStep(e,t),this._renderlooperrors=0}catch(i){this._renderlooperrors+=1,(E()||Xe)&&(i instanceof Error||i instanceof TypeError)&&Te("Caught unhandled exception during render-loop - see console for details.",xi.Error),console.error("Frame #"+this.time.frame+`
791
791
  `,i),this._renderlooperrors>=3&&(console.warn("Stopping render loop due to error"),this.renderer.setAnimationLoop(null)),this.domElement.dispatchEvent(new CustomEvent("error",{detail:i}))}else this.internalStep(e,t)}updatePhysics(e){this.internalUpdatePhysics(e)}setCameraFocusRect(e,t){this._focusRect=e,t&&Object.assign(this.focusRectSettings,t)}get focusRect(){return this._focusRect}focusRectSettings={damping:.05};_focusRect=null;_lastTimestamp=0;_accumulatedTime=0;_dispatchReadyAfterFrame=!1;internalStep(e,t){this.internalOnBeforeRender(e,t)!==!1&&(this.internalOnRender(),this.internalOnAfterRender())}internalOnBeforeRender(e,t){this.renderer.info.autoReset=!!t,this.renderer.info.autoReset===!1&&this.renderer.info.reset(),this._needsVisibleUpdate=!0;const i=t!==null&&this._xrFrame===null;if(this._xrFrame=t,i&&this.domElement.dispatchEvent(new CustomEvent("xr-session-started",{detail:{context:this,session:this.xrSession,frame:t}})),this._currentFrameEvent=-1,this.isManagedExternally===!1&&this.isInXR===!1&&this.targetFrameRate!==void 0){this._lastTimestamp===0&&(this._lastTimestamp=e),this._accumulatedTime+=(e-this._lastTimestamp)/1e3,this._lastTimestamp=e;let n=this.targetFrameRate;if(typeof n=="object"&&(n=n.value),this._accumulatedTime<1/(n+1))return!1;this._accumulatedTime=0}if(this._stats?.begin(),z.Current=this,this.onHandlePaused())return!1;for(z.Current=this,this.time.update(),sM&&console.log("FPS",this.time.smoothedFps.toFixed(0)),Nd(this),Wd(this.scene),W_(this),Fn(this,-1);this._cameraStack.length>0&&(!this.mainCameraComponent||this.mainCameraComponent.destroyed);){this._cameraStack.splice(this._cameraStack.length-1,1);const n=this._cameraStack[this._cameraStack.length-1];this.setCurrentCamera(n)}if(this.pre_update_oneshot_callbacks){for(const n in this.pre_update_oneshot_callbacks)this.pre_update_oneshot_callbacks[n]();this.pre_update_oneshot_callbacks.length=0}if(this.pre_update_callbacks)for(const n in this.pre_update_callbacks)this.pre_update_callbacks[n]();this._currentFrameEvent=0;for(let n=0;n<this.scripts_earlyUpdate.length;n++){const s=this.scripts_earlyUpdate[n];s.activeAndEnabled&&s.earlyUpdate!==void 0&&(z.Current=this,s.earlyUpdate())}this.executeCoroutines(0),Fn(this,0),this._currentFrameEvent=1;for(let n=0;n<this.scripts_update.length;n++){const s=this.scripts_update[n];s.activeAndEnabled&&s.update!==void 0&&(z.Current=this,s.update())}this.executeCoroutines(1),Fn(this,1),this._currentFrameEvent=2;for(let n=0;n<this.scripts_lateUpdate.length;n++){const s=this.scripts_lateUpdate[n];s.activeAndEnabled&&s.lateUpdate!==void 0&&(z.Current=this,s.lateUpdate())}if(this.executeCoroutines(2),Fn(this,2),this.physicsSteps===void 0&&(this.physicsSteps=1),this.physics.engine&&this.physicsSteps>0&&this.internalUpdatePhysics(this.physicsSteps),this.isVisibleToUser||this.runInBackground){if(this._focusRect&&this.mainCamera instanceof de){const n=this.focusRectSettings,s=n.damping>0?this.time.deltaTime/n.damping:1;FP(this._focusRect,s,this.mainCamera,this.renderer)}this._currentFrameEvent=3;for(let n=0;n<this.scripts_onBeforeRender.length;n++){const s=this.scripts_onBeforeRender[n];s.activeAndEnabled&&s.onBeforeRender!==void 0&&(z.Current=this,s.onBeforeRender(t))}if(this.executeCoroutines(3),Fn(this,3),this._needsUpdateSize&&this.updateSize(),this.pre_render_callbacks)for(const n in this.pre_render_callbacks)this.pre_render_callbacks[n](t)}return!0}internalUpdatePhysics(e){if(!this.physics.engine)return!1;const t=e,i=this.time.deltaTime/t;for(let n=0;n<t;n++)this._currentFrameEvent=9,this.executeCoroutines(9),this.physics.engine.step(i),this._currentFrameEvent=10,this.executeCoroutines(10);return this.physics.engine.postStep(),!0}internalOnRender(){this.isManagedExternally||(rk(this),this._currentFrameEvent=-1,vC.update(),this.renderNow(),this._currentFrameEvent=4)}internalOnAfterRender(){if(this.isVisibleToUser||this.runInBackground){for(let e=0;e<this.scripts_onAfterRender.length;e++){const t=this.scripts_onAfterRender[e];t.activeAndEnabled&&t.onAfterRender!==void 0&&(z.Current=this,t.onAfterRender())}if(this.executeCoroutines(4),Fn(this,4),this.post_render_callbacks)for(const e in this.post_render_callbacks)this.post_render_callbacks[e]()}this._currentFrameEvent=-1,this.connection.sendBufferedMessagesNow(),this._stats&&(this._stats.end(),this.time.frameCount%150===0&&console.log(this.renderer.info.render.calls+" DrawCalls",`
792
792
  Render:`,{...this.renderer.info.render},`
793
793
  Memory:`,{...this.renderer.info.memory},`
@@ -862,10 +862,10 @@ Target Framerate: `+this.targetFrameRate)),this._dispatchReadyAfterFrame&&(this.
862
862
  padding-left: 25px;
863
863
  border-radius: .5em;
864
864
  border: 2px solid rgba(160,160,160,.3);
865
- `,i=`Needle Engine \u2014 No license active, commercial use is not allowed. Visit https://needle.tools/pricing for more information and licensing options! v${mn}`;z.Current?.xr?console.log(i):console.log("%c "+i,t)}async function mM(o){if(!window.crossOriginIsolated){if(Nn==="pro"){const e=o?.domElement?.getAttribute("no-telemetry");if(e===""||e==="true"||e==="1"){Pi&&console.debug("Telemetry is disabled");return}Pi&&console.debug("Telemetry attribute: "+e)}try{const e="https://needle-engine-analytics-v2-r26roub2hq-lz.a.run.app";if(e){const t=window.location.href.split("?")[0];let i="api/v2/new/request";e.endsWith("/")||(i="/"+i);const n=Nn,s=`${e}${i}`;Pi&&console.debug("Sending beacon");const r={license:n,url:t,hostname:window.location.hostname,pathname:window.location.pathname,version:mn,generator:Pd,build_time:$m,public_key:xa},a=navigator.sendBeacon?.(s,JSON.stringify(r));Pi&&console.debug("Sent beacon: "+a)}}catch(e){Pi&&console.log("Failed to send non-commercial usage message to analytics backend",e)}}}function Kv(o,e){return xo(o,he.ContextCreated,e),()=>ds(o,he.ContextCreated)}function gM(o,e){return xo(o,he.ContextClearing,e),()=>ds(o,he.ContextClearing)}function fM(o,e){return xo(o,he.ContextDestroying,e),()=>ds(o,he.ContextDestroying)}function hu(o,e){return xo(o,we.Start,e),()=>ds(o,we.Start)}function Zv(o,e){return xo(o,we.Update,e),()=>ds(o,we.Update)}function yM(o,e){return xo(o,we.OnBeforeRender,e),()=>ds(o,we.OnBeforeRender)}function bM(o,e){return xo(o,we.OnAfterRender,e),()=>ds(o,we.OnAfterRender)}const _M=w("debugdecoders");let Qg=null;function Jv(){if(!Qg){const o=pm(null);Qg={dracoLoader:o.dracoLoader,ktx2Loader:o.ktx2Loader,meshoptDecoder:o.meshoptDecoder}}return Qg}function ew(o){o!==void 0&&typeof o=="string"&&gC(o)}function tw(o){if(o!==void 0&&typeof o=="string"&&o!=="js"){const e=Jv();_M&&console.log("Setting draco decoder type to",o),e.dracoLoader.setDecoderConfig({type:o})}}function iw(o){o!==void 0&&typeof o=="string"&&mC(o)}function Yg(o,e){const t=Jv();return e.renderer?t.ktx2Loader.detectSupport(e.renderer):console.warn("No renderer provided to detect ktx2 support - loading KTX2 textures will probably fail"),uC(o),o.dracoLoader||o.setDRACOLoader(t.dracoLoader),o.ktx2Loader||o.setKTX2Loader(t.ktx2Loader),o.meshoptDecoder||o.setMeshoptDecoder(t.meshoptDecoder),pC(o,{progressive:!0}),o}const Qe=function(o){return u(o)},u=function(o){if(o===void 0&&(o=null),!Array.isArray(o))o=nw(o);else for(let e=0;e<o.length;e++){const t=o[e];o[e]=nw(t)}return function(e,t){if(!e){const n=typeof t=="string"?t:t.name;console.warn(`@serializable without a target at '${n}'.`);return}typeof t!="string"&&(t=t.name),Object.getOwnPropertyDescriptor(e,"$serializedTypes")||(e.$serializedTypes={});const i=e.$serializedTypes=e.$serializedTypes||{};i[t]=o}};function nw(o){switch(o?.prototype?.constructor?.name){case"Number":case"String":case"Boolean":return null}return o}const gs=w("debughotreload");let _c=!1;const vc=new Map;function vM(){return _c}function Kg(){return globalThis.NEEDLE_HOT_RELOAD_ENABLED===!0}function ow(o){if(_c){gs&&console.warn("[Needle Engine] Hot reloading is in progress, not registering instance",o);return}gs&&console.log("[Needle Engine] Registering hot reload instance",o);const e=o.constructor.name;vc.has(e)?vc.get(e)?.push(o):vc.set(e,[o])}function sw(o){if(_c){gs&&console.warn("[Needle Engine] Hot reloading is in progress, not unregistering instance",o);return}gs&&console.log("[Needle Engine] Unregistering hot reload instance",o);const e=o.constructor.name,t=vc.get(e);if(!t)return;const i=t.indexOf(o);i!==-1&&t.splice(i,1)}let rw=!1;function wM(){if(gs||rw)return;rw=!0;const o=console.error;console.error=(...e)=>{if(e.length){const t=e[0];if(typeof t=="string"&&t.includes("[hmr] Failed to reload ")){console.log("[Needle Engine] Hot reloading failed"),window.location.reload();return}}o.apply(console,e)}}function xM(o){gs&&console.log("[HMR] Apply changes",o,Object.keys(o)),wM();for(const e of Object.keys(o))try{_c=!0;const t=C.get(e);if(!t){gs&&console.log("[HMR] Type not found: "+e);continue}const i=o[e],n=vc.get(i.name);let s="[Needle Engine] Updating type: "+e;const r=n?.length??-1;r>0?s+=" x"+r:s+=" (No instances registered)",console.log(s);const a=Object.getOwnPropertyNames(t.prototype),l=Object.getOwnPropertyDescriptors(i.prototype);for(const c in l)l[c].writable&&(t.prototype[c]=o[e].prototype[c]);for(const c of a)l[c]||delete t.prototype[c];if(n){const c=new i,h=Object.getOwnPropertyDescriptors(c);for(const d of n){const p=d,g=p.isComponent===!0,f=g?p.activeAndEnabled:!0,m=g?p.context:void 0;try{if(g&&m&&So(p,m),g&&f&&(p.enabled=!1),d.onBeforeHotReloadFields&&d.onBeforeHotReloadFields()===!1)continue;for(const y in h)if(h[y].writable){if(d[y]===void 0)d[y]=c[y];else if(typeof d[y]=="function"&&!d[y].prototype){const _=d[y],v=_.name,P="bound ";if(v===P)continue;const R=_.name.substring(P.length),k=i.prototype[R];k&&(d[y]=k.bind(d))}}d.onAfterHotReloadFields&&d.onAfterHotReloadFields()}finally{g&&m&&gg(p,m),g&&f&&(p.enabled=!0)}}}}catch(t){if(gs)console.error(t);else return!1}finally{_c=!1,or(xi.Log,"Script changes applied (HMR)")}return!0}class x extends O{guid;static isDestroyed(e){return vr(e)}static setActive(e,t,i=!0){e&&(mc(e,t),Wd(e),t&&i&&W_(z.Current,e))}static isActiveSelf(e){return La(e)}static isActiveInHierarchy(e){return vv(e)}static markAsInstancedRendered(e,t){wv(e,t)}static isUsingInstancing(e){return Kd(e)}static foreachComponent(e,t,i=!0){return wr(e,t,i)}static instantiateSynced(e,t){return e?xg(e,t):null}static instantiate(e,t=null){return"isAssetReference"in e,Da(e,t)}static destroySynced(e,t,i=!0){if(!e)return;const n=e;t=t??z.Current,ac(n,t.connection,i)}static destroy(e,t=!0){return Ci(e,t)}static add(e,t,i){if(!(!e||!t)){if(e===t){console.warn("Can not add object to self",e);return}i||(i=z.Current),t.add(e),mc(e,!0),Wd(e),i?x.foreachComponent(e,n=>{gg(n,i),!n.__internalDidAwakeAndStart&&i.new_script_start.includes(n)===!1&&i.new_script_start.push(n)},!0):console.warn("Missing context")}}static remove(e){e&&(e.parent?.remove(e),mc(e,!1),Wd(e),x.foreachComponent(e,t=>{nk(t)},!0))}static invokeOnChildren(e,t,...i){this.invoke(e,t,!0,i)}static invoke(e,t,i=!1,...n){e&&this.foreachComponent(e,s=>{const r=s[t];r&&typeof r=="function"&&r?.call(s,...n)},i)}static addNewComponent(e,t,i,n=!0){return bn(e,t,i,{callAwake:n})}static addComponent(e,t,i,n){return bn(e,t,i,n)}static moveComponent(e,t){return bn(e,t)}static removeComponent(e){return Eg(e.gameObject,e),e}static getOrAddComponent(e,t){return cc(e,t)}static getComponent(e,t){return e===null?null:br(e,t)}static getComponents(e,t,i=null){return e===null?i??[]:hc(e,t,i)}static findByGuid(e,t){return Ag(e,t)}static findObjectOfType(e,t,i=!0){return pc(e,t??z.Current,i)}static findObjectsOfType(e,t){const i=[];return _v(e,i,t),i}static getComponentInChildren(e,t){return dc(e,t)}static getComponentsInChildren(e,t,i=null){return Ia(e,t,i??void 0)}static getComponentInParent(e,t){return uc(e,t)}static getComponentsInParent(e,t,i=null){return Xd(e,t,i)}static getAllComponents(e){const t=e.userData?.components;return t?[...t]:[]}static*iterateComponents(e){const t=e?.userData?.components;if(t&&Array.isArray(t))for(let i=0;i<t.length;i++)yield t[i]}}class M{get isComponent(){return!0}__context;get context(){return this.__context??z.Current}set context(e){this.__context=e}get scene(){return this.context.scene}get layer(){return this.gameObject?.userData?.layer}get name(){return this.gameObject?.name?this.gameObject.name:this.gameObject?.userData.name}__name;set name(e){this.gameObject?(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.name=e,this.__name=e):this.__name=e}get tag(){return this.gameObject?.userData.tag}set tag(e){this.gameObject&&(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.tag=e)}get static(){return this.gameObject?.userData.static}set static(e){this.gameObject&&(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.static=e)}get activeAndEnabled(){return!(this.destroyed||this.__isEnabled===!1||!this.__isActiveInHierarchy)}get __isActive(){return this.gameObject.visible}get __isActiveInHierarchy(){if(!this.gameObject)return!1;const e=this.gameObject[_o];return e===void 0?!0:e}set __isActiveInHierarchy(e){this.gameObject&&(this.gameObject[_o]=e)}gameObject;guid="invalid";sourceId;awake(){}onEnable(){}onDisable(){}onDestroy(){this.__destroyed=!0}startCoroutine(e,t=we.Update){return this.context.registerCoroutineUpdate(this,e,t)}stopCoroutine(e,t=we.Update){this.context.unregisterCoroutineUpdate(e,t)}get destroyed(){return this.__destroyed}destroy(){this.__destroyed||this.__internalDestroy()}__didAwake=!1;__didStart=!1;__didEnable=!1;__isEnabled=void 0;__destroyed=!1;get __internalDidAwakeAndStart(){return this.__didAwake&&this.__didStart}constructor(e){this.__didAwake=!1,this.__didStart=!1,this.__didEnable=!1,this.__isEnabled=void 0,this.__destroyed=!1,this._internalInit(e),Kg()&&ow(this)}__internalNewInstanceCreated(e){return this.__didAwake=!1,this.__didStart=!1,this.__didEnable=!1,this.__isEnabled=void 0,this.__destroyed=!1,this._internalInit(e),this}_internalInit(e){if(typeof e=="object")for(const t of Object.keys(e)){const i=e[t];typeof i!="function"&&(this[t]=i)}}__internalAwake(){this.__didAwake||(this.__didAwake=!0,this.awake())}__internalStart(){this.__didStart||(this.__didStart=!0,this.start&&this.start())}__internalEnable(e){return this.__destroyed?(E()&&console.warn("[Needle Engine Dev] Trying to enable destroyed component"),!1):this.__didAwake?this.__didEnable?(e!==!0&&(this.__isEnabled=!0),!1):(this.__didEnable=!0,this.__isEnabled=!0,this.onEnable(),!0):!1}__internalDisable(e){if(this.__didAwake){if(!this.__didEnable){e!==!0&&(this.__isEnabled=!1);return}this.__didEnable=!1,this.__isEnabled=!1,this.onDisable()}}__internalDestroy(){this.__destroyed||(this.__destroyed=!0,this.__didAwake&&(this.onDestroy?.call(this),this.dispatchEvent(new CustomEvent("destroyed",{detail:this}))),fv(this),Kg()&&sw(this))}get enabled(){return typeof this.__isEnabled=="boolean"?this.__isEnabled:!0}set enabled(e){if(this.__destroyed){E()&&console.warn(`[Needle Engine Dev] Trying to ${e?"enable":"disable"} destroyed component`);return}if(typeof e=="number"&&(e>=.5?e=!0:e=!1),!this.__didAwake){this.__isEnabled=e;return}e?this.__internalEnable():this.__internalDisable()}get worldPosition(){return Z(this.gameObject)}set worldPosition(e){mt(this.gameObject,e)}setWorldPosition(e,t,i){sr(this.gameObject,e,t,i)}get worldQuaternion(){return be(this.gameObject)}set worldQuaternion(e){pn(this.gameObject,e)}setWorldQuaternion(e,t,i,n){Dm(this.gameObject,e,t,i,n)}get worldEuler(){return Bm(this.gameObject)}set worldEuler(e){Fm(this.gameObject,e)}get worldRotation(){return this.gameObject.worldRotation}set worldRotation(e){this.setWorldRotation(e.x,e.y,e.z,!0)}setWorldRotation(e,t,i,n=!0){Hl(this.gameObject,e,t,i,n)}static _forward=new b;get forward(){return M._forward.set(0,0,-1).applyQuaternion(this.worldQuaternion)}static _right=new b;get right(){return M._right.set(1,0,0).applyQuaternion(this.worldQuaternion)}static _up=new b;get up(){return M._up.set(0,1,0).applyQuaternion(this.worldQuaternion)}_eventListeners=new Map;addEventListener(e,t){this._eventListeners[e]=this._eventListeners[e]||[],this._eventListeners[e].push(t)}removeEventListener(e,t){if(!this._eventListeners[e])return;const i=this._eventListeners[e].indexOf(t);i>=0&&this._eventListeners[e].splice(i,1)}dispatchEvent(e){if(!e||!this._eventListeners[e.type])return!1;const t=this._eventListeners[e.type];for(let i=0;i<t.length;i++)t[i](e);return!1}}const SM=Object.freeze(Object.defineProperty({__proto__:null,Behaviour:M,Component:M,GameObject:x},Symbol.toStringTag,{value:"Module"}));var CM=Object.defineProperty,aw=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&CM(e,t,n),n};class wc extends M{from;to;width=0;centered=!0;_centerPos;awake(){this._centerPos=new b}update(){if(!this.from||!this.to)return;const e=Z(this.from).clone(),t=Z(this.to).clone(),i=e.distanceTo(t);this._centerPos.copy(e),this._centerPos.add(t),this._centerPos.multiplyScalar(.5),mt(this.gameObject,this.centered?this._centerPos:e),this.gameObject.lookAt(Z(this.to).clone()),this.gameObject.scale.set(this.width,this.width,i)}}aw([u(x)],wc.prototype,"from"),aw([u(x)],wc.prototype,"to");var PM=Object.defineProperty,OM=Object.getOwnPropertyDescriptor,Cr=(o,e,t,i)=>{for(var n=i>1?void 0:i?OM(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&PM(e,t,n),n};const fs=w("debuganimation");let lw=class{x;y};class Ht extends M{get isAnimationComponent(){return!0}addClip(e){this.animations||(this.animations=[]),this.animations.includes(e)||this.animations.push(e)}playAutomatically=!0;randomStartTime=!0;minMaxSpeed;minMaxOffsetNormalized;loop=!0;clampWhenFinished=!1;get time(){if(this.actions){for(const e of this.actions)if(e.isRunning())return e.time}return 0}set time(e){if(this.actions)for(const t of this.actions)t.time=e}get duration(){if(this.actions){for(const e of this.actions)if(e.isRunning())return e.getClip().duration}return 0}_tempAnimationClipBeforeGameObjectExisted=null;get clip(){return this.animations?.length?this.animations[0]:null}set clip(e){if(!this.__didAwake){fs&&console.warn("Assign clip during serialization",e),this._tempAnimationClipBeforeGameObjectExisted=e;return}e&&(this.gameObject.animations||(this.gameObject.animations=[]),!this.animations.includes(e)&&(this.animations.length>0?this.animations.splice(0,0,e):this.animations.push(e)))}set clips(e){this.animations=e}_tempAnimationsArray;set animations(e){e==null||!Array.isArray(e)||(this.gameObject?this.gameObject.animations=e:this._tempAnimationsArray=e)}get animations(){return this.gameObject?.animations||this._tempAnimationsArray||[]}mixer=void 0;get actions(){return this._actions}set actions(e){this._actions=e}_actions;_handles;awake(){this.mixer=void 0,fs&&console.log("Animation Awake",this.name,this),this._tempAnimationsArray&&(this.animations=this._tempAnimationsArray,this._tempAnimationsArray=void 0),this._tempAnimationClipBeforeGameObjectExisted&&(this.clip=this._tempAnimationClipBeforeGameObjectExisted,this._tempAnimationClipBeforeGameObjectExisted=null),this.actions=[],this._handles=[]}onEnable(){if(this.playAutomatically&&this.animations?.length>0){const e=Math.floor(Math.random()*this.animations.length),t=this.animations[e];this.play(e,{exclusive:!0,fadeDuration:0,startTime:this.randomStartTime?Math.random()*t.duration:0,loop:this.loop,clampWhenFinished:this.clampWhenFinished})}}update(){this.mixer&&(this.mixer.update(this.context.time.deltaTime),this._handles.forEach(e=>e.update()))}onDisable(){this.mixer&&this.mixer.stopAllAction()}onDestroy(){this.context.animations.unregisterAnimationMixer(this.mixer)}getAction(e){return this.actions?.find(t=>t.getClip().name===e)||null}get isPlaying(){if(this.actions){for(let e=0;e<this.actions.length;e++)if(this.actions[e].isRunning())return!0}return!1}stopAll(e){if(this.actions)for(const t of this.actions)e?.fadeDuration?t.fadeOut(e.fadeDuration):t.stop()}stop(e,t){if(e===void 0){this.stopAll();return}else if(typeof e=="number"){if(e>=this.animations.length){fs&&console.log("No animation at index",e);return}e=this.animations[e]}else typeof e=="string"&&(e=this.animations.find(n=>n.name===e));if(!e){console.error("Could not find clip",e);return}const i=this.actions.find(n=>n.getClip()===e);if(!i){console.error("Could not find action",e);return}t?.fadeDuration?i.fadeOut(t.fadeDuration):i.stop()}pause(e,t=!1){if(e===void 0){for(const n of this.actions)n.paused=!t;return}else if(typeof e=="number"){if(e>=this.animations.length){fs&&console.log("No animation at index",e);return}e=this.animations[e]}else typeof e=="string"&&(e=this.animations.find(n=>n.name===e));if(!e){console.error("Could not find clip",e);return}const i=this.actions.find(n=>n.getClip()===e);if(!i){console.error("Could not find action",e);return}i.paused=!t}resume(){for(const e of this.actions)e.paused=!1}play(e=0,t){if(fs&&console.log("PLAY",e),this.ensureMixer(),!this.mixer){fs&&console.warn("Missing mixer",this);return}e===void 0&&(e=0);let i=e;if(typeof e=="number"){if(e>=this.animations.length){fs&&console.log("No animation at index",e);return}i=this.animations[e]}else typeof e=="string"&&(i=this.animations.find(s=>s.name===e));if(!i){console.error("Could not find clip",e);return}t||(t={});for(const s of this.actions)if(s.getClip()===i)return this.internalOnPlay(s,t);if(!i.tracks){console.warn("Clip is no AnimationClip",i);return}const n=this.mixer.clipAction(i);return this.actions.push(n),this.internalOnPlay(n,t)}internalOnPlay(e,t){var i=this.actions.find(s=>s===e);if(i===e&&i.isRunning()&&i.time<i.getClip().duration){const s=this.tryFindHandle(e);if(i.paused&&(i.paused=!1),s)return s.waitForFinish()}if(t.loop===void 0&&(t.loop=this.loop),t.clampWhenFinished===void 0&&(t.clampWhenFinished=this.clampWhenFinished),t.minMaxOffsetNormalized===void 0&&this.randomStartTime&&(t.minMaxOffsetNormalized=this.minMaxOffsetNormalized),t.minMaxSpeed===void 0&&(t.minMaxSpeed=this.minMaxSpeed),t?.exclusive??!0)for(const s of this.actions)s!=i&&(t.fadeDuration?s.fadeOut(t.fadeDuration):s.stop());if(t?.fadeDuration&&e.fadeIn(t.fadeDuration),e.enabled=!0,t?.startTime!=null)e.time=t.startTime;else if(t?.minMaxOffsetNormalized&&t.minMaxOffsetNormalized.x!=0&&t.minMaxOffsetNormalized.y!=0){const s=e.getClip();e.time=D.lerp(t.minMaxOffsetNormalized.x,t.minMaxOffsetNormalized.y,Math.random())*s.duration}else e.time>=e.getClip().duration&&(e.time=0);t?.minMaxSpeed?e.timeScale=D.lerp(t.minMaxSpeed.x,t.minMaxSpeed.y,Math.random()):e.timeScale=t?.speed??1,t?.loop!=null?e.loop=t.loop?uS:sm:e.loop=sm,t?.clampWhenFinished&&(e.clampWhenFinished=!0),e.paused=!1,e.play(),fs&&console.log("PLAY",e.getClip().name,e);const n=new kM(e,this.mixer,t,s=>{this._handles.splice(this._handles.indexOf(n),1)});return this._handles.push(n),n.waitForFinish()}tryFindHandle(e){for(const t of this._handles)if(t.action===e)return t}ensureMixer(){if(!this.mixer){const e="animationMixer";this.gameObject[e]&&(this.mixer=this.gameObject[e]),(!this.mixer||!this.mixer.clipAction)&&(this.mixer=new rm(this.gameObject),this.gameObject[e]=this.mixer)}this.context.animations.registerAnimationMixer(this.mixer)}}Cr([u()],Ht.prototype,"playAutomatically",2),Cr([u()],Ht.prototype,"randomStartTime",2),Cr([u(lw)],Ht.prototype,"minMaxSpeed",2),Cr([u(lw)],Ht.prototype,"minMaxOffsetNormalized",2),Cr([u()],Ht.prototype,"loop",2),Cr([u()],Ht.prototype,"clampWhenFinished",2),Cr([u(rs)],Ht.prototype,"clips",1);class kM{mixer;action;promise=null;_options;_resolveCallback=null;_resolvedOrRejectedCallback;constructor(e,t,i,n){this.action=e,this.mixer=t,this._resolvedOrRejectedCallback=n,this._options=i}waitForFinish(){return this.promise?this.promise:(this.promise=new Promise(e=>{this._resolveCallback=e}),this.mixer.addEventListener("finished",this.onFinished),this.promise)}update(){this._options&&this._options.endTime!==void 0&&this.action.time>this._options.endTime&&(this._options.loop===!0?this.action.time=this._options.startTime??0:(this.action.time=this._options.endTime,this.action.timeScale=0,this.onResolve()))}onResolve(){this.dispose(),this._resolvedOrRejectedCallback?.call(this,this),this._resolveCallback?.call(this,this.action)}onFinished=e=>{e.action===this.action&&this.onResolve()};dispose(){this.mixer.removeEventListener("finished",this.onFinished)}}const du=Symbol("objectIsAnimatedData");function cw(o,e,t){if(!o)return;if(o[du]===void 0){if(!t)return;o[du]=new Set}const i=o[du];t?i.add(e):i.has(e)&&i.delete(e)}function MM(o){if(!o)return!1;const e=o[du];return e!==void 0&&e.size>0}class RM{_context;get context(){return this._context??z.Current}get isStateMachineBehaviour(){return!0}}class xc{name;nameHash;normalizedTime;length;speed;action;hasTransitions;constructor(e,t,i,n){this.name=e.name,this.nameHash=e.hash,this.normalizedTime=t,this.length=i,this.speed=n,this.action=e.motion.action||null,this.hasTransitions=e.transitions?.length>0||!1}}function hw(o,e){return{name:"Empty",isLooping:!1,guid:e?.generateUUID()??uo.generateUUID(),index:-1,clip:new rs(o,0,[])}}var ys=(o=>(o[o.If=1]="If",o[o.IfNot=2]="IfNot",o[o.Greater=3]="Greater",o[o.Less=4]="Less",o[o.Equals=6]="Equals",o[o.NotEqual=7]="NotEqual",o))(ys||{}),Zg=(o=>(o[o.Float=1]="Float",o[o.Int=3]="Int",o[o.Bool=4]="Bool",o[o.Trigger=9]="Trigger",o))(Zg||{});const st=w("debuganimatorcontroller"),uu=w("debugrootmotion");class ln{static createFromClips(e,t={looping:!1,autoTransition:!0,transitionDuration:0}){const i=[];for(let s=0;s<e.length;s++){const r=e[s],a=[];if(t.autoTransition!==!1){const c=t.transitionDuration??0,h=c/r.duration;let d=s;(t.autoTransition===void 0||t.autoTransition===!0)&&(d=(s+1)%e.length),a.push({exitTime:1-h,offset:0,duration:c,hasExitTime:!0,destinationState:d,conditions:[]})}const l={name:r.name,hash:s,motion:{name:r.name,clip:r,isLooping:t?.looping??!1},transitions:a,behaviours:[]};i.push(l)}const n={name:"AnimatorController",guid:new At(Date.now()).generateUUID(),parameters:[],layers:[{name:"Base Layer",stateMachine:{defaultState:0,states:i}}]};return new ln(n)}play(e,t=-1,i=Number.NEGATIVE_INFINITY,n=0){if(t<0)t=0;else if(t>=this.model.layers.length){console.warn("invalid layer");return}const s=this.model.layers[t].stateMachine;for(const r of s.states)if(r.name===e||r.hash===e){st&&console.log("transition to ",r),this.transitionTo(r,n,i);return}console.warn("Could not find "+e+" to play")}reset(){this.setStartTransition()}setBool(e,t){const i=typeof e=="string"?"name":"hash";return this.model?.parameters?.filter(n=>n[i]===e).forEach(n=>n.value=t)}getBool(e){const t=typeof e=="string"?"name":"hash";return this.model?.parameters?.find(i=>i[t]===e)?.value??!1}setFloat(e,t){const i=typeof e=="string"?"name":"hash",n=this.model?.parameters?.filter(s=>s[i]===e);return n.forEach(s=>s.value=t),n?.length>0}getFloat(e){const t=typeof e=="string"?"name":"hash";return this.model?.parameters?.find(i=>i[t]===e)?.value??0}setInteger(e,t){const i=typeof e=="string"?"name":"hash";return this.model?.parameters?.filter(n=>n[i]===e).forEach(n=>n.value=t)}getInteger(e){const t=typeof e=="string"?"name":"hash";return this.model?.parameters?.find(i=>i[t]===e)?.value??0}setTrigger(e){st&&console.log("SET TRIGGER",e);const t=typeof e=="string"?"name":"hash";return this.model?.parameters?.filter(i=>i[t]===e).forEach(i=>i.value=!0)}resetTrigger(e){const t=typeof e=="string"?"name":"hash";return this.model?.parameters?.filter(i=>i[t]===e).forEach(i=>i.value=!1)}getTrigger(e){const t=typeof e=="string"?"name":"hash";return this.model?.parameters?.find(i=>i[t]===e)?.value??!1}isInTransition(){return this._activeStates.length>1}setSpeed(e){this._speed=e}_speed=1;FindState(e){return this.findState(e)}findState(e){if(!e)return null;if(Array.isArray(this.model.layers)){for(const t of this.model.layers)for(const i of t.stateMachine.states)if(i.name===e||i.hash==e)return i}return null}getCurrentStateInfo(){if(!this._activeState)return null;const e=this._activeState.motion.action;if(!e)return null;const t=this._activeState.motion.clip.duration,i=t<=0?0:Math.abs(e.time/t);return new xc(this._activeState,i,t,this._speed)}get currentAction(){return this._activeState&&this._activeState.motion.action||null}normalizedStartOffset=0;animator;model;get context(){return this.animator?.context}get mixer(){return this._mixer}dispose(){if(this._mixer.stopAllAction(),this.animator){this._mixer.uncacheRoot(this.animator.gameObject);for(const e of this._activeStates)e.motion.clip&&this.mixer.uncacheAction(e.motion.clip,this.animator.gameObject)}this.context?.animations.unregisterAnimationMixer(this._mixer)}bind(e){e?this.animator!==e&&(this._mixer&&(this._mixer.stopAllAction(),this.context?.animations.unregisterAnimationMixer(this._mixer)),this.animator=e,this._mixer=new rm(this.animator.gameObject),this.context?.animations.registerAnimationMixer(this._mixer),this.createActions(this.animator)):console.error("AnimatorController.bind: animator is null")}clone(){if(typeof this.model=="string")return console.warn("AnimatorController has not been resolved, can not create model from string",this.model),null;st&&console.warn("AnimatorController clone()",this.model);const e=Nl(this.model,(t,i,n)=>n==null?!0:!(n.type==="Object3D"||n.isObject3D===!0||zb(n)||n.tracks!==void 0||n instanceof ln));return console.assert(e!==this.model),new ln(e)}update(e){if(!this.animator)return;this.evaluateTransitions(),this.updateActiveStates(e);const t=this.animator.context.time.deltaTime;this.animator.applyRootMotion&&this.rootMotionHandler?.onBeforeUpdate(e),this._mixer.update(t),this.animator.applyRootMotion&&this.rootMotionHandler?.onAfterUpdate(e)}_mixer;_activeState;get activeState(){return this._activeState}constructor(e){this.model=e,st&&console.log(this)}_activeStates=[];updateActiveStates(e){for(let t=0;t<this._activeStates.length;t++){const i=this._activeStates[t],n=i.motion;if(!n.action)this._activeStates.splice(t,1),t--;else{const s=n.action;s.weight=e,s.getEffectiveWeight()<=0&&!s.isRunning()&&(st&&console.debug("REMOVE",i.name,s.getEffectiveWeight(),s.isRunning(),s.isScheduled()),this._activeStates.splice(t,1),t--)}}}setStartTransition(){this.model.layers.length>1&&(st||E())&&console.warn("Multiple layers are not supported yet "+this.animator?.name);for(const e of this.model.layers){const t=e.stateMachine;t.defaultState===void 0&&(st&&console.warn("AnimatorController default state is undefined, will assign state 0 as default",e),t.defaultState=0);const i=t.states[t.defaultState];this.transitionTo(i,0,this.normalizedStartOffset);break}}evaluateTransitions(){let e=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;e=!0}const t=this._activeState,i=t.motion.action;for(const s of t.transitions){if(!s.hasExitTime&&s.conditions.length<=0)continue;let r=!0;for(const a of s.conditions)if(!this.evaluateCondition(a)){r=!1;break}if(r)if(i){const a=t.motion.clip.duration,l=a<=0?1:Math.abs(i.time/a);let c=s.exitTime;i.timeScale<0&&(c=1-c);let h=!1;if(s.hasExitTime?i.timeScale>0?h=l>=s.exitTime:i.timeScale<0&&(h=1-l>=s.exitTime):h=!0,h){for(const d of s.conditions){const p=this.model.parameters.find(g=>g.name===d.parameter);p?.type===Zg.Trigger&&p.value&&(p.value=!1)}if(i.clampWhenFinished=!0,st){const d=this.getState(s.destinationState,0);console.log(`Transition to ${s.destinationState} / ${d?.name}`,s,`
865
+ `,i=`Needle Engine \u2014 No license active, commercial use is not allowed. Visit https://needle.tools/pricing for more information and licensing options! v${mn}`;z.Current?.xr?console.log(i):console.log("%c "+i,t)}async function mM(o){if(!window.crossOriginIsolated){if(Nn==="pro"){const e=o?.domElement?.getAttribute("no-telemetry");if(e===""||e==="true"||e==="1"){Pi&&console.debug("Telemetry is disabled");return}Pi&&console.debug("Telemetry attribute: "+e)}try{const e="https://needle-engine-analytics-v2-r26roub2hq-lz.a.run.app";if(e){const t=window.location.href.split("?")[0];let i="api/v2/new/request";e.endsWith("/")||(i="/"+i);const n=Nn,s=`${e}${i}`;Pi&&console.debug("Sending beacon");const r={license:n,url:t,hostname:window.location.hostname,pathname:window.location.pathname,version:mn,generator:Pd,build_time:$m,public_key:xa},a=navigator.sendBeacon?.(s,JSON.stringify(r));Pi&&console.debug("Sent beacon: "+a)}}catch(e){Pi&&console.log("Failed to send non-commercial usage message to analytics backend",e)}}}function Kv(o,e){return xo(o,he.ContextCreated,e),()=>ds(o,he.ContextCreated)}function gM(o,e){return xo(o,he.ContextClearing,e),()=>ds(o,he.ContextClearing)}function fM(o,e){return xo(o,he.ContextDestroying,e),()=>ds(o,he.ContextDestroying)}function hu(o,e){return xo(o,we.Start,e),()=>ds(o,we.Start)}function Zv(o,e){return xo(o,we.Update,e),()=>ds(o,we.Update)}function yM(o,e){return xo(o,we.OnBeforeRender,e),()=>ds(o,we.OnBeforeRender)}function bM(o,e){return xo(o,we.OnAfterRender,e),()=>ds(o,we.OnAfterRender)}const _M=w("debugdecoders");let Qg=null;function Jv(){if(!Qg){const o=pm(null);Qg={dracoLoader:o.dracoLoader,ktx2Loader:o.ktx2Loader,meshoptDecoder:o.meshoptDecoder}}return Qg}function ew(o){o!==void 0&&typeof o=="string"&&gC(o)}function tw(o){if(o!==void 0&&typeof o=="string"&&o!=="js"){const e=Jv();_M&&console.log("Setting draco decoder type to",o),e.dracoLoader.setDecoderConfig({type:o})}}function iw(o){o!==void 0&&typeof o=="string"&&mC(o)}function Yg(o,e){const t=Jv();return e.renderer?t.ktx2Loader.detectSupport(e.renderer):console.warn("No renderer provided to detect ktx2 support - loading KTX2 textures will probably fail"),uC(o),o.dracoLoader||o.setDRACOLoader(t.dracoLoader),o.ktx2Loader||o.setKTX2Loader(t.ktx2Loader),o.meshoptDecoder||o.setMeshoptDecoder(t.meshoptDecoder),pC(o,{progressive:!0}),o}const Qe=function(o){return u(o)},u=function(o){if(o===void 0&&(o=null),!Array.isArray(o))o=nw(o);else for(let e=0;e<o.length;e++){const t=o[e];o[e]=nw(t)}return function(e,t){if(!e){const n=typeof t=="string"?t:t.name;console.warn(`@serializable without a target at '${n}'.`);return}typeof t!="string"&&(t=t.name),Object.getOwnPropertyDescriptor(e,"$serializedTypes")||(e.$serializedTypes={});const i=e.$serializedTypes=e.$serializedTypes||{};i[t]=o}};function nw(o){switch(o?.prototype?.constructor?.name){case"Number":case"String":case"Boolean":return null}return o}const gs=w("debughotreload");let _c=!1;const vc=new Map;function vM(){return _c}function Kg(){return globalThis.NEEDLE_HOT_RELOAD_ENABLED===!0}function ow(o){if(_c){gs&&console.warn("[Needle Engine] Hot reloading is in progress, not registering instance",o);return}gs&&console.log("[Needle Engine] Registering hot reload instance",o);const e=o.constructor.name;vc.has(e)?vc.get(e)?.push(o):vc.set(e,[o])}function sw(o){if(_c){gs&&console.warn("[Needle Engine] Hot reloading is in progress, not unregistering instance",o);return}gs&&console.log("[Needle Engine] Unregistering hot reload instance",o);const e=o.constructor.name,t=vc.get(e);if(!t)return;const i=t.indexOf(o);i!==-1&&t.splice(i,1)}let rw=!1;function wM(){if(gs||rw)return;rw=!0;const o=console.error;console.error=(...e)=>{if(e.length){const t=e[0];if(typeof t=="string"&&t.includes("[hmr] Failed to reload ")){console.log("[Needle Engine] Hot reloading failed"),window.location.reload();return}}o.apply(console,e)}}function xM(o){gs&&console.log("[HMR] Apply changes",o,Object.keys(o)),wM();for(const e of Object.keys(o))try{_c=!0;const t=C.get(e);if(!t){gs&&console.log("[HMR] Type not found: "+e);continue}const i=o[e],n=vc.get(i.name);let s="[Needle Engine] Updating type: "+e;const r=n?.length??-1;r>0?s+=" x"+r:s+=" (No instances registered)",console.log(s);const a=Object.getOwnPropertyNames(t.prototype),l=Object.getOwnPropertyDescriptors(i.prototype);for(const c in l)l[c].writable&&(t.prototype[c]=o[e].prototype[c]);for(const c of a)l[c]||delete t.prototype[c];if(n){const c=new i,h=Object.getOwnPropertyDescriptors(c);for(const d of n){const p=d,m=p.isComponent===!0,f=m?p.activeAndEnabled:!0,g=m?p.context:void 0;try{if(m&&g&&So(p,g),m&&f&&(p.enabled=!1),d.onBeforeHotReloadFields&&d.onBeforeHotReloadFields()===!1)continue;for(const y in h)if(h[y].writable){if(d[y]===void 0)d[y]=c[y];else if(typeof d[y]=="function"&&!d[y].prototype){const _=d[y],v=_.name,P="bound ";if(v===P)continue;const R=_.name.substring(P.length),k=i.prototype[R];k&&(d[y]=k.bind(d))}}d.onAfterHotReloadFields&&d.onAfterHotReloadFields()}finally{m&&g&&gg(p,g),m&&f&&(p.enabled=!0)}}}}catch(t){if(gs)console.error(t);else return!1}finally{_c=!1,or(xi.Log,"Script changes applied (HMR)")}return!0}class x extends O{guid;static isDestroyed(e){return vr(e)}static setActive(e,t,i=!0){e&&(mc(e,t),Wd(e),t&&i&&W_(z.Current,e))}static isActiveSelf(e){return La(e)}static isActiveInHierarchy(e){return vv(e)}static markAsInstancedRendered(e,t){wv(e,t)}static isUsingInstancing(e){return Kd(e)}static foreachComponent(e,t,i=!0){return wr(e,t,i)}static instantiateSynced(e,t){return e?xg(e,t):null}static instantiate(e,t=null){return"isAssetReference"in e,Da(e,t)}static destroySynced(e,t,i=!0){if(!e)return;const n=e;t=t??z.Current,ac(n,t.connection,i)}static destroy(e,t=!0){return Ci(e,t)}static add(e,t,i){if(!(!e||!t)){if(e===t){console.warn("Can not add object to self",e);return}i||(i=z.Current),t.add(e),mc(e,!0),Wd(e),i?x.foreachComponent(e,n=>{gg(n,i),!n.__internalDidAwakeAndStart&&i.new_script_start.includes(n)===!1&&i.new_script_start.push(n)},!0):console.warn("Missing context")}}static remove(e){e&&(e.parent?.remove(e),mc(e,!1),Wd(e),x.foreachComponent(e,t=>{nk(t)},!0))}static invokeOnChildren(e,t,...i){this.invoke(e,t,!0,i)}static invoke(e,t,i=!1,...n){e&&this.foreachComponent(e,s=>{const r=s[t];r&&typeof r=="function"&&r?.call(s,...n)},i)}static addNewComponent(e,t,i,n=!0){return bn(e,t,i,{callAwake:n})}static addComponent(e,t,i,n){return bn(e,t,i,n)}static moveComponent(e,t){return bn(e,t)}static removeComponent(e){return Eg(e.gameObject,e),e}static getOrAddComponent(e,t){return cc(e,t)}static getComponent(e,t){return e===null?null:br(e,t)}static getComponents(e,t,i=null){return e===null?i??[]:hc(e,t,i)}static findByGuid(e,t){return Ag(e,t)}static findObjectOfType(e,t,i=!0){return pc(e,t??z.Current,i)}static findObjectsOfType(e,t){const i=[];return _v(e,i,t),i}static getComponentInChildren(e,t){return dc(e,t)}static getComponentsInChildren(e,t,i=null){return Ia(e,t,i??void 0)}static getComponentInParent(e,t){return uc(e,t)}static getComponentsInParent(e,t,i=null){return Xd(e,t,i)}static getAllComponents(e){const t=e.userData?.components;return t?[...t]:[]}static*iterateComponents(e){const t=e?.userData?.components;if(t&&Array.isArray(t))for(let i=0;i<t.length;i++)yield t[i]}}class M{get isComponent(){return!0}__context;get context(){return this.__context??z.Current}set context(e){this.__context=e}get scene(){return this.context.scene}get layer(){return this.gameObject?.userData?.layer}get name(){return this.gameObject?.name?this.gameObject.name:this.gameObject?.userData.name}__name;set name(e){this.gameObject?(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.name=e,this.__name=e):this.__name=e}get tag(){return this.gameObject?.userData.tag}set tag(e){this.gameObject&&(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.tag=e)}get static(){return this.gameObject?.userData.static}set static(e){this.gameObject&&(this.gameObject.userData||(this.gameObject.userData={}),this.gameObject.userData.static=e)}get activeAndEnabled(){return!(this.destroyed||this.__isEnabled===!1||!this.__isActiveInHierarchy)}get __isActive(){return this.gameObject.visible}get __isActiveInHierarchy(){if(!this.gameObject)return!1;const e=this.gameObject[_o];return e===void 0?!0:e}set __isActiveInHierarchy(e){this.gameObject&&(this.gameObject[_o]=e)}gameObject;guid="invalid";sourceId;awake(){}onEnable(){}onDisable(){}onDestroy(){this.__destroyed=!0}startCoroutine(e,t=we.Update){return this.context.registerCoroutineUpdate(this,e,t)}stopCoroutine(e,t=we.Update){this.context.unregisterCoroutineUpdate(e,t)}get destroyed(){return this.__destroyed}destroy(){this.__destroyed||this.__internalDestroy()}__didAwake=!1;__didStart=!1;__didEnable=!1;__isEnabled=void 0;__destroyed=!1;get __internalDidAwakeAndStart(){return this.__didAwake&&this.__didStart}constructor(e){this.__didAwake=!1,this.__didStart=!1,this.__didEnable=!1,this.__isEnabled=void 0,this.__destroyed=!1,this._internalInit(e),Kg()&&ow(this)}__internalNewInstanceCreated(e){return this.__didAwake=!1,this.__didStart=!1,this.__didEnable=!1,this.__isEnabled=void 0,this.__destroyed=!1,this._internalInit(e),this}_internalInit(e){if(typeof e=="object")for(const t of Object.keys(e)){const i=e[t];typeof i!="function"&&(this[t]=i)}}__internalAwake(){this.__didAwake||(this.__didAwake=!0,this.awake())}__internalStart(){this.__didStart||(this.__didStart=!0,this.start&&this.start())}__internalEnable(e){return this.__destroyed?(E()&&console.warn("[Needle Engine Dev] Trying to enable destroyed component"),!1):this.__didAwake?this.__didEnable?(e!==!0&&(this.__isEnabled=!0),!1):(this.__didEnable=!0,this.__isEnabled=!0,this.onEnable(),!0):!1}__internalDisable(e){if(this.__didAwake){if(!this.__didEnable){e!==!0&&(this.__isEnabled=!1);return}this.__didEnable=!1,this.__isEnabled=!1,this.onDisable()}}__internalDestroy(){this.__destroyed||(this.__destroyed=!0,this.__didAwake&&(this.onDestroy?.call(this),this.dispatchEvent(new CustomEvent("destroyed",{detail:this}))),fv(this),Kg()&&sw(this))}get enabled(){return typeof this.__isEnabled=="boolean"?this.__isEnabled:!0}set enabled(e){if(this.__destroyed){E()&&console.warn(`[Needle Engine Dev] Trying to ${e?"enable":"disable"} destroyed component`);return}if(typeof e=="number"&&(e>=.5?e=!0:e=!1),!this.__didAwake){this.__isEnabled=e;return}e?this.__internalEnable():this.__internalDisable()}get worldPosition(){return Z(this.gameObject)}set worldPosition(e){mt(this.gameObject,e)}setWorldPosition(e,t,i){sr(this.gameObject,e,t,i)}get worldQuaternion(){return be(this.gameObject)}set worldQuaternion(e){pn(this.gameObject,e)}setWorldQuaternion(e,t,i,n){Dm(this.gameObject,e,t,i,n)}get worldEuler(){return Bm(this.gameObject)}set worldEuler(e){Fm(this.gameObject,e)}get worldRotation(){return this.gameObject.worldRotation}set worldRotation(e){this.setWorldRotation(e.x,e.y,e.z,!0)}setWorldRotation(e,t,i,n=!0){Hl(this.gameObject,e,t,i,n)}static _forward=new b;get forward(){return M._forward.set(0,0,-1).applyQuaternion(this.worldQuaternion)}static _right=new b;get right(){return M._right.set(1,0,0).applyQuaternion(this.worldQuaternion)}static _up=new b;get up(){return M._up.set(0,1,0).applyQuaternion(this.worldQuaternion)}_eventListeners=new Map;addEventListener(e,t){this._eventListeners[e]=this._eventListeners[e]||[],this._eventListeners[e].push(t)}removeEventListener(e,t){if(!this._eventListeners[e])return;const i=this._eventListeners[e].indexOf(t);i>=0&&this._eventListeners[e].splice(i,1)}dispatchEvent(e){if(!e||!this._eventListeners[e.type])return!1;const t=this._eventListeners[e.type];for(let i=0;i<t.length;i++)t[i](e);return!1}}const SM=Object.freeze(Object.defineProperty({__proto__:null,Behaviour:M,Component:M,GameObject:x},Symbol.toStringTag,{value:"Module"}));var CM=Object.defineProperty,aw=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&CM(e,t,n),n};class wc extends M{from;to;width=0;centered=!0;_centerPos;awake(){this._centerPos=new b}update(){if(!this.from||!this.to)return;const e=Z(this.from).clone(),t=Z(this.to).clone(),i=e.distanceTo(t);this._centerPos.copy(e),this._centerPos.add(t),this._centerPos.multiplyScalar(.5),mt(this.gameObject,this.centered?this._centerPos:e),this.gameObject.lookAt(Z(this.to).clone()),this.gameObject.scale.set(this.width,this.width,i)}}aw([u(x)],wc.prototype,"from"),aw([u(x)],wc.prototype,"to");var PM=Object.defineProperty,OM=Object.getOwnPropertyDescriptor,Cr=(o,e,t,i)=>{for(var n=i>1?void 0:i?OM(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&PM(e,t,n),n};const fs=w("debuganimation");let lw=class{x;y};class Ht extends M{get isAnimationComponent(){return!0}addClip(e){this.animations||(this.animations=[]),this.animations.includes(e)||this.animations.push(e)}playAutomatically=!0;randomStartTime=!0;minMaxSpeed;minMaxOffsetNormalized;loop=!0;clampWhenFinished=!1;get time(){if(this.actions){for(const e of this.actions)if(e.isRunning())return e.time}return 0}set time(e){if(this.actions)for(const t of this.actions)t.time=e}get duration(){if(this.actions){for(const e of this.actions)if(e.isRunning())return e.getClip().duration}return 0}_tempAnimationClipBeforeGameObjectExisted=null;get clip(){return this.animations?.length?this.animations[0]:null}set clip(e){if(!this.__didAwake){fs&&console.warn("Assign clip during serialization",e),this._tempAnimationClipBeforeGameObjectExisted=e;return}e&&(this.gameObject.animations||(this.gameObject.animations=[]),!this.animations.includes(e)&&(this.animations.length>0?this.animations.splice(0,0,e):this.animations.push(e)))}set clips(e){this.animations=e}_tempAnimationsArray;set animations(e){e==null||!Array.isArray(e)||(this.gameObject?this.gameObject.animations=e:this._tempAnimationsArray=e)}get animations(){return this.gameObject?.animations||this._tempAnimationsArray||[]}mixer=void 0;get actions(){return this._actions}set actions(e){this._actions=e}_actions;_handles;awake(){this.mixer=void 0,fs&&console.log("Animation Awake",this.name,this),this._tempAnimationsArray&&(this.animations=this._tempAnimationsArray,this._tempAnimationsArray=void 0),this._tempAnimationClipBeforeGameObjectExisted&&(this.clip=this._tempAnimationClipBeforeGameObjectExisted,this._tempAnimationClipBeforeGameObjectExisted=null),this.actions=[],this._handles=[]}onEnable(){if(this.playAutomatically&&this.animations?.length>0){const e=Math.floor(Math.random()*this.animations.length),t=this.animations[e];this.play(e,{exclusive:!0,fadeDuration:0,startTime:this.randomStartTime?Math.random()*t.duration:0,loop:this.loop,clampWhenFinished:this.clampWhenFinished})}}update(){this.mixer&&(this.mixer.update(this.context.time.deltaTime),this._handles.forEach(e=>e.update()))}onDisable(){this.mixer&&this.mixer.stopAllAction()}onDestroy(){this.context.animations.unregisterAnimationMixer(this.mixer)}getAction(e){return this.actions?.find(t=>t.getClip().name===e)||null}get isPlaying(){if(this.actions){for(let e=0;e<this.actions.length;e++)if(this.actions[e].isRunning())return!0}return!1}stopAll(e){if(this.actions)for(const t of this.actions)e?.fadeDuration?t.fadeOut(e.fadeDuration):t.stop()}stop(e,t){if(e===void 0){this.stopAll();return}else if(typeof e=="number"){if(e>=this.animations.length){fs&&console.log("No animation at index",e);return}e=this.animations[e]}else typeof e=="string"&&(e=this.animations.find(n=>n.name===e));if(!e){console.error("Could not find clip",e);return}const i=this.actions.find(n=>n.getClip()===e);if(!i){console.error("Could not find action",e);return}t?.fadeDuration?i.fadeOut(t.fadeDuration):i.stop()}pause(e,t=!1){if(e===void 0){for(const n of this.actions)n.paused=!t;return}else if(typeof e=="number"){if(e>=this.animations.length){fs&&console.log("No animation at index",e);return}e=this.animations[e]}else typeof e=="string"&&(e=this.animations.find(n=>n.name===e));if(!e){console.error("Could not find clip",e);return}const i=this.actions.find(n=>n.getClip()===e);if(!i){console.error("Could not find action",e);return}i.paused=!t}resume(){for(const e of this.actions)e.paused=!1}play(e=0,t){if(fs&&console.log("PLAY",e),this.ensureMixer(),!this.mixer){fs&&console.warn("Missing mixer",this);return}e===void 0&&(e=0);let i=e;if(typeof e=="number"){if(e>=this.animations.length){fs&&console.log("No animation at index",e);return}i=this.animations[e]}else typeof e=="string"&&(i=this.animations.find(s=>s.name===e));if(!i){console.error("Could not find clip",e);return}t||(t={});for(const s of this.actions)if(s.getClip()===i)return this.internalOnPlay(s,t);if(!i.tracks){console.warn("Clip is no AnimationClip",i);return}const n=this.mixer.clipAction(i);return this.actions.push(n),this.internalOnPlay(n,t)}internalOnPlay(e,t){var i=this.actions.find(s=>s===e);if(i===e&&i.isRunning()&&i.time<i.getClip().duration){const s=this.tryFindHandle(e);if(i.paused&&(i.paused=!1),s)return s.waitForFinish()}if(t.loop===void 0&&(t.loop=this.loop),t.clampWhenFinished===void 0&&(t.clampWhenFinished=this.clampWhenFinished),t.minMaxOffsetNormalized===void 0&&this.randomStartTime&&(t.minMaxOffsetNormalized=this.minMaxOffsetNormalized),t.minMaxSpeed===void 0&&(t.minMaxSpeed=this.minMaxSpeed),t?.exclusive??!0)for(const s of this.actions)s!=i&&(t.fadeDuration?s.fadeOut(t.fadeDuration):s.stop());if(t?.fadeDuration&&e.fadeIn(t.fadeDuration),e.enabled=!0,t?.startTime!=null)e.time=t.startTime;else if(t?.minMaxOffsetNormalized&&t.minMaxOffsetNormalized.x!=0&&t.minMaxOffsetNormalized.y!=0){const s=e.getClip();e.time=D.lerp(t.minMaxOffsetNormalized.x,t.minMaxOffsetNormalized.y,Math.random())*s.duration}else e.time>=e.getClip().duration&&(e.time=0);t?.minMaxSpeed?e.timeScale=D.lerp(t.minMaxSpeed.x,t.minMaxSpeed.y,Math.random()):e.timeScale=t?.speed??1,t?.loop!=null?e.loop=t.loop?uS:sm:e.loop=sm,t?.clampWhenFinished&&(e.clampWhenFinished=!0),e.paused=!1,e.play(),fs&&console.log("PLAY",e.getClip().name,e);const n=new kM(e,this.mixer,t,s=>{this._handles.splice(this._handles.indexOf(n),1)});return this._handles.push(n),n.waitForFinish()}tryFindHandle(e){for(const t of this._handles)if(t.action===e)return t}ensureMixer(){if(!this.mixer){const e="animationMixer";this.gameObject[e]&&(this.mixer=this.gameObject[e]),(!this.mixer||!this.mixer.clipAction)&&(this.mixer=new rm(this.gameObject),this.gameObject[e]=this.mixer)}this.context.animations.registerAnimationMixer(this.mixer)}}Cr([u()],Ht.prototype,"playAutomatically",2),Cr([u()],Ht.prototype,"randomStartTime",2),Cr([u(lw)],Ht.prototype,"minMaxSpeed",2),Cr([u(lw)],Ht.prototype,"minMaxOffsetNormalized",2),Cr([u()],Ht.prototype,"loop",2),Cr([u()],Ht.prototype,"clampWhenFinished",2),Cr([u(rs)],Ht.prototype,"clips",1);class kM{mixer;action;promise=null;_options;_resolveCallback=null;_resolvedOrRejectedCallback;constructor(e,t,i,n){this.action=e,this.mixer=t,this._resolvedOrRejectedCallback=n,this._options=i}waitForFinish(){return this.promise?this.promise:(this.promise=new Promise(e=>{this._resolveCallback=e}),this.mixer.addEventListener("finished",this.onFinished),this.promise)}update(){this._options&&this._options.endTime!==void 0&&this.action.time>this._options.endTime&&(this._options.loop===!0?this.action.time=this._options.startTime??0:(this.action.time=this._options.endTime,this.action.timeScale=0,this.onResolve()))}onResolve(){this.dispose(),this._resolvedOrRejectedCallback?.call(this,this),this._resolveCallback?.call(this,this.action)}onFinished=e=>{e.action===this.action&&this.onResolve()};dispose(){this.mixer.removeEventListener("finished",this.onFinished)}}const du=Symbol("objectIsAnimatedData");function cw(o,e,t){if(!o)return;if(o[du]===void 0){if(!t)return;o[du]=new Set}const i=o[du];t?i.add(e):i.has(e)&&i.delete(e)}function MM(o){if(!o)return!1;const e=o[du];return e!==void 0&&e.size>0}class RM{_context;get context(){return this._context??z.Current}get isStateMachineBehaviour(){return!0}}class xc{name;nameHash;normalizedTime;length;speed;action;hasTransitions;constructor(e,t,i,n){this.name=e.name,this.nameHash=e.hash,this.normalizedTime=t,this.length=i,this.speed=n,this.action=e.motion.action||null,this.hasTransitions=e.transitions?.length>0||!1}}function hw(o,e){return{name:"Empty",isLooping:!1,guid:e?.generateUUID()??uo.generateUUID(),index:-1,clip:new rs(o,0,[])}}var ys=(o=>(o[o.If=1]="If",o[o.IfNot=2]="IfNot",o[o.Greater=3]="Greater",o[o.Less=4]="Less",o[o.Equals=6]="Equals",o[o.NotEqual=7]="NotEqual",o))(ys||{}),Zg=(o=>(o[o.Float=1]="Float",o[o.Int=3]="Int",o[o.Bool=4]="Bool",o[o.Trigger=9]="Trigger",o))(Zg||{});const st=w("debuganimatorcontroller"),uu=w("debugrootmotion");class ln{static createFromClips(e,t={looping:!1,autoTransition:!0,transitionDuration:0}){const i=[];for(let s=0;s<e.length;s++){const r=e[s],a=[];if(t.autoTransition!==!1){const c=t.transitionDuration??0,h=c/r.duration;let d=s;(t.autoTransition===void 0||t.autoTransition===!0)&&(d=(s+1)%e.length),a.push({exitTime:1-h,offset:0,duration:c,hasExitTime:!0,destinationState:d,conditions:[]})}const l={name:r.name,hash:s,motion:{name:r.name,clip:r,isLooping:t?.looping??!1},transitions:a,behaviours:[]};i.push(l)}const n={name:"AnimatorController",guid:new At(Date.now()).generateUUID(),parameters:[],layers:[{name:"Base Layer",stateMachine:{defaultState:0,states:i}}]};return new ln(n)}play(e,t=-1,i=Number.NEGATIVE_INFINITY,n=0){if(t<0)t=0;else if(t>=this.model.layers.length){console.warn("invalid layer");return}const s=this.model.layers[t].stateMachine;for(const r of s.states)if(r.name===e||r.hash===e){st&&console.log("transition to ",r),this.transitionTo(r,n,i);return}console.warn("Could not find "+e+" to play")}reset(){this.setStartTransition()}setBool(e,t){const i=typeof e=="string"?"name":"hash";return this.model?.parameters?.filter(n=>n[i]===e).forEach(n=>n.value=t)}getBool(e){const t=typeof e=="string"?"name":"hash";return this.model?.parameters?.find(i=>i[t]===e)?.value??!1}setFloat(e,t){const i=typeof e=="string"?"name":"hash",n=this.model?.parameters?.filter(s=>s[i]===e);return n.forEach(s=>s.value=t),n?.length>0}getFloat(e){const t=typeof e=="string"?"name":"hash";return this.model?.parameters?.find(i=>i[t]===e)?.value??0}setInteger(e,t){const i=typeof e=="string"?"name":"hash";return this.model?.parameters?.filter(n=>n[i]===e).forEach(n=>n.value=t)}getInteger(e){const t=typeof e=="string"?"name":"hash";return this.model?.parameters?.find(i=>i[t]===e)?.value??0}setTrigger(e){st&&console.log("SET TRIGGER",e);const t=typeof e=="string"?"name":"hash";return this.model?.parameters?.filter(i=>i[t]===e).forEach(i=>i.value=!0)}resetTrigger(e){const t=typeof e=="string"?"name":"hash";return this.model?.parameters?.filter(i=>i[t]===e).forEach(i=>i.value=!1)}getTrigger(e){const t=typeof e=="string"?"name":"hash";return this.model?.parameters?.find(i=>i[t]===e)?.value??!1}isInTransition(){return this._activeStates.length>1}setSpeed(e){this._speed=e}_speed=1;FindState(e){return this.findState(e)}findState(e){if(!e)return null;if(Array.isArray(this.model.layers)){for(const t of this.model.layers)for(const i of t.stateMachine.states)if(i.name===e||i.hash==e)return i}return null}getCurrentStateInfo(){if(!this._activeState)return null;const e=this._activeState.motion.action;if(!e)return null;const t=this._activeState.motion.clip.duration,i=t<=0?0:Math.abs(e.time/t);return new xc(this._activeState,i,t,this._speed)}get currentAction(){return this._activeState&&this._activeState.motion.action||null}normalizedStartOffset=0;animator;model;get context(){return this.animator?.context}get mixer(){return this._mixer}dispose(){if(this._mixer.stopAllAction(),this.animator){this._mixer.uncacheRoot(this.animator.gameObject);for(const e of this._activeStates)e.motion.clip&&this.mixer.uncacheAction(e.motion.clip,this.animator.gameObject)}this.context?.animations.unregisterAnimationMixer(this._mixer)}bind(e){e?this.animator!==e&&(this._mixer&&(this._mixer.stopAllAction(),this.context?.animations.unregisterAnimationMixer(this._mixer)),this.animator=e,this._mixer=new rm(this.animator.gameObject),this.context?.animations.registerAnimationMixer(this._mixer),this.createActions(this.animator)):console.error("AnimatorController.bind: animator is null")}clone(){if(typeof this.model=="string")return console.warn("AnimatorController has not been resolved, can not create model from string",this.model),null;st&&console.warn("AnimatorController clone()",this.model);const e=Nl(this.model,(t,i,n)=>n==null?!0:!(n.type==="Object3D"||n.isObject3D===!0||zb(n)||n.tracks!==void 0||n instanceof ln));return console.assert(e!==this.model),new ln(e)}update(e){if(!this.animator)return;this.evaluateTransitions(),this.updateActiveStates(e);const t=this.animator.context.time.deltaTime;this.animator.applyRootMotion&&this.rootMotionHandler?.onBeforeUpdate(e),this._mixer.update(t),this.animator.applyRootMotion&&this.rootMotionHandler?.onAfterUpdate(e)}_mixer;_activeState;get activeState(){return this._activeState}constructor(e){this.model=e,st&&console.log(this)}_activeStates=[];updateActiveStates(e){for(let t=0;t<this._activeStates.length;t++){const i=this._activeStates[t],n=i.motion;if(!n.action)this._activeStates.splice(t,1),t--;else{const s=n.action;s.weight=e,s.getEffectiveWeight()<=0&&!s.isRunning()&&(st&&console.debug("REMOVE",i.name,s.getEffectiveWeight(),s.isRunning(),s.isScheduled()),this._activeStates.splice(t,1),t--)}}}setStartTransition(){this.model.layers.length>1&&(st||E())&&console.warn("Multiple layers are not supported yet "+this.animator?.name);for(const e of this.model.layers){const t=e.stateMachine;t.defaultState===void 0&&(st&&console.warn("AnimatorController default state is undefined, will assign state 0 as default",e),t.defaultState=0);const i=t.states[t.defaultState];this.transitionTo(i,0,this.normalizedStartOffset);break}}evaluateTransitions(){let e=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;e=!0}const t=this._activeState,i=t.motion.action;for(const s of t.transitions){if(!s.hasExitTime&&s.conditions.length<=0)continue;let r=!0;for(const a of s.conditions)if(!this.evaluateCondition(a)){r=!1;break}if(r)if(i){const a=t.motion.clip.duration,l=a<=0?1:Math.abs(i.time/a);let c=s.exitTime;i.timeScale<0&&(c=1-c);let h=!1;if(s.hasExitTime?i.timeScale>0?h=l>=s.exitTime:i.timeScale<0&&(h=1-l>=s.exitTime):h=!0,h){for(const d of s.conditions){const p=this.model.parameters.find(m=>m.name===d.parameter);p?.type===Zg.Trigger&&p.value&&(p.value=!1)}if(i.clampWhenFinished=!0,st){const d=this.getState(s.destinationState,0);console.log(`Transition to ${s.destinationState} / ${d?.name}`,s,`
866
866
  Timescale: `+i.timeScale,`
867
867
  Normalized time: `+l.toFixed(3),`
868
- Exit Time: `+c,s.hasExitTime)}this.transitionTo(s.destinationState,s.duration,s.offset);return}}else{this.transitionTo(s.destinationState,s.duration,s.offset);return}}i&&this.setTimescale(i,t);let n=!1;if(t.motion.isLooping&&i&&(i.time>=i.getClip().duration?(n=!0,i.reset(),i.time=0,i.play()):i.time<=0&&i.timeScale<0&&(n=!0,i.reset(),i.time=i.getClip().duration,i.play())),!n&&t&&!e&&i&&this.animator&&t.behaviours){const s=i?.getClip().duration,r=i.time/s,a=new xc(this._activeState,r,s,this._speed);for(const l of t.behaviours)l.instance&&l.instance.onStateUpdate?.call(l.instance,this.animator,a,0)}}setTimescale(e,t){let i=t.speed??1;t.speedParameter&&(i*=this.getFloat(t.speedParameter)),i!==void 0&&(e.timeScale=i*this._speed)}getState(e,t){return typeof e=="number"&&(e==-1&&(e=this.model.layers[t].stateMachine.defaultState,e===void 0&&(st&&console.warn("AnimatorController default state is undefined: ",this.model,"Layer: "+t),e=0)),e=this.model.layers[t].stateMachine.states[e]),e}_heldActions=[];releaseHeldActions(e){for(const t of this._heldActions)t.fadeOut(e);this._heldActions.length=0}transitionTo(e,t,i){if(!this.animator)return;const n=0;if(e=this.getState(e,n),!e?.motion||!e.motion.clip||!(e.motion.clip instanceof rs))return;const s=this._activeState===e;if(s){const h=e.motion;if(!h.action_loopback&&h.clip){const d=this.rootMotionHandler?this.animator.gameObject.matrix.clone():null;this._mixer.uncacheAction(h.clip,this.animator.gameObject),d&&d.decompose(this.animator.gameObject.position,this.animator.gameObject.quaternion,this.animator.gameObject.scale),h.action_loopback=this.createAction(h.clip)}}if(this._activeState?.behaviours&&this._activeState.motion.action){const h=this._activeState?.motion.clip.duration,d=this._activeState.motion.action.time/h,p=new xc(this._activeState,d,h,this._speed);for(const g of this._activeState.behaviours)g.instance?.onStateExit?.call(g.instance,this.animator,p,n)}const r=this._activeState?.motion.action;s&&(e.motion.action=e.motion.action_loopback,e.motion.action_loopback=r);const a=this._activeState;this._activeState=e;const l=e.motion?.action,c=e.motion.clip;if(c?.duration<=0&&c.tracks.length<=0?r&&this._heldActions.push(r):r&&(r.fadeOut(t),this.releaseHeldActions(t)),l){if(i=Math.max(0,Math.min(1,i)),e.cycleOffsetParameter){let d=this.getFloat(e.cycleOffsetParameter);typeof d=="number"?(d<0&&(d+=1),i+=d,i%=1):st&&console.warn("AnimatorController cycle offset parameter is not a number",e.cycleOffsetParameter)}else typeof e.cycleOffset=="number"&&(i+=e.cycleOffset,i%=1);l.isRunning()&&l.stop(),l.reset(),l.enabled=!0,this.setTimescale(l,e);const h=e.motion.clip.duration;if(l.time=s?0:i*h,l.timeScale<0&&(l.time=h-l.time),l.clampWhenFinished=!0,l.setLoop(sm,0),t>0?l.fadeIn(t):l.weight=1,l.play(),this.rootMotionHandler&&this.rootMotionHandler.onStart(l),this._activeStates.includes(e)||this._activeStates.push(e),this._activeState.behaviours){const d=new xc(e,i,h,this._speed);for(const p of this._activeState.behaviours)p.instance?.onStateEnter?.call(p.instance,this.animator,d,n)}}else st&&(e.__warned_no_motion||(e.__warned_no_motion=!0,console.warn("No action",e.motion,this)));st&&console.log("TRANSITION FROM "+a?.name+" TO "+e.name,t,r,l,l?.getEffectiveTimeScale(),l?.getEffectiveWeight(),l?.isRunning(),l?.isScheduled(),l?.paused)}createAction(e){if(this._mixer.existingAction(e)&&this._mixer.uncacheAction(e,this.animator?.gameObject),this.animator?.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new TM(this));const t=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,t,e)}else return this._mixer.clipAction(e)}evaluateCondition(e){const t=this.model.parameters.find(i=>i.name===e.parameter);if(!t)return!1;switch(e.mode){case ys.If:return t.value===!0;case ys.IfNot:return t.value===!1;case ys.Greater:return t.value>e.threshold;case ys.Less:return t.value<e.threshold;case ys.Equals:return t.value===e.threshold;case ys.NotEqual:return t.value!==e.threshold}return!1}createActions(e){st&&console.log("AnimatorController createActions",this.model);for(const t of this.model.layers){const i=t.stateMachine;for(let n=0;n<i.states.length;n++){const s=i.states[n];s.transitions||(s.transitions=[]);for(const r of s.transitions)r.conditions||(r.conditions=[]);if(s.motion||(st&&console.warn("No motion",s),s.motion=hw(s.name)),this.animator&&s.motion.clips){const r=s.motion.clips?.find(a=>a.node.name===this.animator?.gameObject?.name);r?s.motion.clip=r.clip:(st||E())&&console.warn('Could not find clip for animator "'+this.animator?.gameObject?.name+'"',s.motion.clips.map(a=>a.node.name))}if(!s.motion.clip){st&&console.warn("No clip assigned to state",s);const r=new rs(void 0,void 0,[]);s.motion.clip=r}if(s.motion?.clip){const r=s.motion.clip;if(r instanceof rs){const a=this.createAction(r);s.motion.action=a}else(st||E())&&console.warn("No valid animationclip assigned",s)}if(s.behaviours&&Array.isArray(s.behaviours))for(const r of s.behaviours){if(!r?.typeName)continue;const a=C.get(r.typeName);if(a){const l=new a;l.isStateMachineBehaviour&&(l._context=this.context??void 0,Aa(l,r.properties),r.instance=l),st&&console.log("Created animator controller behaviour",s.name,r.typeName,r.properties,l)}else(st||E())&&console.warn("Could not find AnimatorBehaviour type: "+r.typeName)}}}}*enumerateActions(){if(this.model.layers)for(const e of this.model.layers){const t=e.stateMachine;for(let i=0;i<t.states.length;i++){const n=t.states[i];n?.motion&&(n.motion.action&&(yield n.motion.action),n.motion.action_loopback&&(yield n.motion.action_loopback))}}}rootMotionHandler}class dw{track;createdInterpolant;originalEvaluate;customEvaluate;constructor(e,t){this.track=e;const i=e,n=i.createInterpolant.bind(e);i.createInterpolant=()=>(i.createInterpolant=n,this.createdInterpolant=n(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=s=>{if(!this.originalEvaluate)return;const r=this.originalEvaluate(s);return t(s,r)},this.createdInterpolant.evaluate=this.customEvaluate,this.createdInterpolant)}dispose(){this.createdInterpolant&&this.originalEvaluate&&(this.createdInterpolant.evaluate=this.originalEvaluate),this.track=void 0,this.createdInterpolant=null,this.originalEvaluate=void 0,this.customEvaluate=void 0}}class dt{static lastObjPosition={};static lastObjRotation={};static firstKeyframeRotation={};static spaceRotation={};static effectiveSpaceRotation={};static clipOffsetRotation={};set action(e){this._action=e}get action(){return this._action}get cacheId(){return this.root.uuid}_action;root;clip;positionWrapper=null;rotationWrapper=null;context;positionChange=new b;rotationChange=new U;constructor(e,t,i,n,s){if(this.context=e,this.root=t,this.clip=i,dt.firstKeyframeRotation[this.cacheId]||(dt.firstKeyframeRotation[this.cacheId]=new U),s){const r=s.values;dt.firstKeyframeRotation[this.cacheId].set(r[0],r[1],r[2],r[3])}dt.spaceRotation[this.cacheId]||(dt.spaceRotation[this.cacheId]=new U),dt.effectiveSpaceRotation[this.cacheId]||(dt.effectiveSpaceRotation[this.cacheId]=new U),dt.clipOffsetRotation[this.cacheId]=new U,s&&dt.clipOffsetRotation[this.cacheId].set(s.values[0],s.values[1],s.values[2],s.values[3]).invert(),this.handlePosition(i,n),this.handleRotation(i,s)}onStart(e){if(e.getClip()!==this.clip)return;dt.lastObjRotation[this.cacheId]||(dt.lastObjRotation[this.cacheId]=this.root.quaternion.clone());const t=dt.lastObjRotation[this.cacheId];if(dt.spaceRotation[this.cacheId].copy(t),uu){const i=new nt().setFromQuaternion(t);console.log("START",this.clip.name,D.toDegrees(i.y),this.root.position.z)}}getClipRotationOffset(){return dt.clipOffsetRotation[this.cacheId]}_prevTime=0;handlePosition(e,t){if(t){const i=this.root;uu&&i.add(new _i),dt.lastObjPosition[this.cacheId]||(dt.lastObjPosition[this.cacheId]=this.root.position.clone());const n=new b,s=new b;this.positionWrapper=new dw(t,(r,a)=>{const l=this.action.getEffectiveWeight();return uu&&i.position.length()>8&&i.position.set(0,i.position.y,0),r>this._prevTime&&(n.set(a[0],a[1],a[2]),n.sub(s),n.multiplyScalar(l),n.applyQuaternion(this.getClipRotationOffset()),n.applyQuaternion(i.quaternion),this.positionChange.copy(n)),s.fromArray(a),this._prevTime=r,a[0]=0,a[1]=0,a[2]=0,a})}}static identityQuaternion=new U;handleRotation(e,t){if(t){if(uu){const r=t.values,a=new nt().setFromQuaternion(new U(r[0],r[1],r[2],r[3]));console.log(e.name,t.name,"FIRST ROTATION IN TRACK",D.toDegrees(a.y));const l=t.values.length-4,c=new U().set(r[l],r[l+1],r[l+2],r[l+3]),h=new nt().setFromQuaternion(c);console.log(e.name,t.name,"LAST ROTATION IN TRACK",D.toDegrees(h.y))}let i=0;const n=new U,s=new U;this.rotationWrapper=new dw(t,(r,a)=>(r>i&&(s.set(a[0],a[1],a[2],a[3]),n.invert(),s.multiply(n),this.rotationChange.copy(s)),n.fromArray(a),i=r,a[0]=0,a[1]=0,a[2]=0,a[3]=1,a))}}onBeforeUpdate(e){this.positionChange.set(0,0,0),this.rotationChange.set(0,0,0,1)}onAfterUpdate(e){return!this.action||(e*=this.action.getEffectiveWeight(),e<=0)?!1:(this.positionChange.multiplyScalar(e),this.rotationChange.slerp(dt.identityQuaternion,1-e),!0)}}class TM{controller;handler=[];root;basePosition=new b;baseQuaternion=new U;baseRotation=new nt;constructor(e){this.controller=e}createClip(e,t,i){this.root=t,t&&"name"in t&&t.name;const n=this.findRootTrack(i,".position"),s=this.findRootTrack(i,".quaternion"),r=new dt(this.controller.context,t,i,n,s);this.handler.push(r);const a=e.clipAction(i);return r.action=a,a}onStart(e){for(const t of this.handler)t.onStart(e)}onBeforeUpdate(e){this.basePosition.copy(this.root.position),this.baseQuaternion.copy(this.root.quaternion);for(const t of this.handler)t.onBeforeUpdate(e)}summedPosition=new b;summedRotation=new U;onAfterUpdate(e){if(!(e<=0)){this.root.position.copy(this.basePosition),this.root.quaternion.copy(this.baseQuaternion),this.summedPosition.set(0,0,0),this.summedRotation.set(0,0,0,1);for(const t of this.handler)t.onAfterUpdate(e)&&(this.summedPosition.add(t.positionChange),this.summedRotation.multiply(t.rotationChange));this.root.position.add(this.summedPosition),this.root.quaternion.multiply(this.summedRotation)}}findRootTrack(e,t){const i=e.tracks;if(!i)return null;for(const n of i)if(n.name.endsWith(t))return n;return null}}class EM extends Xi{onSerialize(e,t){}onDeserialize(e,t){if(t.type===ln&&e?.__type==="AnimatorController")return new ln(e)}}new EM(ln);var AM=Object.defineProperty,IM=Object.getOwnPropertyDescriptor,pu=(o,e,t,i)=>{for(var n=i>1?void 0:i?IM(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&AM(e,t,n),n};const Qi=w("debuganimator");class ft extends M{get isAnimationComponent(){return!0}applyRootMotion=!1;hasRootMotion=!1;keepAnimatorControllerStateOnDisable=!1;set runtimeAnimatorController(e){this._animatorController&&this._animatorController.model===e||(e?e instanceof ln?(e.animator&&e.animator!==this&&(console.warn("AnimatorController can not be bound to multiple animators",e.model?.name),e.model||console.error("AnimatorController has no model"),e=new ln(e.model)),this._animatorController=e,this._animatorController.bind(this)):(Qi&&console.log("Assign animator controller",e,this),this._animatorController=new ln(e),this.__didAwake&&this._animatorController.bind(this)):this._animatorController=null)}get runtimeAnimatorController(){return this._animatorController}getCurrentStateInfo(){return this.runtimeAnimatorController?.getCurrentStateInfo()}get currentAction(){return this.runtimeAnimatorController?.currentAction||null}get parametersAreDirty(){return this._parametersAreDirty}_parametersAreDirty=!1;get isDirty(){return this._isDirty}_isDirty=!1;Play(e,t=-1,i=Number.NEGATIVE_INFINITY,n=0){this.play(e,t,i,n)}play(e,t=-1,i=Number.NEGATIVE_INFINITY,n=0){this.runtimeAnimatorController?.play(e,t,i,n),this._isDirty=!0}Reset(){this.reset()}reset(){this._animatorController?.reset(),this._isDirty=!0}SetBool(e,t){this.setBool(e,t)}setBool(e,t){Qi&&console.log("setBool",e,t),this.runtimeAnimatorController?.getBool(e)!==t&&(this._parametersAreDirty=!0),this.runtimeAnimatorController?.setBool(e,t)}GetBool(e){return this.getBool(e)}getBool(e){const t=this.runtimeAnimatorController?.getBool(e)??!1;return Qi&&console.log("getBool",e,t),t}toggleBool(e){this.setBool(e,!this.getBool(e))}SetFloat(e,t){this.setFloat(e,t)}setFloat(e,t){this.runtimeAnimatorController?.getFloat(e)!==t&&(this._parametersAreDirty=!0),Qi&&console.log("setFloat",e,t),this.runtimeAnimatorController?.setFloat(e,t)}GetFloat(e){return this.getFloat(e)}getFloat(e){const t=this.runtimeAnimatorController?.getFloat(e)??-1;return Qi&&console.log("getFloat",e,t),t}SetInteger(e,t){this.setInteger(e,t)}setInteger(e,t){this.runtimeAnimatorController?.getInteger(e)!==t&&(this._parametersAreDirty=!0),Qi&&console.log("setInteger",e,t),this.runtimeAnimatorController?.setInteger(e,t)}GetInteger(e){return this.getInteger(e)}getInteger(e){const t=this.runtimeAnimatorController?.getInteger(e)??-1;return Qi&&console.log("getInteger",e,t),t}SetTrigger(e){this.setTrigger(e)}setTrigger(e){this._parametersAreDirty=!0,Qi&&console.log("setTrigger",e),this.runtimeAnimatorController?.setTrigger(e)}ResetTrigger(e){this.resetTrigger(e)}resetTrigger(e){this._parametersAreDirty=!0,Qi&&console.log("resetTrigger",e),this.runtimeAnimatorController?.resetTrigger(e)}GetTrigger(e){this.getTrigger(e)}getTrigger(e){const t=this.runtimeAnimatorController?.getTrigger(e);return Qi&&console.log("getTrigger",e,t),t}IsInTransition(){return this.isInTransition()}isInTransition(){return this.runtimeAnimatorController?.isInTransition()??!1}SetSpeed(e){return this.setSpeed(e)}setSpeed(e){e!==this._speed&&(Qi&&console.log("setSpeed",e),this._speed=e,this._animatorController?.animator==this&&this._animatorController.setSpeed(e))}set minMaxSpeed(e){this._speed=D.lerp(e.x,e.y,Math.random()),this._animatorController?.animator==this&&this._animatorController.setSpeed(this._speed)}set minMaxOffsetNormalized(e){this._normalizedStartOffset=D.lerp(e.x,e.y,Math.random()),this.runtimeAnimatorController?.animator==this&&(this.runtimeAnimatorController.normalizedStartOffset=this._normalizedStartOffset)}_speed=1;_normalizedStartOffset=0;_animatorController=null;awake(){Qi&&console.log("ANIMATOR",this.name,this),this.gameObject&&this.initializeRuntimeAnimatorController()}_initializeWithRuntimeAnimatorController;initializeRuntimeAnimatorController(e=!1){const t=e||this.runtimeAnimatorController!==this._initializeWithRuntimeAnimatorController;if(this.runtimeAnimatorController&&t){const i=this.runtimeAnimatorController.clone();this._initializeWithRuntimeAnimatorController=i,i?(console.assert(this.runtimeAnimatorController!==i),this.runtimeAnimatorController=i,console.assert(this.runtimeAnimatorController===i),this.runtimeAnimatorController.bind(this),this.runtimeAnimatorController.setSpeed(this._speed),this.runtimeAnimatorController.normalizedStartOffset=this._normalizedStartOffset):console.warn("Could not clone animator controller",this.runtimeAnimatorController)}}onDisable(){this.keepAnimatorControllerStateOnDisable||this._animatorController?.reset()}onBeforeRender(){this._isDirty=!1,this._parametersAreDirty=!1,!MM(this.gameObject)&&this._animatorController&&this._animatorController.update(1)}}pu([u()],ft.prototype,"applyRootMotion",2),pu([u()],ft.prototype,"hasRootMotion",2),pu([u()],ft.prototype,"keepAnimatorControllerStateOnDisable",2),pu([u()],ft.prototype,"runtimeAnimatorController",1);const uw=Symbol("previous-visibility");class ho extends jn{render(e,t,i){if("addPass"in i)this._unsupported_effectcomposer_warning||(console.warn("RenderTexture.render() does not yet support EffectComposer"),this._unsupported_effectcomposer_warning=!0);else if(i instanceof er){this.onBeforeRender();const n=i.getRenderTarget(),s=i.xr.enabled;i.xr.enabled=!1,i.setRenderTarget(this),i.clear(!0,!0,!0),i.render(e,t),i.setRenderTarget(n),i.xr.enabled=s,this.onAfterRender()}}static _userSet=new Set;onBeforeRender(){ho._userSet.clear();const e=ug(this.texture,!0,null,ho._userSet);for(const t of e)t instanceof H&&(t[uw]=t.visible,t.visible=!1)}onAfterRender(){for(const e of ho._userSet)e instanceof H&&(e.visible=e[uw]);ho._userSet.clear()}}var LM=Object.defineProperty,jM=Object.getOwnPropertyDescriptor,Sc=(o,e,t,i)=>{for(var n=i>1?void 0:i?jM(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&LM(e,t,n),n};const mu=w("debuggroundprojection");class $n extends M{applyOnAwake=!1;autoFit=!0;set radius(e){this._radius=e,this._projection&&this.updateProjection()}get radius(){return this._radius}_radius=50;set height(e){this._height=e,this._projection&&this.updateProjection()}get height(){return this._height}_height=3;set arBlending(e){this._arblending=e,this._needsTextureUpdate=!0}get arBlending(){return this._arblending}_arblending=0;_lastBackground;_lastRadius;_lastHeight;_projection;_watcher;awake(){this.applyOnAwake&&this.updateAndCreate()}onEnable(){this.context.time.frameCount>0&&this.applyOnAwake&&this.updateAndCreate(),this._watcher||(this._watcher=new Ko(this.context.scene,"background"),this._watcher.subscribeWrite(e=>{mu&&console.log("Background changed",this.context.scene.background),this._needsTextureUpdate=!0}))}onDisable(){this._watcher?.revoke(),this._projection?.removeFromParent()}onEnterXR(){this.activeAndEnabled&&(this._needsTextureUpdate=!0,this.updateProjection())}async onLeaveXR(){this.activeAndEnabled&&(await Wl(1),this.updateProjection())}onBeforeRender(){this._projection&&this.scene.backgroundRotation&&this._projection.rotation.copy(this.scene.backgroundRotation),this.context.scene.backgroundBlurriness!==void 0&&this._lastBlurriness!=this.context.scene.backgroundBlurriness&&this.context.scene.backgroundBlurriness>.001?this.updateProjection():this._needsTextureUpdate&&this.context.scene.background instanceof Re&&this.updateBlurriness(this.context.scene.background,this.context.scene.backgroundBlurriness)}updateAndCreate(){this.updateProjection(),this._watcher?.apply()}_needsTextureUpdate=!1;updateProjection(){if(!this.context.scene.background){this._projection?.removeFromParent();return}const e=this.context.scene.background;if(!(e instanceof Re)){this._projection?.removeFromParent();return}if((this.context.xr?.isPassThrough||this.context.xr?.isAR)&&this.arBlending===0){this._projection?.removeFromParent();return}if(!this.gameObject||this.destroyed)return;let t=!0;const i=0,n=e!==this._lastBackground||this._height!==this._lastHeight||this._radius!==this._lastRadius;if(!this._projection||n){mu&&console.log("Create/Update Ground Projection",e.name),this._projection?.removeFromParent();try{this._projection=new ba(e,this._height,this._radius,64)}catch(s){console.error("Error creating three GroundProjection",s);return}this._projection.position.y=this._height-i,this._projection.name="GroundProjection",Um(this._projection,!1)}else t=!1;if(this._projection.parent||this.gameObject.add(this._projection),this.autoFit&&t){this._projection.updateWorldMatrix(!0,!0);const s=Wt(this.context.scene.children,[this._projection]),r=s.min.y;if(r<1/0){const a=$();a.x=s.min.x+(s.max.x-s.min.x)*.5;const l=$e(this.gameObject).x;a.y=r+this._height*l-i,a.z=s.min.z+(s.max.z-s.min.z)*.5,mt(this._projection,a)}mu&&F.DrawWireBox3(s,65280,5)}this.context.scene.backgroundBlurriness>.001&&this._needsTextureUpdate&&this.updateBlurriness(e,this.context.scene.backgroundBlurriness),this._lastBackground=e,this._lastHeight=this._height,this._lastRadius=this._radius,this._needsTextureUpdate=!1}_blurrynessShader=null;_lastBlurriness=-1;updateBlurriness(e,t){if(this._projection){if(!e)return}else return;this._needsTextureUpdate=!1,mu&&console.log("Update Blurriness",t),this._blurrynessShader??=new Ln({name:"GroundProjectionBlurriness",uniforms:{map:{value:e},blurriness:{value:t},blending:{value:0},alphaFactor:{value:1}},vertexShader:DM,fragmentShader:BM}),this._blurrynessShader.depthWrite=!1,this._blurrynessShader.uniforms.map.value=e,this._blurrynessShader.uniforms.blurriness.value=t,this._lastBlurriness=t,e.needsUpdate=!0;const i=this._projection.material.transparent;this._projection.material.transparent=(this.context.xr?.isAR===!0&&this.arBlending>1e-6)??!1,this._projection.material.transparent?this._blurrynessShader.uniforms.blending.value=this.arBlending:this._blurrynessShader.uniforms.blending.value=0,this.context.isInPassThrough?this._blurrynessShader.uniforms.alphaFactor.value=.95:this._blurrynessShader.uniforms.alphaFactor.value=1,i!==this._projection.material.transparent&&(this._projection.material.needsUpdate=!0),this._projection.material.map=Ys.copyTexture(e,this._blurrynessShader),this._projection.material.depthTest=!0,this._projection.material.depthWrite=!1}}Sc([u()],$n.prototype,"applyOnAwake",2),Sc([u()],$n.prototype,"autoFit",2),Sc([u()],$n.prototype,"radius",1),Sc([u()],$n.prototype,"height",1),Sc([u()],$n.prototype,"arBlending",1);const DM=`
868
+ Exit Time: `+c,s.hasExitTime)}this.transitionTo(s.destinationState,s.duration,s.offset);return}}else{this.transitionTo(s.destinationState,s.duration,s.offset);return}}i&&this.setTimescale(i,t);let n=!1;if(t.motion.isLooping&&i&&(i.time>=i.getClip().duration?(n=!0,i.reset(),i.time=0,i.play()):i.time<=0&&i.timeScale<0&&(n=!0,i.reset(),i.time=i.getClip().duration,i.play())),!n&&t&&!e&&i&&this.animator&&t.behaviours){const s=i?.getClip().duration,r=i.time/s,a=new xc(this._activeState,r,s,this._speed);for(const l of t.behaviours)l.instance&&l.instance.onStateUpdate?.call(l.instance,this.animator,a,0)}}setTimescale(e,t){let i=t.speed??1;t.speedParameter&&(i*=this.getFloat(t.speedParameter)),i!==void 0&&(e.timeScale=i*this._speed)}getState(e,t){return typeof e=="number"&&(e==-1&&(e=this.model.layers[t].stateMachine.defaultState,e===void 0&&(st&&console.warn("AnimatorController default state is undefined: ",this.model,"Layer: "+t),e=0)),e=this.model.layers[t].stateMachine.states[e]),e}_heldActions=[];releaseHeldActions(e){for(const t of this._heldActions)t.fadeOut(e);this._heldActions.length=0}transitionTo(e,t,i){if(!this.animator)return;const n=0;if(e=this.getState(e,n),!e?.motion||!e.motion.clip||!(e.motion.clip instanceof rs))return;const s=this._activeState===e;if(s){const h=e.motion;if(!h.action_loopback&&h.clip){const d=this.rootMotionHandler?this.animator.gameObject.matrix.clone():null;this._mixer.uncacheAction(h.clip,this.animator.gameObject),d&&d.decompose(this.animator.gameObject.position,this.animator.gameObject.quaternion,this.animator.gameObject.scale),h.action_loopback=this.createAction(h.clip)}}if(this._activeState?.behaviours&&this._activeState.motion.action){const h=this._activeState?.motion.clip.duration,d=this._activeState.motion.action.time/h,p=new xc(this._activeState,d,h,this._speed);for(const m of this._activeState.behaviours)m.instance?.onStateExit?.call(m.instance,this.animator,p,n)}const r=this._activeState?.motion.action;s&&(e.motion.action=e.motion.action_loopback,e.motion.action_loopback=r);const a=this._activeState;this._activeState=e;const l=e.motion?.action,c=e.motion.clip;if(c?.duration<=0&&c.tracks.length<=0?r&&this._heldActions.push(r):r&&(r.fadeOut(t),this.releaseHeldActions(t)),l){if(i=Math.max(0,Math.min(1,i)),e.cycleOffsetParameter){let d=this.getFloat(e.cycleOffsetParameter);typeof d=="number"?(d<0&&(d+=1),i+=d,i%=1):st&&console.warn("AnimatorController cycle offset parameter is not a number",e.cycleOffsetParameter)}else typeof e.cycleOffset=="number"&&(i+=e.cycleOffset,i%=1);l.isRunning()&&l.stop(),l.reset(),l.enabled=!0,this.setTimescale(l,e);const h=e.motion.clip.duration;if(l.time=s?0:i*h,l.timeScale<0&&(l.time=h-l.time),l.clampWhenFinished=!0,l.setLoop(sm,0),t>0?l.fadeIn(t):l.weight=1,l.play(),this.rootMotionHandler&&this.rootMotionHandler.onStart(l),this._activeStates.includes(e)||this._activeStates.push(e),this._activeState.behaviours){const d=new xc(e,i,h,this._speed);for(const p of this._activeState.behaviours)p.instance?.onStateEnter?.call(p.instance,this.animator,d,n)}}else st&&(e.__warned_no_motion||(e.__warned_no_motion=!0,console.warn("No action",e.motion,this)));st&&console.log("TRANSITION FROM "+a?.name+" TO "+e.name,t,r,l,l?.getEffectiveTimeScale(),l?.getEffectiveWeight(),l?.isRunning(),l?.isScheduled(),l?.paused)}createAction(e){if(this._mixer.existingAction(e)&&this._mixer.uncacheAction(e,this.animator?.gameObject),this.animator?.applyRootMotion){this.rootMotionHandler||(this.rootMotionHandler=new TM(this));const t=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,t,e)}else return this._mixer.clipAction(e)}evaluateCondition(e){const t=this.model.parameters.find(i=>i.name===e.parameter);if(!t)return!1;switch(e.mode){case ys.If:return t.value===!0;case ys.IfNot:return t.value===!1;case ys.Greater:return t.value>e.threshold;case ys.Less:return t.value<e.threshold;case ys.Equals:return t.value===e.threshold;case ys.NotEqual:return t.value!==e.threshold}return!1}createActions(e){st&&console.log("AnimatorController createActions",this.model);for(const t of this.model.layers){const i=t.stateMachine;for(let n=0;n<i.states.length;n++){const s=i.states[n];s.transitions||(s.transitions=[]);for(const r of s.transitions)r.conditions||(r.conditions=[]);if(s.motion||(st&&console.warn("No motion",s),s.motion=hw(s.name)),this.animator&&s.motion.clips){const r=s.motion.clips?.find(a=>a.node.name===this.animator?.gameObject?.name);r?s.motion.clip=r.clip:(st||E())&&console.warn('Could not find clip for animator "'+this.animator?.gameObject?.name+'"',s.motion.clips.map(a=>a.node.name))}if(!s.motion.clip){st&&console.warn("No clip assigned to state",s);const r=new rs(void 0,void 0,[]);s.motion.clip=r}if(s.motion?.clip){const r=s.motion.clip;if(r instanceof rs){const a=this.createAction(r);s.motion.action=a}else(st||E())&&console.warn("No valid animationclip assigned",s)}if(s.behaviours&&Array.isArray(s.behaviours))for(const r of s.behaviours){if(!r?.typeName)continue;const a=C.get(r.typeName);if(a){const l=new a;l.isStateMachineBehaviour&&(l._context=this.context??void 0,Aa(l,r.properties),r.instance=l),st&&console.log("Created animator controller behaviour",s.name,r.typeName,r.properties,l)}else(st||E())&&console.warn("Could not find AnimatorBehaviour type: "+r.typeName)}}}}*enumerateActions(){if(this.model.layers)for(const e of this.model.layers){const t=e.stateMachine;for(let i=0;i<t.states.length;i++){const n=t.states[i];n?.motion&&(n.motion.action&&(yield n.motion.action),n.motion.action_loopback&&(yield n.motion.action_loopback))}}}rootMotionHandler}class dw{track;createdInterpolant;originalEvaluate;customEvaluate;constructor(e,t){this.track=e;const i=e,n=i.createInterpolant.bind(e);i.createInterpolant=()=>(i.createInterpolant=n,this.createdInterpolant=n(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=s=>{if(!this.originalEvaluate)return;const r=this.originalEvaluate(s);return t(s,r)},this.createdInterpolant.evaluate=this.customEvaluate,this.createdInterpolant)}dispose(){this.createdInterpolant&&this.originalEvaluate&&(this.createdInterpolant.evaluate=this.originalEvaluate),this.track=void 0,this.createdInterpolant=null,this.originalEvaluate=void 0,this.customEvaluate=void 0}}class dt{static lastObjPosition={};static lastObjRotation={};static firstKeyframeRotation={};static spaceRotation={};static effectiveSpaceRotation={};static clipOffsetRotation={};set action(e){this._action=e}get action(){return this._action}get cacheId(){return this.root.uuid}_action;root;clip;positionWrapper=null;rotationWrapper=null;context;positionChange=new b;rotationChange=new U;constructor(e,t,i,n,s){if(this.context=e,this.root=t,this.clip=i,dt.firstKeyframeRotation[this.cacheId]||(dt.firstKeyframeRotation[this.cacheId]=new U),s){const r=s.values;dt.firstKeyframeRotation[this.cacheId].set(r[0],r[1],r[2],r[3])}dt.spaceRotation[this.cacheId]||(dt.spaceRotation[this.cacheId]=new U),dt.effectiveSpaceRotation[this.cacheId]||(dt.effectiveSpaceRotation[this.cacheId]=new U),dt.clipOffsetRotation[this.cacheId]=new U,s&&dt.clipOffsetRotation[this.cacheId].set(s.values[0],s.values[1],s.values[2],s.values[3]).invert(),this.handlePosition(i,n),this.handleRotation(i,s)}onStart(e){if(e.getClip()!==this.clip)return;dt.lastObjRotation[this.cacheId]||(dt.lastObjRotation[this.cacheId]=this.root.quaternion.clone());const t=dt.lastObjRotation[this.cacheId];if(dt.spaceRotation[this.cacheId].copy(t),uu){const i=new nt().setFromQuaternion(t);console.log("START",this.clip.name,D.toDegrees(i.y),this.root.position.z)}}getClipRotationOffset(){return dt.clipOffsetRotation[this.cacheId]}_prevTime=0;handlePosition(e,t){if(t){const i=this.root;uu&&i.add(new _i),dt.lastObjPosition[this.cacheId]||(dt.lastObjPosition[this.cacheId]=this.root.position.clone());const n=new b,s=new b;this.positionWrapper=new dw(t,(r,a)=>{const l=this.action.getEffectiveWeight();return uu&&i.position.length()>8&&i.position.set(0,i.position.y,0),r>this._prevTime&&(n.set(a[0],a[1],a[2]),n.sub(s),n.multiplyScalar(l),n.applyQuaternion(this.getClipRotationOffset()),n.applyQuaternion(i.quaternion),this.positionChange.copy(n)),s.fromArray(a),this._prevTime=r,a[0]=0,a[1]=0,a[2]=0,a})}}static identityQuaternion=new U;handleRotation(e,t){if(t){if(uu){const r=t.values,a=new nt().setFromQuaternion(new U(r[0],r[1],r[2],r[3]));console.log(e.name,t.name,"FIRST ROTATION IN TRACK",D.toDegrees(a.y));const l=t.values.length-4,c=new U().set(r[l],r[l+1],r[l+2],r[l+3]),h=new nt().setFromQuaternion(c);console.log(e.name,t.name,"LAST ROTATION IN TRACK",D.toDegrees(h.y))}let i=0;const n=new U,s=new U;this.rotationWrapper=new dw(t,(r,a)=>(r>i&&(s.set(a[0],a[1],a[2],a[3]),n.invert(),s.multiply(n),this.rotationChange.copy(s)),n.fromArray(a),i=r,a[0]=0,a[1]=0,a[2]=0,a[3]=1,a))}}onBeforeUpdate(e){this.positionChange.set(0,0,0),this.rotationChange.set(0,0,0,1)}onAfterUpdate(e){return!this.action||(e*=this.action.getEffectiveWeight(),e<=0)?!1:(this.positionChange.multiplyScalar(e),this.rotationChange.slerp(dt.identityQuaternion,1-e),!0)}}class TM{controller;handler=[];root;basePosition=new b;baseQuaternion=new U;baseRotation=new nt;constructor(e){this.controller=e}createClip(e,t,i){this.root=t,t&&"name"in t&&t.name;const n=this.findRootTrack(i,".position"),s=this.findRootTrack(i,".quaternion"),r=new dt(this.controller.context,t,i,n,s);this.handler.push(r);const a=e.clipAction(i);return r.action=a,a}onStart(e){for(const t of this.handler)t.onStart(e)}onBeforeUpdate(e){this.basePosition.copy(this.root.position),this.baseQuaternion.copy(this.root.quaternion);for(const t of this.handler)t.onBeforeUpdate(e)}summedPosition=new b;summedRotation=new U;onAfterUpdate(e){if(!(e<=0)){this.root.position.copy(this.basePosition),this.root.quaternion.copy(this.baseQuaternion),this.summedPosition.set(0,0,0),this.summedRotation.set(0,0,0,1);for(const t of this.handler)t.onAfterUpdate(e)&&(this.summedPosition.add(t.positionChange),this.summedRotation.multiply(t.rotationChange));this.root.position.add(this.summedPosition),this.root.quaternion.multiply(this.summedRotation)}}findRootTrack(e,t){const i=e.tracks;if(!i)return null;for(const n of i)if(n.name.endsWith(t))return n;return null}}class EM extends Xi{onSerialize(e,t){}onDeserialize(e,t){if(t.type===ln&&e?.__type==="AnimatorController")return new ln(e)}}new EM(ln);var AM=Object.defineProperty,IM=Object.getOwnPropertyDescriptor,pu=(o,e,t,i)=>{for(var n=i>1?void 0:i?IM(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&AM(e,t,n),n};const Qi=w("debuganimator");class ft extends M{get isAnimationComponent(){return!0}applyRootMotion=!1;hasRootMotion=!1;keepAnimatorControllerStateOnDisable=!1;set runtimeAnimatorController(e){this._animatorController&&this._animatorController.model===e||(e?e instanceof ln?(e.animator&&e.animator!==this&&(console.warn("AnimatorController can not be bound to multiple animators",e.model?.name),e.model||console.error("AnimatorController has no model"),e=new ln(e.model)),this._animatorController=e,this._animatorController.bind(this)):(Qi&&console.log("Assign animator controller",e,this),this._animatorController=new ln(e),this.__didAwake&&this._animatorController.bind(this)):this._animatorController=null)}get runtimeAnimatorController(){return this._animatorController}getCurrentStateInfo(){return this.runtimeAnimatorController?.getCurrentStateInfo()}get currentAction(){return this.runtimeAnimatorController?.currentAction||null}get parametersAreDirty(){return this._parametersAreDirty}_parametersAreDirty=!1;get isDirty(){return this._isDirty}_isDirty=!1;Play(e,t=-1,i=Number.NEGATIVE_INFINITY,n=0){this.play(e,t,i,n)}play(e,t=-1,i=Number.NEGATIVE_INFINITY,n=0){this.runtimeAnimatorController?.play(e,t,i,n),this._isDirty=!0}Reset(){this.reset()}reset(){this._animatorController?.reset(),this._isDirty=!0}SetBool(e,t){this.setBool(e,t)}setBool(e,t){Qi&&console.log("setBool",e,t),this.runtimeAnimatorController?.getBool(e)!==t&&(this._parametersAreDirty=!0),this.runtimeAnimatorController?.setBool(e,t)}GetBool(e){return this.getBool(e)}getBool(e){const t=this.runtimeAnimatorController?.getBool(e)??!1;return Qi&&console.log("getBool",e,t),t}toggleBool(e){this.setBool(e,!this.getBool(e))}SetFloat(e,t){this.setFloat(e,t)}setFloat(e,t){this.runtimeAnimatorController?.getFloat(e)!==t&&(this._parametersAreDirty=!0),Qi&&console.log("setFloat",e,t),this.runtimeAnimatorController?.setFloat(e,t)}GetFloat(e){return this.getFloat(e)}getFloat(e){const t=this.runtimeAnimatorController?.getFloat(e)??-1;return Qi&&console.log("getFloat",e,t),t}SetInteger(e,t){this.setInteger(e,t)}setInteger(e,t){this.runtimeAnimatorController?.getInteger(e)!==t&&(this._parametersAreDirty=!0),Qi&&console.log("setInteger",e,t),this.runtimeAnimatorController?.setInteger(e,t)}GetInteger(e){return this.getInteger(e)}getInteger(e){const t=this.runtimeAnimatorController?.getInteger(e)??-1;return Qi&&console.log("getInteger",e,t),t}SetTrigger(e){this.setTrigger(e)}setTrigger(e){this._parametersAreDirty=!0,Qi&&console.log("setTrigger",e),this.runtimeAnimatorController?.setTrigger(e)}ResetTrigger(e){this.resetTrigger(e)}resetTrigger(e){this._parametersAreDirty=!0,Qi&&console.log("resetTrigger",e),this.runtimeAnimatorController?.resetTrigger(e)}GetTrigger(e){this.getTrigger(e)}getTrigger(e){const t=this.runtimeAnimatorController?.getTrigger(e);return Qi&&console.log("getTrigger",e,t),t}IsInTransition(){return this.isInTransition()}isInTransition(){return this.runtimeAnimatorController?.isInTransition()??!1}SetSpeed(e){return this.setSpeed(e)}setSpeed(e){e!==this._speed&&(Qi&&console.log("setSpeed",e),this._speed=e,this._animatorController?.animator==this&&this._animatorController.setSpeed(e))}set minMaxSpeed(e){this._speed=D.lerp(e.x,e.y,Math.random()),this._animatorController?.animator==this&&this._animatorController.setSpeed(this._speed)}set minMaxOffsetNormalized(e){this._normalizedStartOffset=D.lerp(e.x,e.y,Math.random()),this.runtimeAnimatorController?.animator==this&&(this.runtimeAnimatorController.normalizedStartOffset=this._normalizedStartOffset)}_speed=1;_normalizedStartOffset=0;_animatorController=null;awake(){Qi&&console.log("ANIMATOR",this.name,this),this.gameObject&&this.initializeRuntimeAnimatorController()}_initializeWithRuntimeAnimatorController;initializeRuntimeAnimatorController(e=!1){const t=e||this.runtimeAnimatorController!==this._initializeWithRuntimeAnimatorController;if(this.runtimeAnimatorController&&t){const i=this.runtimeAnimatorController.clone();this._initializeWithRuntimeAnimatorController=i,i?(console.assert(this.runtimeAnimatorController!==i),this.runtimeAnimatorController=i,console.assert(this.runtimeAnimatorController===i),this.runtimeAnimatorController.bind(this),this.runtimeAnimatorController.setSpeed(this._speed),this.runtimeAnimatorController.normalizedStartOffset=this._normalizedStartOffset):console.warn("Could not clone animator controller",this.runtimeAnimatorController)}}onDisable(){this.keepAnimatorControllerStateOnDisable||this._animatorController?.reset()}onBeforeRender(){this._isDirty=!1,this._parametersAreDirty=!1,!MM(this.gameObject)&&this._animatorController&&this._animatorController.update(1)}}pu([u()],ft.prototype,"applyRootMotion",2),pu([u()],ft.prototype,"hasRootMotion",2),pu([u()],ft.prototype,"keepAnimatorControllerStateOnDisable",2),pu([u()],ft.prototype,"runtimeAnimatorController",1);const uw=Symbol("previous-visibility");class ho extends jn{render(e,t,i){if("addPass"in i)this._unsupported_effectcomposer_warning||(console.warn("RenderTexture.render() does not yet support EffectComposer"),this._unsupported_effectcomposer_warning=!0);else if(i instanceof er){this.onBeforeRender();const n=i.getRenderTarget(),s=i.xr.enabled;i.xr.enabled=!1,i.setRenderTarget(this),i.clear(!0,!0,!0),i.render(e,t),i.setRenderTarget(n),i.xr.enabled=s,this.onAfterRender()}}static _userSet=new Set;onBeforeRender(){ho._userSet.clear();const e=ug(this.texture,!0,null,ho._userSet);for(const t of e)t instanceof H&&(t[uw]=t.visible,t.visible=!1)}onAfterRender(){for(const e of ho._userSet)e instanceof H&&(e.visible=e[uw]);ho._userSet.clear()}}var LM=Object.defineProperty,jM=Object.getOwnPropertyDescriptor,Sc=(o,e,t,i)=>{for(var n=i>1?void 0:i?jM(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&LM(e,t,n),n};const mu=w("debuggroundprojection");class $n extends M{applyOnAwake=!1;autoFit=!0;set radius(e){this._radius=e,this._projection&&this.updateProjection()}get radius(){return this._radius}_radius=50;set height(e){this._height=e,this._projection&&this.updateProjection()}get height(){return this._height}_height=3;set arBlending(e){this._arblending=e,this._needsTextureUpdate=!0}get arBlending(){return this._arblending}_arblending=0;_lastBackground;_lastRadius;_lastHeight;_projection;_watcher;awake(){this.applyOnAwake&&this.updateAndCreate()}onEnable(){this.context.time.frameCount>0&&this.applyOnAwake&&this.updateAndCreate(),this._watcher||(this._watcher=new Ko(this.context.scene,"background"),this._watcher.subscribeWrite(e=>{mu&&console.log("Background changed",this.context.scene.background),this._needsTextureUpdate=!0}))}onDisable(){this._watcher?.revoke(),this._projection?.removeFromParent()}onEnterXR(){this.activeAndEnabled&&(this._needsTextureUpdate=!0,this.updateProjection())}async onLeaveXR(){this.activeAndEnabled&&(await Wl(1),this.updateProjection())}onBeforeRender(){this._projection&&this.scene.backgroundRotation&&this._projection.rotation.copy(this.scene.backgroundRotation),this.context.scene.backgroundBlurriness!==void 0&&this._lastBlurriness!=this.context.scene.backgroundBlurriness&&this.context.scene.backgroundBlurriness>.001?this.updateProjection():this._needsTextureUpdate&&this.context.scene.background instanceof Re&&this.updateBlurriness(this.context.scene.background,this.context.scene.backgroundBlurriness)}updateAndCreate(){this.updateProjection(),this._watcher?.apply()}_needsTextureUpdate=!1;updateProjection(){if(!this.context.scene.background){this._projection?.removeFromParent();return}const e=this.context.scene.background;if(!(e instanceof Re)){this._projection?.removeFromParent();return}if((this.context.xr?.isPassThrough||this.context.xr?.isAR)&&this.arBlending===0){this._projection?.removeFromParent();return}if(!this.gameObject||this.destroyed)return;let t=!0;const i=0,n=e!==this._lastBackground||this._height!==this._lastHeight||this._radius!==this._lastRadius;if(!this._projection||n){mu&&console.log("Create/Update Ground Projection",e.name),this._projection?.removeFromParent();try{this._projection=new ba(e,this._height,this._radius,64)}catch(s){console.error("Error creating three GroundProjection",s);return}this._projection.position.y=this._height-i,this._projection.name="GroundProjection",Um(this._projection,!1)}else t=!1;if(this._projection.parent||this.gameObject.add(this._projection),this.autoFit&&t){this._projection.updateWorldMatrix(!0,!0);const s=Wt(this.context.scene.children,[this._projection]),r=s.min.y;if(r<1/0){const a=$();a.x=s.min.x+(s.max.x-s.min.x)*.5;const l=$e(this.gameObject).x;a.y=r+this._height*l-i,a.z=s.min.z+(s.max.z-s.min.z)*.5,mt(this._projection,a)}mu&&F.DrawWireBox3(s,65280,5)}this.context.scene.backgroundBlurriness>.001&&this._needsTextureUpdate&&this.updateBlurriness(e,this.context.scene.backgroundBlurriness),this._lastBackground=e,this._lastHeight=this._height,this._lastRadius=this._radius,this._needsTextureUpdate=!1}_blurrynessShader=null;_lastBlurriness=-1;updateBlurriness(e,t){if(this._projection){if(!e)return}else return;this._needsTextureUpdate=!1,mu&&console.log("Update Blurriness",t),this._blurrynessShader??=new Ln({name:"GroundProjectionBlurriness",uniforms:{map:{value:e},blurriness:{value:t},blending:{value:0},alphaFactor:{value:1}},vertexShader:DM,fragmentShader:BM}),this._blurrynessShader.depthWrite=!1,this._blurrynessShader.uniforms.map.value=e,this._blurrynessShader.uniforms.blurriness.value=t,this._lastBlurriness=t,e.needsUpdate=!0;const i=this._projection.material.transparent;this._projection.material.transparent=(this.context.xr?.isAR===!0&&this.arBlending>1e-6)??!1,this._projection.material.transparent?this._blurrynessShader.uniforms.blending.value=this.arBlending:this._blurrynessShader.uniforms.blending.value=0,this.context.isInPassThrough?this._blurrynessShader.uniforms.alphaFactor.value=.95:this._blurrynessShader.uniforms.alphaFactor.value=1,i!==this._projection.material.transparent&&(this._projection.material.needsUpdate=!0),this._projection.material.map=Ys.copyTexture(e,this._blurrynessShader),this._projection.material.depthTest=!0,this._projection.material.depthWrite=!1}}Sc([u()],$n.prototype,"applyOnAwake",2),Sc([u()],$n.prototype,"autoFit",2),Sc([u()],$n.prototype,"radius",1),Sc([u()],$n.prototype,"height",1),Sc([u()],$n.prototype,"arBlending",1);const DM=`
869
869
  varying vec2 vUv;
870
870
 
871
871
  void main() {
@@ -946,7 +946,7 @@ ${t.path}! : AssetReference;
946
946
  Could not find method ${r.method} on object ${l.name}. Please rename ${r.method} to ${d}?
947
947
  `,l[d],`
948
948
  in script: `,l),ge("EventList methods must start with lowercase letter, see console for details");return}else console.warn(`EventList method:
949
- Could not find method ${r.method} on object ${l.name}`,l,typeof l[r.method])};if(typeof l[r.method]!="function"){let d=!1,p=l;for(;p;){const g=Object.getOwnPropertyDescriptor(p,r.method);if(g&&(g.writable===!0||g.set)){d=!0;break}p=Object.getPrototypeOf(p)}!d&&(E()||gt)&&h()}}if(l){let h=r.argument;if(h!==void 0?h=a(h):r.arguments!==void 0&&(h=r.arguments.map(a)),!l[r.method])console.warn(`EventList method not found: "${r.method}" on ${l?.name}`);else{h!==void 0&&!Array.isArray(h)&&(h=[h]);const d=new Oo(l,r.method,h,r.enabled);i.push(d)}}else E()&&console.warn(`[Dev] EventList: Could not find event listener in scene (${t.object?.name})`,r)}const n=new ce(i);gt&&console.log(n);const s=t.target;return s!==void 0&&t.path!==void 0&&n.setEventTarget(t.path,s),n}}}const ZM=new KM,_u=new WeakMap,JM=Re.prototype.clone;Re.prototype.clone=function(){const o=JM.call(this);return _u.has(o)||_u.set(o,this),o};class fw extends Xi{constructor(){super([ho,jn])}onSerialize(e,t){}onDeserialize(e,t){if(e instanceof Re&&t.type===ho){let i=e;_u.has(i)&&(i=_u.get(i)),i.isRenderTargetTexture=!0,i.flipY=!0,i.offset.y=1,i.repeat.y=-1,i.needsUpdate=!0,i.mipmaps=[],i instanceof pS&&(i.isCompressedTexture=!1,i.format=ad);const n=new ho(i.image.width,i.image.height,{colorSpace:po});return n.texture=i,n}}}new fw;class yw extends Xi{constructor(){super([URL])}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"&&e.length>0)return ls(t.gltfId,e)}}new yw;var eR=Object.defineProperty,tR=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&eR(e,t,n),n};class Wa extends M{awake(){ei.createIfNoneExists(this.context)}onEnable(){ei.get(this.context)?.register(this)}onDisable(){ei.get(this.context)?.unregister(this)}}class ki extends Wa{targets=null;raycastHits=[];ignoreSkinnedMeshes=!1;start(){this.targets=[this.gameObject]}performRaycast(e=null){if(!this.targets)return null;e??=new us,e.targets=this.targets,e.results=this.raycastHits,e.useAcceleratedRaycast=!0;const t=e.testObject;this.ignoreSkinnedMeshes&&(e.testObject=n=>n instanceof ss?"continue in children":t?t(n):!0);const i=this.context.physics.raycast(e);return e.testObject=t,i}}tR([u()],ki.prototype,"ignoreSkinnedMeshes");class vu extends ki{constructor(){super(),this.ignoreSkinnedMeshes=!0}}class ra extends Wa{static allow=!0;performRaycast(e){if(!K.active||!ra.allow||!e?.ray)return null;const t=e.ray.origin;return this.context.physics.sphereOverlap(t,.015,!1,!0)}}class tf{static getObject(e){const t=e[Si];return t&&(t.isComponent===!0?e=t.gameObject:e=t),e}static isInteractable(e,t){if(t&&(t.canvasGroup=void 0,t.graphic=void 0),e==null||!e.visible||(e=this.getObject(e),!e.visible))return!1;const i=this.tryFindCanvasGroup(e);if(i?.isCanvasGroup===!0&&(t&&(t.canvasGroup=i),i.blocksRaycasts===!1||i.interactable===!1))return!1;const n=wr(e,s=>{if(s.isGraphic===!0)return s},!1);return t&&n?.isGraphic===!0&&(t.graphic=n),!(n?.raycastTarget===!1||n?.layer===2)}static tryFindCanvasGroup(e){if(!e)return null;const t=wr(e,i=>{const n=i;if(n.blocksRaycasts!==void 0&&n.interactable!==void 0)return n},!1);return t!==void 0?t:this.tryFindCanvasGroup(e.parent)}}function nf(o){return o[Si]||(o.parent?nf(o.parent):null)}function iR(o){return o.isUI===!0||typeof o[Si]=="object"}function wu(o,e){if(!o)return;const t=o.material;if(t?.isMaterial===!0){const i=o.parent;i&&i.isText,t.side=e.doubleSided??!0?vi:as,t.shadowSide=e.doubleSided?vi:as,o.castShadow=e.castShadows?e.castShadows:!1,o.receiveShadow=e.receiveShadows?e.receiveShadows:!1}for(const i of o.children)wu(i,e)}function Va(o,e,t){o[e]===void 0&&console.warn("Field",e,"is undefined on",o);const i=Proxy.revocable(o[e],{set(r,a,l,c){const h=r[a],d=Reflect.set(r,a,l,c);return t(l,h),d}}),n=i.revoke,s=o[e];return i.revoke=()=>{o[e]=s,n()},o[e]=i.proxy,i}const bw=Symbol("Scheduled action");function nR(o,e,t=we.OnBeforeRender){let i=o[bw];i||(i=o[bw]={});const n=e.name;i[t]||(i[t]={});const s=i[t];if(s[n])return;function*r(){e?.call(o),s[n]=null}const a=o.startCoroutine(r(),t);s[n]=a}const _s=w("debugeventsystem");var of=(o=>(o.BeforeHandleInput="BeforeHandleInput",o.AfterHandleInput="AfterHandleInput",o))(of||{});Kv(o=>{ei.createIfNoneExists(o)});class ei extends M{static ensureUpdateMeshUI(e,t,i=!1){Oc.update(e,t,i)}static markUIDirty(e){Oc.markDirty()}static createIfNoneExists(e){e.scene.getComponent(ei)||e.scene.addComponent(ei)}static get(e){return this.createIfNoneExists(e),e.scene.getComponent(ei)}static get instance(){return this.get(z.Current)}raycaster=[];register(e){e&&this.raycaster&&!this.raycaster.includes(e)&&this.raycaster?.push(e)}unregister(e){const t=this.raycaster?.indexOf(e);t!==void 0&&t!==-1&&this.raycaster?.splice(t,1)}get hasActiveUI(){return this.currentActiveMeshUIComponents.length>0}get isHoveringObjects(){return this.hoveredByID.size>0}awake(){this.gameObject!==this.context.scene&&(console.debug(`[Needle Engine] EventSystem is only allowed on the scene root. Disabling EventSystem on '${this.gameObject.name}'`),this.enabled=!1)}start(){this.context.scene.getComponent(Wa)||this.context.scene.addComponent(ki)}onEnable(){this.context.input.addEventListener(Ee.PointerDown,this.onPointerEvent),this.context.input.addEventListener(Ee.PointerUp,this.onPointerEvent),this.context.input.addEventListener(Ee.PointerMove,this.onPointerEvent)}onDisable(){this.context.input.removeEventListener(Ee.PointerDown,this.onPointerEvent),this.context.input.removeEventListener(Ee.PointerUp,this.onPointerEvent),this.context.input.removeEventListener(Ee.PointerMove,this.onPointerEvent)}pressedByID=new Map;hoveredByID=new Map;onBeforeRender(){this.resetMeshUIStates()}onPointerEvent=e=>{if(e===void 0||e.propagationStopped||e.defaultPrevented||e.used)return;const t=new Jh(this.context.input,e);this._currentPointerEventName=e.type,t.inputSource=this.context.input,t.isClick=e.isClick,t.isDoubleClick=e.isDoubleClick,t.isDown=e.type==Ee.PointerDown,t.isUp=e.type==Ee.PointerUp,t.isPressed=this.context.input.getPointerPressed(e.pointerId);const i=new us;e.hasRay?i.ray=e.ray:i.screenPoint=this.context.input.getPointerPositionRC(e.pointerId),i.allowSlowRaycastFallback=e.isClick||e.isDoubleClick;const n=this.performRaycast(i);if(_s&&(t.isDown?console.log("DOWN",{id:t.pointerId,hits:n.length}):t.isUp&&console.log("UP",{id:t.pointerId,hits:n.length}),t.isClick&&console.log("CLICK",{id:t.pointerId,hits:n.length})),n){for(const r of n)r.event=e,e.intersections.push(r);e.origin.onPointerHits&&e.origin.onPointerHits({sender:this,event:e,hits:n})}_s&&t.isClick&&Te("EventSystem: "+t.pointerId+" - "+this.context.time.frame+" - Up:"+t.isUp+", Down:"+t.isDown);const s={sender:this,args:t,hasActiveUI:this.currentActiveMeshUIComponents.length>0};this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:s})),this.handleIntersections(n,t),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:s}))};_sortedHits=[];_testObjectsCache=new Map;_currentlyActiveRaycaster=null;_currentPointerEventName=null;shouldRaycastObject=e=>{const t=e&&"getComponent"in e?e.getComponent(Wa):null;if(t&&t!=this._currentlyActiveRaycaster)return!1;let i=null;if(iR(e)&&(i=e[Si]?.gameObject),this._testObjectsCache.has(e)||i&&this._testObjectsCache.has(i))return this._testObjectsCache.get(e)===!1?"continue in children":!0;{let n=fu(e,this._currentPointerEventName);if(!n&&i&&(n=fu(i,this._currentPointerEventName)),n){this._testObjectsCache.set(e,!0);for(const s of e.children)this.shouldRaycastObject_AddToYesCache(s);return!0}return this._testObjectsCache.set(e,!1),"continue in children"}};shouldRaycastObject_AddToYesCache(e){this._testObjectsCache.set(e,!0);for(const t of e.children)this.shouldRaycastObject_AddToYesCache(t)}performRaycast(e){if(!this.raycaster)return null;this._testObjectsCache.clear(),this._sortedHits.length=0,e.testObject=this.shouldRaycastObject;for(const t of this.raycaster){if(!t.activeAndEnabled)continue;this._currentlyActiveRaycaster=t;const i=t.performRaycast(e);this._currentlyActiveRaycaster=null,i&&i.length>0&&this._sortedHits.push(...i)}return this._sortedHits.sort((t,i)=>t.distance-i.distance),this._sortedHits}assignHitInformation(e,t){t?(e.intersection=t,e.point=t.point,e.normal=t.normal,e.face=t.face,e.distance=t.distance,e.instanceId=t.instanceId):(e.intersection=void 0,e.point=void 0,e.normal=void 0,e.face=void 0,e.distance=void 0,e.instanceId=void 0)}handleIntersections(e,t){if(e?.length){e=this.sortCandidates(e);for(const n of e){if(t.event.immediatePropagationStopped)return!1;if(this.assignHitInformation(t,n),this.handleEventOnObject(n.object,t))return!0}}this.assignHitInformation(t,e?.[0]),this.invokePointerCapture(t);const i=this.hoveredByID.get(t.pointerId);return i&&this.propagatePointerExit(i.obj,i.data,null),this.hoveredByID.delete(t.pointerId),t.isUp&&(this.pressedByID.get(t.pointerId)?.handlers.forEach(n=>this.invokeOnPointerUp(t,n)),this.pressedByID.delete(t.pointerId)),!1}_sortingBuffer=[];_noDepthTestingResults=[];sortCandidates(e){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let t=0;t<e.length;t++){const i=e[t],n=i.object;if(n.material&&n.material.depthTest===!1){this._noDepthTestingResults.push(i);continue}this._sortingBuffer.push(i)}for(const t of this._sortingBuffer)this._noDepthTestingResults.push(t);return this._noDepthTestingResults}out={};handleEventOnObject(e,t){if(!this.testIsVisible(e))return t.isClick&&_s&&console.log("not allowed",e),!1;if(t.pointerId===void 0)return _s&&console.error("Event without pointer can't be handled",t),!1;t.object=e;const i=e.parent,n=t.isClick??!1;let s=null;if(i&&i.isUI){const c=(t.isPressed||t.isClick)??!1;if(i[Si]){const h=i[Si].gameObject;if(h){if(!tf.isInteractable(h,this.out))return!1;s=this.out.canvasGroup??null,this.handleMeshUIIntersection(e,c),e=h}}}n&&_s&&console.log(this.context.time.frame,e);const r=this.hoveredByID.get(t.pointerId),a=r?.obj;a!==e&&a&&this.propagatePointerExit(a,r.data,e);const l=this.hoveredByID.get(t.pointerId);if(l?(l.obj=e,l.data=t):this.hoveredByID.set(t.pointerId,{obj:e,data:t}),t.isDown){const c=this.pressedByID.get(t.pointerId);c?(c.obj=e,c.data=t):this.pressedByID.set(t.pointerId,{obj:e,data:t,handlers:new Set})}return(s===null||s.interactable)&&this.handleMainInteraction(e,t,a??null),!0}propagate(e,t){for(;e;)x.foreachComponent(e,i=>{t(i)},!1),e=e.parent}handleMainInteraction(e,t,i){const n=this.pressedByID.get(t.pointerId),s=i!==e;let r=!0;switch(t.event.pointerType){case"mouse":case"touch":const a=this.context.input.getPointerPositionLastFrame(t.pointerId),l=this.context.input.getPointerPosition(t.pointerId);r=a&&!D.approximately(a,l);break}this.propagate(e,a=>{const l=a;l.interactable!==!1&&(!l.activeAndEnabled||!l.enabled||(l.onPointerEnter&&s&&this.handlePointerEnter(l,t),t.isDown&&l.onPointerDown&&(l.onPointerDown(t),n?.handlers.add(l),this.handlePointerCapture(t,l)),l.onPointerMove&&(r&&l.onPointerMove(t),this.handlePointerCapture(t,l)),t.isUp&&(l.onPointerUp&&(this.invokeOnPointerUp(t,l),n?.handlers.delete(l)),l.onPointerExit&&t.event?.pointerType===Rd.Touch&&(this.handlePointerExit(l,t),this.hoveredByID.delete(t.pointerId))),t.isClick&&l.onPointerClick&&l.onPointerClick(t)))}),t.isUp&&(n?.handlers.forEach(a=>{this.invokeOnPointerUp(t,a)}),this.pressedByID.delete(t.pointerId))}propagatePointerExit(e,t,i){this.propagate(e,n=>{if(!n.gameObject||n.destroyed)return;const s=n;if(s.onPointerExit||s.onPointerEnter){if(i&&this.isChild(i,n.gameObject))return;this.handlePointerExit(s,t)}})}invokeOnPointerUp(e,t){t.onPointerUp?.call(t,e),this.releasePointerCapture(e,t)}handlePointerEnter(e,t){e.onPointerEnter&&this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!0)&&e.onPointerEnter(t),this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!1)}handlePointerExit(e,t){e.onPointerExit&&this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!0)&&e.onPointerExit(t),this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!1)}updatePointerState(e,t,i,n){let s=e[i];if(n)return s&&s.includes(t)?!1:(s=s||[],s.push(t),e[i]=s,!0);{if(!s||!s.includes(t))return!1;const r=s.indexOf(t);return r!==-1&&s.splice(r,1),!0}}_capturedPointer={};handlePointerCapture(e,t){if(e.z__pointer_ctured){e.z__pointer_ctured=!1;const i=e.pointerId;if(t.onPointerMove){const n=this._capturedPointer[i]||[];n.push(t),this._capturedPointer[i]=n}else E()&&!t.z__warned_no_pointermove&&(t.z__warned_no_pointermove=!0,console.warn("PointerCapture was requested but the component doesn't implement onPointerMove. It will not receive any pointer events"))}else e.z__pointer_cture_rleased&&(e.z__pointer_cture_rleased=!1,this.releasePointerCapture(e,t))}releasePointerCapture(e,t){const i=e.pointerId;if(this._capturedPointer[i]){const n=this._capturedPointer[i].indexOf(t);n!==-1&&(this._capturedPointer[i].splice(n,1),_s&&console.log("released pointer capture",i,t,this._capturedPointer))}}invokePointerCapture(e){if(e.event.type===Ee.PointerMove){const t=e.pointerId,i=this._capturedPointer[t];if(i){_s&&console.log("Captured",t,i);for(let n=0;n<i.length;n++){const s=i[n];if(s.destroyed){i.splice(n,1),n--;continue}s.onPointerMove?.call(s,e)}}}}pointerEnterSymbol=Symbol("pointerEnter");pointerExitSymbol=Symbol("pointerExit");isChild(e,t){return!e||!t?!1:e===t?!0:e.parent?this.isChild(e.parent,t):!1}handleMeshUiObjectWithoutShadowDom(e,t){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,t)}currentActiveMeshUIComponents=[];handleMeshUIIntersection(e,t){const i=Oc.updateState(e,t);return i&&this.currentActiveMeshUIComponents.push(i),i!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&Oc.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){const t=this.currentActiveMeshUIComponents[e];Oc.resetState(t)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?x.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}}class Oc{static lastSelected=null;static lastUpdateFrame=[];static needsUpdate=!1;static markDirty(){this.needsUpdate=!0}static update(e,t,i=!1){if(i){e.update();return}const n=t.time.frameCount;for(const s of this.lastUpdateFrame)if(s.context===t){if(n===s.frame)return;s.frame=n;let r=this.needsUpdate||n<1;s.nextUpdate<=n&&(r=!0),r&&(_s&&console.log("Update threemeshui"),this.needsUpdate=!1,s.nextUpdate=n+60,e.update());return}this.lastUpdateFrame=[{context:t,frame:n,nextUpdate:n+60}],e.update(),this.needsUpdate=!1}static updateState(e,t){let i=null;if(e&&(i=this.findBlockOrTextInParent(e),i&&i!==this.lastSelected)){if(i.interactable===!1)return null;this.needsUpdate=!0}return i}static resetLastSelected(){const e=this.lastSelected;e&&(this.lastSelected=null,this.resetState(e))}static resetState(e){e&&(this.needsUpdate=!0)}static findBlockOrTextInParent(e){return e?e.isBlock||e.isText?e:this.findBlockOrTextInParent(e.parent):null}}var oR=Object.defineProperty,Ie=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&oR(e,t,n),n};const Gt=w("debugorbit"),sf=w("freecam"),kc=w("debugcamerafit"),xu=w("smoothcam"),sR={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let rf;class Mc extends CustomEvent{constructor(e,t){super("target-reached",{detail:{controls:e,type:t}})}}class fe extends M{get isCameraController(){return!0}get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(e){this.controls?.addEventListener("start",e)}autoTarget=!0;autoFit=!1;enableRotate=!0;autoRotate=!1;autoRotateSpeed=1;minAzimuthAngle=1/0;maxAzimuthAngle=1/0;minPolarAngle=0;maxPolarAngle=Math.PI;enableKeys=!1;enableDamping=!0;dampingFactor=.1;enableZoom=!0;minZoom=0;maxZoom=1/0;zoomSpeed=1;zoomToCursor=!1;enablePan=!0;lookAtConstraint=null;lookAtConstraint01=1;allowInterrupt=!0;middleClickToFocus=!0;doubleClickToFocus=!0;clickBackgroundToFitScene=2;get targetElement(){return this._controls?.domElement??this._targetElement}set targetElement(e){this._targetElement=e,this._controls&&this._controls.domElement!==e&&(this._controls.disconnect(),this._controls.domElement=e,this._controls.connect())}_targetElement=null;debugLog=!1;get targetLerpSpeed(){return 5}set targetLerpSpeed(e){this.targetLerpDuration=1/e}targetLerpDuration=1;rotateLeft(e){this._controls?._rotateLeft(e)}rotateUp(e){this._controls?._rotateUp(e)}pan(e,t){this._controls?._pan(e,t)}zoomIn(e){e>0?this._controls?._dollyIn(1-e):e<0&&this._controls?._dollyOut(1+e)}_controls=null;_cameraObject=null;_lookTargetLerpActive=!1;_lookTargetStartPosition=new b;_lookTargetEndPosition=new b;_lookTargetLerp01=0;_lookTargetLerpDuration=0;_cameraLerpActive=!1;_cameraStartPosition=new b;_cameraEndPosition=new b;_cameraLerp01=0;_cameraLerpDuration=0;_fovLerpActive=!1;_fovLerpStartValue=0;_fovLerpEndValue=0;_fovLerp01=0;_fovLerpDuration=0;_inputs=0;_enableTime=0;_startedListeningToKeyEvents=!1;_eventSystem;_afterHandleInputFn;_camera=null;_syncedTransform;_didSetTarget=0;awake(){Gt&&console.debug("OrbitControls",this),this._didSetTarget=0,this._startedListeningToKeyEvents=!1}start(){this._eventSystem=ei.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(of.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){this._controls?.dispose(),this._eventSystem?.removeEventListener(of.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._didSetTarget=0,this._enableTime=this.context.time.time;const e=x.getComponent(this.gameObject,si);this._camera=e;let t=e?.threeCamera;if(!t&&this.gameObject instanceof de&&(t=this.gameObject),t&&Em(t,this,!0),!this._controls&&t instanceof O){this._cameraObject=t;const i=this.targetElement??this.context.renderer.domElement,n=t?.quaternion.clone();this._controls=new Y0(t,i),t?.quaternion.copy(n),rf===void 0&&(rf={...this._controls.keys});const s=Z(t),r=this.gameObject.worldForward,a=s.clone().sub(r.multiplyScalar(2.5));this._controls.target.copy(a)}if(this._controls)if(sf&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,G.isMobileDevice()&&(this.doubleClickToFocus=!0)),this._controls.addEventListener("start",this.onControlsChangeStarted),this._controls.addEventListener("endMovement",this.onControlsChangeEnded),!this._startedListeningToKeyEvents&&this.enableKeys)this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(this.context.domElement);else try{this._controls.stopListenToKeyEvents()}catch{}this._syncedTransform=x.getComponent(this.gameObject,vn)??void 0,this.context.pre_render_callbacks.push(this.__onPreRender),this._activePointerEvents=[],this.context.input.addEventListener("pointerdown",this._onPointerDown,{queue:ii.Early}),this.context.input.addEventListener("pointerdown",this._onPointerDownLate,{queue:ii.Late}),this.context.input.addEventListener("pointerup",this._onPointerUp,{queue:ii.Early}),this.context.input.addEventListener("pointerup",this._onPointerUpLate,{queue:ii.Late})}onDisable(){if(this._camera?.threeCamera&&Em(this._camera.threeCamera,this,!1),this._controls){this._controls.enabled=!1,this._controls.autoRotate=!1,this._controls.removeEventListener("start",this.onControlsChangeStarted),this._controls.removeEventListener("endMovement",this.onControlsChangeEnded);try{this._controls.stopListenToKeyEvents()}catch{}this._startedListeningToKeyEvents=!1}this._activePointerEvents.length=0,this.context.input.removeEventListener("pointerdown",this._onPointerDown),this.context.input.removeEventListener("pointerdown",this._onPointerDownLate),this.context.input.removeEventListener("pointerup",this._onPointerUp),this.context.input.removeEventListener("pointerup",this._onPointerUpLate)}_activePointerEvents;_lastTimeClickOnBackground=-1;_clickOnBackgroundCount=0;_onPointerDown=e=>{this._activePointerEvents.push(e)};_onPointerDownLate=e=>{e.used&&this._controls&&(this._controls.enabled=!1)};_onPointerUp=e=>{for(let t=this._activePointerEvents.length-1;t>=0;t--){const i=this._activePointerEvents[t];if(i.pointerId===e.pointerId&&i.button===e.button){this._activePointerEvents.splice(t,1);break}}if(this.clickBackgroundToFitScene>0&&e.isClick&&e.button===0){if(e.hasRay||e.intersections.push(...this.context.physics.raycast()),e.intersections.length<=0){const t=this.context.time.time-this._lastTimeClickOnBackground;this._lastTimeClickOnBackground=this.context.time.time,this.clickBackgroundToFitScene<=1||t<this.clickBackgroundToFitScene*.15?(this._clickOnBackgroundCount+=1,this._clickOnBackgroundCount>=this.clickBackgroundToFitScene-1&&this.fitCamera(this.context.scene.children,{immediate:!1})):this._clickOnBackgroundCount=0}Gt&&console.log(this.clickBackgroundToFitScene,e.intersections.length,this._clickOnBackgroundCount)}};_onPointerUpLate=e=>{this.doubleClickToFocus&&e.isDoubleClick&&!e.used&&this.setTargetFromRaycast()};updateTargetNow(e){const t=new ns(this._cameraObject?.worldPosition,this._cameraObject?.worldForward.multiplyScalar(-1)),i=this.context.physics.raycastFromRay(t,e),n=i.length>0?i[0]:void 0;n&&n.distance>this.minZoom&&n.distance<this.maxZoom?(Gt&&F.DrawWireSphere(n.point,.1,16711680,2),this._controls?.target.copy(i[0].point)):Gt&&console.log("OrbitControls: No hit found when updating target",{hits:[...i]})}_orbitStartAngle=0;_zoomStartDistance=0;onControlsChangeStarted=()=>{Gt&&console.debug("OrbitControls: Change started"),this._controls&&(this._orbitStartAngle=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle(),this._zoomStartDistance=this._controls.getDistance()),this._syncedTransform&&this._syncedTransform.requestOwnership()};onControlsChangeEnded=()=>{if(Gt&&console.debug("OrbitControls: Change ended",{autoTarget:this.autoTarget}),this._controls&&this.autoTarget){const e=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle()-this._orbitStartAngle;Math.abs(e)<.01?(Gt&&console.debug("OrbitControls: Update target",{deltaAngle:e}),this.updateTargetNow({allowSlowRaycastFallback:!1})):Gt&&console.debug("OrbitControls: No target update",{deltaAngle:e})}};_shouldDisable=!1;afterHandleInput(e){e.detail.args.pointerId===0&&(e.detail.args.isDown?this._controls&&this._eventSystem&&(this._shouldDisable=this._eventSystem.hasActiveUI):(!e.detail.args.isPressed||e.detail.args.isUp)&&(this._shouldDisable=!1))}onPausedChanged(e){this._controls&&e&&(this._controls.enabled=!1)}onBeforeRender(){if(!!this._controls){if(this._cameraObject!==this.context.mainCamera){this._controls.enabled=!1;return}if(this._controls.enabled=!0,(this.context.input.getPointerDown(1)||this.context.input.getPointerDown(2)||this.context.input.mouseWheelChanged||this.context.input.getPointerPressed(0)&&this.context.input.getPointerPositionDelta(0)?.length())&&(this._inputs+=1),this._inputs>0&&this.allowInterrupt&&(this.enableRotate&&(this.autoRotate=!1),this._cameraLerpActive=!1,this._lookTargetLerpActive=!1),this._inputs=0,this.autoTarget&&this._didSetTarget++===0){const e=x.getComponent(this.gameObject,si);if(e&&!this.setLookTargetFromConstraint()){this.debugLog&&console.log("NO TARGET");const t=Z(e.threeCamera),i=Math.max(.01,t.length()),n=new b(0,0,-i).applyMatrix4(e.threeCamera.matrixWorld);Gt&&F.DrawLine(t,n,5592575,10),this.setLookTargetPosition(n,!0)}if(!this.setLookTargetFromConstraint()){const t=new us;t.screenPoint=new J(0,0),t.lineThreshold=.1;const i=this.context.physics.raycast(t);i.length>0&&this.setLookTargetPosition(i[0].point,!0),kc&&console.log("OrbitControls hits",...i)}}if(this.middleClickToFocus&&this.context.input.getPointerClicked(1)&&this.setTargetFromRaycast(),this._lookTargetLerpActive||this._cameraLerpActive||this._fovLerpActive){if(this._cameraLerpActive&&this._cameraObject)if(this._cameraLerp01+=this.context.time.deltaTime/this._cameraLerpDuration,this._cameraLerp01>=1)this._cameraObject.position.copy(this._cameraEndPosition),this._cameraLerpActive=!1,this.dispatchEvent(new Mc(this,"camera"));else{const e=D.easeInOutCubic(this._cameraLerp01);this._cameraObject.position.lerpVectors(this._cameraStartPosition,this._cameraEndPosition,e)}if(this._lookTargetLerpActive)if(this._lookTargetLerp01+=this.context.time.deltaTime/this._lookTargetLerpDuration,this._lookTargetLerp01>=1)this.lerpLookTarget(this._lookTargetEndPosition,this._lookTargetEndPosition,1),this._lookTargetLerpActive=!1,this.dispatchEvent(new Mc(this,"lookat"));else{const e=D.easeInOutCubic(this._lookTargetLerp01);this.lerpLookTarget(this._lookTargetStartPosition,this._lookTargetEndPosition,e)}if(this._fovLerpActive&&this._cameraObject){const e=this._cameraObject;if(this._fovLerp01+=this.context.time.deltaTime/this._fovLerpDuration,this._fovLerp01>=1)e.fov=this._fovLerpEndValue,this._fovLerpActive=!1;else{const t=D.easeInOutCubic(this._fovLerp01);e.fov=D.lerp(this._fovLerpStartValue,this._fovLerpEndValue,t)}e.updateProjectionMatrix()}}if(this._controls){if(this.debugLog&&(this._controls.domElement=this.context.renderer.domElement),this._controls.enabled=!this._shouldDisable&&this._camera===this.context.mainCameraComponent&&!this.context.isInXR&&!this._activePointerEvents.some(e=>e.used),this._controls.keys=this.enableKeys?rf:sR,this._controls.autoRotate=this.autoRotate,this._controls.autoRotateSpeed=this.autoRotateSpeed,this._controls.enableZoom=this.enableZoom,this._controls.zoomSpeed=this.zoomSpeed,this._controls.zoomToCursor=this.zoomToCursor,this._controls.enableDamping=this.enableDamping,this._controls.dampingFactor=this.dampingFactor,this._controls.enablePan=this.enablePan,this._controls.enableRotate=this.enableRotate,this._controls.minAzimuthAngle=this.minAzimuthAngle,this._controls.maxAzimuthAngle=this.maxAzimuthAngle,this._controls.minPolarAngle=this.minPolarAngle,this._controls.maxPolarAngle=this.maxPolarAngle,sf||(this._camera?.threeCamera?.type==="PerspectiveCamera"?(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom,this._controls.minZoom=0,this._controls.maxZoom=1/0):(this._controls.minDistance=0,this._controls.maxDistance=1/0,this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom)),typeof xu=="number"||xu===!0){this._controls.enableDamping=!0;const e=typeof xu=="number"?xu:.99;this._controls.dampingFactor=Math.max(.001,1-Math.min(1,e))}this.allowInterrupt||(this._lookTargetLerpActive&&(this._controls.enablePan=!1),this._cameraLerpActive&&(this._controls.enableRotate=!1,this._controls.autoRotate=!1),(this._lookTargetLerpActive||this._cameraLerpActive)&&(this._controls.enableZoom=!1)),this.context.isInXR||(!sf&&this.lookAtConstraint?.locked&&!this._lookTargetLerpActive&&this.setLookTargetFromConstraint(0,this.lookAtConstraint01),this._controls.update(this.context.time.deltaTime),Gt&&F.DrawWireSphere(this._controls.target,.1,65280))}}}__onPreRender=()=>{const e=this.context.pre_render_callbacks.indexOf(this.__onPreRender);e>=0&&this.context.pre_render_callbacks.splice(e,1),this.autoFit&&(this.autoFit=!1,this.fitCamera({centerCamera:"y",immediate:!0,objects:this.scene.children}))};setCameraAndLookTarget(e,t=!1){if(!e)return(E()||Gt)&&console.warn("[OrbitControls] setCameraAndLookTarget target is null"),!1;if(!(e instanceof O)&&!(e instanceof si))return(E()||Gt)&&console.warn("[OrbitControls] setCameraAndLookTarget target is not an Object3D or Camera"),!1;e instanceof si&&(e=e.gameObject);const i=e.worldPosition,n=e.worldForward;e instanceof mS&&(Gt&&console.debug("[OrbitControls] setCameraAndLookTarget flip forward direction for camera"),n.multiplyScalar(-1));const s=new ns(i,n);return Gt&&F.DrawRay(s.origin,s.direction,16711680,10),this.setTargetFromRaycast(s,t)||this.setLookTargetPosition(s.at(2,$()),t),this.setCameraTargetPosition(i,t),!0}setCameraTargetPosition(e,t=!1){e&&(e instanceof O&&(e=Z(e)),this._cameraEndPosition||(this._cameraEndPosition=new b),this._cameraEndPosition.copy(e),t===!0?(this._cameraLerpActive=!1,this._cameraObject&&this._cameraObject.position.copy(this._cameraEndPosition)):this._cameraObject&&(this._cameraLerpActive=!0,this._cameraLerp01=0,this._cameraStartPosition.copy(this._cameraObject?.position),typeof t=="number"?this._cameraLerpDuration=t:this._cameraLerpDuration=this.targetLerpDuration))}get cameraLerpActive(){return this._cameraLerpActive}stopCameraLerp(){this._cameraLerpActive=!1}setFieldOfView(e,t=!1){if(!this._controls||typeof e!="number")return;const i=this._camera?.threeCamera;i&&(t===!0?i.fov=e:(this._fovLerpActive=!0,this._fovLerp01=0,this._fovLerpStartValue=i.fov,this._fovLerpEndValue=e,typeof t=="number"?this._fovLerpDuration=t:this._fovLerpDuration=this.targetLerpDuration))}setLookTargetPosition(e=null,t=!1){this._controls&&e&&(e instanceof O&&(e=Z(e)),this._lookTargetEndPosition.copy(e),this._didSetTarget++,Gt&&(console.warn("OrbitControls: setLookTargetPosition",e,t),F.DrawWireSphere(this._lookTargetEndPosition,.2,16711680,2)),t===!0?this.lerpLookTarget(this._lookTargetEndPosition,this._lookTargetEndPosition,1):(this._lookTargetLerpActive=!0,this._lookTargetLerp01=0,this._lookTargetStartPosition.copy(this._controls.target),typeof t=="number"?this._lookTargetLerpDuration=t:this._lookTargetLerpDuration=this.targetLerpDuration))}get lookTargetLerpActive(){return this._lookTargetLerpActive}stopLookTargetLerp(){this._lookTargetLerpActive=!1}setLookTargetFromConstraint(e=0,t=1){if(!this._controls||this.lookAtConstraint?.enabled===!1)return!1;const i=this.lookAtConstraint?.sources;if(i&&i.length>0){const n=i[e];if(n)return n.getWorldPosition(this._lookTargetEndPosition),this.lerpLookTarget(this._controls.target,this._lookTargetEndPosition,t),!0}return!1}lerpLookTarget(e,t,i){this._controls&&(i>=1?this._controls.target.copy(t):this._controls.target.lerpVectors(e,t,i),this.lookAtConstraint&&this.lookAtConstraint.setConstraintPosition(this._controls.target))}setTargetFromRaycast(e,t=!1){if(!this.controls)return!1;const i=e?this.context.physics.raycastFromRay(e):this.context.physics.raycast();for(const n of i)if(n.distance>0&&x.isActiveInHierarchy(n.object)){const s=nf(n.object);if(s&&s.canvas?.screenspace)break;return this.setLookTargetPosition(n.point,t),!0}return!1}fitCamera(e,t){if(this.context.isInXR){console.warn("[OrbitControls] Can not fit camera while XR session is active");return}let i;if(Array.isArray(e)||e&&"type"in e?i=e:e&&typeof e=="object"&&!(e instanceof O)&&!Array.isArray(e)&&(t=e,i=t.objects),i&&!Array.isArray(i)&&(i=[i]),(!Array.isArray(i)||i&&i.length<=0)&&(i=this.context.scene.children),!Array.isArray(i)||i.length<=0){console.warn("No objects to fit camera to...");return}const n=this._cameraObject,s=this._controls;if(!n||!s){console.warn("No camera or controls found to fit camera to objects...");return}t||(t={});const{immediate:r=!1,centerCamera:a,cameraNearFar:l="auto",fitOffset:c=1.1,fov:h=n?.fov}=t,d=new b,p=new b,g=Wt(i,void 0,this._camera?.threeCamera?.layers),f=g.clone();g.getCenter(p);const m=new b;if(g.getSize(m),n.updateMatrixWorld(),g.applyMatrix4(n.matrixWorldInverse),g.getSize(d),g.setFromCenterAndSize(p,d),Number.isNaN(d.x)||Number.isNaN(d.y)||Number.isNaN(d.z)){console.warn("Camera fit size resultet in NaN",n,g,[...i]);return}if(d.length()<=1e-10){kc&&console.warn("Camera fit size is zero",g,[...i]);return}const y=h,_=2*Math.atan(Math.tan(y*Math.PI/360/2)*n.aspect)/Math.PI*360,v=d.y/(2*Math.atan(Math.PI*y/360)),P=d.x/(2*Math.atan(Math.PI*_/360)),R=c*Math.max(v,P)+d.z/2;kc&&console.log("Fit camera to objects",{fitHeightDistance:v,fitWidthDistance:P,distance:R,verticalFov:y,horizontalFov:_}),this.maxZoom=R*10,this.minZoom=R*.01;const k=.05,A=p.clone();if(A.y-=d.y*k,t.targetOffset&&(t.targetOffset.x!==void 0&&(A.x+=t.targetOffset.x),t.targetOffset.y!==void 0&&(A.y+=t.targetOffset.y),t.targetOffset.z!==void 0&&(A.z+=t.targetOffset.z)),t.relativeTargetOffset&&(t.relativeTargetOffset.x!==void 0&&(A.x+=t.relativeTargetOffset.x*d.x),t.relativeTargetOffset.y!==void 0&&(A.y+=t.relativeTargetOffset.y*d.y),t.relativeTargetOffset.z!==void 0&&(A.z+=t.relativeTargetOffset.z*d.z)),this.setLookTargetPosition(A,r),this.setFieldOfView(t.fov,r),l==null||l=="auto"){const q=x.findObjectOfType($n),Y=q?q.radius:0,I=Math.max(m.x,m.y,m.z,Y);n.near=R/100,n.far=I+R*10,n.updateProjectionMatrix(),q&&(this.maxZoom=Math.max(Math.min(this.maxZoom,Y*.5),R))}const L=s.getDistance();L<this.minZoom&&(this.minZoom=L*.9),L>this.maxZoom&&(this.maxZoom=L*1.1);const N=p.clone();t.fitDirection?N.sub(new b().copy(t.fitDirection).multiplyScalar(1e6)):N.sub(n.worldPosition),a==="y"&&(N.y=0),N.normalize(),N.multiplyScalar(R),a==="y"&&(N.y+=-k*4*R);let j=p.clone().sub(N);t.cameraOffset&&(t.cameraOffset.x!==void 0&&(j.x+=t.cameraOffset.x),t.cameraOffset.y!==void 0&&(j.y+=t.cameraOffset.y),t.cameraOffset.z!==void 0&&(j.z+=t.cameraOffset.z)),t.relativeCameraOffset&&(t.relativeCameraOffset.x!==void 0&&(j.x+=t.relativeCameraOffset.x*d.x),t.relativeCameraOffset.y!==void 0&&(j.y+=t.relativeCameraOffset.y*d.y),t.relativeCameraOffset.z!==void 0&&(j.z+=t.relativeCameraOffset.z*d.z)),n.parent&&(j=n.parent.worldToLocal(j)),this.setCameraTargetPosition(j,r),(kc||t.debug)&&(F.DrawWireBox3(g,16777011,10),F.DrawWireBox3(f,65280,10),!this._haveAttachedKeyboardEvents&&kc&&(this._haveAttachedKeyboardEvents=!0,document.body.addEventListener("keydown",q=>{if(q.code==="KeyF"){let Y;this._cameraObject instanceof de&&(Y=Math.random()*Math.random()*170+10),this.fitCamera({objects:i,fitOffset:c,immediate:!1,fov:Y})}q.code==="KeyV"&&this._cameraObject instanceof de&&(this._cameraObject.fov=60)}))),this.onBeforeRender()}_haveAttachedKeyboardEvents=!1}Ie([u()],fe.prototype,"autoTarget"),Ie([u()],fe.prototype,"autoFit"),Ie([u()],fe.prototype,"enableRotate"),Ie([u()],fe.prototype,"autoRotate"),Ie([u()],fe.prototype,"autoRotateSpeed"),Ie([u()],fe.prototype,"minAzimuthAngle"),Ie([u()],fe.prototype,"maxAzimuthAngle"),Ie([u()],fe.prototype,"minPolarAngle"),Ie([u()],fe.prototype,"maxPolarAngle"),Ie([u()],fe.prototype,"enableKeys"),Ie([u()],fe.prototype,"enableDamping"),Ie([u()],fe.prototype,"dampingFactor"),Ie([u()],fe.prototype,"enableZoom"),Ie([u()],fe.prototype,"minZoom"),Ie([u()],fe.prototype,"maxZoom"),Ie([u()],fe.prototype,"zoomSpeed"),Ie([u()],fe.prototype,"enablePan"),Ie([u(Pr)],fe.prototype,"lookAtConstraint"),Ie([u()],fe.prototype,"lookAtConstraint01"),Ie([u()],fe.prototype,"allowInterrupt"),Ie([u()],fe.prototype,"middleClickToFocus"),Ie([u()],fe.prototype,"doubleClickToFocus"),Ie([u()],fe.prototype,"clickBackgroundToFitScene"),Ie([u()],fe.prototype,"targetLerpDuration");var rR=Object.defineProperty,aR=Object.getOwnPropertyDescriptor,qt=(o,e,t,i)=>{for(var n=i>1?void 0:i?aR(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&rR(e,t,n),n},kr=(o=>(o[o.None=0]="None",o[o.Skybox=1]="Skybox",o[o.SolidColor=2]="SolidColor",o[o.Uninitialized=4]="Uninitialized",o))(kr||{});const vs=w("debugcam"),_w=w("debugscreenpointtoray"),Lt=class Gh extends M{get isCamera(){return!0}get aspect(){return this._cam instanceof de?this._cam.aspect:this.context.domWidth/this.context.domHeight}set aspect(e){this._cam instanceof de&&this._cam.aspect!==e&&(this._cam.aspect=e,this._cam.updateProjectionMatrix())}get fieldOfView(){return this._cam instanceof de?this._cam.fov:this._fov}set fieldOfView(e){const t=this.fieldOfView!=e;if(this._fov=e,t&&this._cam&&this._cam instanceof de){if(this._fov===void 0){console.warn("Can not set undefined fov on PerspectiveCamera");return}this._cam.fov=this._fov,this._cam.updateProjectionMatrix()}}get nearClipPlane(){return this._nearClipPlane}set nearClipPlane(e){const t=this._nearClipPlane!=e;this._nearClipPlane=e,this._cam&&(t||this._cam.near!=e)&&(this._cam.near=e,this._cam.updateProjectionMatrix())}_nearClipPlane=.1;get farClipPlane(){return this._farClipPlane}set farClipPlane(e){const t=this._farClipPlane!=e;this._farClipPlane=e,this._cam&&(t||this._cam.far!=e)&&(this._cam.far=e,this._cam.updateProjectionMatrix())}_farClipPlane=1e3;applyClippingPlane(){this._cam&&(this._cam.near=this._nearClipPlane,this._cam.far=this._farClipPlane,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(e){if(typeof e=="string")switch(e){case"skybox":e=1;break;case"solidcolor":e=2;break;default:e=0;break}e!==this._clearFlags&&(this._clearFlags=e,this.applyClearFlagsIfIsActiveCamera())}orthographic=!1;orthographicSize=5;ARBackgroundAlpha=0;set cullingMask(e){this._cullingMask=e,this._cam&&(this._cam.layers.mask=e)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}_cullingMask=4294967295;set cullingLayer(e){this.cullingMask=(1<<e|0)>>>0}set backgroundBlurriness(e){e!==this._backgroundBlurriness&&(e===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(e,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}_backgroundBlurriness=void 0;set backgroundIntensity(e){e!==this._backgroundIntensity&&(e===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(e,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}_backgroundIntensity=void 0;set backgroundRotation(e){e!==this._backgroundRotation&&(e===void 0?this._backgroundRotation=void 0:this._backgroundRotation=e,this.applyClearFlagsIfIsActiveCamera())}get backgroundRotation(){return this._backgroundRotation}_backgroundRotation=void 0;set environmentIntensity(e){this._environmentIntensity=e}get environmentIntensity(){return this._environmentIntensity}_environmentIntensity=void 0;get backgroundColor(){return this._backgroundColor??null}set backgroundColor(e){e&&(this._backgroundColor||(this._backgroundColor=new se(1,1,1,1)),this._backgroundColor.copy(e),(!("alpha"in e)||e.alpha===void 0)&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera())}set targetTexture(e){this._targetTexture=e}get targetTexture(){return this._targetTexture}_targetTexture=null;_backgroundColor;_fov;_cam=null;_clearFlags=2;_skybox;get cam(){return this.threeCamera}get threeCamera(){return this.activeAndEnabled&&this.buildCamera(),this._cam}static _origin=new b;static _direction=new b;screenPointToRay(e,t,i){const n=this.threeCamera,s=Gh._origin;s.set(e,t,-1),this.context.input.convertScreenspaceToRaycastSpace(s),_w&&console.log("screenPointToRay",e.toFixed(2),t.toFixed(2),"now:",s.x.toFixed(2),s.y.toFixed(2),"isInXR:"+this.context.isInXR),s.z=-1,s.unproject(n);const r=Gh._direction.set(s.x,s.y,s.z),a=Z(n);return r.sub(a),r.normalize(),i?(i.set(a,r),i):new ns(a.clone(),r.clone())}_frustum;getFrustum(){return this._frustum||(this._frustum=new U0,this.updateFrustum()),this._frustum}updateFrustum(){this._frustum||(this._frustum=new U0),this._frustum.setFromProjectionMatrix(this.getProjectionScreenMatrix(this._projScreenMatrix,!0),this.context.renderer.coordinateSystem)}getProjectionScreenMatrix(e,t){return t&&this._projScreenMatrix.multiplyMatrices(this.threeCamera.projectionMatrix,this.threeCamera.matrixWorldInverse),e===this._projScreenMatrix?e:e.copy(this._projScreenMatrix)}_projScreenMatrix=new ee;awake(){_w&&window.addEventListener("pointerdown",e=>{const t=e.clientX,i=e.clientY;console.log("touch",t.toFixed(2),i.toFixed(2));const n=this.screenPointToRay(t,i),s="#"+Math.floor(Math.random()*16777215).toString(16);F.DrawRay(n.origin,n.direction,s,10)})}onEnable(){vs&&console.log(`Camera enabled: "${this.name}". ClearFlags=${kr[this._clearFlags]}`,this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),cR(this)),this.applyClearFlagsIfIsActiveCamera({applySkybox:!0})}onDisable(){this.context.removeCamera(this)}onLeaveXR(e){this.fieldOfView=this._fov}onBeforeRender(){if(this._cam&&(this._frustum&&this.updateFrustum(),this._clearFlags===2&&this.applyClearFlagsIfIsActiveCamera(),this._targetTexture)){this.context.isManagedExternally&&(this._warnedAboutExternalRenderer||(this._warnedAboutExternalRenderer=!0,console.warn("Rendering with external renderer is not supported yet. This may not work or throw errors. Please remove the the target texture from your camera: "+this.name,this.targetTexture))),this.context.composer;const e=this.context.renderer;if(e){const t=this.context.mainCameraComponent;this.applyClearFlags(),this._targetTexture.render(this.context.scene,this._cam,e),t?.applyClearFlags()}}}buildCamera(){if(this._cam)return;const e=this.gameObject.isCamera;let t=null;if(e?(t=this.gameObject,t?.layers.enableAll(),t instanceof de&&(this._fov=t.fov)):t=this.gameObject.children[0],t&&t.isCamera)t instanceof de&&(this._fov&&(t.fov=this._fov),t.near=this._nearClipPlane,t.far=this._farClipPlane,t.updateProjectionMatrix());else if(!this.orthographic)t=new de(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),this.fieldOfView&&(t.fov=this.fieldOfView),this.gameObject.add(t);else{const i=this.orthographicSize*100;t=new nd(window.innerWidth/-i,window.innerWidth/i,window.innerHeight/i,window.innerHeight/-i,this._nearClipPlane,this._farClipPlane),this.gameObject.add(t)}this._cam=t,this._cam.layers.mask=this._cullingMask,this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(e){this.context.mainCameraComponent===this&&this.applyClearFlags(e)}applyClearFlags(e){if(!this._cam){vs&&console.log("Camera does not exist (apply clear flags)");return}if(this.fieldOfView=this.fieldOfView,vs){const i=`[Camera] Apply ClearFlags: ${kr[this._clearFlags]} - "${this.name}"`;console.debug(i)}const t=this.context.domElement.getAttribute("background-image")||this.context.domElement.getAttribute("background-color");switch(this._clearFlags){case 0:return;case 1:if(Gh.backgroundShouldBeTransparent(this.context)&&(!this.ARBackgroundAlpha||this.ARBackgroundAlpha<.001)){this.context.scene.background=null,this.context.renderer.setClearColor(0,0);return}(!this.scene.background||!this._skybox||e?.applySkybox===!0)&&this.applySceneSkybox(),this._backgroundBlurriness!==void 0&&!this.context.domElement.getAttribute("background-blurriness")?this.context.scene.backgroundBlurriness=this._backgroundBlurriness:vs&&console.warn(`Camera "${this.name}" has no background blurriness`),this._backgroundIntensity!==void 0&&!this.context.domElement.getAttribute("background-intensity")&&(this.context.scene.backgroundIntensity=this._backgroundIntensity),this._backgroundRotation!==void 0&&!this.context.domElement.getAttribute("background-rotation")?this.context.scene.backgroundRotation=this._backgroundRotation:vs&&console.warn(`Camera "${this.name}" has no background intensity`);break;case 2:if(this._backgroundColor&&!t){let i=this._backgroundColor.alpha;Gh.backgroundShouldBeTransparent(this.context)&&(i=this.ARBackgroundAlpha??0),this.context.scene.background=null,this.context.xr?.isVR?this.context.renderer.setClearColor(Ab(this._backgroundColor).convertLinearToSRGB()):this.context.renderer.setClearColor(this._backgroundColor,i)}else this._backgroundColor||vs&&console.warn(`[Camera] has no background color "${this.name}" `);break;case 4:t||(this.context.scene.background=null,this.context.renderer.setClearColor(0,0));break}}applySceneSkybox(){this._skybox||(this._skybox=new lR(this)),this._skybox.apply()}static backgroundShouldBeTransparent(e){const t=e.renderer.xr?.getSession();if(!t)return!1;if(typeof t._transparent=="boolean")return t._transparent;const i=t.environmentBlendMode;vs&&Te("Environment blend mode: "+i+" on "+navigator.userAgent);let n=i==="additive"||i==="alpha-blend";return e.isInAR&&i==="opaque"&&(navigator.userAgent?.includes("OculusBrowser")||navigator.userAgent?.includes("Mozilla")&&navigator.userAgent?.includes("Mobile WebXRViewer/v2"))&&(n=!0),t._transparent=n,n}};qt([u()],Lt.prototype,"aspect",1),qt([u()],Lt.prototype,"fieldOfView",1),qt([u()],Lt.prototype,"nearClipPlane",1),qt([u()],Lt.prototype,"farClipPlane",1),qt([u()],Lt.prototype,"clearFlags",1),qt([u()],Lt.prototype,"orthographic",2),qt([u()],Lt.prototype,"orthographicSize",2),qt([u()],Lt.prototype,"ARBackgroundAlpha",2),qt([u()],Lt.prototype,"cullingMask",1),qt([u()],Lt.prototype,"backgroundBlurriness",1),qt([u()],Lt.prototype,"backgroundIntensity",1),qt([u(nt)],Lt.prototype,"backgroundRotation",1),qt([u()],Lt.prototype,"environmentIntensity",1),qt([u(se)],Lt.prototype,"backgroundColor",1),qt([u(ho)],Lt.prototype,"targetTexture",1);let si=Lt;class lR{_camera;_skybox;get context(){return this._camera?.context}constructor(e){this._camera=e}apply(){if(this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),!this._skybox)this._did_log_failed_to_find_skybox||(this._did_log_failed_to_find_skybox=!0,console.warn(`Camera "${this._camera.name}" has no skybox texture. ${this._camera.sourceId}`));else if(this.context.scene.background!==this._skybox){const e=this.context.domElement.getAttribute("background-image")||this.context.domElement.getAttribute("background-color");vs&&console.debug(`[Camera] Apply Skybox ${this._skybox?.name} ${e} - "${this._camera.name}"`),e?.length||(this._skybox.mapping=mo,this.context.scene.background=this._skybox)}}}function cR(o){w("freecam")&&o.context.mainCameraComponent===o&&x.getOrAddComponent(o.gameObject,fe)}class ko extends M{get listener(){return this._listener==null&&(this._listener=new gS),this._listener}_listener=null;onEnable(){Tn.registerWaitForInteraction(this.onInteraction),this.addListenerIfItExists()}onDisable(){Tn.unregisterWaitForInteraction(this.onInteraction),this.removeListenerIfItExists()}onInteraction=()=>{this.destroyed||this.listener==null||this.addListenerIfItExists()};addListenerIfItExists(){const e=this._listener;if(!e||e?.parent)return;const t=this.context.mainCameraComponent||x.getComponentInParent(this.gameObject,si);t?.threeCamera?t.threeCamera.add(e):this.gameObject.add(e),e.filter?(e.gain.connect(e.filter),e.filter.connect(e.context.destination)):e.gain.connect(e.context.destination)}removeListenerIfItExists(){const e=this._listener;e&&(e.removeFromParent(),e.filter&&e.filter.disconnect(),e.gain&&e.gain.disconnect())}}var hR=Object.defineProperty,dR=Object.getOwnPropertyDescriptor,wn=(o,e,t,i)=>{for(var n=i>1?void 0:i?dR(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&hR(e,t,n),n};const Ot=w("debugaudio"),Yi=class qs extends M{static get userInteractionRegistered(){return Tn.userInteractionRegistered}static registerWaitForAllowAudio(e){Tn.registerWaitForInteraction(e)}clip="";playOnAwake=!1;preload=!0;playInBackground=!0;get isPlaying(){return this.sound?.isPlaying??!1}get duration(){return this.sound?.buffer?.duration}get time01(){const e=this.duration;return e&&this.sound?this.sound?.context.currentTime/e:0}set time01(e){const t=this.duration;t&&this.sound&&(this.time=e*t)}get time(){return this.sound?.source?this.sound.source?.context.currentTime-this._lastContextTime+this.sound.offset:0}set time(e){if(this.sound){if(e===this.sound.offset)return;const t=this.isPlaying;this.stop(),this.sound.offset=e,t&&this.play()}}get loop(){return this.sound&&(this._loop=this.sound.getLoop()),this._loop}set loop(e){this._loop=e,this.sound&&this.sound.setLoop(e)}get spatialBlend(){return this._spatialBlend}set spatialBlend(e){e!==this._spatialBlend&&(this._spatialBlend=e,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(e){this._minDistance!==e&&(this._minDistance=e,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(e){this._maxDistance!==e&&(this._maxDistance=e,this._needUpdateSpatialDistanceSettings=!0)}_spatialBlend=0;_minDistance=1;_maxDistance=100;get volume(){return this._volume}set volume(e){this._volume=e,this.sound&&!this.context.application.muted&&(Ot&&console.log(this.name,"audio set volume",e),this.sound.setVolume(e))}_volume=1;set pitch(e){this.sound&&this.sound.setPlaybackRate(e)}get pitch(){return this.sound?this.sound.getPlaybackRate():1}rollOffMode=0;_loop=!1;sound=null;helper=null;wasPlaying=!1;audioLoader=null;shouldPlay=!1;_lastClipStartedLoading=null;_audioElement=null;get Sound(){if(!this.sound&&qs.userInteractionRegistered){let e=this.gameObject.getComponent(ko)??this.context.mainCamera.getComponent(ko)??pc(ko,this.context,!1);!e&&this.context.mainCamera&&(e=this.context.mainCamera.addComponent(ko)),e?.listener?(this.sound=new fS(e.listener),this.gameObject?.add(this.sound)):Ot&&console.warn("No audio listener found in scene - can not play audio")}return this.sound}get ShouldPlay(){return this.shouldPlay}get audioContext(){return this.sound?.context}awake(){Ot&&console.log("[AudioSource]",this),this.audioLoader=new am,this.playOnAwake&&(this.shouldPlay=!0),this.preload&&typeof this.clip=="string"&&this.audioLoader.load(this.clip,this.createAudio,()=>{},console.error)}onEnable(){this.sound&&this.gameObject.add(this.sound),qs.userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():qs.registerWaitForAllowAudio(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.onNewClip(this.clip)}),globalThis.addEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.addEventListener(Ym.MuteChanged,this.onApplicationMuteChanged)}onDisable(){globalThis.removeEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.removeEventListener(Ym.MuteChanged,this.onApplicationMuteChanged),this.pause()}onVisibilityChanged=()=>{switch(document.visibilityState){case"hidden":(this.playInBackground===!1||G.isMobileDevice())&&(this.wasPlaying=this.isPlaying,this.isPlaying&&this.pause());break;case"visible":Ot&&console.log("visible",this.enabled,this.playOnAwake,!this.isPlaying,qs.userInteractionRegistered,this.wasPlaying),this.enabled&&this.playOnAwake&&!this.isPlaying&&qs.userInteractionRegistered&&this.wasPlaying&&this.play();break}};onApplicationMuteChanged=()=>{this.context.application.muted?this.sound?.setVolume(0):this.sound?.setVolume(this.volume)};createAudio=e=>{if(this.destroyed){Ot&&console.warn("AudioSource destroyed, not creating audio",this.name);return}Ot&&console.log("AudioBuffer finished loading",e);const t=this.Sound;if(!t){Ot&&console.warn("Failed getting sound?",this.name);return}t.isPlaying&&t.stop(),e&&t.setBuffer(e),t.loop=this._loop,this.context.application.muted?t.setVolume(0):t.setVolume(this.volume),t.autoplay=this.shouldPlay&&qs.userInteractionRegistered,this.applySpatialDistanceSettings(),t.isPlaying&&t.stop(),qs.registerWaitForAllowAudio(this.__onAllowAudioCallback)};__onAllowAudioCallback=()=>{this.shouldPlay&&this.play()};applySpatialDistanceSettings(){const e=this.sound;if(!e)return;this._needUpdateSpatialDistanceSettings=!1;const t=D.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(Ot&&console.log(this.name,this._minDistance,this._maxDistance,this.spatialBlend,"Ref distance="+t),e.setRefDistance(t),e.setMaxDistance(Math.max(.01,this._maxDistance)),this.rollOffMode){case 0:e.setDistanceModel("exponential");break;case 1:e.setDistanceModel("linear");break;case 2:console.warn("Custom rolloff for AudioSource is not supported: "+this.name);break}this.spatialBlend>0?Ot&&!this.helper&&(this.helper=new wC(e,e.getRefDistance()),e.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}async onNewClip(e){if(e&&(this.clip=e),typeof e=="string")if(Ot&&console.log(e),e.endsWith(".mp3")||e.endsWith(".wav")){if(this.audioLoader||(this.audioLoader=new am),this.shouldPlay=!0,this._lastClipStartedLoading===e){Ot&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=e,Ot&&console.log("load audio",e);const t=await this.audioLoader.loadAsync(e).catch(console.error);if(this.destroyed)return;this._lastClipStartedLoading===e&&(this._lastClipStartedLoading=null),t&&this.createAudio(t)}else console.warn("Unsupported audio clip type",e);else this.shouldPlay=!0,this.createAudio()}play(e=void 0){!e&&this.clip&&(e=this.clip),e!==void 0&&typeof e!="string"&&!(e instanceof MediaStream)&&(E()&&console.warn("Called play on AudioSource with unknown argument type:",e+`
949
+ Could not find method ${r.method} on object ${l.name}`,l,typeof l[r.method])};if(typeof l[r.method]!="function"){let d=!1,p=l;for(;p;){const m=Object.getOwnPropertyDescriptor(p,r.method);if(m&&(m.writable===!0||m.set)){d=!0;break}p=Object.getPrototypeOf(p)}!d&&(E()||gt)&&h()}}if(l){let h=r.argument;if(h!==void 0?h=a(h):r.arguments!==void 0&&(h=r.arguments.map(a)),!l[r.method])console.warn(`EventList method not found: "${r.method}" on ${l?.name}`);else{h!==void 0&&!Array.isArray(h)&&(h=[h]);const d=new Oo(l,r.method,h,r.enabled);i.push(d)}}else E()&&console.warn(`[Dev] EventList: Could not find event listener in scene (${t.object?.name})`,r)}const n=new ce(i);gt&&console.log(n);const s=t.target;return s!==void 0&&t.path!==void 0&&n.setEventTarget(t.path,s),n}}}const ZM=new KM,_u=new WeakMap,JM=Re.prototype.clone;Re.prototype.clone=function(){const o=JM.call(this);return _u.has(o)||_u.set(o,this),o};class fw extends Xi{constructor(){super([ho,jn])}onSerialize(e,t){}onDeserialize(e,t){if(e instanceof Re&&t.type===ho){let i=e;_u.has(i)&&(i=_u.get(i)),i.isRenderTargetTexture=!0,i.flipY=!0,i.offset.y=1,i.repeat.y=-1,i.needsUpdate=!0,i.mipmaps=[],i instanceof pS&&(i.isCompressedTexture=!1,i.format=ad);const n=new ho(i.image.width,i.image.height,{colorSpace:po});return n.texture=i,n}}}new fw;class yw extends Xi{constructor(){super([URL])}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"&&e.length>0)return ls(t.gltfId,e)}}new yw;var eR=Object.defineProperty,tR=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&eR(e,t,n),n};class Wa extends M{awake(){ei.createIfNoneExists(this.context)}onEnable(){ei.get(this.context)?.register(this)}onDisable(){ei.get(this.context)?.unregister(this)}}class ki extends Wa{targets=null;raycastHits=[];ignoreSkinnedMeshes=!1;start(){this.targets=[this.gameObject]}performRaycast(e=null){if(!this.targets)return null;e??=new us,e.targets=this.targets,e.results=this.raycastHits,e.useAcceleratedRaycast=!0;const t=e.testObject;this.ignoreSkinnedMeshes&&(e.testObject=n=>n instanceof ss?"continue in children":t?t(n):!0);const i=this.context.physics.raycast(e);return e.testObject=t,i}}tR([u()],ki.prototype,"ignoreSkinnedMeshes");class vu extends ki{constructor(){super(),this.ignoreSkinnedMeshes=!0}}class ra extends Wa{static allow=!0;performRaycast(e){if(!K.active||!ra.allow||!e?.ray)return null;const t=e.ray.origin;return this.context.physics.sphereOverlap(t,.015,!1,!0)}}class tf{static getObject(e){const t=e[Si];return t&&(t.isComponent===!0?e=t.gameObject:e=t),e}static isInteractable(e,t){if(t&&(t.canvasGroup=void 0,t.graphic=void 0),e==null||!e.visible||(e=this.getObject(e),!e.visible))return!1;const i=this.tryFindCanvasGroup(e);if(i?.isCanvasGroup===!0&&(t&&(t.canvasGroup=i),i.blocksRaycasts===!1||i.interactable===!1))return!1;const n=wr(e,s=>{if(s.isGraphic===!0)return s},!1);return t&&n?.isGraphic===!0&&(t.graphic=n),!(n?.raycastTarget===!1||n?.layer===2)}static tryFindCanvasGroup(e){if(!e)return null;const t=wr(e,i=>{const n=i;if(n.blocksRaycasts!==void 0&&n.interactable!==void 0)return n},!1);return t!==void 0?t:this.tryFindCanvasGroup(e.parent)}}function nf(o){return o[Si]||(o.parent?nf(o.parent):null)}function iR(o){return o.isUI===!0||typeof o[Si]=="object"}function wu(o,e){if(!o)return;const t=o.material;if(t?.isMaterial===!0){const i=o.parent;i&&i.isText,t.side=e.doubleSided??!0?vi:as,t.shadowSide=e.doubleSided?vi:as,o.castShadow=e.castShadows?e.castShadows:!1,o.receiveShadow=e.receiveShadows?e.receiveShadows:!1}for(const i of o.children)wu(i,e)}function Va(o,e,t){o[e]===void 0&&console.warn("Field",e,"is undefined on",o);const i=Proxy.revocable(o[e],{set(r,a,l,c){const h=r[a],d=Reflect.set(r,a,l,c);return t(l,h),d}}),n=i.revoke,s=o[e];return i.revoke=()=>{o[e]=s,n()},o[e]=i.proxy,i}const bw=Symbol("Scheduled action");function nR(o,e,t=we.OnBeforeRender){let i=o[bw];i||(i=o[bw]={});const n=e.name;i[t]||(i[t]={});const s=i[t];if(s[n])return;function*r(){e?.call(o),s[n]=null}const a=o.startCoroutine(r(),t);s[n]=a}const _s=w("debugeventsystem");var of=(o=>(o.BeforeHandleInput="BeforeHandleInput",o.AfterHandleInput="AfterHandleInput",o))(of||{});Kv(o=>{ei.createIfNoneExists(o)});class ei extends M{static ensureUpdateMeshUI(e,t,i=!1){Oc.update(e,t,i)}static markUIDirty(e){Oc.markDirty()}static createIfNoneExists(e){e.scene.getComponent(ei)||e.scene.addComponent(ei)}static get(e){return this.createIfNoneExists(e),e.scene.getComponent(ei)}static get instance(){return this.get(z.Current)}raycaster=[];register(e){e&&this.raycaster&&!this.raycaster.includes(e)&&this.raycaster?.push(e)}unregister(e){const t=this.raycaster?.indexOf(e);t!==void 0&&t!==-1&&this.raycaster?.splice(t,1)}get hasActiveUI(){return this.currentActiveMeshUIComponents.length>0}get isHoveringObjects(){return this.hoveredByID.size>0}awake(){this.gameObject!==this.context.scene&&(console.debug(`[Needle Engine] EventSystem is only allowed on the scene root. Disabling EventSystem on '${this.gameObject.name}'`),this.enabled=!1)}start(){this.context.scene.getComponent(Wa)||this.context.scene.addComponent(ki)}onEnable(){this.context.input.addEventListener(Ee.PointerDown,this.onPointerEvent),this.context.input.addEventListener(Ee.PointerUp,this.onPointerEvent),this.context.input.addEventListener(Ee.PointerMove,this.onPointerEvent)}onDisable(){this.context.input.removeEventListener(Ee.PointerDown,this.onPointerEvent),this.context.input.removeEventListener(Ee.PointerUp,this.onPointerEvent),this.context.input.removeEventListener(Ee.PointerMove,this.onPointerEvent)}pressedByID=new Map;hoveredByID=new Map;onBeforeRender(){this.resetMeshUIStates()}onPointerEvent=e=>{if(e===void 0||e.propagationStopped||e.defaultPrevented||e.used)return;const t=new Jh(this.context.input,e);this._currentPointerEventName=e.type,t.inputSource=this.context.input,t.isClick=e.isClick,t.isDoubleClick=e.isDoubleClick,t.isDown=e.type==Ee.PointerDown,t.isUp=e.type==Ee.PointerUp,t.isPressed=this.context.input.getPointerPressed(e.pointerId);const i=new us;e.hasRay?i.ray=e.ray:i.screenPoint=this.context.input.getPointerPositionRC(e.pointerId),i.allowSlowRaycastFallback=e.isClick||e.isDoubleClick;const n=this.performRaycast(i);if(_s&&(t.isDown?console.log("DOWN",{id:t.pointerId,hits:n.length}):t.isUp&&console.log("UP",{id:t.pointerId,hits:n.length}),t.isClick&&console.log("CLICK",{id:t.pointerId,hits:n.length})),n){for(const r of n)r.event=e,e.intersections.push(r);e.origin.onPointerHits&&e.origin.onPointerHits({sender:this,event:e,hits:n})}_s&&t.isClick&&Te("EventSystem: "+t.pointerId+" - "+this.context.time.frame+" - Up:"+t.isUp+", Down:"+t.isDown);const s={sender:this,args:t,hasActiveUI:this.currentActiveMeshUIComponents.length>0};this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:s})),this.handleIntersections(n,t),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:s}))};_sortedHits=[];_testObjectsCache=new Map;_currentlyActiveRaycaster=null;_currentPointerEventName=null;shouldRaycastObject=e=>{const t=e&&"getComponent"in e?e.getComponent(Wa):null;if(t&&t!=this._currentlyActiveRaycaster)return!1;let i=null;if(iR(e)&&(i=e[Si]?.gameObject),this._testObjectsCache.has(e)||i&&this._testObjectsCache.has(i))return this._testObjectsCache.get(e)===!1?"continue in children":!0;{let n=fu(e,this._currentPointerEventName);if(!n&&i&&(n=fu(i,this._currentPointerEventName)),n){this._testObjectsCache.set(e,!0);for(const s of e.children)this.shouldRaycastObject_AddToYesCache(s);return!0}return this._testObjectsCache.set(e,!1),"continue in children"}};shouldRaycastObject_AddToYesCache(e){this._testObjectsCache.set(e,!0);for(const t of e.children)this.shouldRaycastObject_AddToYesCache(t)}performRaycast(e){if(!this.raycaster)return null;this._testObjectsCache.clear(),this._sortedHits.length=0,e.testObject=this.shouldRaycastObject;for(const t of this.raycaster){if(!t.activeAndEnabled)continue;this._currentlyActiveRaycaster=t;const i=t.performRaycast(e);this._currentlyActiveRaycaster=null,i&&i.length>0&&this._sortedHits.push(...i)}return this._sortedHits.sort((t,i)=>t.distance-i.distance),this._sortedHits}assignHitInformation(e,t){t?(e.intersection=t,e.point=t.point,e.normal=t.normal,e.face=t.face,e.distance=t.distance,e.instanceId=t.instanceId):(e.intersection=void 0,e.point=void 0,e.normal=void 0,e.face=void 0,e.distance=void 0,e.instanceId=void 0)}handleIntersections(e,t){if(e?.length){e=this.sortCandidates(e);for(const n of e){if(t.event.immediatePropagationStopped)return!1;if(this.assignHitInformation(t,n),this.handleEventOnObject(n.object,t))return!0}}this.assignHitInformation(t,e?.[0]),this.invokePointerCapture(t);const i=this.hoveredByID.get(t.pointerId);return i&&this.propagatePointerExit(i.obj,i.data,null),this.hoveredByID.delete(t.pointerId),t.isUp&&(this.pressedByID.get(t.pointerId)?.handlers.forEach(n=>this.invokeOnPointerUp(t,n)),this.pressedByID.delete(t.pointerId)),!1}_sortingBuffer=[];_noDepthTestingResults=[];sortCandidates(e){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let t=0;t<e.length;t++){const i=e[t],n=i.object;if(n.material&&n.material.depthTest===!1){this._noDepthTestingResults.push(i);continue}this._sortingBuffer.push(i)}for(const t of this._sortingBuffer)this._noDepthTestingResults.push(t);return this._noDepthTestingResults}out={};handleEventOnObject(e,t){if(!this.testIsVisible(e))return t.isClick&&_s&&console.log("not allowed",e),!1;if(t.pointerId===void 0)return _s&&console.error("Event without pointer can't be handled",t),!1;t.object=e;const i=e.parent,n=t.isClick??!1;let s=null;if(i&&i.isUI){const c=(t.isPressed||t.isClick)??!1;if(i[Si]){const h=i[Si].gameObject;if(h){if(!tf.isInteractable(h,this.out))return!1;s=this.out.canvasGroup??null,this.handleMeshUIIntersection(e,c),e=h}}}n&&_s&&console.log(this.context.time.frame,e);const r=this.hoveredByID.get(t.pointerId),a=r?.obj;a!==e&&a&&this.propagatePointerExit(a,r.data,e);const l=this.hoveredByID.get(t.pointerId);if(l?(l.obj=e,l.data=t):this.hoveredByID.set(t.pointerId,{obj:e,data:t}),t.isDown){const c=this.pressedByID.get(t.pointerId);c?(c.obj=e,c.data=t):this.pressedByID.set(t.pointerId,{obj:e,data:t,handlers:new Set})}return(s===null||s.interactable)&&this.handleMainInteraction(e,t,a??null),!0}propagate(e,t){for(;e;)x.foreachComponent(e,i=>{t(i)},!1),e=e.parent}handleMainInteraction(e,t,i){const n=this.pressedByID.get(t.pointerId),s=i!==e;let r=!0;switch(t.event.pointerType){case"mouse":case"touch":const a=this.context.input.getPointerPositionLastFrame(t.pointerId),l=this.context.input.getPointerPosition(t.pointerId);r=a&&!D.approximately(a,l);break}this.propagate(e,a=>{const l=a;l.interactable!==!1&&(!l.activeAndEnabled||!l.enabled||(l.onPointerEnter&&s&&this.handlePointerEnter(l,t),t.isDown&&l.onPointerDown&&(l.onPointerDown(t),n?.handlers.add(l),this.handlePointerCapture(t,l)),l.onPointerMove&&(r&&l.onPointerMove(t),this.handlePointerCapture(t,l)),t.isUp&&(l.onPointerUp&&(this.invokeOnPointerUp(t,l),n?.handlers.delete(l)),l.onPointerExit&&t.event?.pointerType===Rd.Touch&&(this.handlePointerExit(l,t),this.hoveredByID.delete(t.pointerId))),t.isClick&&l.onPointerClick&&l.onPointerClick(t)))}),t.isUp&&(n?.handlers.forEach(a=>{this.invokeOnPointerUp(t,a)}),this.pressedByID.delete(t.pointerId))}propagatePointerExit(e,t,i){this.propagate(e,n=>{if(!n.gameObject||n.destroyed)return;const s=n;if(s.onPointerExit||s.onPointerEnter){if(i&&this.isChild(i,n.gameObject))return;this.handlePointerExit(s,t)}})}invokeOnPointerUp(e,t){t.onPointerUp?.call(t,e),this.releasePointerCapture(e,t)}handlePointerEnter(e,t){e.onPointerEnter&&this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!0)&&e.onPointerEnter(t),this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!1)}handlePointerExit(e,t){e.onPointerExit&&this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!0)&&e.onPointerExit(t),this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!1)}updatePointerState(e,t,i,n){let s=e[i];if(n)return s&&s.includes(t)?!1:(s=s||[],s.push(t),e[i]=s,!0);{if(!s||!s.includes(t))return!1;const r=s.indexOf(t);return r!==-1&&s.splice(r,1),!0}}_capturedPointer={};handlePointerCapture(e,t){if(e.z__pointer_ctured){e.z__pointer_ctured=!1;const i=e.pointerId;if(t.onPointerMove){const n=this._capturedPointer[i]||[];n.push(t),this._capturedPointer[i]=n}else E()&&!t.z__warned_no_pointermove&&(t.z__warned_no_pointermove=!0,console.warn("PointerCapture was requested but the component doesn't implement onPointerMove. It will not receive any pointer events"))}else e.z__pointer_cture_rleased&&(e.z__pointer_cture_rleased=!1,this.releasePointerCapture(e,t))}releasePointerCapture(e,t){const i=e.pointerId;if(this._capturedPointer[i]){const n=this._capturedPointer[i].indexOf(t);n!==-1&&(this._capturedPointer[i].splice(n,1),_s&&console.log("released pointer capture",i,t,this._capturedPointer))}}invokePointerCapture(e){if(e.event.type===Ee.PointerMove){const t=e.pointerId,i=this._capturedPointer[t];if(i){_s&&console.log("Captured",t,i);for(let n=0;n<i.length;n++){const s=i[n];if(s.destroyed){i.splice(n,1),n--;continue}s.onPointerMove?.call(s,e)}}}}pointerEnterSymbol=Symbol("pointerEnter");pointerExitSymbol=Symbol("pointerExit");isChild(e,t){return!e||!t?!1:e===t?!0:e.parent?this.isChild(e.parent,t):!1}handleMeshUiObjectWithoutShadowDom(e,t){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,t)}currentActiveMeshUIComponents=[];handleMeshUIIntersection(e,t){const i=Oc.updateState(e,t);return i&&this.currentActiveMeshUIComponents.push(i),i!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&Oc.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){const t=this.currentActiveMeshUIComponents[e];Oc.resetState(t)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?x.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}}class Oc{static lastSelected=null;static lastUpdateFrame=[];static needsUpdate=!1;static markDirty(){this.needsUpdate=!0}static update(e,t,i=!1){if(i){e.update();return}const n=t.time.frameCount;for(const s of this.lastUpdateFrame)if(s.context===t){if(n===s.frame)return;s.frame=n;let r=this.needsUpdate||n<1;s.nextUpdate<=n&&(r=!0),r&&(_s&&console.log("Update threemeshui"),this.needsUpdate=!1,s.nextUpdate=n+60,e.update());return}this.lastUpdateFrame=[{context:t,frame:n,nextUpdate:n+60}],e.update(),this.needsUpdate=!1}static updateState(e,t){let i=null;if(e&&(i=this.findBlockOrTextInParent(e),i&&i!==this.lastSelected)){if(i.interactable===!1)return null;this.needsUpdate=!0}return i}static resetLastSelected(){const e=this.lastSelected;e&&(this.lastSelected=null,this.resetState(e))}static resetState(e){e&&(this.needsUpdate=!0)}static findBlockOrTextInParent(e){return e?e.isBlock||e.isText?e:this.findBlockOrTextInParent(e.parent):null}}var oR=Object.defineProperty,Ie=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&oR(e,t,n),n};const Gt=w("debugorbit"),sf=w("freecam"),kc=w("debugcamerafit"),xu=w("smoothcam"),sR={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let rf;class Mc extends CustomEvent{constructor(e,t){super("target-reached",{detail:{controls:e,type:t}})}}class fe extends M{get isCameraController(){return!0}get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(e){this.controls?.addEventListener("start",e)}autoTarget=!0;autoFit=!1;enableRotate=!0;autoRotate=!1;autoRotateSpeed=1;minAzimuthAngle=1/0;maxAzimuthAngle=1/0;minPolarAngle=0;maxPolarAngle=Math.PI;enableKeys=!1;enableDamping=!0;dampingFactor=.1;enableZoom=!0;minZoom=0;maxZoom=1/0;zoomSpeed=1;zoomToCursor=!1;enablePan=!0;lookAtConstraint=null;lookAtConstraint01=1;allowInterrupt=!0;middleClickToFocus=!0;doubleClickToFocus=!0;clickBackgroundToFitScene=2;get targetElement(){return this._controls?.domElement??this._targetElement}set targetElement(e){this._targetElement=e,this._controls&&this._controls.domElement!==e&&(this._controls.disconnect(),this._controls.domElement=e,this._controls.connect())}_targetElement=null;debugLog=!1;get targetLerpSpeed(){return 5}set targetLerpSpeed(e){this.targetLerpDuration=1/e}targetLerpDuration=1;rotateLeft(e){this._controls?._rotateLeft(e)}rotateUp(e){this._controls?._rotateUp(e)}pan(e,t){this._controls?._pan(e,t)}zoomIn(e){e>0?this._controls?._dollyIn(1-e):e<0&&this._controls?._dollyOut(1+e)}_controls=null;_cameraObject=null;_lookTargetLerpActive=!1;_lookTargetStartPosition=new b;_lookTargetEndPosition=new b;_lookTargetLerp01=0;_lookTargetLerpDuration=0;_cameraLerpActive=!1;_cameraStartPosition=new b;_cameraEndPosition=new b;_cameraLerp01=0;_cameraLerpDuration=0;_fovLerpActive=!1;_fovLerpStartValue=0;_fovLerpEndValue=0;_fovLerp01=0;_fovLerpDuration=0;_inputs=0;_enableTime=0;_startedListeningToKeyEvents=!1;_eventSystem;_afterHandleInputFn;_camera=null;_syncedTransform;_didSetTarget=0;awake(){Gt&&console.debug("OrbitControls",this),this._didSetTarget=0,this._startedListeningToKeyEvents=!1}start(){this._eventSystem=ei.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(of.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){this._controls?.dispose(),this._eventSystem?.removeEventListener(of.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._didSetTarget=0,this._enableTime=this.context.time.time;const e=x.getComponent(this.gameObject,si);this._camera=e;let t=e?.threeCamera;if(!t&&this.gameObject instanceof de&&(t=this.gameObject),t&&Em(t,this,!0),!this._controls&&t instanceof O){this._cameraObject=t;const i=this.targetElement??this.context.renderer.domElement,n=t?.quaternion.clone();this._controls=new Y0(t,i),t?.quaternion.copy(n),rf===void 0&&(rf={...this._controls.keys});const s=Z(t),r=this.gameObject.worldForward,a=s.clone().sub(r.multiplyScalar(2.5));this._controls.target.copy(a)}if(this._controls)if(sf&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,G.isMobileDevice()&&(this.doubleClickToFocus=!0)),this._controls.addEventListener("start",this.onControlsChangeStarted),this._controls.addEventListener("endMovement",this.onControlsChangeEnded),!this._startedListeningToKeyEvents&&this.enableKeys)this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(this.context.domElement);else try{this._controls.stopListenToKeyEvents()}catch{}this._syncedTransform=x.getComponent(this.gameObject,vn)??void 0,this.context.pre_render_callbacks.push(this.__onPreRender),this._activePointerEvents=[],this.context.input.addEventListener("pointerdown",this._onPointerDown,{queue:ii.Early}),this.context.input.addEventListener("pointerdown",this._onPointerDownLate,{queue:ii.Late}),this.context.input.addEventListener("pointerup",this._onPointerUp,{queue:ii.Early}),this.context.input.addEventListener("pointerup",this._onPointerUpLate,{queue:ii.Late})}onDisable(){if(this._camera?.threeCamera&&Em(this._camera.threeCamera,this,!1),this._controls){this._controls.enabled=!1,this._controls.autoRotate=!1,this._controls.removeEventListener("start",this.onControlsChangeStarted),this._controls.removeEventListener("endMovement",this.onControlsChangeEnded);try{this._controls.stopListenToKeyEvents()}catch{}this._startedListeningToKeyEvents=!1}this._activePointerEvents.length=0,this.context.input.removeEventListener("pointerdown",this._onPointerDown),this.context.input.removeEventListener("pointerdown",this._onPointerDownLate),this.context.input.removeEventListener("pointerup",this._onPointerUp),this.context.input.removeEventListener("pointerup",this._onPointerUpLate)}_activePointerEvents;_lastTimeClickOnBackground=-1;_clickOnBackgroundCount=0;_onPointerDown=e=>{this._activePointerEvents.push(e)};_onPointerDownLate=e=>{e.used&&this._controls&&(this._controls.enabled=!1)};_onPointerUp=e=>{for(let t=this._activePointerEvents.length-1;t>=0;t--){const i=this._activePointerEvents[t];if(i.pointerId===e.pointerId&&i.button===e.button){this._activePointerEvents.splice(t,1);break}}if(this.clickBackgroundToFitScene>0&&e.isClick&&e.button===0){if(e.hasRay||e.intersections.push(...this.context.physics.raycast()),e.intersections.length<=0){const t=this.context.time.time-this._lastTimeClickOnBackground;this._lastTimeClickOnBackground=this.context.time.time,this.clickBackgroundToFitScene<=1||t<this.clickBackgroundToFitScene*.15?(this._clickOnBackgroundCount+=1,this._clickOnBackgroundCount>=this.clickBackgroundToFitScene-1&&this.fitCamera(this.context.scene.children,{immediate:!1})):this._clickOnBackgroundCount=0}Gt&&console.log(this.clickBackgroundToFitScene,e.intersections.length,this._clickOnBackgroundCount)}};_onPointerUpLate=e=>{this.doubleClickToFocus&&e.isDoubleClick&&!e.used&&this.setTargetFromRaycast()};updateTargetNow(e){const t=new ns(this._cameraObject?.worldPosition,this._cameraObject?.worldForward.multiplyScalar(-1)),i=this.context.physics.raycastFromRay(t,e),n=i.length>0?i[0]:void 0;n&&n.distance>this.minZoom&&n.distance<this.maxZoom?(Gt&&F.DrawWireSphere(n.point,.1,16711680,2),this._controls?.target.copy(i[0].point)):Gt&&console.log("OrbitControls: No hit found when updating target",{hits:[...i]})}_orbitStartAngle=0;_zoomStartDistance=0;onControlsChangeStarted=()=>{Gt&&console.debug("OrbitControls: Change started"),this._controls&&(this._orbitStartAngle=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle(),this._zoomStartDistance=this._controls.getDistance()),this._syncedTransform&&this._syncedTransform.requestOwnership()};onControlsChangeEnded=()=>{if(Gt&&console.debug("OrbitControls: Change ended",{autoTarget:this.autoTarget}),this._controls&&this.autoTarget){const e=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle()-this._orbitStartAngle;Math.abs(e)<.01?(Gt&&console.debug("OrbitControls: Update target",{deltaAngle:e}),this.updateTargetNow({allowSlowRaycastFallback:!1})):Gt&&console.debug("OrbitControls: No target update",{deltaAngle:e})}};_shouldDisable=!1;afterHandleInput(e){e.detail.args.pointerId===0&&(e.detail.args.isDown?this._controls&&this._eventSystem&&(this._shouldDisable=this._eventSystem.hasActiveUI):(!e.detail.args.isPressed||e.detail.args.isUp)&&(this._shouldDisable=!1))}onPausedChanged(e){this._controls&&e&&(this._controls.enabled=!1)}onBeforeRender(){if(!!this._controls){if(this._cameraObject!==this.context.mainCamera){this._controls.enabled=!1;return}if(this._controls.enabled=!0,(this.context.input.getPointerDown(1)||this.context.input.getPointerDown(2)||this.context.input.mouseWheelChanged||this.context.input.getPointerPressed(0)&&this.context.input.getPointerPositionDelta(0)?.length())&&(this._inputs+=1),this._inputs>0&&this.allowInterrupt&&(this.enableRotate&&(this.autoRotate=!1),this._cameraLerpActive=!1,this._lookTargetLerpActive=!1),this._inputs=0,this.autoTarget&&this._didSetTarget++===0){const e=x.getComponent(this.gameObject,si);if(e&&!this.setLookTargetFromConstraint()){this.debugLog&&console.log("NO TARGET");const t=Z(e.threeCamera),i=Math.max(.01,t.length()),n=new b(0,0,-i).applyMatrix4(e.threeCamera.matrixWorld);Gt&&F.DrawLine(t,n,5592575,10),this.setLookTargetPosition(n,!0)}if(!this.setLookTargetFromConstraint()){const t=new us;t.screenPoint=new J(0,0),t.lineThreshold=.1;const i=this.context.physics.raycast(t);i.length>0&&this.setLookTargetPosition(i[0].point,!0),kc&&console.log("OrbitControls hits",...i)}}if(this.middleClickToFocus&&this.context.input.getPointerClicked(1)&&this.setTargetFromRaycast(),this._lookTargetLerpActive||this._cameraLerpActive||this._fovLerpActive){if(this._cameraLerpActive&&this._cameraObject)if(this._cameraLerp01+=this.context.time.deltaTime/this._cameraLerpDuration,this._cameraLerp01>=1)this._cameraObject.position.copy(this._cameraEndPosition),this._cameraLerpActive=!1,this.dispatchEvent(new Mc(this,"camera"));else{const e=D.easeInOutCubic(this._cameraLerp01);this._cameraObject.position.lerpVectors(this._cameraStartPosition,this._cameraEndPosition,e)}if(this._lookTargetLerpActive)if(this._lookTargetLerp01+=this.context.time.deltaTime/this._lookTargetLerpDuration,this._lookTargetLerp01>=1)this.lerpLookTarget(this._lookTargetEndPosition,this._lookTargetEndPosition,1),this._lookTargetLerpActive=!1,this.dispatchEvent(new Mc(this,"lookat"));else{const e=D.easeInOutCubic(this._lookTargetLerp01);this.lerpLookTarget(this._lookTargetStartPosition,this._lookTargetEndPosition,e)}if(this._fovLerpActive&&this._cameraObject){const e=this._cameraObject;if(this._fovLerp01+=this.context.time.deltaTime/this._fovLerpDuration,this._fovLerp01>=1)e.fov=this._fovLerpEndValue,this._fovLerpActive=!1;else{const t=D.easeInOutCubic(this._fovLerp01);e.fov=D.lerp(this._fovLerpStartValue,this._fovLerpEndValue,t)}e.updateProjectionMatrix()}}if(this._controls){if(this.debugLog&&(this._controls.domElement=this.context.renderer.domElement),this._controls.enabled=!this._shouldDisable&&this._camera===this.context.mainCameraComponent&&!this.context.isInXR&&!this._activePointerEvents.some(e=>e.used),this._controls.keys=this.enableKeys?rf:sR,this._controls.autoRotate=this.autoRotate,this._controls.autoRotateSpeed=this.autoRotateSpeed,this._controls.enableZoom=this.enableZoom,this._controls.zoomSpeed=this.zoomSpeed,this._controls.zoomToCursor=this.zoomToCursor,this._controls.enableDamping=this.enableDamping,this._controls.dampingFactor=this.dampingFactor,this._controls.enablePan=this.enablePan,this._controls.enableRotate=this.enableRotate,this._controls.minAzimuthAngle=this.minAzimuthAngle,this._controls.maxAzimuthAngle=this.maxAzimuthAngle,this._controls.minPolarAngle=this.minPolarAngle,this._controls.maxPolarAngle=this.maxPolarAngle,sf||(this._camera?.threeCamera?.type==="PerspectiveCamera"?(this._controls.minDistance=this.minZoom,this._controls.maxDistance=this.maxZoom,this._controls.minZoom=0,this._controls.maxZoom=1/0):(this._controls.minDistance=0,this._controls.maxDistance=1/0,this._controls.minZoom=this.minZoom,this._controls.maxZoom=this.maxZoom)),typeof xu=="number"||xu===!0){this._controls.enableDamping=!0;const e=typeof xu=="number"?xu:.99;this._controls.dampingFactor=Math.max(.001,1-Math.min(1,e))}this.allowInterrupt||(this._lookTargetLerpActive&&(this._controls.enablePan=!1),this._cameraLerpActive&&(this._controls.enableRotate=!1,this._controls.autoRotate=!1),(this._lookTargetLerpActive||this._cameraLerpActive)&&(this._controls.enableZoom=!1)),this.context.isInXR||(!sf&&this.lookAtConstraint?.locked&&!this._lookTargetLerpActive&&this.setLookTargetFromConstraint(0,this.lookAtConstraint01),this._controls.update(this.context.time.deltaTime),Gt&&F.DrawWireSphere(this._controls.target,.1,65280))}}}__onPreRender=()=>{const e=this.context.pre_render_callbacks.indexOf(this.__onPreRender);e>=0&&this.context.pre_render_callbacks.splice(e,1),this.autoFit&&(this.autoFit=!1,this.fitCamera({centerCamera:"y",immediate:!0,objects:this.scene.children}))};setCameraAndLookTarget(e,t=!1){if(!e)return(E()||Gt)&&console.warn("[OrbitControls] setCameraAndLookTarget target is null"),!1;if(!(e instanceof O)&&!(e instanceof si))return(E()||Gt)&&console.warn("[OrbitControls] setCameraAndLookTarget target is not an Object3D or Camera"),!1;e instanceof si&&(e=e.gameObject);const i=e.worldPosition,n=e.worldForward;e instanceof mS&&(Gt&&console.debug("[OrbitControls] setCameraAndLookTarget flip forward direction for camera"),n.multiplyScalar(-1));const s=new ns(i,n);return Gt&&F.DrawRay(s.origin,s.direction,16711680,10),this.setTargetFromRaycast(s,t)||this.setLookTargetPosition(s.at(2,$()),t),this.setCameraTargetPosition(i,t),!0}setCameraTargetPosition(e,t=!1){e&&(e instanceof O&&(e=Z(e)),this._cameraEndPosition||(this._cameraEndPosition=new b),this._cameraEndPosition.copy(e),t===!0?(this._cameraLerpActive=!1,this._cameraObject&&this._cameraObject.position.copy(this._cameraEndPosition)):this._cameraObject&&(this._cameraLerpActive=!0,this._cameraLerp01=0,this._cameraStartPosition.copy(this._cameraObject?.position),typeof t=="number"?this._cameraLerpDuration=t:this._cameraLerpDuration=this.targetLerpDuration))}get cameraLerpActive(){return this._cameraLerpActive}stopCameraLerp(){this._cameraLerpActive=!1}setFieldOfView(e,t=!1){if(!this._controls||typeof e!="number")return;const i=this._camera?.threeCamera;i&&(t===!0?i.fov=e:(this._fovLerpActive=!0,this._fovLerp01=0,this._fovLerpStartValue=i.fov,this._fovLerpEndValue=e,typeof t=="number"?this._fovLerpDuration=t:this._fovLerpDuration=this.targetLerpDuration))}setLookTargetPosition(e=null,t=!1){this._controls&&e&&(e instanceof O&&(e=Z(e)),this._lookTargetEndPosition.copy(e),this._didSetTarget++,Gt&&(console.warn("OrbitControls: setLookTargetPosition",e,t),F.DrawWireSphere(this._lookTargetEndPosition,.2,16711680,2)),t===!0?this.lerpLookTarget(this._lookTargetEndPosition,this._lookTargetEndPosition,1):(this._lookTargetLerpActive=!0,this._lookTargetLerp01=0,this._lookTargetStartPosition.copy(this._controls.target),typeof t=="number"?this._lookTargetLerpDuration=t:this._lookTargetLerpDuration=this.targetLerpDuration))}get lookTargetLerpActive(){return this._lookTargetLerpActive}stopLookTargetLerp(){this._lookTargetLerpActive=!1}setLookTargetFromConstraint(e=0,t=1){if(!this._controls||this.lookAtConstraint?.enabled===!1)return!1;const i=this.lookAtConstraint?.sources;if(i&&i.length>0){const n=i[e];if(n)return n.getWorldPosition(this._lookTargetEndPosition),this.lerpLookTarget(this._controls.target,this._lookTargetEndPosition,t),!0}return!1}lerpLookTarget(e,t,i){this._controls&&(i>=1?this._controls.target.copy(t):this._controls.target.lerpVectors(e,t,i),this.lookAtConstraint&&this.lookAtConstraint.setConstraintPosition(this._controls.target))}setTargetFromRaycast(e,t=!1){if(!this.controls)return!1;const i=e?this.context.physics.raycastFromRay(e):this.context.physics.raycast();for(const n of i)if(n.distance>0&&x.isActiveInHierarchy(n.object)){const s=nf(n.object);if(s&&s.canvas?.screenspace)break;return this.setLookTargetPosition(n.point,t),!0}return!1}fitCamera(e,t){if(this.context.isInXR){console.warn("[OrbitControls] Can not fit camera while XR session is active");return}let i;if(Array.isArray(e)||e&&"type"in e?i=e:e&&typeof e=="object"&&!(e instanceof O)&&!Array.isArray(e)&&(t=e,i=t.objects),i&&!Array.isArray(i)&&(i=[i]),(!Array.isArray(i)||i&&i.length<=0)&&(i=this.context.scene.children),!Array.isArray(i)||i.length<=0){console.warn("No objects to fit camera to...");return}const n=this._cameraObject,s=this._controls;if(!n||!s){console.warn("No camera or controls found to fit camera to objects...");return}t||(t={});const{immediate:r=!1,centerCamera:a,cameraNearFar:l="auto",fitOffset:c=1.1,fov:h=n?.fov}=t,d=new b,p=new b,m=Wt(i,void 0,this._camera?.threeCamera?.layers),f=m.clone();m.getCenter(p);const g=new b;if(m.getSize(g),n.updateMatrixWorld(),m.applyMatrix4(n.matrixWorldInverse),m.getSize(d),m.setFromCenterAndSize(p,d),Number.isNaN(d.x)||Number.isNaN(d.y)||Number.isNaN(d.z)){console.warn("Camera fit size resultet in NaN",n,m,[...i]);return}if(d.length()<=1e-10){kc&&console.warn("Camera fit size is zero",m,[...i]);return}const y=h,_=2*Math.atan(Math.tan(y*Math.PI/360/2)*n.aspect)/Math.PI*360,v=d.y/(2*Math.atan(Math.PI*y/360)),P=d.x/(2*Math.atan(Math.PI*_/360)),R=c*Math.max(v,P)+d.z/2;kc&&console.log("Fit camera to objects",{fitHeightDistance:v,fitWidthDistance:P,distance:R,verticalFov:y,horizontalFov:_}),this.maxZoom=R*10,this.minZoom=R*.01;const k=.05,A=p.clone();if(A.y-=d.y*k,t.targetOffset&&(t.targetOffset.x!==void 0&&(A.x+=t.targetOffset.x),t.targetOffset.y!==void 0&&(A.y+=t.targetOffset.y),t.targetOffset.z!==void 0&&(A.z+=t.targetOffset.z)),t.relativeTargetOffset&&(t.relativeTargetOffset.x!==void 0&&(A.x+=t.relativeTargetOffset.x*d.x),t.relativeTargetOffset.y!==void 0&&(A.y+=t.relativeTargetOffset.y*d.y),t.relativeTargetOffset.z!==void 0&&(A.z+=t.relativeTargetOffset.z*d.z)),this.setLookTargetPosition(A,r),this.setFieldOfView(t.fov,r),l==null||l=="auto"){const q=x.findObjectOfType($n),Y=q?q.radius:0,I=Math.max(g.x,g.y,g.z,Y);n.near=R/100,n.far=I+R*10,n.updateProjectionMatrix(),q&&(this.maxZoom=Math.max(Math.min(this.maxZoom,Y*.5),R))}const L=s.getDistance();L<this.minZoom&&(this.minZoom=L*.9),L>this.maxZoom&&(this.maxZoom=L*1.1);const N=p.clone();t.fitDirection?N.sub(new b().copy(t.fitDirection).multiplyScalar(1e6)):N.sub(n.worldPosition),a==="y"&&(N.y=0),N.normalize(),N.multiplyScalar(R),a==="y"&&(N.y+=-k*4*R);let j=p.clone().sub(N);t.cameraOffset&&(t.cameraOffset.x!==void 0&&(j.x+=t.cameraOffset.x),t.cameraOffset.y!==void 0&&(j.y+=t.cameraOffset.y),t.cameraOffset.z!==void 0&&(j.z+=t.cameraOffset.z)),t.relativeCameraOffset&&(t.relativeCameraOffset.x!==void 0&&(j.x+=t.relativeCameraOffset.x*d.x),t.relativeCameraOffset.y!==void 0&&(j.y+=t.relativeCameraOffset.y*d.y),t.relativeCameraOffset.z!==void 0&&(j.z+=t.relativeCameraOffset.z*d.z)),n.parent&&(j=n.parent.worldToLocal(j)),this.setCameraTargetPosition(j,r),(kc||t.debug)&&(F.DrawWireBox3(m,16777011,10),F.DrawWireBox3(f,65280,10),!this._haveAttachedKeyboardEvents&&kc&&(this._haveAttachedKeyboardEvents=!0,document.body.addEventListener("keydown",q=>{if(q.code==="KeyF"){let Y;this._cameraObject instanceof de&&(Y=Math.random()*Math.random()*170+10),this.fitCamera({objects:i,fitOffset:c,immediate:!1,fov:Y})}q.code==="KeyV"&&this._cameraObject instanceof de&&(this._cameraObject.fov=60)}))),this.onBeforeRender()}_haveAttachedKeyboardEvents=!1}Ie([u()],fe.prototype,"autoTarget"),Ie([u()],fe.prototype,"autoFit"),Ie([u()],fe.prototype,"enableRotate"),Ie([u()],fe.prototype,"autoRotate"),Ie([u()],fe.prototype,"autoRotateSpeed"),Ie([u()],fe.prototype,"minAzimuthAngle"),Ie([u()],fe.prototype,"maxAzimuthAngle"),Ie([u()],fe.prototype,"minPolarAngle"),Ie([u()],fe.prototype,"maxPolarAngle"),Ie([u()],fe.prototype,"enableKeys"),Ie([u()],fe.prototype,"enableDamping"),Ie([u()],fe.prototype,"dampingFactor"),Ie([u()],fe.prototype,"enableZoom"),Ie([u()],fe.prototype,"minZoom"),Ie([u()],fe.prototype,"maxZoom"),Ie([u()],fe.prototype,"zoomSpeed"),Ie([u()],fe.prototype,"enablePan"),Ie([u(Pr)],fe.prototype,"lookAtConstraint"),Ie([u()],fe.prototype,"lookAtConstraint01"),Ie([u()],fe.prototype,"allowInterrupt"),Ie([u()],fe.prototype,"middleClickToFocus"),Ie([u()],fe.prototype,"doubleClickToFocus"),Ie([u()],fe.prototype,"clickBackgroundToFitScene"),Ie([u()],fe.prototype,"targetLerpDuration");var rR=Object.defineProperty,aR=Object.getOwnPropertyDescriptor,qt=(o,e,t,i)=>{for(var n=i>1?void 0:i?aR(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&rR(e,t,n),n},kr=(o=>(o[o.None=0]="None",o[o.Skybox=1]="Skybox",o[o.SolidColor=2]="SolidColor",o[o.Uninitialized=4]="Uninitialized",o))(kr||{});const vs=w("debugcam"),_w=w("debugscreenpointtoray"),Lt=class Gh extends M{get isCamera(){return!0}get aspect(){return this._cam instanceof de?this._cam.aspect:this.context.domWidth/this.context.domHeight}set aspect(e){this._cam instanceof de&&this._cam.aspect!==e&&(this._cam.aspect=e,this._cam.updateProjectionMatrix())}get fieldOfView(){return this._cam instanceof de?this._cam.fov:this._fov}set fieldOfView(e){const t=this.fieldOfView!=e;if(this._fov=e,t&&this._cam&&this._cam instanceof de){if(this._fov===void 0){console.warn("Can not set undefined fov on PerspectiveCamera");return}this._cam.fov=this._fov,this._cam.updateProjectionMatrix()}}get nearClipPlane(){return this._nearClipPlane}set nearClipPlane(e){const t=this._nearClipPlane!=e;this._nearClipPlane=e,this._cam&&(t||this._cam.near!=e)&&(this._cam.near=e,this._cam.updateProjectionMatrix())}_nearClipPlane=.1;get farClipPlane(){return this._farClipPlane}set farClipPlane(e){const t=this._farClipPlane!=e;this._farClipPlane=e,this._cam&&(t||this._cam.far!=e)&&(this._cam.far=e,this._cam.updateProjectionMatrix())}_farClipPlane=1e3;applyClippingPlane(){this._cam&&(this._cam.near=this._nearClipPlane,this._cam.far=this._farClipPlane,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(e){if(typeof e=="string")switch(e){case"skybox":e=1;break;case"solidcolor":e=2;break;default:e=0;break}e!==this._clearFlags&&(this._clearFlags=e,this.applyClearFlagsIfIsActiveCamera())}orthographic=!1;orthographicSize=5;ARBackgroundAlpha=0;set cullingMask(e){this._cullingMask=e,this._cam&&(this._cam.layers.mask=e)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}_cullingMask=4294967295;set cullingLayer(e){this.cullingMask=(1<<e|0)>>>0}set backgroundBlurriness(e){e!==this._backgroundBlurriness&&(e===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(e,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}_backgroundBlurriness=void 0;set backgroundIntensity(e){e!==this._backgroundIntensity&&(e===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(e,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}_backgroundIntensity=void 0;set backgroundRotation(e){e!==this._backgroundRotation&&(e===void 0?this._backgroundRotation=void 0:this._backgroundRotation=e,this.applyClearFlagsIfIsActiveCamera())}get backgroundRotation(){return this._backgroundRotation}_backgroundRotation=void 0;set environmentIntensity(e){this._environmentIntensity=e}get environmentIntensity(){return this._environmentIntensity}_environmentIntensity=void 0;get backgroundColor(){return this._backgroundColor??null}set backgroundColor(e){e&&(this._backgroundColor||(this._backgroundColor=new se(1,1,1,1)),this._backgroundColor.copy(e),(!("alpha"in e)||e.alpha===void 0)&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera())}set targetTexture(e){this._targetTexture=e}get targetTexture(){return this._targetTexture}_targetTexture=null;_backgroundColor;_fov;_cam=null;_clearFlags=2;_skybox;get cam(){return this.threeCamera}get threeCamera(){return this.activeAndEnabled&&this.buildCamera(),this._cam}static _origin=new b;static _direction=new b;screenPointToRay(e,t,i){const n=this.threeCamera,s=Gh._origin;s.set(e,t,-1),this.context.input.convertScreenspaceToRaycastSpace(s),_w&&console.log("screenPointToRay",e.toFixed(2),t.toFixed(2),"now:",s.x.toFixed(2),s.y.toFixed(2),"isInXR:"+this.context.isInXR),s.z=-1,s.unproject(n);const r=Gh._direction.set(s.x,s.y,s.z),a=Z(n);return r.sub(a),r.normalize(),i?(i.set(a,r),i):new ns(a.clone(),r.clone())}_frustum;getFrustum(){return this._frustum||(this._frustum=new U0,this.updateFrustum()),this._frustum}updateFrustum(){this._frustum||(this._frustum=new U0),this._frustum.setFromProjectionMatrix(this.getProjectionScreenMatrix(this._projScreenMatrix,!0),this.context.renderer.coordinateSystem)}getProjectionScreenMatrix(e,t){return t&&this._projScreenMatrix.multiplyMatrices(this.threeCamera.projectionMatrix,this.threeCamera.matrixWorldInverse),e===this._projScreenMatrix?e:e.copy(this._projScreenMatrix)}_projScreenMatrix=new ee;awake(){_w&&window.addEventListener("pointerdown",e=>{const t=e.clientX,i=e.clientY;console.log("touch",t.toFixed(2),i.toFixed(2));const n=this.screenPointToRay(t,i),s="#"+Math.floor(Math.random()*16777215).toString(16);F.DrawRay(n.origin,n.direction,s,10)})}onEnable(){vs&&console.log(`Camera enabled: "${this.name}". ClearFlags=${kr[this._clearFlags]}`,this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),cR(this)),this.applyClearFlagsIfIsActiveCamera({applySkybox:!0})}onDisable(){this.context.removeCamera(this)}onLeaveXR(e){this.fieldOfView=this._fov}onBeforeRender(){if(this._cam&&(this._frustum&&this.updateFrustum(),this._clearFlags===2&&this.applyClearFlagsIfIsActiveCamera(),this._targetTexture)){this.context.isManagedExternally&&(this._warnedAboutExternalRenderer||(this._warnedAboutExternalRenderer=!0,console.warn("Rendering with external renderer is not supported yet. This may not work or throw errors. Please remove the the target texture from your camera: "+this.name,this.targetTexture))),this.context.composer;const e=this.context.renderer;if(e){const t=this.context.mainCameraComponent;this.applyClearFlags(),this._targetTexture.render(this.context.scene,this._cam,e),t?.applyClearFlags()}}}buildCamera(){if(this._cam)return;const e=this.gameObject.isCamera;let t=null;if(e?(t=this.gameObject,t?.layers.enableAll(),t instanceof de&&(this._fov=t.fov)):t=this.gameObject.children[0],t&&t.isCamera)t instanceof de&&(this._fov&&(t.fov=this._fov),t.near=this._nearClipPlane,t.far=this._farClipPlane,t.updateProjectionMatrix());else if(!this.orthographic)t=new de(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),this.fieldOfView&&(t.fov=this.fieldOfView),this.gameObject.add(t);else{const i=this.orthographicSize*100;t=new nd(window.innerWidth/-i,window.innerWidth/i,window.innerHeight/i,window.innerHeight/-i,this._nearClipPlane,this._farClipPlane),this.gameObject.add(t)}this._cam=t,this._cam.layers.mask=this._cullingMask,this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(e){this.context.mainCameraComponent===this&&this.applyClearFlags(e)}applyClearFlags(e){if(!this._cam){vs&&console.log("Camera does not exist (apply clear flags)");return}if(this.fieldOfView=this.fieldOfView,vs){const i=`[Camera] Apply ClearFlags: ${kr[this._clearFlags]} - "${this.name}"`;console.debug(i)}const t=this.context.domElement.getAttribute("background-image")||this.context.domElement.getAttribute("background-color");switch(this._clearFlags){case 0:return;case 1:if(Gh.backgroundShouldBeTransparent(this.context)&&(!this.ARBackgroundAlpha||this.ARBackgroundAlpha<.001)){this.context.scene.background=null,this.context.renderer.setClearColor(0,0);return}(!this.scene.background||!this._skybox||e?.applySkybox===!0)&&this.applySceneSkybox(),this._backgroundBlurriness!==void 0&&!this.context.domElement.getAttribute("background-blurriness")?this.context.scene.backgroundBlurriness=this._backgroundBlurriness:vs&&console.warn(`Camera "${this.name}" has no background blurriness`),this._backgroundIntensity!==void 0&&!this.context.domElement.getAttribute("background-intensity")&&(this.context.scene.backgroundIntensity=this._backgroundIntensity),this._backgroundRotation!==void 0&&!this.context.domElement.getAttribute("background-rotation")?this.context.scene.backgroundRotation=this._backgroundRotation:vs&&console.warn(`Camera "${this.name}" has no background intensity`);break;case 2:if(this._backgroundColor&&!t){let i=this._backgroundColor.alpha;Gh.backgroundShouldBeTransparent(this.context)&&(i=this.ARBackgroundAlpha??0),this.context.scene.background=null,this.context.xr?.isVR?this.context.renderer.setClearColor(Ab(this._backgroundColor).convertLinearToSRGB()):this.context.renderer.setClearColor(this._backgroundColor,i)}else this._backgroundColor||vs&&console.warn(`[Camera] has no background color "${this.name}" `);break;case 4:t||(this.context.scene.background=null,this.context.renderer.setClearColor(0,0));break}}applySceneSkybox(){this._skybox||(this._skybox=new lR(this)),this._skybox.apply()}static backgroundShouldBeTransparent(e){const t=e.renderer.xr?.getSession();if(!t)return!1;if(typeof t._transparent=="boolean")return t._transparent;const i=t.environmentBlendMode;vs&&Te("Environment blend mode: "+i+" on "+navigator.userAgent);let n=i==="additive"||i==="alpha-blend";return e.isInAR&&i==="opaque"&&(navigator.userAgent?.includes("OculusBrowser")||navigator.userAgent?.includes("Mozilla")&&navigator.userAgent?.includes("Mobile WebXRViewer/v2"))&&(n=!0),t._transparent=n,n}};qt([u()],Lt.prototype,"aspect",1),qt([u()],Lt.prototype,"fieldOfView",1),qt([u()],Lt.prototype,"nearClipPlane",1),qt([u()],Lt.prototype,"farClipPlane",1),qt([u()],Lt.prototype,"clearFlags",1),qt([u()],Lt.prototype,"orthographic",2),qt([u()],Lt.prototype,"orthographicSize",2),qt([u()],Lt.prototype,"ARBackgroundAlpha",2),qt([u()],Lt.prototype,"cullingMask",1),qt([u()],Lt.prototype,"backgroundBlurriness",1),qt([u()],Lt.prototype,"backgroundIntensity",1),qt([u(nt)],Lt.prototype,"backgroundRotation",1),qt([u()],Lt.prototype,"environmentIntensity",1),qt([u(se)],Lt.prototype,"backgroundColor",1),qt([u(ho)],Lt.prototype,"targetTexture",1);let si=Lt;class lR{_camera;_skybox;get context(){return this._camera?.context}constructor(e){this._camera=e}apply(){if(this._skybox=this.context.lightmaps.tryGetSkybox(this._camera.sourceId),!this._skybox)this._did_log_failed_to_find_skybox||(this._did_log_failed_to_find_skybox=!0,console.warn(`Camera "${this._camera.name}" has no skybox texture. ${this._camera.sourceId}`));else if(this.context.scene.background!==this._skybox){const e=this.context.domElement.getAttribute("background-image")||this.context.domElement.getAttribute("background-color");vs&&console.debug(`[Camera] Apply Skybox ${this._skybox?.name} ${e} - "${this._camera.name}"`),e?.length||(this._skybox.mapping=mo,this.context.scene.background=this._skybox)}}}function cR(o){w("freecam")&&o.context.mainCameraComponent===o&&x.getOrAddComponent(o.gameObject,fe)}class ko extends M{get listener(){return this._listener==null&&(this._listener=new gS),this._listener}_listener=null;onEnable(){Tn.registerWaitForInteraction(this.onInteraction),this.addListenerIfItExists()}onDisable(){Tn.unregisterWaitForInteraction(this.onInteraction),this.removeListenerIfItExists()}onInteraction=()=>{this.destroyed||this.listener==null||this.addListenerIfItExists()};addListenerIfItExists(){const e=this._listener;if(!e||e?.parent)return;const t=this.context.mainCameraComponent||x.getComponentInParent(this.gameObject,si);t?.threeCamera?t.threeCamera.add(e):this.gameObject.add(e),e.filter?(e.gain.connect(e.filter),e.filter.connect(e.context.destination)):e.gain.connect(e.context.destination)}removeListenerIfItExists(){const e=this._listener;e&&(e.removeFromParent(),e.filter&&e.filter.disconnect(),e.gain&&e.gain.disconnect())}}var hR=Object.defineProperty,dR=Object.getOwnPropertyDescriptor,wn=(o,e,t,i)=>{for(var n=i>1?void 0:i?dR(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&hR(e,t,n),n};const Ot=w("debugaudio"),Yi=class qs extends M{static get userInteractionRegistered(){return Tn.userInteractionRegistered}static registerWaitForAllowAudio(e){Tn.registerWaitForInteraction(e)}clip="";playOnAwake=!1;preload=!0;playInBackground=!0;get isPlaying(){return this.sound?.isPlaying??!1}get duration(){return this.sound?.buffer?.duration}get time01(){const e=this.duration;return e&&this.sound?this.sound?.context.currentTime/e:0}set time01(e){const t=this.duration;t&&this.sound&&(this.time=e*t)}get time(){return this.sound?.source?this.sound.source?.context.currentTime-this._lastContextTime+this.sound.offset:0}set time(e){if(this.sound){if(e===this.sound.offset)return;const t=this.isPlaying;this.stop(),this.sound.offset=e,t&&this.play()}}get loop(){return this.sound&&(this._loop=this.sound.getLoop()),this._loop}set loop(e){this._loop=e,this.sound&&this.sound.setLoop(e)}get spatialBlend(){return this._spatialBlend}set spatialBlend(e){e!==this._spatialBlend&&(this._spatialBlend=e,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(e){this._minDistance!==e&&(this._minDistance=e,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(e){this._maxDistance!==e&&(this._maxDistance=e,this._needUpdateSpatialDistanceSettings=!0)}_spatialBlend=0;_minDistance=1;_maxDistance=100;get volume(){return this._volume}set volume(e){this._volume=e,this.sound&&!this.context.application.muted&&(Ot&&console.log(this.name,"audio set volume",e),this.sound.setVolume(e))}_volume=1;set pitch(e){this.sound&&this.sound.setPlaybackRate(e)}get pitch(){return this.sound?this.sound.getPlaybackRate():1}rollOffMode=0;_loop=!1;sound=null;helper=null;wasPlaying=!1;audioLoader=null;shouldPlay=!1;_lastClipStartedLoading=null;_audioElement=null;get Sound(){if(!this.sound&&qs.userInteractionRegistered){let e=this.gameObject.getComponent(ko)??this.context.mainCamera.getComponent(ko)??pc(ko,this.context,!1);!e&&this.context.mainCamera&&(e=this.context.mainCamera.addComponent(ko)),e?.listener?(this.sound=new fS(e.listener),this.gameObject?.add(this.sound)):Ot&&console.warn("No audio listener found in scene - can not play audio")}return this.sound}get ShouldPlay(){return this.shouldPlay}get audioContext(){return this.sound?.context}awake(){Ot&&console.log("[AudioSource]",this),this.audioLoader=new am,this.playOnAwake&&(this.shouldPlay=!0),this.preload&&typeof this.clip=="string"&&this.audioLoader.load(this.clip,this.createAudio,()=>{},console.error)}onEnable(){this.sound&&this.gameObject.add(this.sound),qs.userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():qs.registerWaitForAllowAudio(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.onNewClip(this.clip)}),globalThis.addEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.addEventListener(Ym.MuteChanged,this.onApplicationMuteChanged)}onDisable(){globalThis.removeEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.removeEventListener(Ym.MuteChanged,this.onApplicationMuteChanged),this.pause()}onVisibilityChanged=()=>{switch(document.visibilityState){case"hidden":(this.playInBackground===!1||G.isMobileDevice())&&(this.wasPlaying=this.isPlaying,this.isPlaying&&this.pause());break;case"visible":Ot&&console.log("visible",this.enabled,this.playOnAwake,!this.isPlaying,qs.userInteractionRegistered,this.wasPlaying),this.enabled&&this.playOnAwake&&!this.isPlaying&&qs.userInteractionRegistered&&this.wasPlaying&&this.play();break}};onApplicationMuteChanged=()=>{this.context.application.muted?this.sound?.setVolume(0):this.sound?.setVolume(this.volume)};createAudio=e=>{if(this.destroyed){Ot&&console.warn("AudioSource destroyed, not creating audio",this.name);return}Ot&&console.log("AudioBuffer finished loading",e);const t=this.Sound;if(!t){Ot&&console.warn("Failed getting sound?",this.name);return}t.isPlaying&&t.stop(),e&&t.setBuffer(e),t.loop=this._loop,this.context.application.muted?t.setVolume(0):t.setVolume(this.volume),t.autoplay=this.shouldPlay&&qs.userInteractionRegistered,this.applySpatialDistanceSettings(),t.isPlaying&&t.stop(),qs.registerWaitForAllowAudio(this.__onAllowAudioCallback)};__onAllowAudioCallback=()=>{this.shouldPlay&&this.play()};applySpatialDistanceSettings(){const e=this.sound;if(!e)return;this._needUpdateSpatialDistanceSettings=!1;const t=D.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(Ot&&console.log(this.name,this._minDistance,this._maxDistance,this.spatialBlend,"Ref distance="+t),e.setRefDistance(t),e.setMaxDistance(Math.max(.01,this._maxDistance)),this.rollOffMode){case 0:e.setDistanceModel("exponential");break;case 1:e.setDistanceModel("linear");break;case 2:console.warn("Custom rolloff for AudioSource is not supported: "+this.name);break}this.spatialBlend>0?Ot&&!this.helper&&(this.helper=new wC(e,e.getRefDistance()),e.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}async onNewClip(e){if(e&&(this.clip=e),typeof e=="string")if(Ot&&console.log(e),e.endsWith(".mp3")||e.endsWith(".wav")){if(this.audioLoader||(this.audioLoader=new am),this.shouldPlay=!0,this._lastClipStartedLoading===e){Ot&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=e,Ot&&console.log("load audio",e);const t=await this.audioLoader.loadAsync(e).catch(console.error);if(this.destroyed)return;this._lastClipStartedLoading===e&&(this._lastClipStartedLoading=null),t&&this.createAudio(t)}else console.warn("Unsupported audio clip type",e);else this.shouldPlay=!0,this.createAudio()}play(e=void 0){!e&&this.clip&&(e=this.clip),e!==void 0&&typeof e!="string"&&!(e instanceof MediaStream)&&(E()&&console.warn("Called play on AudioSource with unknown argument type:",e+`
950
950
  Using the assigned clip instead:`,this.clip),e=this.clip);let t=!this.sound||e&&e!==this.clip;if(typeof e=="string"&&!this.audioLoader&&(t=!0),(e instanceof MediaStream||typeof e=="string")&&(this.clip=e),t){this.shouldPlay=!0,this.onNewClip(e);return}if(this.shouldPlay=!0,this._hasEnded=!1,Ot&&console.log("play",this.sound?.getVolume(),this.sound),this.sound&&!this.sound.isPlaying){const i=this.context.application.muted;i&&this.sound.setVolume(0),this.gameObject?.add(this.sound),this.clip instanceof MediaStream?(this.sound.setMediaStreamSource(this.clip),this._audioElement||(this._audioElement=document.createElement("audio"),this._audioElement.style.display="none"),this._audioElement.parentNode||this.context.domElement.shadowRoot?.append(this._audioElement),this._audioElement.srcObject=this.clip,this._audioElement.autoplay=!1):(this._audioElement&&this._audioElement.remove(),this.sound.play(i?.1:0))}}pause(){Ot&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&this.sound.source&&(this._lastContextTime=this.sound?.context.currentTime,this.sound.pause()),this._audioElement?.remove()}stop(){Ot&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.source&&(this._lastContextTime=this.sound?.context.currentTime,Ot&&console.log(this._lastContextTime),this.sound.stop()),this._audioElement?.remove()}_lastContextTime=0;_hasEnded=!0;_needUpdateSpatialDistanceSettings=!1;update(){this.helper&&(this.isPlaying&&this.helper.update(),this.helper.visible=this.isPlaying),this._needUpdateSpatialDistanceSettings&&this.applySpatialDistanceSettings(),this.sound&&!this.sound.isPlaying&&this.shouldPlay&&!this._hasEnded&&(this._hasEnded=!0,Ot&&console.log("Audio clip ended",this.clip),this.dispatchEvent(new CustomEvent("ended",{detail:this})))}};wn([u(URL)],Yi.prototype,"clip",2),wn([u()],Yi.prototype,"playOnAwake",2),wn([u()],Yi.prototype,"preload",2),wn([u()],Yi.prototype,"playInBackground",2),wn([u()],Yi.prototype,"loop",1),wn([u()],Yi.prototype,"spatialBlend",1),wn([u()],Yi.prototype,"minDistance",1),wn([u()],Yi.prototype,"maxDistance",1),wn([u()],Yi.prototype,"volume",1),wn([u()],Yi.prototype,"pitch",1),wn([u()],Yi.prototype,"rollOffMode",2);let Mi=Yi;const uR=w("debugavatar");class Le extends M{static getAvatar(e){return e>=0&&e<Le.instances.length?Le.instances[e]:null}static instances=[];static onAvatarMarkerCreated(e){return Le._onNewAvatarMarkerAdded.push(e),e}static onAvatarMarkerDestroyed(e){return Le._onAvatarMarkerDestroyed.push(e),e}static _onNewAvatarMarkerAdded=[];static _onAvatarMarkerDestroyed=[];connectionId;avatar;awake(){Le.instances.push(this),uR&&console.log(this);for(const e of Le._onNewAvatarMarkerAdded)e({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){Le.instances.splice(Le.instances.indexOf(this),1);for(const e of Le._onAvatarMarkerDestroyed)e({avatarMarker:this,gameObject:this.gameObject})}isLocalAvatar(){return this.connectionId===this.context.connection.connectionId}}class Mr{static Pois=[];static LastChangeTime=0;static Add(e,t,i=null){if(t){for(const n of this.Pois)if(n.obj===t)return;this.Pois.push({obj:t,avatar:i}),this.LastChangeTime=e.time.time}}static Remove(e,t){if(t){for(const i of this.Pois)if(i.obj===t){this.Pois.splice(this.Pois.indexOf(i),1),this.LastChangeTime=e?.time.time??z.Current?.time.time;return}}}}class pR{guid;position=new b}class Rc extends M{set controlledTarget(e){this.target=e;const t=C.get("MoveRandom");if(t&&this.target){const i=x.getComponent(this.target,t);i&&i.destroy()}}target=null;avatar=null;_model=null;_targetModel=new pR;_currentTargetObject=null;_lastUpdateTime=0;_lookDuration=0;_lastPoiChangedTime=0;awake(){if(this.avatar=x.getComponentInParent(this.gameObject,Le),this.avatar){const e=x.getComponentInParent(this.gameObject,Le);this._model=new tg(this.context.connection,this.guid),e?.isLocalAvatar&&this._model.requestOwnership()}this.context.connection.beginListen("avatar-look-target-changed",e=>{this.target&&e&&e.guid===this.avatar?.guid&&mt(this.target,e.position)})}update(){if((!this.context.connection.isConnected||this._model?.hasOwnership)&&(Mr.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=Mr.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){const e=Z(this._currentTargetObject);mt(this.target,e),this.context.connection.isConnected&&this.avatar&&(this.context.connection.send("avatar-look-target-changed",this._targetModel),this._targetModel.guid=this.avatar.guid,this._targetModel.position.copy(e))}}selectTarget(){if(this.context.time.time-this._lastUpdateTime>this._lookDuration){this._lastUpdateTime=this.context.time.time,this._lookDuration=Math.random()*.5+.2;const e=Mr.Pois;if(e.length>0){const t=e[Math.floor(Math.random()*e.length)];if(t&&t.obj){if(t.avatar&&t.avatar===this.avatar)return;this._currentTargetObject=t.obj}}}}}function vw(o){const e=o;return!!(e.parser&&e.parser.json)}var Su=(o=>(o[o.None=0]="None",o[o.DontExport=1]="DontExport",o))(Su||{});function ww(o){return o&&o.isComponent}const mR=Symbol("object"),af=new wi(()=>new b,20);class xw{_point;_normal;_tangentVelocity;distance;impulse;friction;get point(){return af.get().set(this._point.x,this._point.y,this._point.z)}get normal(){return af.get().set(this._normal.x,this._normal.y,this._normal.z)}get tangentVelocity(){return af.get().set(this._tangentVelocity.x,this._tangentVelocity.y,this._tangentVelocity.z)}constructor(e,t,i,n,s,r){this._point=e,this.distance=t,this._normal=i,this.impulse=n,this.friction=s,this._tangentVelocity=r}}class Sw{contacts;constructor(e,t,i){this.me=e,this._collider=t,this._gameObject=t.gameObject,this.contacts=i}me;_collider;get collider(){return this._collider}_gameObject;get gameObject(){return this._gameObject}get rigidBody(){return this.collider?.attachedRigidbody}}class Cw{object;collider;constructor(e,t){this.object=e,this.collider=t}}const je=w("debugnetworkingstreams");var Gn=(o=>(o.Connected="peer-user-connected",o.StreamReceived="receive-stream",o.StreamEnded="call-ended",o.Disconnected="peer-user-disconnected",o.UserJoined="user-joined",o))(Gn||{});class lf{type="call-ended";userId;direction;constructor(e,t){this.userId=e,this.direction=t}}class Pw{type="receive-stream";userId;stream;target;constructor(e,t,i){this.userId=e,this.stream=t,this.target=i}}class gR{guid;peerId;dontSave=!0;constructor(e,t){this.guid=e.id,this.peerId=t}}var Ow=(o=>(o.Incoming="incoming",o.Outgoing="outgoing",o))(Ow||{});class fR extends lm{peerId;userId;direction;call;get stream(){return this._stream}_stream=null;_isDisposed=!1;close(){this._isDisposed||(this._isDisposed=!0,this.call.close(),qn(this._stream))}get isOpen(){return this.call.peerConnection?.connectionState==="connected"}get isOpening(){return this.call.peerConnection?.connectionState==="connecting"}get isClosed(){return!this.isOpen||this._isDisposed}constructor(e,t,i,n=null){super(),this.peerId=t.peer,this.userId=e,this.call=t,this.direction=i,this._stream=n,t.on("stream",s=>{if(je&&console.log("Receive stream",`
951
951
  Audio:`,s.getAudioTracks(),`
952
952
  Video:`,s.getVideoTracks()),this._stream=s,i==="incoming"){const r=new Pw(e,s,this);this.dispatchEvent(r)}}),t.on("close",()=>{this.dispatchEvent(new lf(e,i))})}}function kw(o){return o=o.replace("a=fmtp:111 minptime=10;useinbandfec=1","a=fmtp:111 ptime=5;useinbandfec=1;stereo=1;maxplaybackrate=48000;maxaveragebitrat=128000;sprop-stereo=1"),o}class Jo extends lm{static instances=new Map;static getOrCreate(e,t){if(Jo.instances.has(t))return Jo.instances.get(t);const i=new Jo(e,t);return Jo.instances.set(t,i),i}getMyPeerId(){if(this.context.connection.connectionId)return this.getPeerIdFromUserId(this.context.connection.connectionId)}getPeerIdFromUserId(e){return this.id+"-"+e}getUserIdFromPeerId(e){return e.substring(this.id.length+1)}makeCall(e,t){if(!t?.id){je?console.warn("Can not make a call: mediastream has no id or is undefined"):console.debug("Can not make a call: mediastream has no id or is undefined");return}const i={metadata:{userId:this.context.connection.connectionId,streamId:t.id},sdpTransform:s=>kw(s)},n=this._peer?.call(e,t,i);if(n){const s=this.registerCall(n,"outgoing",t);return je&&console.warn(`\u{1F4DE} CALL ${e}`,`
@@ -954,9 +954,9 @@ Outgoing:`,this._outgoingCalls,`
954
954
  Incoming:`,this._incomingCalls),s}else je&&console.error("Failed to make call",e,t,this._peer)}closeAll(){for(const e of this._incomingCalls)e.close();for(const e of this._outgoingCalls)e.close();this.updateCalls()}updateCalls=()=>{for(let e=this._incomingCalls.length-1;e>=0;e--){const t=this._incomingCalls[e];t.isClosed&&!t.isOpening&&this._incomingCalls.splice(e,1)}for(let e=this._outgoingCalls.length-1;e>=0;e--){const t=this._outgoingCalls[e];let i=!1;t.isClosed&&!t.isOpening&&(t.stream?.active?je&&console.warn("!!! Stream is still active, don't remove call",t.userId,"Your id: "+this.context.connection.connectionId):(je&&console.warn("!!! Remove closed call",t.userId),i=!0)),this.context.connection.userIsInRoom(t.userId)===!1&&(je&&console.warn("!!! User is not in room anymore, remove call",t.userId),i=!0),i&&(t.close(),this._outgoingCalls.splice(e,1))}};get peer(){return this._peer}get incomingCalls(){return this._incomingCalls}id;context;_incomingCalls=[];_outgoingCalls=[];_peer;constructor(e,t){super(),this.context=e,this.id=t,this.setupPeer();const i=Object.getOwnPropertyDescriptor(navigator,"getUserMedia")?.writable;try{i?navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia:je&&console.warn("[PeerJs] getUserMedia is not writable")}catch(n){je&&console.error("[PeerJs] Error setting getUserMedia",n)}}_enabled=!1;_enabledPeer=!1;onConnectRoomFn=this.onConnectRoom.bind(this);enable(){this._enabled||(this._enabled=!0,this.context.connection.beginListen(te.JoinedRoom,this.onConnectRoomFn),this.subscribePeerEvents())}disable(){this._enabled&&(this._enabled=!1,this.context.connection.stopListen(te.JoinedRoom,this.onConnectRoomFn),this.unsubscribePeerEvents())}onConnectRoom(){this.setupPeer()}setupPeer(){if(this.context.connection.connectionId&&!this._enabledPeer){if(this._enabledPeer=!0,!this._peer){const e=this.getMyPeerId();e?this._peer=m_(e):console.error("Failed to setup peerjs because we dont have a connection id",this.context.connection.connectionId)}this._enabled&&this.subscribePeerEvents()}}subscribePeerEvents(){this._peer&&(this._peer.on("open",this.onPeerConnect),this._peer.on("close",this.onPeerClose),this._peer.on("call",this.onPeerReceivingCall),this._peer.on("disconnected",this.onPeerDisconnected),this._peer.on("error",this.onPeerError))}unsubscribePeerEvents(){this._peer&&(this._peer.off("open",this.onPeerConnect),this._peer.off("close",this.onPeerClose),this._peer.off("call",this.onPeerReceivingCall),this._peer.off("disconnected",this.onPeerDisconnected),this._peer.off("error",this.onPeerError))}onPeerConnect=e=>{if(je&&console.log("PEER opened as",e),e===null){console.error("Peer connection failed",e);return}this.context.connection.send("peer-user-connected",new gR(this,e))};onPeerClose=()=>{je&&console.log("PEER closed"),this.updateCalls()};onPeerDisconnected=()=>{je&&console.log("PEER disconnected"),this.updateCalls()};onPeerError=e=>{je&&console.error("PEER error",e)};onPeerReceivingCall=e=>{e.answer(void 0,{sdpTransform:t=>kw(t)}),this.registerCall(e,"incoming",null)};registerCall(e,t,i){const n=e.metadata;(!n||!n.userId)&&console.error("Missing call metadata",e);const s=n.userId;t==="incoming"&&je?console.warn("\u2190 Receive call from",e.metadata,e.connectionId):je&&console.warn("\u2192 Make call to",e.metadata);const r=t==="incoming"?this._incomingCalls:this._outgoingCalls,a=new fR(s,e,t,i);return r.push(a),e.on("error",l=>{console.error("Call error",l)}),e.on("close",()=>{je&&console.log("Call ended",e.metadata);const l=r.indexOf(a);l!==-1&&r.splice(l,1),a.close(),this.dispatchEvent(new lf(s,t))}),a.addEventListener("call-ended",l=>{this.dispatchEvent(l)}),t==="incoming"&&(a.addEventListener("receive-stream",l=>{this.dispatchEvent(l)}),e.on("stream",()=>{je&&console.log("Received stream for call",e.metadata);let l=0;const c=setInterval(()=>{const h=l===0;!a.isOpen&&h&&(je&&console.warn("Close call because stream is not active",e.metadata),l+=1,clearInterval(c),a.close())},2e3)})),a}}class ed extends lm{static create(e,t){const i=Jo.getOrCreate(e.context,t||e.context.connection.connectionId||e.guid);return new ed(e.context,i)}context;peer;_sendingStreams=new Map;debug=!1;constructor(e,t){if(super(),ww(e)){const i=e;e=i.context,t=Jo.getOrCreate(i.context,i.guid)}else typeof t=="string"&&(t=Jo.getOrCreate(e,t));if(e){if(!(e instanceof z))throw new Error("Failed to create NetworkedStreams because context is not an instance of Context")}else throw new Error("Failed to create NetworkedStreams because context is undefined");if(!t)throw new Error("Failed to create NetworkedStreams because peer is undefined");this.context=e,this.peer=t,je&&(this.debug=!0)}startSendingStream(e){this._sendingStreams.has(e)?console.warn("Received start sending stream with stream that is already being sent"):(this._sendingStreams.set(e,[]),this.updateSendingCalls())}stopSendingStream(e){if(e){const t=this._sendingStreams.get(e);if(t){for(const i of t)i.close();t.length=0}this._sendingStreams.delete(e),t&&this.debug&&this.debugLogCurrentState()}this.updateSendingCalls()}_enabled=!1;get enabled(){return this._enabled}enable(){this._enabled||(this._enabled=!0,this.peer.enable(),this.peer.addEventListener("receive-stream",this.onCallStreamReceived),this.peer.addEventListener("call-ended",this.onCallEnded),this.context.connection.beginListen("peer-user-connected",this.onUserConnected),this.context.connection.beginListen(te.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(te.UserJoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(te.UserLeftRoom,this.onUserLeft),this.context.connection.beginListen(te.LeftRoom,this.onLeftRoom),this._tickIntervalId=setInterval(this.tick,5e3))}disable(){this._enabled&&(this._enabled=!1,this.peer.disable(),this.peer.removeEventListener("receive-stream",this.onCallStreamReceived),this.peer.removeEventListener("call-ended",this.onCallEnded),this.context.connection.stopListen("peer-user-connected",this.onUserConnected),this.context.connection.stopListen(te.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(te.UserJoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(te.UserLeftRoom,this.onUserLeft),this.context.connection.stopListen(te.LeftRoom,this.onLeftRoom),this._tickIntervalId!=null&&(clearInterval(this._tickIntervalId),this._tickIntervalId=void 0))}_tickIntervalId;tick=()=>{this.updateSendingCalls()};onJoinedRoom=e=>{this._sendingStreams.size>0&&(this.debug&&console.warn(`${e?.userId?`User ${e.userId}`:"You"} joined room`,e,this._sendingStreams.size),this.updateSendingCalls())};onLeftRoom=e=>{this.debug&&console.warn(`${e?.userId||"You"} left room`,e),this.stopCallsToUsersThatAreNotInTheRoomAnymore(),this.peer.closeAll()};onCallStreamReceived=e=>{this.debug&&console.log("Call with "+e.userId+" started"),this.dispatchEvent({type:"receive-stream",target:this,stream:e.stream,userId:e.userId}),this.debug&&this.debugLogCurrentState()};onCallEnded=e=>{this.debug&&console.log("Call with "+e.userId+" ended"),this.dispatchEvent(e),this.debug&&this.debugLogCurrentState()};onUserConnected=e=>{if(this.peer.id===e.guid){this.debug&&console.log("PEER USER CONNECTED",e.guid,e,this._sendingStreams.size);const t=this._sendingStreams.keys().next().value;this.peer.makeCall(e.peerId,t)}else je&&console.log("Unknown user connected",e.guid,e.peerId)};onUserLeft=e=>{this.debug&&console.log("User left room: "+e.userId),this.stopCallsToUsersThatAreNotInTheRoomAnymore()};updateSendingCalls(){const e=this.context.connection.connectionId;for(const t of this._sendingStreams.keys()){const i=this._sendingStreams.get(t)||[];for(const n of this.context.connection.usersInRoom()){if(n===e)continue;const s=this.peer.getPeerIdFromUserId(n);if(i.find(r=>r.peerId===s&&r.direction==="outgoing"&&!r.isClosed&&r.stream?.active))je&&console.debug("Already have a call with user "+n+" / peer "+s);else{const r=this.peer.makeCall(s,t);r&&i.push(r)}}this._sendingStreams.set(t,i)}this.stopCallsToUsersThatAreNotInTheRoomAnymore()}stopCallsToUsersThatAreNotInTheRoomAnymore(){for(const e of this._sendingStreams.keys()){const t=this._sendingStreams.get(e);if(t)for(let i=t.length-1;i>=0;i--){const n=t[i];this.context.connection.userIsInRoom(n.userId)?je&&(this.context.connection.connectionId===n.userId?console.warn(`You are still in the room [${i}] ${n.userId}`):console.log(`User is still in room [${i}] ${n.userId}`)):(je&&console.log(`Remove call ${[i]} to user that is not in room anymore ${n.userId}`),n.close(),t.splice(i,1))}}this.peer.updateCalls(),this.debug&&this.debugLogCurrentState()}debugLogCurrentState(){console.warn(`You (${this.context.connection.connectionId}) are currently sending ${this._sendingStreams.size} and receiving ${this.peer.incomingCalls.length} calls (${this.peer.incomingCalls.map(e=>e.userId).join(", ")})`,this.peer.incomingCalls)}}function qn(o){if(o&&o instanceof MediaStream)for(const e of o.getTracks())e.stop()}var yR=Object.defineProperty,cf=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&yR(e,t,n),n};const bR="noVoip",_R=w("debugvoip");class ws extends M{autoConnect=!0;runInBackground=!0;createMenuButton=!0;debug=!1;_net;_menubutton;awake(){_R&&(this.debug=!0),this.debug&&(console.log("VOIP debugging: press 'v' to toggle mute or 'c' to toggle connect/disconnect"),window.addEventListener("keydown",async e=>{switch(e.key.toLowerCase()){case"v":console.log("MUTE?",!this.isMuted),this.setMuted(!this.isMuted);break;case"c":this.isSending?this.disconnect():this.connect();break}}),window.addEventListener("blur",()=>{console.log("VOIP: MUTE ON BLUR"),this.setMuted(!0)}),window.addEventListener("focus",()=>{console.log("VOIP: UNMUTE ON FOCUS"),this.setMuted(!1)}))}onEnable(){this._net||(this._net=ed.create(this)),this.debug&&(this._net.debug=!0),this._net.addEventListener(Gn.StreamReceived,this.onReceiveStream),this._net.addEventListener(Gn.StreamEnded,this.onStreamEnded),this._net.enable(),this.autoConnect&&this.context.connection.isConnected&&this.connect(),this.context.connection.beginListen(te.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(te.LeftRoom,this.onLeftRoom),this.onEnabledChanged(),this.updateButton(),window.addEventListener("visibilitychange",this.onVisibilityChanged)}onDisable(){this._net&&(this._net.stopSendingStream(this._outputStream),this._net.removeEventListener(Gn.StreamReceived,this.onReceiveStream),this._net.removeEventListener(Gn.StreamEnded,this.onStreamEnded),this._net?.disable()),this.context.connection.stopListen(te.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(te.LeftRoom,this.onLeftRoom),this.onEnabledChanged(),this.updateButton(),window.removeEventListener("visibilitychange",this.onVisibilityChanged)}onDestroy(){this._menubutton?.remove(),this._menubutton=void 0}_allowSending=!0;_outputStream=null;get isSending(){return this._outputStream!=null&&this._outputStream.active}async connect(e){if(!this._net)return console.error("Cannot connect to voice chat - NetworkedStreams not initialized. Make sure the component is enabled before calling this method."),!1;if(this.context.connection.isConnected){if(!await G.microphonePermissionsGranted())return console.error("Cannot connect to voice chat - microphone permissions not granted"),this.updateButton(),!1}else return console.error("Cannot connect to voice chat - not connected to server"),this.updateButton(),!1;return this._allowSending=!0,this._net?.stopSendingStream(this._outputStream),qn(this._outputStream),this._outputStream=await this.getAudioStream(e),this._outputStream?(this.debug&&console.log("VOIP: Got audio stream"),this._net?.startSendingStream(this._outputStream),this.updateButton(),!0):(this.updateButton(),await G.microphonePermissionsGranted()?console.error("VOIP: Could not get audio stream - please make sure to connect an audio device and grant microphone permissions"):Xl("Microphone permissions not granted: Please grant microphone permissions to use voice chat"),(this.debug||E())&&console.log("VOIP: Failed to get audio stream"),!1)}disconnect(e){e?.remember&&(this._allowSending=!1),this._net?.stopSendingStream(this._outputStream),qn(this._outputStream),this._outputStream=null,this.updateButton()}setMuted(e){const t=this._outputStream?.getAudioTracks();if(t)for(const i of t)i.enabled=!e}get isMuted(){if(this._outputStream===null)return!1;const e=this._outputStream?.getAudioTracks();if(e){for(const t of e)if(!t.enabled)return!0}return!1}async updateButton(){if(this.createMenuButton){if(this._menubutton||(this._menubutton=document.createElement("button"),this._menubutton.addEventListener("click",()=>{this.isSending?this.disconnect({remember:!0}):this.connect(),G.microphonePermissionsGranted().then(e=>{e||ge("<strong>Microphone permissions not granted</strong>. Please allow your browser to use the microphone to be able to talk. Click on the button on the left side of your browser's address bar to allow microphone permissions.")})})),this._menubutton){this.context.menu.appendChild(this._menubutton),this.activeAndEnabled?this._menubutton.style.display="":this._menubutton.style.display="none",this._menubutton.title=this.isSending?"Click to disable your microphone":"Click to enable your microphone";let e=(this.isSending,""),t=this.isSending?"mic":"mic_off";await G.microphonePermissionsGranted()||(e="No Permission",t="mic_off",this._menubutton.title="Microphone permissions not granted. Please allow your browser to use the microphone to be able to talk. This can usually be done in the addressbar of the webpage."),this._menubutton.innerText=e,this._menubutton.prepend(Ct(t)),this.context.connection.isConnected==!1?this._menubutton.setAttribute("disabled",""):this._menubutton.removeAttribute("disabled")}}else this.activeAndEnabled||this._menubutton?.remove()}getFrequency(e){return this.unsupported_getfrequency||(this.unsupported_getfrequency=!0,E()&&ge("VOIP: getFrequency is currently not supported"),console.warn("VOIP: getFrequency is currently not supported")),null}async getAudioStream(e){if(!navigator.mediaDevices.getUserMedia)return console.error("No getDisplayMedia support"),null;const t=async n=>await navigator.mediaDevices.getUserMedia({audio:n??!0,video:!1}).catch(s=>(console.warn("VOIP failed getting audio stream",s),null)),i=await t(e);if(!i)return null;if(G.isiOS()&&e?.deviceId===void 0){const n=(await navigator.mediaDevices.enumerateDevices()).find(s=>(s.kind==="audioinput"||s.kind==="audiooutput")&&!s.label.includes("iPhone"));if(n){const s=Object.assign({},e);return s.deviceId=n.deviceId,await t(s)}}return i}onJoinedRoom=async()=>{this.debug&&console.log("VOIP: Joined room"),await Dn(300),this.autoConnect&&!this.isSending&&this._allowSending&&this.connect()};onLeftRoom=()=>{this.debug&&console.log("VOIP: Left room"),this.disconnect();for(const e of this._incomingStreams.values())qn(e.srcObject);this._incomingStreams.clear()};_incomingStreams=new Map;onReceiveStream=e=>{const t=e.target.userId,i=e.stream;let n=this._incomingStreams.get(t);n||(n=new Audio,this._incomingStreams.set(t,n)),n.srcObject=i,n.setAttribute("autoplay","true"),Tn.registerWaitForInteraction(()=>{n?.play().catch(s=>{console.error("VOIP: Failed to play audio",s)})})};onStreamEnded=e=>{const t=this._incomingStreams.get(e.userId);qn(t?.srcObject),this._incomingStreams.delete(e.userId)};onEnabledChanged=()=>{for(const e of this._incomingStreams){const t=e[1];t.muted=!this.enabled}};onVisibilityChanged=()=>{if(this.runInBackground)return;const e=document.visibilityState!=="visible";this.setMuted(e);for(const t of this._incomingStreams){const i=t[1];i.muted=e}}}cf([u()],ws.prototype,"autoConnect"),cf([u()],ws.prototype,"runInBackground"),cf([u()],ws.prototype,"createMenuButton");var vR=Object.defineProperty,Mw=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&vR(e,t,n),n};const wR=w("debugmouth");class Tc extends M{idle=[];talking=[];marker=null;voip=null;lastMouthChangeTime=0;mouthChangeLength=0;awake(){setTimeout(()=>{this.voip=x.findObjectOfType(ws,this.context),this.marker||(this.marker=x.getComponentInParent(this.gameObject,Le))},3e3)}update(){if(!this.voip||this.context.time.frameCount%10!==0)return;let e=this.marker?.connectionId??null;if(!e){wR&&(e=null);return}const t=this.voip.getFrequency(e)??0;this.updateLips(t)}updateLips(e){if(this.context.time.time-this.lastMouthChangeTime>this.mouthChangeLength){if(this.mouthChangeLength=.05+Math.random()*.1,this.talking&&this.talking.length>0&&e>30){this.lastMouthChangeTime=this.context.time.time;const t=Math.floor(Math.random()*this.talking.length);this.setMouthShapeActive(this.talking,t)}else if(this.idle.length>0&&this.context.time.time-this.lastMouthChangeTime>.5){this.lastMouthChangeTime=this.context.time.time;const t=Math.floor(Math.random()*this.idle.length);this.setMouthShapeActive(this.idle,t)}}}setMouthShapeActive(e,t){if(e){e!=this.idle?this.idle.map(i=>i.visible=!1):this.talking.map(i=>i.visible=!1);for(let i=0;i<e.length;i++){const n=e[i];n&&(n.visible=i===t)}}}}Mw([u(O)],Tc.prototype,"idle"),Mw([u(O)],Tc.prototype,"talking");class hf extends M{voip=null;marker=null;_startPosition=null;awake(){this.voip=x.findObjectOfType(ws,this.context),this.marker=x.getComponentInParent(this.gameObject,Le)}update(){if(!this.voip||!this.marker||this.context.time.frameCount%10!==0)return;const e=this.marker.connectionId,t=this.voip.getFrequency(e);if(t==null)return;this._startPosition||(this._startPosition=this.gameObject.position.clone());const i=t/100;this.gameObject.position.y=this._startPosition.y+i*.07}}var xR=Object.defineProperty,SR=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&xR(e,t,n),n};const $a=w("debugxrflags"),Rw=w("disablexrflags");Rw&&console.warn("XRFlags are disabled");var Xn=(o=>(o[o.Never=0]="Never",o[o.Browser=1]="Browser",o[o.AR=2]="AR",o[o.VR=4]="VR",o[o.FirstPerson=8]="FirstPerson",o[o.ThirdPerson=16]="ThirdPerson",o[o.All=4294967295]="All",o))(Xn||{});class Jt{static Global=new Jt;Mask=17;Has(e){return(this.Mask&e)!==0}Set(e){$a&&console.warn("Set XR flag state to",e),this.Mask=e,Ki.Apply()}Enable(e){this.Mask|=e,Ki.Apply()}Disable(e){this.Mask&=~e,Ki.Apply()}Toggle(e){this.Mask^=e,Ki.Apply()}EnableAll(){this.Mask=-1,Ki.Apply()}DisableAll(){this.Mask=0,Ki.Apply()}}const Tw=class Xo extends M{static registry=[];static Apply(){for(const e of this.registry)e.UpdateVisible(Jt.Global)}static firstApply;static buffer=new Jt;visibleIn;awake(){Xo.registry.push(this)}onEnable(){Xo.firstApply?this.UpdateVisible(Jt.Global):(Xo.firstApply=!0,Xo.Apply())}onDestroy(){const e=Xo.registry.indexOf(this);e>=0&&Xo.registry.splice(e,1)}get isOn(){return this.gameObject.visible}UpdateVisible(e=null){if(Rw)return;let t;const i=e;if(i&&typeof i=="number"&&(console.assert(typeof i=="number","XRFlag.UpdateVisible: state must be a number",i),$a&&console.log(i),Xo.buffer.Mask=i,e=Xo.buffer),e instanceof Jt?($a&&console.warn(this.name,"use passed in mask",e.Mask,this.visibleIn),t=e.Has(this.visibleIn)):($a&&console.log(this.name,"use global mask"),Jt.Global.Has(this.visibleIn)),t!==void 0)if(t)$a&&console.log(this.name,"is visible",this.gameObject.uuid),x.setActive(this.gameObject,!0);else{if($a&&console.log(this.name,"is not visible",this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}};SR([u()],Tw.prototype,"visibleIn");let Ki=Tw;var CR=Object.defineProperty,Cu=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&CR(e,t,n),n};class Rr extends M{eyes=[];lastBlinkTime=0;blinkLength=0;eyesOpen=!0;state=null;awake(){this.state=x.getComponentInParent(this.gameObject,Ki)}update(){if(!(!this.gameObject||!this.gameObject.visible||!this.eyes||!Array.isArray(this.eyes)||this.eyes.length===0)&&this.context.time.time-this.lastBlinkTime>this.blinkLength){if(this.lastBlinkTime=this.context.time.time,this.state&&!this.state.isOn||!this.activeAndEnabled)return;if(this.eyesOpen=!this.eyesOpen,this.blinkLength=Math.random(),this.eyesOpen?(this.blinkLength*=3,this.blinkLength+=.5,Math.random()<.1&&(this.blinkLength=.1+Math.random()*.2)):(this.blinkLength*=Math.random()*.2,this.blinkLength+=.1),Math.random()<.1&&(this.blinkLength*=3),this.blinkLength=Math.max(.2,this.blinkLength),this.blinkLength=Math.min(3,this.blinkLength),this.eyes)for(const e of this.eyes)e&&(e.visible=this.eyesOpen)}}}Cu([u(O)],Rr.prototype,"eyes"),Cu([u()],Rr.prototype,"lastBlinkTime"),Cu([u()],Rr.prototype,"blinkLength"),Cu([u()],Rr.prototype,"eyesOpen");var PR=Object.defineProperty,df=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&PR(e,t,n),n};const Pu=class z1 extends M{head=null;eyes=null;target=null;brain=null;awake(){this.brain||(this.brain=x.getComponentInParent(this.gameObject,Rc)),this.brain||(this.brain=x.addComponent(this.gameObject,Rc)),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}vec=new b;static forward=new b(0,0,1);currentTargetPoint=new b;update(){const e=this.target;if(e&&this.head){const t=this.eyes;if(t){const i=Z(e);this.currentTargetPoint.lerp(i,this.context.time.deltaTime/.1);const n=Z(this.head),s=this.vec.copy(this.currentTargetPoint).sub(n).normalize();if(s.length()<.1)return;const r=z1.forward;if(r.set(0,0,1),r.applyQuaternion(be(this.head)),r.dot(s)>.45)for(let a=0;a<t.length;a++)t[a].lookAt(this.currentTargetPoint)}}}};df([u(O)],Pu.prototype,"head"),df([u(O)],Pu.prototype,"eyes"),df([u(O)],Pu.prototype,"target");let uf=Pu;var OR=Object.defineProperty,pf=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&OR(e,t,n),n};class Ha extends M{length=1;depthTest=!0;isGizmo=!1;_axes=null;onEnable(){if(this.isGizmo&&!lc)return;this._axes||(this._axes=new _i(this.length)),this._axes.layers.disableAll(),this._axes.layers.set(this.layer),this.gameObject.add(this._axes);const e=this._axes.material;e&&e.depthTest!==void 0&&(e.depthTest=this.depthTest)}onDisable(){this._axes&&this.gameObject.remove(this._axes)}}pf([u()],Ha.prototype,"length"),pf([u()],Ha.prototype,"depthTest"),pf([u()],Ha.prototype,"isGizmo");class mf extends M{from;to;hint;desiredDistance=1;onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;const e=Z(this.to).clone(),t=Z(this.from).clone(),i=e.distanceTo(t),n=e.clone();n.sub(t);const s=t.clone();s.add(e),s.multiplyScalar(.5);const r=Z(this.hint).clone();r.sub(s);const a=new b;a.crossVectors(r,n),a.crossVectors(n,a),a.normalize();const l=i*.5,c=Math.max(this.desiredDistance,l),h=Math.sqrt(c*c-l*l),d=a.clone();d.multiplyScalar(h),d.add(s),mt(this.gameObject,d);const p=s.clone();p.sub(a),this.gameObject.lookAt(p)}}const kR=w("gizmos"),MR=w("debugboxhelper");class xt extends M{box=null;static testBox=new bi;_lastMatrixUpdateFrame=-1;static _position=new b;static _size=new b(.01,.01,.01);static _emptyObjectSize=new b(.01,.01,.01);isInBox(e){if(!e)return;if(this.box||(this.box=new bi),Wt([e],void 0,void 0,xt.testBox),xt.testBox.isEmpty()){const i=Z(e,xt._position);xt.testBox.setFromCenterAndSize(i,xt._emptyObjectSize)}this.updateBox();const t=this.box?.intersectsBox(xt.testBox);return t&&MR&&F.DrawWireBox3(xt.testBox,16711680,5),t}intersects(e){return e?this.updateBox(!1).intersectsBox(e):!1}updateBox(e=!1){if(this.box||(this.box=new bi),e||this.context.time.frameCount!=this._lastMatrixUpdateFrame){const t=this._lastMatrixUpdateFrame<0;this._lastMatrixUpdateFrame=this.context.time.frameCount;const i=t,n=Z(this.gameObject,xt._position,i),s=$e(this.gameObject,xt._size);this.box.setFromCenterAndSize(n,s)}return this.box}_helper=null;_color=null;awake(){this._helper=null,this._color=null,this.box=null}showHelper(e=null,t=!1){if(!(!kR&&!t)){if(this._helper){e&&this._color?.set(e),this.gameObject.add(this._helper);return}this._helper=cg(e),this.gameObject.add(this._helper)}}}var RR=Object.defineProperty,ri=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&RR(e,t,n),n};class ai extends M{get isCollider(){return!0}attachedRigidbody=null;isTrigger=!1;sharedMaterial;membership=[0];filter;awake(){super.awake(),this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Ye))}start(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Ye))}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Ye))}onDisable(){this.context.physics.engine?.removeBody(this)}get body(){return this.context.physics.engine?.getBody(this)}updateProperties=()=>{this.context.physics.engine?.updateProperties(this)};updatePhysicsMaterial(){this.context.physics.engine?.updatePhysicsMaterial(this)}}ri([u(Ye)],ai.prototype,"attachedRigidbody"),ri([u()],ai.prototype,"isTrigger"),ri([u()],ai.prototype,"sharedMaterial"),ri([u()],ai.prototype,"membership"),ri([u()],ai.prototype,"filter");class Ga extends ai{radius=.5;center=new b(0,0,0);onEnable(){super.onEnable(),this.context.physics.engine?.addSphereCollider(this),fd(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),Sm(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}}ri([Pt(),u()],Ga.prototype,"radius"),ri([u(b)],Ga.prototype,"center");const gf=class N1 extends ai{static add(e,t){const i=bn(e,N1);return i.autoFit(),t?.rigidbody===!0&&bn(e,Ye,{isKinematic:!1}),i}size=new b(1,1,1);center=new b(0,0,0);onEnable(){super.onEnable(),this.context.physics.engine?.addBoxCollider(this,this.size),fd(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),Sm(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}autoFit(e){const t=this.gameObject,i=t.position.clone(),n=t.quaternion.clone(),s=t.scale.clone(),r=t.parent;t.position.set(0,0,0),t.quaternion.set(0,0,0,1),t.scale.set(1,1,1),t.parent=null,t.updateMatrix();const a=Wt([t]);t.position.copy(i),t.quaternion.copy(n),t.scale.copy(s),t.parent=r,e?.debug===!0&&F.DrawWireBox3(a,16768256,20),this.size=a.getSize(new b)||new b(1,1,1),this.center=a.getCenter(new b)||new b(0,0,0),this.size.length()<=0&&this.size.set(.01,.01,.01)}};ri([Pt(),u(b)],gf.prototype,"size"),ri([u(b)],gf.prototype,"center");let Ou=gf;class xs extends ai{sharedMesh;convex=!1;onEnable(){if(super.onEnable(),!this.context.physics.engine)return;this.sharedMesh?.isMesh||(this.gameObject instanceof H||this.gameObject instanceof os)&&(this.sharedMesh=this.gameObject);const e=0;if(this.sharedMesh?.isMesh)this.context.physics.engine.addMeshCollider(this,this.sharedMesh,this.convex),Ve.assignMeshLOD(this.sharedMesh,e).then(t=>{t&&this.activeAndEnabled&&this.context.physics.engine&&this.sharedMesh&&(this.context.physics.engine.removeBody(this),this.sharedMesh.geometry=t,this.context.physics.engine.addMeshCollider(this,this.sharedMesh,this.convex))});else{const t=this.sharedMesh;if(t?.isGroup){console.warn(`MeshCollider mesh is a group "${this.sharedMesh?.name||this.gameObject.name}", adding all children as colliders. This is currently not fully supported (colliders can not be removed from world again)`,this);const i=new Array;for(const n in t.children){const s=t.children[n];s.isMesh&&(this.context.physics.engine.addMeshCollider(this,s,this.convex),i.push(Ve.assignMeshLOD(s,e)))}Promise.all(i).then(n=>{if(n.some(r=>r)==!1)return;this.context.physics.engine?.removeBody(this);const s=new H;for(const r of n)r&&this.activeAndEnabled&&(s.geometry=r,this.context.physics.engine?.addMeshCollider(this,s,this.convex))})}else(E()||w("showcolliders"))&&console.warn(`[MeshCollider] A MeshCollider mesh is assigned to an unknown object on "${this.gameObject.name}", but it's neither a Mesh nor a Group. Please double check that you attached the collider component to the right object and report a bug otherwise!`,this)}}}ri([u(H)],xs.prototype,"sharedMesh"),ri([u()],xs.prototype,"convex");class Mo extends ai{center=new b(0,0,0);radius=.5;height=2;onEnable(){super.onEnable(),this.context.physics.engine?.addCapsuleCollider(this,this.height,this.radius)}}ri([u(b)],Mo.prototype,"center"),ri([u()],Mo.prototype,"radius"),ri([u()],Mo.prototype,"height");var TR=Object.defineProperty,Ro=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&TR(e,t,n),n};const Ew=w("debugcharactercontroller");class Tr extends M{center=new b(0,0,0);radius=.5;height=2;_rigidbody=null;get rigidbody(){return this._rigidbody?this._rigidbody:(this._rigidbody=this.gameObject.getComponent(Ye),this._rigidbody||(this._rigidbody=this.gameObject.addComponent(Ye)),this.rigidbody)}_activeGroundCollisions;awake(){this._activeGroundCollisions=new Set}onEnable(){const e=this.rigidbody;let t=this.gameObject.getComponent(Mo);t||(t=this.gameObject.addComponent(Mo)),t.center.copy(this.center),t.radius=this.radius,t.height=this.height;const i=new b(0,0,1),n=new b(1,0,0),s=new b(0,1,0),r=this.gameObject.getWorldDirection(new b);r.y=0;const a=n.dot(r)<0?-1:1,l=i.angleTo(r)*a;this.gameObject.setRotationFromAxisAngle(s,l),e.lockRotationX=!0,e.lockRotationY=!0,e.lockRotationZ=!0}move(e){this.gameObject.position.add(e)}onCollisionEnter(e){(e.contacts.length==0||e.contacts.some(t=>t.normal.y>.2))&&(this._activeGroundCollisions.add(e),Ew&&console.log(`Collision(${this._activeGroundCollisions.size}): ${e.contacts.map(t=>t.normal.y.toFixed(2)).join(", ")} - ${this.isGrounded}`))}onCollisionExit(e){this._activeGroundCollisions.delete(e),Ew&&console.log(`Collision(${this._activeGroundCollisions.size}) - ${this.isGrounded}`)}get isGrounded(){return this._activeGroundCollisions.size>0}_contactVelocity=new b;get contactVelocity(){this._contactVelocity.set(0,0,0);for(const e of this._activeGroundCollisions){const t=this.context.physics.engine?.getLinearVelocity(e.collider);t&&(this._contactVelocity.x+=t.x,this._contactVelocity.y+=t.y,this._contactVelocity.z+=t.z)}return this._contactVelocity}}Ro([u(b)],Tr.prototype,"center"),Ro([u()],Tr.prototype,"radius"),Ro([u()],Tr.prototype,"height");class To extends M{controller;movementSpeed=2;rotationSpeed=2;jumpForce=1;doubleJumpForce=2;animator;lookForward=!0;awake(){this._currentRotation=new U}update(){const e=this.context.input;e.isKeyPressed("KeyW")?this.moveInput.y+=1:e.isKeyPressed("KeyS")&&(this.moveInput.y-=1),e.isKeyPressed("KeyD")?this.lookInput.x+=1:e.isKeyPressed("KeyA")&&(this.lookInput.x-=1),this.jumpInput||=e.isKeyDown("Space")}move(e){this.moveInput.add(e)}look(e){this.lookInput.add(e)}jump(){this.jumpInput=!0}lookInput=new J(0,0);moveInput=new J(0,0);jumpInput=!1;onBeforeRender(){this.handleInput(this.moveInput,this.lookInput,this.jumpInput),this.lookInput.set(0,0),this.moveInput.set(0,0),this.jumpInput=!1}_currentSpeed=new b(0,0,0);_currentAngularSpeed=new b(0,0,0);_temp=new b(0,0,0);_jumpCount=0;_currentRotation;handleInput(e,t,i){if(this.controller?.isGrounded&&(this._jumpCount=0,this.doubleJumpForce>0&&this.animator?.setBool("doubleJump",!1)),this._currentSpeed.z+=e.y*this.movementSpeed*this.context.time.deltaTime,this.animator?.setBool("running",e.length()>.01),this.animator?.setBool("jumping",this.controller?.isGrounded===!0&&i),this._temp.copy(this._currentSpeed),this._temp.applyQuaternion(this.gameObject.quaternion),this.controller?this.controller.move(this._temp):this.gameObject.position.add(this._temp),this._currentAngularSpeed.y+=D.toRadians(-t.x*this.rotationSpeed)*this.context.time.deltaTime,this.lookForward&&Math.abs(this._currentAngularSpeed.y)<.01){const n=this.context.mainCameraComponent.forward;n.y=0,n.normalize(),this._currentRotation.setFromUnitVectors(new b(0,0,1),n),this.gameObject.quaternion.slerp(this._currentRotation,this.context.time.deltaTime*10)}if(this.gameObject.rotateY(this._currentAngularSpeed.y),this._currentSpeed.multiplyScalar(1-this.context.time.deltaTime*10),this._currentAngularSpeed.y*=1-this.context.time.deltaTime*10,this.controller&&i&&this.jumpForce>0){let n=this.controller?.isGrounded;if(this.doubleJumpForce>0&&!this.controller?.isGrounded&&this._jumpCount===1&&(n=!0,this.animator?.setBool("doubleJump",!0)),n){this._jumpCount+=1;const s=this.controller.rigidbody,r=this._jumpCount===2?this.doubleJumpForce:this.jumpForce;s.applyImpulse(new b(0,1,0).multiplyScalar(r))}}if(this.controller){const n=this.controller?.rigidbody.getVelocity().y;if(n<-1){this._raycastOptions.ray||(this._raycastOptions.ray=new ns),this._raycastOptions.ray.origin.copy(Z(this.gameObject)),this._raycastOptions.ray.direction.set(0,-1,0);const s=this.layer;this.gameObject.layers.disableAll(),this.gameObject.layers.set(2);const r=this.context.physics.raycast(this._raycastOptions);this.gameObject.layers.set(s),(r.length&&r[0].distance>2||n<-10)&&this.animator?.setBool("falling",!0)}else this.animator?.setBool("falling",!1)}}_raycastOptions=new us}Ro([u(Tr)],To.prototype,"controller"),Ro([u()],To.prototype,"movementSpeed"),Ro([u()],To.prototype,"rotationSpeed"),Ro([u()],To.prototype,"jumpForce"),Ro([u()],To.prototype,"doubleJumpForce"),Ro([u(ft)],To.prototype,"animator");var ER=Object.defineProperty,qa=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&ER(e,t,n),n};const Ec=w("debugcontactshadows");hu(o=>{const e=o.domElement.getAttribute("contactshadows")||o.domElement.getAttribute("contact-shadows");if(e!=null&&e!="0"&&e!="false"){console.debug("Auto-creating ContactShadows because of `contactshadows` attribute");const t=Ac.auto(o),i=parseFloat(e);isNaN(i)||(t.opacity=i,t.darkness=i)}});const Er=class qh extends M{static _instances=new Map;static auto(e,t){if(e||(e=z.Current),!e)throw new Error("No context provided and no current context set.");let i=this._instances.get(e);if(!i||i.destroyed){const n=new O;i=bn(n,qh,{autoFit:!1,occludeBelowGround:!1}),this._instances.set(e,i)}return e.scene.add(i.gameObject),i.fitShadows(t),i}autoFit=!1;darkness=.5;opacity=.5;blur=4;occludeBelowGround=!1;backfaceShadows=!0;minSize;manualUpdate=!1;set needsUpdate(e){this._needsUpdate=e}get needsUpdate(){return this._needsUpdate}_needsUpdate=!1;shadowsRoot=new O;shadowCamera;shadowGroup=new os;renderTarget;renderTargetBlur;plane;occluderMesh;blurPlane;depthMaterial;horizontalBlurMaterial;verticalBlurMaterial;textureSize=512;fitShadows(e={}){Ec&&console.warn("Fitting shadows to scene"),vd(this.shadowsRoot,!1);const t=e.object||this.context.scene,i=Wt(t,[this.shadowsRoot]),n=Math.max(1,this.blur/32),s=i.max.x-i.min.x,r=i.max.z-i.min.z;i.expandByVector(new b(n*s,0,n*r)),Ec&&F.DrawWireBox3(i,16776960,60),this.gameObject.parent&&i.applyMatrix4(this.gameObject.parent.matrixWorld.clone().invert());const a=i.min,l=Math.max(1e-5,(i.max.y-a.y)*.002);i.max.y+=l,this.shadowsRoot.position.set((a.x+i.max.x)/2,a.y-l,(a.z+i.max.z)/2),this.shadowsRoot.scale.set(i.max.x-a.x,i.max.y-a.y,i.max.z-a.z),e.positionOffset&&(e.positionOffset.x!==void 0&&(this.shadowsRoot.position.x+=e.positionOffset.x),e.positionOffset.y!==void 0&&(this.shadowsRoot.position.y+=e.positionOffset.y),e.positionOffset.z!==void 0&&(this.shadowsRoot.position.z+=e.positionOffset.z)),e.scaleFactor&&(e.scaleFactor.x!==void 0&&(this.shadowsRoot.scale.x*=e.scaleFactor.x),e.scaleFactor.y!==void 0&&(this.shadowsRoot.scale.y*=e.scaleFactor.y),e.scaleFactor.z!==void 0&&(this.shadowsRoot.scale.z*=e.scaleFactor.z)),this.applyMinSize(),this.shadowsRoot.matrixWorldNeedsUpdate=!0,Ec&&console.log("Fitted shadows to scene",this.shadowsRoot.scale.clone())}awake(){qh._instances.set(this.context,this),this.shadowsRoot.hideFlags=Su.DontExport,vd(this.shadowsRoot,!1)}start(){Ec&&console.log("Create ContactShadows on "+this.gameObject.name,this),this.gameObject.add(this.shadowsRoot),this.shadowsRoot.add(this.shadowGroup),this.renderTarget=new jn(this.textureSize,this.textureSize),this.renderTarget.texture.generateMipmaps=!1,this.renderTargetBlur=new jn(this.textureSize,this.textureSize),this.renderTargetBlur.texture.generateMipmaps=!1;const e=new In(1,1).rotateX(Math.PI/2);this.gameObject instanceof H&&(console.warn("ContactShadows can not be added to a Mesh. Please add it to a Group or an empty Object"),Co(this.gameObject,!1));const t=new xe({map:this.renderTarget.texture,opacity:this.opacity,color:0,transparent:!0,depthWrite:!1,side:as});this.plane=new H(e,t),this.plane.scale.y=-1,this.plane.layers.set(2),this.shadowsRoot.add(this.plane),this.plane&&(this.plane.renderOrder=1),this.occluderMesh=new H(this.plane.geometry,new xe({depthWrite:!0,stencilWrite:!0,colorWrite:!1,side:ud})).translateY(-1e-4),this.occluderMesh.renderOrder=-100,this.occluderMesh.layers.set(2),this.shadowsRoot.add(this.occluderMesh),this.blurPlane=new H(e),this.blurPlane.visible=!1,this.shadowGroup.add(this.blurPlane);const i=0,n=1;this.shadowCamera=new nd(-1/2,1/2,1/2,-1/2,i,n),this.shadowCamera.layers.enableAll(),this.shadowCamera.rotation.x=Math.PI/2,this.shadowGroup.add(this.shadowCamera),this.depthMaterial=new yS,this.depthMaterial.userData.darkness={value:this.darkness},this.depthMaterial.blending=bS,this.depthMaterial.blendEquation=_S,this.depthMaterial.onBeforeCompile=s=>{this.depthMaterial&&(s.uniforms.darkness=this.depthMaterial.userData.darkness,s.fragmentShader=`
955
955
  uniform float darkness;
956
956
  ${s.fragmentShader.replace("gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );","gl_FragColor = vec4( vec3( 1.0 ), ( 1.0 - fragCoordZ ) * darkness * opacity * (gl_FrontFacing ? 1.0 : 0.66) );")}
957
- `)},this.depthMaterial.depthTest=!1,this.depthMaterial.depthWrite=!1,this.horizontalBlurMaterial=new Ln(xC),this.horizontalBlurMaterial.depthTest=!1,this.verticalBlurMaterial=new Ln(SC),this.verticalBlurMaterial.depthTest=!1,this.shadowGroup.visible=!1,this.autoFit?this.fitShadows():this.applyMinSize()}onEnable(){this._needsUpdate=!0}onDestroy(){qh._instances.get(this.context)===this&&qh._instances.delete(this.context),this.renderTarget?.dispose(),this.renderTargetBlur?.dispose(),this.depthMaterial?.dispose(),this.horizontalBlurMaterial?.dispose(),this.verticalBlurMaterial?.dispose(),this.blurPlane?.geometry.dispose(),this.plane?.geometry.dispose(),this.occluderMesh?.geometry.dispose()}onBeforeRender(e){if(this.manualUpdate&&!this._needsUpdate)return;if(this._needsUpdate=!1,!this.renderTarget||!this.renderTargetBlur||!this.depthMaterial||!this.shadowCamera||!this.blurPlane||!this.shadowGroup||!this.plane||!this.horizontalBlurMaterial||!this.verticalBlurMaterial){Ec&&console.error("ContactShadows: not initialized yet");return}const t=this.context.scene,i=this.context.renderer,n=i.getRenderTarget();this.shadowGroup.visible=!0,this.occluderMesh&&(this.occluderMesh.visible=!1);const s=this.plane.visible;this.plane.visible=!1,this.gameObject instanceof H&&Co(this.gameObject,!1);const r=t.background;t.background=null,t.overrideMaterial=this.depthMaterial,this.backfaceShadows?this.depthMaterial.side=vi:this.depthMaterial.side=as;const a=i.getClearAlpha();i.setClearAlpha(0);const l=i.xr.enabled;i.xr.enabled=!1;const c=this.context.scene.matrixWorldAutoUpdate;this.context.scene.matrixWorldAutoUpdate=!1;const h=i.renderLists.get(t,0),d=h.transparent;Aw.length=0,h.transparent=Aw,ff.length=0;for(const g of h.opaque){if(!g.object.visible)continue;const f=g.material;let m=g.material.colorWrite==!1||f.wireframe===!0||Wb(g.object)===!1;!m&&g.material.isLineMaterial&&(m=!0),!m&&g.material.isPointsMaterial&&(m=!0),m&&(ff.push(g.object),g.object["needle:visible"]=g.object.visible,g.object.visible=!1)}i.setRenderTarget(this.renderTarget),i.clear(),i.render(t,this.shadowCamera),h.transparent=d;for(const g of ff)g["needle:visible"]!=null&&(g.visible=g["needle:visible"]);t.overrideMaterial=null;const p=Math.max(this.blur,.05);this.blurShadow(p*2),this.blurShadow(p*.5),this.shadowGroup.visible=!1,this.occluderMesh&&(this.occluderMesh.visible=this.occludeBelowGround),this.plane.visible=s,i.setRenderTarget(n),i.setClearAlpha(a),t.background=r,i.xr.enabled=l,this.context.scene.matrixWorldAutoUpdate=c}blurShadow(e){if(!this.blurPlane||!this.shadowCamera||!this.renderTarget||!this.renderTargetBlur||!this.horizontalBlurMaterial||!this.verticalBlurMaterial)return;this.blurPlane.visible=!0;const t=this.shadowsRoot.worldScale,i=(t.x+t.z)/2,n=t.z/i,s=t.x/i;this.blurPlane.material=this.horizontalBlurMaterial,this.blurPlane.material.uniforms.tDiffuse.value=this.renderTarget.texture,this.horizontalBlurMaterial.uniforms.h.value=e*1/this.textureSize*n;const r=this.context.renderer,a=r.getRenderTarget();r.setRenderTarget(this.renderTargetBlur),r.render(this.blurPlane,this.shadowCamera),this.blurPlane.material=this.verticalBlurMaterial,this.blurPlane.material.uniforms.tDiffuse.value=this.renderTargetBlur.texture,this.verticalBlurMaterial.uniforms.v.value=e*1/this.textureSize*s,r.setRenderTarget(this.renderTarget),r.render(this.blurPlane,this.shadowCamera),this.blurPlane.visible=!1,r.setRenderTarget(a)}applyMinSize(){this.minSize&&this.shadowsRoot.scale.set(Math.max(this.minSize.x||0,this.shadowsRoot.scale.x),Math.max(this.minSize.y||0,this.shadowsRoot.scale.y),Math.max(this.minSize.z||0,this.shadowsRoot.scale.z))}};qa([u()],Er.prototype,"autoFit"),qa([u()],Er.prototype,"darkness"),qa([u()],Er.prototype,"opacity"),qa([u()],Er.prototype,"blur"),qa([u()],Er.prototype,"occludeBelowGround"),qa([u()],Er.prototype,"backfaceShadows");let Ac=Er;const Aw=[],ff=new Array,AR=w("logstats");class yf extends M{onEnable(){console.log(this),AR&&this.startCoroutine(this.run(),we.OnAfterRender)}*run(){for(;this.enabled;){const e=this.context.renderer.info;console.log(e.memory,e.render,e.programs),yield}}}class Ic extends M{isUsed=!0;usedBy=null}class bf extends M{}const Iw=w("debugdeletable");class Zs extends xt{static _instances=[];onEnable(){Zs._instances.push(this)}onDisable(){const e=Zs._instances.indexOf(this);e>=0&&Zs._instances.splice(e,1)}}class _f extends M{update(){for(const e of Zs._instances){const t=this.gameObject;if(e.isInBox(t)===!0){const i=x.getComponentInParent(this.gameObject,Ic);if(i)Iw&&console.warn("DeleteBox: Not deleting object with usage marker",this.guid,i);else{if(Iw)try{if(e.box){const n=e.box,s=xt.testBox;F.DrawWireBox3(n,16711680,5),F.DrawWireBox3(s,255,5),console.log("DeleteBox: Destroying",this.gameObject,{deleteBoxArea:n,deletedObjectArea:s})}else console.log("DeleteBox: Destroying",this.gameObject)}catch{}ac(this.gameObject,this.context.connection)}}}}}var IR=Object.defineProperty,LR=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&IR(e,t,n),n};class ku extends M{visibleOn;onEnable(){this.apply()}apply(){this.test()||x.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:G.isMobileDevice()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}}LR([u()],ku.prototype,"visibleOn");var jR=Object.defineProperty,Ar=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&jR(e,t,n),n};const Qn=w("debugdrag"),vf=[];var wf=(o=>(o[o.XZPlane=0]="XZPlane",o[o.Attached=1]="Attached",o[o.HitNormal=2]="HitNormal",o[o.DynamicViewAngle=3]="DynamicViewAngle",o[o.SnapToSurfaces=4]="SnapToSurfaces",o[o.None=5]="None",o))(wf||{});const Ss=class sn extends M{static get HasAnySelected(){return this._active>0}static _active=0;static get CurrentlySelected(){vf.length=0;for(const e of this._instances)e._isDragging&&vf.push(e);return vf}static _instances=[];dragMode=3;snapGridResolution=0;keepRotation=!0;xrDragMode=1;xrKeepRotation=!1;xrDistanceDragFactor=1;showGizmo=!1;get draggedObject(){return this._targetObject}setTargetObject(e){this._targetObject=e;for(const i of this._dragHandlers.values())i.setTargetObject(e);const t="_rigidbody-was-kinematic";this._rigidbody?.[t]===!1&&(this._rigidbody.isKinematic=!1,this._rigidbody[t]=void 0),this._rigidbody=null,e&&(this._rigidbody=x.getComponentInChildren(e,Ye),this._rigidbody?.isKinematic===!1&&(this._rigidbody.isKinematic=!0,this._rigidbody[t]=!1))}_rigidbody=null;_targetObject=null;_dragHelper=null;static lastHovered;_draggingRigidbodies=[];_potentialDragStartEvt=null;_dragHandlers=new Map;_totalMovement=new b;_marker=null;_isDragging=!1;_didDrag=!1;awake(){this._potentialDragStartEvt=null,this._dragHandlers=new Map,this._totalMovement=new b,this._marker=null,this._isDragging=!1,this._didDrag=!1,this._dragHelper=null,this._draggingRigidbodies=[]}start(){this.gameObject.getComponentInParent(ki)||this.gameObject.addComponent(ki)}onEnable(){sn._instances.push(this)}onDisable(){sn._instances=sn._instances.filter(e=>e!==this)}allowEdit(e=null){return this.context.connection.allowEditing}onPointerEnter(e){if(!this.allowEdit(this.gameObject)||e.mode!=="screen"||(e.event.mode==="tracked-pointer"||e.event.mode==="transient-pointer"?this.xrDragMode:this.dragMode)===5)return;const t=x.getComponentInParent(e.object,sn);!t||t!==this||(sn.lastHovered=e.object,this.context.domElement.style.cursor="pointer")}onPointerMove(e){(this._isDragging||this._potentialDragStartEvt!==null)&&e.use()}onPointerExit(e){this.allowEdit(this.gameObject)&&e.mode==="screen"&&sn.lastHovered===e.object&&(this.context.domElement.style.cursor="auto")}onPointerDown(e){if(!(!this.allowEdit(this.gameObject)||e.used||(e.mode==="tracked-pointer"||e.mode==="transient-pointer"?this.xrDragMode:this.dragMode)===5)&&(sn.lastHovered=e.object,e.button===0)){this._dragHandlers.size===0&&(this._didDrag=!1,this._totalMovement.set(0,0,0),this._potentialDragStartEvt=e),this._targetObject||this.setTargetObject(this.gameObject),sn._active+=1;const t=new xf(this,this._targetObject);if(this._dragHandlers.set(e.event.space,t),t.onDragStart(e),this._dragHandlers.size===2){const i=this._dragHandlers.values(),n=i.next().value,s=i.next().value;if(n instanceof xf&&s instanceof xf){const r=new DR(this,this._targetObject,n,s);this._dragHandlers.set(this.gameObject,r),r.onDragStart(e)}else console.error("Attempting to construct a MultiTouchDragHandler with invalid DragPointerHandlers. This is likely a bug.",{a:n,b:s})}e.use()}}onPointerUp(e){if(Qn&&F.DrawLabel(e.point??this.gameObject.worldPosition,"POINTERUP:"+e.pointerId+", "+e.button,.03,3),!this.allowEdit(this.gameObject)||e.button!==0)return;this._potentialDragStartEvt=null;const t=this._dragHandlers.get(e.event.space),i=this._dragHandlers.get(this.gameObject);i&&(i.handlerA===t||i.handlerB===t)&&(this._dragHandlers.delete(this.gameObject),i.onDragEnd(e)),t&&(sn._active>0&&(sn._active-=1),this.setTargetObject(null),t.onDragEnd&&t.onDragEnd(e),this._dragHandlers.delete(e.event.space),this._dragHandlers.size===0&&this.onLastDragEnd(e),e.use())}update(){for(const e of this._dragHandlers.values())e.collectMovementInfo&&e.collectMovementInfo(),e.getTotalMovement&&this._totalMovement.add(e.getTotalMovement());if(this._potentialDragStartEvt){if(!this._didDrag)if(this._totalMovement.length()>3e-4)this._didDrag=!0;else return;const e=this._potentialDragStartEvt;this._potentialDragStartEvt=null,this.onFirstDragStart(e)}for(const e of this._dragHandlers.values())e.onDragUpdate&&e.onDragUpdate(this._dragHandlers.size);this._dragHelper&&this._dragHelper.hasSelected&&this.onAnyDragUpdate()}onFirstDragStart(e){if(!e||!e.object)return;const t=x.getComponentInParent(e.object,sn);if(!t||t!==this&&t._isDragging)return;const i=this._targetObject||this.gameObject;if(!i)return;this._isDragging=!0;const n=x.getComponentInChildren(i,vn);Qn&&console.log("DRAG START",n,i),n&&(n.fastMode=!0,n?.requestOwnership()),this._marker=x.addComponent(i,Ic),this._draggingRigidbodies.length=0;const s=x.getComponentsInChildren(i,Ye);s&&this._draggingRigidbodies.push(...s)}onAnyDragUpdate(){if(!this._dragHelper)return;this._dragHelper.showGizmo=this.showGizmo,this._dragHelper.onUpdate(this.context);for(const t of this._draggingRigidbodies)t.wakeUp(),t.resetVelocities(),t.resetForcesAndTorques();const e=this._targetObject||this.gameObject;an.markDirty(e)}onLastDragEnd(e){if(!this||!this._isDragging)return;this._isDragging=!1;for(const i of this._draggingRigidbodies)i.setVelocity(i.smoothedVelocity);if(this._draggingRigidbodies.length=0,this._targetObject=null,e?.object){const i=x.getComponentInChildren(e.object,vn);i&&(i.fastMode=!1)}if(this._marker&&this._marker.destroy(),!this._dragHelper)return;const t=this._dragHelper.selected;Qn&&console.log("DRAG END",t,t?.visible),this._dragHelper.setSelected(null,this.context)}};Ar([u()],Ss.prototype,"dragMode"),Ar([u()],Ss.prototype,"snapGridResolution"),Ar([u()],Ss.prototype,"keepRotation"),Ar([u()],Ss.prototype,"xrDragMode"),Ar([u()],Ss.prototype,"xrKeepRotation"),Ar([u()],Ss.prototype,"xrDistanceDragFactor"),Ar([u()],Ss.prototype,"showGizmo");let Ir=Ss;class DR{handlerA;handlerB;context;settings;gameObject;_handlerAAttachmentPoint=new b;_handlerBAttachmentPoint=new b;_followObject;_manipulatorObject;_deviceMode;_followObjectStartWorldQuaternion=new U;constructor(e,t,i,n){this.context=e.context,this.settings=e,this.gameObject=t,this.handlerA=i,this.handlerB=n,this._followObject=new O,this._manipulatorObject=new O,this.context.scene.add(this._manipulatorObject);const s=K.active?.rig?.gameObject;if(!this.handlerA||!this.handlerB||!this.handlerA.hitPointInLocalSpace||!this.handlerB.hitPointInLocalSpace){console.error("Invalid: MultiTouchDragHandler needs two valid DragPointerHandlers with hitPointInLocalSpace set.");return}if(this._tempVec1.copy(this.handlerA.hitPointInLocalSpace),this._tempVec2.copy(this.handlerB.hitPointInLocalSpace),this.gameObject.localToWorld(this._tempVec1),this.gameObject.localToWorld(this._tempVec2),s&&(s.worldToLocal(this._tempVec1),s.worldToLocal(this._tempVec2)),this._initialDistance=this._tempVec1.distanceTo(this._tempVec2),this._initialDistance<.02?(Qn&&console.log("Finding alternative drag attachment points since initial distance is too low: "+this._initialDistance.toFixed(2)),this.handlerA.followObject.parent.getWorldPosition(this._tempVec1),this.handlerB.followObject.parent.getWorldPosition(this._tempVec2),this._handlerAAttachmentPoint.copy(this._tempVec1),this._handlerBAttachmentPoint.copy(this._tempVec2),this.gameObject.worldToLocal(this._handlerAAttachmentPoint),this.gameObject.worldToLocal(this._handlerBAttachmentPoint),this._initialDistance=this._tempVec1.distanceTo(this._tempVec2),this._initialDistance<.001&&(console.warn("Not supported right now \u2013 controller drag points for multitouch are too close!"),this._initialDistance=1)):(this._handlerAAttachmentPoint.copy(this.handlerA.hitPointInLocalSpace),this._handlerBAttachmentPoint.copy(this.handlerB.hitPointInLocalSpace)),this._tempVec3.lerpVectors(this._tempVec1,this._tempVec2,.5),this._initialScale.copy(t.scale),Qn){this._followObject.add(new _i(2)),this._manipulatorObject.add(new _i(5));const r=a=>`${a.x.toFixed(2)}, ${a.y.toFixed(2)}, ${a.z.toFixed(2)}`;F.DrawLine(this._tempVec1,this._tempVec2,65535,0,!1),F.DrawLabel(this._tempVec3,"A:B "+this._initialDistance.toFixed(2)+`
957
+ `)},this.depthMaterial.depthTest=!1,this.depthMaterial.depthWrite=!1,this.horizontalBlurMaterial=new Ln(xC),this.horizontalBlurMaterial.depthTest=!1,this.verticalBlurMaterial=new Ln(SC),this.verticalBlurMaterial.depthTest=!1,this.shadowGroup.visible=!1,this.autoFit?this.fitShadows():this.applyMinSize()}onEnable(){this._needsUpdate=!0}onDestroy(){qh._instances.get(this.context)===this&&qh._instances.delete(this.context),this.renderTarget?.dispose(),this.renderTargetBlur?.dispose(),this.depthMaterial?.dispose(),this.horizontalBlurMaterial?.dispose(),this.verticalBlurMaterial?.dispose(),this.blurPlane?.geometry.dispose(),this.plane?.geometry.dispose(),this.occluderMesh?.geometry.dispose()}onBeforeRender(e){if(this.manualUpdate&&!this._needsUpdate)return;if(this._needsUpdate=!1,!this.renderTarget||!this.renderTargetBlur||!this.depthMaterial||!this.shadowCamera||!this.blurPlane||!this.shadowGroup||!this.plane||!this.horizontalBlurMaterial||!this.verticalBlurMaterial){Ec&&console.error("ContactShadows: not initialized yet");return}const t=this.context.scene,i=this.context.renderer,n=i.getRenderTarget();this.shadowGroup.visible=!0,this.occluderMesh&&(this.occluderMesh.visible=!1);const s=this.plane.visible;this.plane.visible=!1,this.gameObject instanceof H&&Co(this.gameObject,!1);const r=t.background;t.background=null,t.overrideMaterial=this.depthMaterial,this.backfaceShadows?this.depthMaterial.side=vi:this.depthMaterial.side=as;const a=i.getClearAlpha();i.setClearAlpha(0);const l=i.xr.enabled;i.xr.enabled=!1;const c=this.context.scene.matrixWorldAutoUpdate;this.context.scene.matrixWorldAutoUpdate=!1;const h=i.renderLists.get(t,0),d=h.transparent;Aw.length=0,h.transparent=Aw,ff.length=0;for(const m of h.opaque){if(!m.object.visible)continue;const f=m.material;let g=m.material.colorWrite==!1||f.wireframe===!0||Wb(m.object)===!1;!g&&m.material.isLineMaterial&&(g=!0),!g&&m.material.isPointsMaterial&&(g=!0),g&&(ff.push(m.object),m.object["needle:visible"]=m.object.visible,m.object.visible=!1)}i.setRenderTarget(this.renderTarget),i.clear(),i.render(t,this.shadowCamera),h.transparent=d;for(const m of ff)m["needle:visible"]!=null&&(m.visible=m["needle:visible"]);t.overrideMaterial=null;const p=Math.max(this.blur,.05);this.blurShadow(p*2),this.blurShadow(p*.5),this.shadowGroup.visible=!1,this.occluderMesh&&(this.occluderMesh.visible=this.occludeBelowGround),this.plane.visible=s,i.setRenderTarget(n),i.setClearAlpha(a),t.background=r,i.xr.enabled=l,this.context.scene.matrixWorldAutoUpdate=c}blurShadow(e){if(!this.blurPlane||!this.shadowCamera||!this.renderTarget||!this.renderTargetBlur||!this.horizontalBlurMaterial||!this.verticalBlurMaterial)return;this.blurPlane.visible=!0;const t=this.shadowsRoot.worldScale,i=(t.x+t.z)/2,n=t.z/i,s=t.x/i;this.blurPlane.material=this.horizontalBlurMaterial,this.blurPlane.material.uniforms.tDiffuse.value=this.renderTarget.texture,this.horizontalBlurMaterial.uniforms.h.value=e*1/this.textureSize*n;const r=this.context.renderer,a=r.getRenderTarget();r.setRenderTarget(this.renderTargetBlur),r.render(this.blurPlane,this.shadowCamera),this.blurPlane.material=this.verticalBlurMaterial,this.blurPlane.material.uniforms.tDiffuse.value=this.renderTargetBlur.texture,this.verticalBlurMaterial.uniforms.v.value=e*1/this.textureSize*s,r.setRenderTarget(this.renderTarget),r.render(this.blurPlane,this.shadowCamera),this.blurPlane.visible=!1,r.setRenderTarget(a)}applyMinSize(){this.minSize&&this.shadowsRoot.scale.set(Math.max(this.minSize.x||0,this.shadowsRoot.scale.x),Math.max(this.minSize.y||0,this.shadowsRoot.scale.y),Math.max(this.minSize.z||0,this.shadowsRoot.scale.z))}};qa([u()],Er.prototype,"autoFit"),qa([u()],Er.prototype,"darkness"),qa([u()],Er.prototype,"opacity"),qa([u()],Er.prototype,"blur"),qa([u()],Er.prototype,"occludeBelowGround"),qa([u()],Er.prototype,"backfaceShadows");let Ac=Er;const Aw=[],ff=new Array,AR=w("logstats");class yf extends M{onEnable(){console.log(this),AR&&this.startCoroutine(this.run(),we.OnAfterRender)}*run(){for(;this.enabled;){const e=this.context.renderer.info;console.log(e.memory,e.render,e.programs),yield}}}class Ic extends M{isUsed=!0;usedBy=null}class bf extends M{}const Iw=w("debugdeletable");class Zs extends xt{static _instances=[];onEnable(){Zs._instances.push(this)}onDisable(){const e=Zs._instances.indexOf(this);e>=0&&Zs._instances.splice(e,1)}}class _f extends M{update(){for(const e of Zs._instances){const t=this.gameObject;if(e.isInBox(t)===!0){const i=x.getComponentInParent(this.gameObject,Ic);if(i)Iw&&console.warn("DeleteBox: Not deleting object with usage marker",this.guid,i);else{if(Iw)try{if(e.box){const n=e.box,s=xt.testBox;F.DrawWireBox3(n,16711680,5),F.DrawWireBox3(s,255,5),console.log("DeleteBox: Destroying",this.gameObject,{deleteBoxArea:n,deletedObjectArea:s})}else console.log("DeleteBox: Destroying",this.gameObject)}catch{}ac(this.gameObject,this.context.connection)}}}}}var IR=Object.defineProperty,LR=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&IR(e,t,n),n};class ku extends M{visibleOn;onEnable(){this.apply()}apply(){this.test()||x.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:G.isMobileDevice()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}}LR([u()],ku.prototype,"visibleOn");var jR=Object.defineProperty,Ar=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&jR(e,t,n),n};const Qn=w("debugdrag"),vf=[];var wf=(o=>(o[o.XZPlane=0]="XZPlane",o[o.Attached=1]="Attached",o[o.HitNormal=2]="HitNormal",o[o.DynamicViewAngle=3]="DynamicViewAngle",o[o.SnapToSurfaces=4]="SnapToSurfaces",o[o.None=5]="None",o))(wf||{});const Ss=class sn extends M{static get HasAnySelected(){return this._active>0}static _active=0;static get CurrentlySelected(){vf.length=0;for(const e of this._instances)e._isDragging&&vf.push(e);return vf}static _instances=[];dragMode=3;snapGridResolution=0;keepRotation=!0;xrDragMode=1;xrKeepRotation=!1;xrDistanceDragFactor=1;showGizmo=!1;get draggedObject(){return this._targetObject}setTargetObject(e){this._targetObject=e;for(const i of this._dragHandlers.values())i.setTargetObject(e);const t="_rigidbody-was-kinematic";this._rigidbody?.[t]===!1&&(this._rigidbody.isKinematic=!1,this._rigidbody[t]=void 0),this._rigidbody=null,e&&(this._rigidbody=x.getComponentInChildren(e,Ye),this._rigidbody?.isKinematic===!1&&(this._rigidbody.isKinematic=!0,this._rigidbody[t]=!1))}_rigidbody=null;_targetObject=null;_dragHelper=null;static lastHovered;_draggingRigidbodies=[];_potentialDragStartEvt=null;_dragHandlers=new Map;_totalMovement=new b;_marker=null;_isDragging=!1;_didDrag=!1;awake(){this._potentialDragStartEvt=null,this._dragHandlers=new Map,this._totalMovement=new b,this._marker=null,this._isDragging=!1,this._didDrag=!1,this._dragHelper=null,this._draggingRigidbodies=[]}start(){this.gameObject.getComponentInParent(ki)||this.gameObject.addComponent(ki)}onEnable(){sn._instances.push(this)}onDisable(){sn._instances=sn._instances.filter(e=>e!==this)}allowEdit(e=null){return this.context.connection.allowEditing}onPointerEnter(e){if(!this.allowEdit(this.gameObject)||e.mode!=="screen"||(e.event.mode==="tracked-pointer"||e.event.mode==="transient-pointer"?this.xrDragMode:this.dragMode)===5)return;const t=x.getComponentInParent(e.object,sn);!t||t!==this||(sn.lastHovered=e.object,this.context.domElement.style.cursor="pointer")}onPointerMove(e){(this._isDragging||this._potentialDragStartEvt!==null)&&e.use()}onPointerExit(e){this.allowEdit(this.gameObject)&&e.mode==="screen"&&sn.lastHovered===e.object&&(this.context.domElement.style.cursor="auto")}onPointerDown(e){if(!(!this.allowEdit(this.gameObject)||e.used||(e.mode==="tracked-pointer"||e.mode==="transient-pointer"?this.xrDragMode:this.dragMode)===5)&&(sn.lastHovered=e.object,e.button===0)){this._dragHandlers.size===0&&(this._didDrag=!1,this._totalMovement.set(0,0,0),this._potentialDragStartEvt=e),this._targetObject||this.setTargetObject(this.gameObject),sn._active+=1;const t=new xf(this,this._targetObject);if(this._dragHandlers.set(e.event.space,t),t.onDragStart(e),this._dragHandlers.size===2){const i=this._dragHandlers.values(),n=i.next().value,s=i.next().value;if(n instanceof xf&&s instanceof xf){const r=new DR(this,this._targetObject,n,s);this._dragHandlers.set(this.gameObject,r),r.onDragStart(e)}else console.error("Attempting to construct a MultiTouchDragHandler with invalid DragPointerHandlers. This is likely a bug.",{a:n,b:s})}e.use()}}onPointerUp(e){if(Qn&&F.DrawLabel(e.point??this.gameObject.worldPosition,"POINTERUP:"+e.pointerId+", "+e.button,.03,3),!this.allowEdit(this.gameObject)||e.button!==0)return;this._potentialDragStartEvt=null;const t=this._dragHandlers.get(e.event.space),i=this._dragHandlers.get(this.gameObject);i&&(i.handlerA===t||i.handlerB===t)&&(this._dragHandlers.delete(this.gameObject),i.onDragEnd(e)),t&&(sn._active>0&&(sn._active-=1),this.setTargetObject(null),t.onDragEnd&&t.onDragEnd(e),this._dragHandlers.delete(e.event.space),this._dragHandlers.size===0&&this.onLastDragEnd(e),e.use())}update(){for(const e of this._dragHandlers.values())e.collectMovementInfo&&e.collectMovementInfo(),e.getTotalMovement&&this._totalMovement.add(e.getTotalMovement());if(this._potentialDragStartEvt){if(!this._didDrag)if(this._totalMovement.length()>3e-4)this._didDrag=!0;else return;const e=this._potentialDragStartEvt;this._potentialDragStartEvt=null,this.onFirstDragStart(e)}for(const e of this._dragHandlers.values())e.onDragUpdate&&e.onDragUpdate(this._dragHandlers.size);this._dragHelper&&this._dragHelper.hasSelected&&this.onAnyDragUpdate()}onFirstDragStart(e){if(!e||!e.object)return;const t=x.getComponentInParent(e.object,sn);if(!t||t!==this&&t._isDragging)return;const i=this._targetObject||this.gameObject;if(!i)return;this._isDragging=!0;const n=x.getComponentInChildren(i,vn);Qn&&console.log("DRAG START",n,i),n&&(n.fastMode=!0,n?.requestOwnership()),this._marker=x.addComponent(i,Ic),this._draggingRigidbodies.length=0;const s=x.getComponentsInChildren(i,Ye);s&&this._draggingRigidbodies.push(...s)}onAnyDragUpdate(){if(!this._dragHelper)return;this._dragHelper.showGizmo=this.showGizmo,this._dragHelper.onUpdate(this.context);for(const t of this._draggingRigidbodies)t.wakeUp(),t.resetVelocities(),t.resetForcesAndTorques();const e=this._targetObject||this.gameObject;an.markDirty(e)}onLastDragEnd(e){if(!this||!this._isDragging)return;this._isDragging=!1;for(const i of this._draggingRigidbodies)i.setVelocity(i.smoothedVelocity);if(this._draggingRigidbodies.length=0,this._targetObject=null,e?.object){const i=x.getComponentInChildren(e.object,vn);i&&(i.fastMode=!1)}if(this._marker&&this._marker.destroy(),!this._dragHelper)return;const t=this._dragHelper.selected;Qn&&console.log("DRAG END",t,t?.visible),this._dragHelper.setSelected(null,this.context)}};Ar([u()],Ss.prototype,"dragMode"),Ar([u()],Ss.prototype,"snapGridResolution"),Ar([u()],Ss.prototype,"keepRotation"),Ar([u()],Ss.prototype,"xrDragMode"),Ar([u()],Ss.prototype,"xrKeepRotation"),Ar([u()],Ss.prototype,"xrDistanceDragFactor"),Ar([u()],Ss.prototype,"showGizmo");let Ir=Ss;class DR{handlerA;handlerB;context;settings;gameObject;_handlerAAttachmentPoint=new b;_handlerBAttachmentPoint=new b;_followObject;_manipulatorObject;_deviceMode;_followObjectStartWorldQuaternion=new U;constructor(e,t,i,n){this.context=e.context,this.settings=e,this.gameObject=t,this.handlerA=i,this.handlerB=n,this._followObject=new O,this._manipulatorObject=new O,this.context.scene.add(this._manipulatorObject);const s=K.active?.rig?.gameObject;if(!this.handlerA||!this.handlerB||!this.handlerA.hitPointInLocalSpace||!this.handlerB.hitPointInLocalSpace){console.error("Invalid: MultiTouchDragHandler needs two valid DragPointerHandlers with hitPointInLocalSpace set.");return}if(this._tempVec1.copy(this.handlerA.hitPointInLocalSpace),this._tempVec2.copy(this.handlerB.hitPointInLocalSpace),this.gameObject.localToWorld(this._tempVec1),this.gameObject.localToWorld(this._tempVec2),s&&(s.worldToLocal(this._tempVec1),s.worldToLocal(this._tempVec2)),this._initialDistance=this._tempVec1.distanceTo(this._tempVec2),this._initialDistance<.02?(Qn&&console.log("Finding alternative drag attachment points since initial distance is too low: "+this._initialDistance.toFixed(2)),this.handlerA.followObject.parent.getWorldPosition(this._tempVec1),this.handlerB.followObject.parent.getWorldPosition(this._tempVec2),this._handlerAAttachmentPoint.copy(this._tempVec1),this._handlerBAttachmentPoint.copy(this._tempVec2),this.gameObject.worldToLocal(this._handlerAAttachmentPoint),this.gameObject.worldToLocal(this._handlerBAttachmentPoint),this._initialDistance=this._tempVec1.distanceTo(this._tempVec2),this._initialDistance<.001&&(console.warn("Not supported right now \u2013 controller drag points for multitouch are too close!"),this._initialDistance=1)):(this._handlerAAttachmentPoint.copy(this.handlerA.hitPointInLocalSpace),this._handlerBAttachmentPoint.copy(this.handlerB.hitPointInLocalSpace)),this._tempVec3.lerpVectors(this._tempVec1,this._tempVec2,.5),this._initialScale.copy(t.scale),Qn){this._followObject.add(new _i(2)),this._manipulatorObject.add(new _i(5));const r=a=>`${a.x.toFixed(2)}, ${a.y.toFixed(2)}, ${a.z.toFixed(2)}`;F.DrawLine(this._tempVec1,this._tempVec2,65535,0,!1),F.DrawLabel(this._tempVec3,"A:B "+this._initialDistance.toFixed(2)+`
958
958
  `+r(this._tempVec1)+`
959
- `+r(this._tempVec2),.03,5)}}onDragStart(e){this.gameObject.add(this._followObject),this._followObject.matrixAutoUpdate=!1,this._followObject.matrix.identity(),this._deviceMode=e.mode,this._followObjectStartWorldQuaternion.copy(this._followObject.worldQuaternion),this.alignManipulator(),this._manipulatorObject.attach(this._followObject),this._manipulatorPosOffset.copy(this._followObject.position),this._manipulatorRotOffset.copy(this._followObject.quaternion),this._manipulatorScaleOffset.copy(this._followObject.scale)}onDragEnd(e){if(!this.handlerA||!this.handlerB){console.error("onDragEnd called on MultiTouchDragHandler without valid handlers. This is likely a bug.");return}this.handlerA.recenter(),this.handlerB.recenter(),this._manipulatorObject.removeFromParent(),this._followObject.removeFromParent(),this._manipulatorObject.destroy(),this._followObject.destroy()}_manipulatorPosOffset=new b;_manipulatorRotOffset=new U;_manipulatorScaleOffset=new b;_tempVec1=new b;_tempVec2=new b;_tempVec3=new b;tempLookMatrix=new ee;_initialScale=new b;_initialDistance=0;alignManipulator(){if(!this.handlerA||!this.handlerB){console.error("alignManipulator called on MultiTouchDragHandler without valid handlers. This is likely a bug.",this);return}if(!this.handlerA.followObject||!this.handlerB.followObject){console.error("alignManipulator called on MultiTouchDragHandler without valid follow objects. This is likely a bug.",this.handlerA,this.handlerB);return}this._tempVec1.copy(this._handlerAAttachmentPoint),this._tempVec2.copy(this._handlerBAttachmentPoint),this.handlerA.followObject.localToWorld(this._tempVec1),this.handlerB.followObject.localToWorld(this._tempVec2),this._tempVec3.lerpVectors(this._tempVec1,this._tempVec2,.5),this._manipulatorObject.position.copy(this._tempVec3);const e=this.context.mainCamera;this.tempLookMatrix.lookAt(this._tempVec3,this._tempVec2,e.worldUp),this._manipulatorObject.quaternion.setFromRotationMatrix(this.tempLookMatrix);const t=this._tempVec1.distanceTo(this._tempVec2);this._manipulatorObject.scale.copy(this._initialScale).multiplyScalar(t/this._initialDistance),this._manipulatorObject.updateMatrix(),this._manipulatorObject.updateMatrixWorld(!0),Qn&&(F.DrawLabel(this._tempVec3.clone().add(new b(0,.2,0)),"A:B "+t.toFixed(2),.03),F.DrawLine(this._tempVec1,this._tempVec2,65280,0,!1))}onDragUpdate(){this.alignManipulator();const e=30,t=1;this._followObject.position.copy(this._manipulatorPosOffset),this._followObject.quaternion.copy(this._manipulatorRotOffset),this._followObject.scale.copy(this._manipulatorScaleOffset);const i=this.gameObject,n=this._followObject;if(!i){console.error("MultiTouchDragHandler has no dragged object. This is likely a bug.");return}n.updateMatrix(),n.updateMatrixWorld(!0);const s=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer"?this.settings.xrKeepRotation:this.settings.keepRotation;if(this.settings.snapGridResolution>0){const h=this._followObject.worldPosition,d=this.settings.snapGridResolution;h.x=Math.round(h.x/d)*d,h.y=Math.round(h.y/d)*d,h.z=Math.round(h.z/d)*d,this._followObject.worldPosition=h,this._followObject.updateMatrix()}s&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion,this._followObject.updateMatrix());const r=D.clamp01(this.context.time.deltaTime*e*t),a=i.worldPosition;a.lerp(n.worldPosition,r),i.worldPosition=a;const l=i.worldQuaternion;l.slerp(n.worldQuaternion,r),i.worldQuaternion=l;const c=i.worldScale;c.lerp(n.worldScale,r),i.worldScale=c}setTargetObject(e){this.gameObject=e}}class xf{getTotalMovement(){return this._totalMovement}get followObject(){return this._followObject}get hitPointInLocalSpace(){return this._hitPointInLocalSpace}context;gameObject;settings;_lastRig=void 0;_followObject;_totalMovement=new b;_totalMovementAlongRayDirection=0;_grabStartDistance=0;_deviceMode;_followObjectStartPosition=new b;_followObjectStartQuaternion=new U;_followObjectStartWorldQuaternion=new U;_lastDragPosRigSpace;_tempVec=new b;_tempMat=new ee;_hitPointInLocalSpace=new b;_hitNormalInLocalSpace=new b;_bottomCenter=new b;_backCenter=new b;_backBottomCenter=new b;_bounds=new bi;_dragPlane=new tr(new b(0,1,0));_draggedOverObject=null;_draggedOverObjectLastSetUp=null;_draggedOverObjectLastNormal=new b;_draggedOverObjectDuration=0;setTargetObject(e){this.gameObject=e}constructor(e,t){this.settings=e,this.context=e.context,this.gameObject=t,this._followObject=new O}recenter(){if(!this._followObject.parent){console.warn("Error: space follow object doesn't have parent but recenter() is called. This is likely a bug");return}if(!this.gameObject){console.warn("Error: space follow object doesn't have a gameObject");return}const e=this._followObject.parent;this.gameObject.add(this._followObject),this._followObject.matrixAutoUpdate=!1,this._followObject.position.set(0,0,0),this._followObject.quaternion.set(0,0,0,1),this._followObject.scale.set(1,1,1),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0),e.attach(this._followObject),this._followObjectStartPosition.copy(this._followObject.position),this._followObjectStartQuaternion.copy(this._followObject.quaternion),this._followObjectStartWorldQuaternion.copy(this._followObject.worldQuaternion),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);const t=this._hitPointInLocalSpace.clone();this.gameObject.localToWorld(t),this._grabStartDistance=t.distanceTo(e.worldPosition);const i=K.active?.rig?.gameObject?.worldScale.x||1;this._grabStartDistance/=i,this._totalMovementAlongRayDirection=0,this._lastDragPosRigSpace=void 0,Qn&&(F.DrawLine(t,e.worldPosition,65280,.5,!1),F.DrawLabel(e.worldPosition.add(new b(0,.1,0)),this._grabStartDistance.toFixed(2),.03,.5))}onDragStart(e){if(!this.gameObject){console.warn("Error: space follow object doesn't have a gameObject");return}if(e.event.space.add(this._followObject),this._lastDragPosRigSpace=void 0,e.point&&e.normal)this._hitPointInLocalSpace.copy(e.point),this.gameObject.worldToLocal(this._hitPointInLocalSpace),this._hitNormalInLocalSpace.copy(e.normal);else if(e){const g=e.event.space,f=g.worldPosition;this.gameObject.worldToLocal(f),this._hitPointInLocalSpace.copy(f);const m=g.worldUp;this._tempMat.copy(this.gameObject.matrixWorld).invert(),m.transformDirection(this._tempMat),this._hitNormalInLocalSpace.copy(m)}this.recenter(),this._totalMovement.set(0,0,0),this._deviceMode=e.mode;const t=this._followObject.parent.worldForward,i=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer"?this.settings.xrDragMode:this.settings.dragMode,n=this._hitPointInLocalSpace.clone();switch(this.gameObject.localToWorld(n),i){case 0:const g=new b(0,1,0);this.gameObject.parent&&g.transformDirection(this.gameObject.parent.matrixWorld.clone().invert()),this._dragPlane.setFromNormalAndCoplanarPoint(g,n);break;case 2:const f=this._hitNormalInLocalSpace.clone();f.transformDirection(this.gameObject.matrixWorld),this._dragPlane.setFromNormalAndCoplanarPoint(f,n);break;case 1:this._dragPlane.setFromNormalAndCoplanarPoint(t,n);break;case 3:this.setPlaneViewAligned(n,!0);break;case 4:this.setPlaneViewAligned(n,!1);break}const s=this.gameObject.parent,r=this.gameObject.position.clone(),a=this.gameObject.quaternion.clone(),l=this.gameObject.scale.clone(),c=this.gameObject.matrixWorld.clone();s&&s.remove(this.gameObject),this.gameObject.position.set(0,0,0),this.gameObject.quaternion.set(0,0,0,1),this.gameObject.scale.set(1,1,1);const h=Wt([this.gameObject]);h.expandByPoint(this.gameObject.worldPosition);const d=new b;h.getCenter(d);const p=new b;h.getSize(p),this._bottomCenter.copy(d.clone().add(new b(0,-p.y/2,0))),this._backCenter.copy(d.clone().add(new b(0,0,p.z/2))),this._backBottomCenter.copy(d.clone().add(new b(0,-p.y/2,p.z/2))),this._bounds.copy(h),s&&s.add(this.gameObject),this.gameObject.position.copy(r),this.gameObject.quaternion.copy(a),this.gameObject.scale.copy(l),this.gameObject.matrixWorld.copy(c),this._draggedOverObject=null,this._draggedOverObjectLastSetUp=null,this._draggedOverObjectLastNormal.set(0,1,0),this._draggedOverObjectDuration=0}collectMovementInfo(){if(!this._followObject.parent)return;const e=this._followObject.parent;this._followObject.updateMatrix();const t=e.worldPosition,i=K.active?.rig?.gameObject;i&&i.worldToLocal(t),(this._lastDragPosRigSpace===void 0||i!=this._lastRig)&&(this._lastDragPosRigSpace=t.clone(),this._lastRig=i),this._tempVec.copy(t).sub(this._lastDragPosRigSpace);const n=e.worldForward;if(i&&(this._tempMat.copy(i.matrixWorld).invert(),n.transformDirection(this._tempMat)),this._totalMovementAlongRayDirection+=n.dot(this._tempVec),this._tempVec.x=Math.abs(this._tempVec.x),this._tempVec.y=Math.abs(this._tempVec.y),this._tempVec.z=Math.abs(this._tempVec.z),this._totalMovement.add(this._tempVec),this._lastDragPosRigSpace.copy(t),Qn){let s=t;i&&(s=s.clone(),s.transformDirection(i.matrixWorld)),F.DrawRay(s,n,255)}}onDragUpdate(e){if(e>1)return;const t=this.gameObject;if(!t||!this._followObject){console.warn("Warning: DragPointerHandler doesn't have a dragged object. This is likely a bug.");return}const i=this._followObject.parent;if(!i){console.warn("Warning: DragPointerHandler doesn't have a drag source. This is likely a bug.");return}this._followObject.updateMatrix();const n=i.worldPosition,s=i.worldForward,r=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer",a=r?this.settings.xrKeepRotation:this.settings.keepRotation,l=r?this.settings.xrDragMode:this.settings.dragMode;if(l===5)return;const c=10;a&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);let h=1,d=2;if(r&&this._grabStartDistance>.5){const v=1+this._totalMovementAlongRayDirection*(2*this.settings.xrDistanceDragFactor);h=Math.max(0,v),h=h*h*h}else this._grabStartDistance<=.5&&(d=3);this._followObject.position.copy(this._followObjectStartPosition),a||this._followObject.quaternion.copy(this._followObjectStartQuaternion),this._followObject.position.multiplyScalar(h),this._followObject.updateMatrix();const p=this._hasLastSurfaceHitPoint;this._hasLastSurfaceHitPoint=!1;const g=new ns(n,s);if(l==4){const v=this.context.physics.raycastFromRay(g,{testObject:P=>P!==this.followObject&&P!==i&&P!==t});if(v.length>0){const P=v[0];if(this._draggedOverObject===P.object?this._draggedOverObjectDuration+=this.context.time.deltaTime:(this._draggedOverObject=P.object,this._draggedOverObjectDuration=0),P.face){this._hasLastSurfaceHitPoint=!0,this._lastSurfaceHitPoint.copy(P.point);const R=this._draggedOverObjectDuration>=.15,k=this._totalMovement.length()>=.001,A=$(P.normal||P.face.normal).applyQuaternion(P.object.worldQuaternion);if((R||k)&&(this._draggedOverObjectLastSetUp!==this._draggedOverObject||this._draggedOverObjectLastNormal.dot(A)<.999999||this.context.time.frame%60===0)){this._draggedOverObjectLastSetUp=this._draggedOverObject,this._draggedOverObjectLastNormal.copy(P.face.normal);const L=$(),N=$();this._bounds.getCenter(L),this._bounds.getSize(N),L.sub(N.multiplyScalar(.5).multiply(A)),this._hitPointInLocalSpace.copy(L),this._hitNormalInLocalSpace.copy(P.face.normal),this._bounds.getCenter(L),this._bounds.getSize(N),L.add(N.multiplyScalar(.5).multiply(P.face.normal));const j=$(this._hitPointInLocalSpace).add(L);this._followObject.localToWorld(j);const q=P.point;this._dragPlane.setFromNormalAndCoplanarPoint(A,q)}else if(!(R||k))return}}else p&&this.gameObject&&this.setPlaneViewAligned(this.gameObject.worldPosition,!1)}if(l!==1&&g.intersectPlane(this._dragPlane,this._tempVec)){this._followObject.worldPosition=this._tempVec,this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);const v=$(this._hitPointInLocalSpace);this._followObject.localToWorld(v),Qn&&F.DrawLine(v,this._tempVec,65535,0,!1),this._followObject.worldPosition=this._tempVec.multiplyScalar(2).sub(v),this._followObject.updateMatrix(),this._followObject.updateMatrix()}if(this.settings.snapGridResolution>0){const v=this._followObject.worldPosition,P=this.settings.snapGridResolution;v.x=Math.round(v.x/P)*P,v.y=Math.round(v.y/P)*P,v.z=Math.round(v.z/P)*P,this._followObject.worldPosition=v,this._followObject.updateMatrix()}a&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion,this._followObject.updateMatrix());const f=D.clamp01(this.context.time.deltaTime*c*d),m=D.clamp01(this.context.time.deltaTime*c*.5*d),y=t.worldPosition;y.lerp(this._followObject.worldPosition,f),t.worldPosition=y;const _=t.worldQuaternion;if(_.slerp(this._followObject.worldQuaternion,m),t.worldQuaternion=_,Qn){const v=this._hitPointInLocalSpace.clone();t.localToWorld(v),F.DrawSphere(v,.02,16711680);const P=this._hitNormalInLocalSpace.clone();P.applyQuaternion(_),F.DrawRay(v,P,16711680),F.DrawLabel(y.add(new b(0,.25,0)),`Distance: ${this._totalMovement.length().toFixed(2)}
959
+ `+r(this._tempVec2),.03,5)}}onDragStart(e){this.gameObject.add(this._followObject),this._followObject.matrixAutoUpdate=!1,this._followObject.matrix.identity(),this._deviceMode=e.mode,this._followObjectStartWorldQuaternion.copy(this._followObject.worldQuaternion),this.alignManipulator(),this._manipulatorObject.attach(this._followObject),this._manipulatorPosOffset.copy(this._followObject.position),this._manipulatorRotOffset.copy(this._followObject.quaternion),this._manipulatorScaleOffset.copy(this._followObject.scale)}onDragEnd(e){if(!this.handlerA||!this.handlerB){console.error("onDragEnd called on MultiTouchDragHandler without valid handlers. This is likely a bug.");return}this.handlerA.recenter(),this.handlerB.recenter(),this._manipulatorObject.removeFromParent(),this._followObject.removeFromParent(),this._manipulatorObject.destroy(),this._followObject.destroy()}_manipulatorPosOffset=new b;_manipulatorRotOffset=new U;_manipulatorScaleOffset=new b;_tempVec1=new b;_tempVec2=new b;_tempVec3=new b;tempLookMatrix=new ee;_initialScale=new b;_initialDistance=0;alignManipulator(){if(!this.handlerA||!this.handlerB){console.error("alignManipulator called on MultiTouchDragHandler without valid handlers. This is likely a bug.",this);return}if(!this.handlerA.followObject||!this.handlerB.followObject){console.error("alignManipulator called on MultiTouchDragHandler without valid follow objects. This is likely a bug.",this.handlerA,this.handlerB);return}this._tempVec1.copy(this._handlerAAttachmentPoint),this._tempVec2.copy(this._handlerBAttachmentPoint),this.handlerA.followObject.localToWorld(this._tempVec1),this.handlerB.followObject.localToWorld(this._tempVec2),this._tempVec3.lerpVectors(this._tempVec1,this._tempVec2,.5),this._manipulatorObject.position.copy(this._tempVec3);const e=this.context.mainCamera;this.tempLookMatrix.lookAt(this._tempVec3,this._tempVec2,e.worldUp),this._manipulatorObject.quaternion.setFromRotationMatrix(this.tempLookMatrix);const t=this._tempVec1.distanceTo(this._tempVec2);this._manipulatorObject.scale.copy(this._initialScale).multiplyScalar(t/this._initialDistance),this._manipulatorObject.updateMatrix(),this._manipulatorObject.updateMatrixWorld(!0),Qn&&(F.DrawLabel(this._tempVec3.clone().add(new b(0,.2,0)),"A:B "+t.toFixed(2),.03),F.DrawLine(this._tempVec1,this._tempVec2,65280,0,!1))}onDragUpdate(){this.alignManipulator();const e=30,t=1;this._followObject.position.copy(this._manipulatorPosOffset),this._followObject.quaternion.copy(this._manipulatorRotOffset),this._followObject.scale.copy(this._manipulatorScaleOffset);const i=this.gameObject,n=this._followObject;if(!i){console.error("MultiTouchDragHandler has no dragged object. This is likely a bug.");return}n.updateMatrix(),n.updateMatrixWorld(!0);const s=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer"?this.settings.xrKeepRotation:this.settings.keepRotation;if(this.settings.snapGridResolution>0){const h=this._followObject.worldPosition,d=this.settings.snapGridResolution;h.x=Math.round(h.x/d)*d,h.y=Math.round(h.y/d)*d,h.z=Math.round(h.z/d)*d,this._followObject.worldPosition=h,this._followObject.updateMatrix()}s&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion,this._followObject.updateMatrix());const r=D.clamp01(this.context.time.deltaTime*e*t),a=i.worldPosition;a.lerp(n.worldPosition,r),i.worldPosition=a;const l=i.worldQuaternion;l.slerp(n.worldQuaternion,r),i.worldQuaternion=l;const c=i.worldScale;c.lerp(n.worldScale,r),i.worldScale=c}setTargetObject(e){this.gameObject=e}}class xf{getTotalMovement(){return this._totalMovement}get followObject(){return this._followObject}get hitPointInLocalSpace(){return this._hitPointInLocalSpace}context;gameObject;settings;_lastRig=void 0;_followObject;_totalMovement=new b;_totalMovementAlongRayDirection=0;_grabStartDistance=0;_deviceMode;_followObjectStartPosition=new b;_followObjectStartQuaternion=new U;_followObjectStartWorldQuaternion=new U;_lastDragPosRigSpace;_tempVec=new b;_tempMat=new ee;_hitPointInLocalSpace=new b;_hitNormalInLocalSpace=new b;_bottomCenter=new b;_backCenter=new b;_backBottomCenter=new b;_bounds=new bi;_dragPlane=new tr(new b(0,1,0));_draggedOverObject=null;_draggedOverObjectLastSetUp=null;_draggedOverObjectLastNormal=new b;_draggedOverObjectDuration=0;setTargetObject(e){this.gameObject=e}constructor(e,t){this.settings=e,this.context=e.context,this.gameObject=t,this._followObject=new O}recenter(){if(!this._followObject.parent){console.warn("Error: space follow object doesn't have parent but recenter() is called. This is likely a bug");return}if(!this.gameObject){console.warn("Error: space follow object doesn't have a gameObject");return}const e=this._followObject.parent;this.gameObject.add(this._followObject),this._followObject.matrixAutoUpdate=!1,this._followObject.position.set(0,0,0),this._followObject.quaternion.set(0,0,0,1),this._followObject.scale.set(1,1,1),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0),e.attach(this._followObject),this._followObjectStartPosition.copy(this._followObject.position),this._followObjectStartQuaternion.copy(this._followObject.quaternion),this._followObjectStartWorldQuaternion.copy(this._followObject.worldQuaternion),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);const t=this._hitPointInLocalSpace.clone();this.gameObject.localToWorld(t),this._grabStartDistance=t.distanceTo(e.worldPosition);const i=K.active?.rig?.gameObject?.worldScale.x||1;this._grabStartDistance/=i,this._totalMovementAlongRayDirection=0,this._lastDragPosRigSpace=void 0,Qn&&(F.DrawLine(t,e.worldPosition,65280,.5,!1),F.DrawLabel(e.worldPosition.add(new b(0,.1,0)),this._grabStartDistance.toFixed(2),.03,.5))}onDragStart(e){if(!this.gameObject){console.warn("Error: space follow object doesn't have a gameObject");return}if(e.event.space.add(this._followObject),this._lastDragPosRigSpace=void 0,e.point&&e.normal)this._hitPointInLocalSpace.copy(e.point),this.gameObject.worldToLocal(this._hitPointInLocalSpace),this._hitNormalInLocalSpace.copy(e.normal);else if(e){const m=e.event.space,f=m.worldPosition;this.gameObject.worldToLocal(f),this._hitPointInLocalSpace.copy(f);const g=m.worldUp;this._tempMat.copy(this.gameObject.matrixWorld).invert(),g.transformDirection(this._tempMat),this._hitNormalInLocalSpace.copy(g)}this.recenter(),this._totalMovement.set(0,0,0),this._deviceMode=e.mode;const t=this._followObject.parent.worldForward,i=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer"?this.settings.xrDragMode:this.settings.dragMode,n=this._hitPointInLocalSpace.clone();switch(this.gameObject.localToWorld(n),i){case 0:const m=new b(0,1,0);this.gameObject.parent&&m.transformDirection(this.gameObject.parent.matrixWorld.clone().invert()),this._dragPlane.setFromNormalAndCoplanarPoint(m,n);break;case 2:const f=this._hitNormalInLocalSpace.clone();f.transformDirection(this.gameObject.matrixWorld),this._dragPlane.setFromNormalAndCoplanarPoint(f,n);break;case 1:this._dragPlane.setFromNormalAndCoplanarPoint(t,n);break;case 3:this.setPlaneViewAligned(n,!0);break;case 4:this.setPlaneViewAligned(n,!1);break}const s=this.gameObject.parent,r=this.gameObject.position.clone(),a=this.gameObject.quaternion.clone(),l=this.gameObject.scale.clone(),c=this.gameObject.matrixWorld.clone();s&&s.remove(this.gameObject),this.gameObject.position.set(0,0,0),this.gameObject.quaternion.set(0,0,0,1),this.gameObject.scale.set(1,1,1);const h=Wt([this.gameObject]);h.expandByPoint(this.gameObject.worldPosition);const d=new b;h.getCenter(d);const p=new b;h.getSize(p),this._bottomCenter.copy(d.clone().add(new b(0,-p.y/2,0))),this._backCenter.copy(d.clone().add(new b(0,0,p.z/2))),this._backBottomCenter.copy(d.clone().add(new b(0,-p.y/2,p.z/2))),this._bounds.copy(h),s&&s.add(this.gameObject),this.gameObject.position.copy(r),this.gameObject.quaternion.copy(a),this.gameObject.scale.copy(l),this.gameObject.matrixWorld.copy(c),this._draggedOverObject=null,this._draggedOverObjectLastSetUp=null,this._draggedOverObjectLastNormal.set(0,1,0),this._draggedOverObjectDuration=0}collectMovementInfo(){if(!this._followObject.parent)return;const e=this._followObject.parent;this._followObject.updateMatrix();const t=e.worldPosition,i=K.active?.rig?.gameObject;i&&i.worldToLocal(t),(this._lastDragPosRigSpace===void 0||i!=this._lastRig)&&(this._lastDragPosRigSpace=t.clone(),this._lastRig=i),this._tempVec.copy(t).sub(this._lastDragPosRigSpace);const n=e.worldForward;if(i&&(this._tempMat.copy(i.matrixWorld).invert(),n.transformDirection(this._tempMat)),this._totalMovementAlongRayDirection+=n.dot(this._tempVec),this._tempVec.x=Math.abs(this._tempVec.x),this._tempVec.y=Math.abs(this._tempVec.y),this._tempVec.z=Math.abs(this._tempVec.z),this._totalMovement.add(this._tempVec),this._lastDragPosRigSpace.copy(t),Qn){let s=t;i&&(s=s.clone(),s.transformDirection(i.matrixWorld)),F.DrawRay(s,n,255)}}onDragUpdate(e){if(e>1)return;const t=this.gameObject;if(!t||!this._followObject){console.warn("Warning: DragPointerHandler doesn't have a dragged object. This is likely a bug.");return}const i=this._followObject.parent;if(!i){console.warn("Warning: DragPointerHandler doesn't have a drag source. This is likely a bug.");return}this._followObject.updateMatrix();const n=i.worldPosition,s=i.worldForward,r=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer",a=r?this.settings.xrKeepRotation:this.settings.keepRotation,l=r?this.settings.xrDragMode:this.settings.dragMode;if(l===5)return;const c=10;a&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);let h=1,d=2;if(r&&this._grabStartDistance>.5){const v=1+this._totalMovementAlongRayDirection*(2*this.settings.xrDistanceDragFactor);h=Math.max(0,v),h=h*h*h}else this._grabStartDistance<=.5&&(d=3);this._followObject.position.copy(this._followObjectStartPosition),a||this._followObject.quaternion.copy(this._followObjectStartQuaternion),this._followObject.position.multiplyScalar(h),this._followObject.updateMatrix();const p=this._hasLastSurfaceHitPoint;this._hasLastSurfaceHitPoint=!1;const m=new ns(n,s);if(l==4){const v=this.context.physics.raycastFromRay(m,{testObject:P=>P!==this.followObject&&P!==i&&P!==t});if(v.length>0){const P=v[0];if(this._draggedOverObject===P.object?this._draggedOverObjectDuration+=this.context.time.deltaTime:(this._draggedOverObject=P.object,this._draggedOverObjectDuration=0),P.face){this._hasLastSurfaceHitPoint=!0,this._lastSurfaceHitPoint.copy(P.point);const R=this._draggedOverObjectDuration>=.15,k=this._totalMovement.length()>=.001,A=$(P.normal||P.face.normal).applyQuaternion(P.object.worldQuaternion);if((R||k)&&(this._draggedOverObjectLastSetUp!==this._draggedOverObject||this._draggedOverObjectLastNormal.dot(A)<.999999||this.context.time.frame%60===0)){this._draggedOverObjectLastSetUp=this._draggedOverObject,this._draggedOverObjectLastNormal.copy(P.face.normal);const L=$(),N=$();this._bounds.getCenter(L),this._bounds.getSize(N),L.sub(N.multiplyScalar(.5).multiply(A)),this._hitPointInLocalSpace.copy(L),this._hitNormalInLocalSpace.copy(P.face.normal),this._bounds.getCenter(L),this._bounds.getSize(N),L.add(N.multiplyScalar(.5).multiply(P.face.normal));const j=$(this._hitPointInLocalSpace).add(L);this._followObject.localToWorld(j);const q=P.point;this._dragPlane.setFromNormalAndCoplanarPoint(A,q)}else if(!(R||k))return}}else p&&this.gameObject&&this.setPlaneViewAligned(this.gameObject.worldPosition,!1)}if(l!==1&&m.intersectPlane(this._dragPlane,this._tempVec)){this._followObject.worldPosition=this._tempVec,this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);const v=$(this._hitPointInLocalSpace);this._followObject.localToWorld(v),Qn&&F.DrawLine(v,this._tempVec,65535,0,!1),this._followObject.worldPosition=this._tempVec.multiplyScalar(2).sub(v),this._followObject.updateMatrix(),this._followObject.updateMatrix()}if(this.settings.snapGridResolution>0){const v=this._followObject.worldPosition,P=this.settings.snapGridResolution;v.x=Math.round(v.x/P)*P,v.y=Math.round(v.y/P)*P,v.z=Math.round(v.z/P)*P,this._followObject.worldPosition=v,this._followObject.updateMatrix()}a&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion,this._followObject.updateMatrix());const f=D.clamp01(this.context.time.deltaTime*c*d),g=D.clamp01(this.context.time.deltaTime*c*.5*d),y=t.worldPosition;y.lerp(this._followObject.worldPosition,f),t.worldPosition=y;const _=t.worldQuaternion;if(_.slerp(this._followObject.worldQuaternion,g),t.worldQuaternion=_,Qn){const v=this._hitPointInLocalSpace.clone();t.localToWorld(v),F.DrawSphere(v,.02,16711680);const P=this._hitNormalInLocalSpace.clone();P.applyQuaternion(_),F.DrawRay(v,P,16711680),F.DrawLabel(y.add(new b(0,.25,0)),`Distance: ${this._totalMovement.length().toFixed(2)}
960
960
 
961
961
  Along Ray: ${this._totalMovementAlongRayDirection.toFixed(2)}
962
962
 
@@ -972,8 +972,8 @@ Consider registering a custom loader via the 'onCreateCustomModelLoader' callbac
972
972
 
973
973
  Content-Type: "${t.headers.get("content-type")}
974
974
  "Text: "${s}"
975
- Binary:`,i)}else console.debug("Could not determine file type from binary data");return"unknown"}var FR=Object.defineProperty,Qa=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&FR(e,t,n),n};const Ri=w("debugdroplistener");class UR extends CustomEvent{constructor(e){super("object-added",{detail:e})}}const zR="blob";class Eo extends M{dropArea;fitIntoVolume=!1;fitVolumeSize=new b(1,1,1);placeAtHitPosition=!0;useNetworking=!1;onDropped=new ce;loadFromURL(e,t){return this.addFromUrl(e,{screenposition:new J,point:t?.point,size:t?.size},!1)}forgetObjects(){this.removePreviouslyAddedObjects(!1)}onEnable(){this.context.renderer.domElement.addEventListener("dragover",this.onDrag),this.context.renderer.domElement.addEventListener("drop",this.onDrop),window.addEventListener("paste",this.handlePaste),this.context.connection.beginListen("droplistener",this.onNetworkEvent)}onDisable(){this.context.renderer.domElement.removeEventListener("dragover",this.onDrag),this.context.renderer.domElement.removeEventListener("drop",this.onDrop),window.removeEventListener("paste",this.handlePaste),this.context.connection.stopListen("droplistener",this.onNetworkEvent)}onNetworkEvent=e=>{if(!this.useNetworking){Ri&&console.debug("[DropListener] Ignoring networked event because networking is disabled",e);return}if(e.guid?.startsWith(this.guid)){const t=e.url;if(console.debug("[DropListener] Received networked event",e),t)if(Array.isArray(t))for(const i of t)this.addFromUrl(i,{screenposition:new J,point:e.point,size:e.size},!0);else this.addFromUrl(t,{screenposition:new J,point:e.point,size:e.size},!0)}};handlePaste=e=>{this.context.connection.allowEditing===!1||e.defaultPrevented||navigator.clipboard.readText().then(t=>{if(t&&(t.startsWith("http")||t.startsWith("https")||t.startsWith("blob"))){const i={screenposition:new J(this.context.input.mousePosition.x,this.context.input.mousePosition.y)};this.testIfIsInDropArea(i)&&this.addFromUrl(t,i,!1)}}).catch(console.warn)};onDrag=e=>{this.context.connection.allowEditing!==!1&&e.preventDefault()};onDrop=async e=>{if(this.context.connection.allowEditing===!1||(Ri&&console.log(e),!e?.dataTransfer)||e["droplistener:handled"])return;e.preventDefault();const t={screenposition:new J(e.offsetX,e.offsetY)};if(this.dropArea&&this.testIfIsInDropArea(t)===!1)return;e["droplistener:handled"]=!0;const i=e.dataTransfer.items;if(!i)return;const n=[];for(const s in i){const r=i[s];if(r.kind==="file"){const a=r.getAsFile();if(!a)continue;n.push(a)}else r.kind==="string"&&r.type=="text/plain"&&r.getAsString(a=>{this.addFromUrl(a,t,!1)})}n.length>0&&await this.addFromFiles(n,t)};async addFromUrl(e,t,i){Ri&&console.log("dropped url",e);try{if(e.startsWith("https://github.com/")){const r=e.split("/"),a=r[3],l=r[4],c=r[6],h=r.slice(7).join("/");e=`https://raw.githubusercontent.com/${a}/${l}/${c}/${h}`}else e.startsWith("https://polyhaven.com/a")&&(e=NR(e));if(!e)return null;const n=e.toLowerCase();if(n.endsWith(".hdr")||n.endsWith(".hdri")||n.endsWith(".exr")||n.endsWith(".png")||n.endsWith(".jpg")||n.endsWith(".jpeg"))return console.warn(`Fileformat is not supported: ${n}`),null;this.removePreviouslyAddedObjects();const s=await Ru.loadFileFromURL(new URL(e),{guid:this.guid,context:this.context,parent:this.gameObject,point:t.point,size:t.size});if(s&&this._addedObjects.length<=0)return t.url=e,this.onObjectLoaded(s,t,i)}catch{console.warn("String is not a valid URL",e)}return null}_abort=null;async addFromFiles(e,t){if(Ri&&console.log("Add files",e),!!Array.isArray(e)&&e.length){this.deleteDropEvent(),this.removePreviouslyAddedObjects(),zl(zR,null),this._abort?.abort("New files dropped"),this._abort=new AbortController;for(const i of e){if(!i)continue;if(i.type.startsWith("image/")){Ri&&console.warn("Ignoring dropped image file",i.name,i.type);continue}else if(i.name.endsWith(".bin")){Ri&&console.warn("Ignoring dropped binary file",i.name,i.type);continue}console.debug("Load file "+i.name+" + "+i.type);const n=await Ru.loadFile(i,this.context,{guid:this.guid});if(n){this.dispatchEvent(new CustomEvent("file-dropped",{detail:i})),t.file=i;const s=this.onObjectLoaded(n,t,!1);s&&this.context.connection.isConnected&&this.useNetworking&&(console.debug("Uploading dropped file to blob storage"),xr.upload(i,{abort:this._abort?.signal}).then(r=>{r?.download_url&&this._addedObjects.includes(s)&&this.sendDropEvent(r.download_url,s,n.contentMD5)}).catch(console.warn));break}}}}_addedObjects=new Array;_addedModels=new Array;removePreviouslyAddedObjects(e=!0){if(e)for(const t of this._addedObjects)t.parent===this.gameObject&&Ci(t,!0,!0);this._addedObjects.length=0,this._addedModels.length=0}onObjectLoaded(e,t,i){const{model:n,contentMD5:s}=e;if(Ri&&console.log(`Dropped ${this.gameObject.name}`,n),!n?.scene)return console.warn("No object specified to add to scene",n),null;this.removePreviouslyAddedObjects();const r=n.scene;this.gameObject.attach(r),r.position.set(0,0,0),r.quaternion.identity(),this._addedObjects.push(r),this._addedModels.push(n);const a=new bi().setFromCenterAndSize(new b(0,this.fitVolumeSize.y*.5,0).add(this.gameObject.worldPosition),this.fitVolumeSize);if(Ri&&F.DrawWireBox3(a,255,5),this.fitIntoVolume&&Vb(r,a,{position:!this.placeAtHitPosition}),this.placeAtHitPosition&&t&&t.screenposition){r.visible=!1;const c=this.context.physics.raycast({screenPoint:this.context.input.convertScreenspaceToRaycastSpace(t.screenposition.clone())});if(r.visible=!0,c&&c.length>0)for(const h of c){const d=h.point.clone();Ri&&console.log("Place object at hit",h),$b(r,d);break}}Ba.autoplayAnimations(n);const l=new UR({sender:this,gltf:n,model:n,object:r,contentMD5:s,dropped:t.file||(t.url?new URL(t.url):void 0)});return this.dispatchEvent(l),this.onDropped?.invoke(l.detail),!i&&t.url?.startsWith("http")&&this.context.connection.isConnected&&r&&this.sendDropEvent(t.url,r,s),r}async sendDropEvent(e,t,i){if(!this.useNetworking){Ri&&console.debug("[DropListener] Ignoring networked event because networking is disabled",e);return}if(this.context.connection.isConnected){console.debug('Sending drop event "'+t.name+'"',e);const n=Wt([t]),s={name:t.name,guid:this.guid,url:e,point:t.worldPosition.clone(),size:n.getSize(new b),contentMD5:i};this.context.connection.send("droplistener",s)}}deleteDropEvent(){this.context.connection.sendDeleteRemoteState(this.guid)}testIfIsInDropArea(e){if(this.dropArea){const t=this.context.input.convertScreenspaceToRaycastSpace(e.screenposition.clone());if(!this.context.physics.raycast({targets:[this.dropArea],screenPoint:t,recursive:!0,testObject:i=>!this._addedObjects.includes(i)}).length)return E()&&console.log(`Dropped outside of drop area for DropListener "${this.name}".`),!1}return!0}}Qa([u(O)],Eo.prototype,"dropArea"),Qa([u()],Eo.prototype,"fitIntoVolume"),Qa([u(b)],Eo.prototype,"fitVolumeSize"),Qa([u()],Eo.prototype,"placeAtHitPosition"),Qa([u()],Eo.prototype,"useNetworking"),Qa([u(ce)],Eo.prototype,"onDropped");function NR(o){if(!o.startsWith("https://polyhaven.com/"))return o;const e="https://dl.polyhaven.org/file/ph-assets/Models/gltf/4k/",t=new URL(o).pathname.split("/").pop(),i=`${e}${t}/${t}_4k.gltf`;return console.log("Resolved polyhaven asset url",o,"\u2192",i),i}var Ru;(o=>{async function e(i,n,s){const r=s.guid,a=new At(r),l=new Blob([i],{type:i.type||jw(i.name)||void 0}),c=URL.createObjectURL(l),h=await gn().loadSync(n,c,i.name,a).catch(d=>(console.error(`Failed to load file "${i.name}" (${i.type}):`,d),null));return URL.revokeObjectURL(c),h?new Promise((d,p)=>{const g=new FileReader;g.readAsArrayBuffer(i),g.onloadend=async f=>{const m=g.result,y=xr.hashMD5(m);return d({model:h,contentMD5:y})}}):(console.warn(`Failed to load "${i.name}" (${i.type})`),null)}o.loadFile=e;async function t(i,n){return new Promise(async(s,r)=>{const a=new At(n.guid),l=i.toString();Ri&&F.DrawWireSphere(n.point,.1,16711680,3);const c=Cs.addPreview({guid:n.guid,parent:n.parent,position:n?.point,size:n?.size}),h=await gn().loadSync(n.context,l,l,a,d=>{c.onProgress(d.loaded/d.total)}).catch(console.warn);if(h){const d=await fetch(l).then(g=>g.arrayBuffer()),p=xr.hashMD5(d);Ri?setTimeout(()=>Cs.removePreview(n.guid),3e3):Cs.removePreview(n.guid),s({model:h,contentMD5:p})}else Ri?setTimeout(()=>Cs.removePreview(n.guid),3e3):Cs.removePreview(n.guid),console.warn("Unsupported file type: "+i.toString())})}o.loadFileFromURL=t})(Ru||(Ru={}));var WR=Object.defineProperty,Cf=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&WR(e,t,n),n};const Tu=class V1 extends M{parent=null;object=null;limitCount=60;_currentCount=0;_startPosition=null;_startQuaternion=null;start(){if(this._currentCount=0,this._startPosition=null,this._startQuaternion=null,this.object||(this.object=this.gameObject),this.object){if(this.object===this.gameObject){const t=new At(this.guid);this.object=x.instantiate(this.object,{idProvider:t,keepWorldPosition:!1}),x.getComponent(this.object,V1)?.destroy();let i=this.object.getComponentInChildren(Ir);i||(i=this.object.addComponent(Ir,{dragMode:wf.SnapToSurfaces}),i.guid=t.generateUUID());let n=x.getComponent(i.gameObject,vn);n||(n=i.gameObject.addComponent(vn),n.guid=t.generateUUID())}this.object.visible=!1;const e=this.gameObject.getComponent(Ir);e&&(e.enabled=!1),this._startPosition=this.object.position?.clone()??new b(0,0,0),this._startQuaternion=this.object.quaternion?.clone()??new U(0,0,0,1)}this.gameObject.getComponentInParent(ki)||this.gameObject.addComponent(ki)}onEnable(){this.startCoroutine(this.cloneLimitIntervalFn())}_forwardPointerEvents=new Map;onPointerEnter(e){e.used||this.object&&this.context.connection.allowEditing&&e.button===0&&this.context.input.setCursor("pointer")}onPointerExit(e){e.used||this.object&&this.context.connection.allowEditing&&e.button===0&&this.context.input.unsetCursor("pointer")}onPointerDown(e){if(e.used||!this.object||!this.context.connection.allowEditing||e.button!==0)return;const t=this.handleDuplication();if(t){const i=x.getComponent(t,Ir);i?(i.onPointerDown(e),this._forwardPointerEvents.set(e.event.space,i)):E()&&console.warn(`Duplicated object (${t.name}) does not have DragControls`)}else this._currentCount>=this.limitCount?console.warn(`[Duplicatable] Limit of ${this.limitCount} objects created within a few seconds reached. Please wait a moment before creating more objects.`):console.warn("[Duplicatable] Could not duplicate object.")}onPointerUp(e){if(e.used)return;const t=this._forwardPointerEvents.get(e.event.space);t&&(t.onPointerUp(e),this._forwardPointerEvents.delete(e.event.space))}*cloneLimitIntervalFn(){for(;this.activeAndEnabled&&!this.destroyed;)this._currentCount>0?this._currentCount-=1:this._currentCount<0&&(this._currentCount=0),yield Dg(1)}handleDuplication(){if(!this.object||this.limitCount>0&&this._currentCount>=this.limitCount||this.object===this.gameObject)return null;if(x.isDestroyed(this.object))return this.object=null,null;this.object.visible=!0,this._startPosition&&this.object.position.copy(this._startPosition),this._startQuaternion&&this.object.quaternion.copy(this._startQuaternion);const e=new En;this.parent||(this.parent=this.gameObject.parent),this.parent&&(e.parent=this.parent.guid??this.parent.userData?.guid,e.keepWorldPosition=!0),e.position=this.worldPosition,e.rotation=this.worldQuaternion,e.context=this.context,this._currentCount+=1;const t=x.instantiateSynced(this.object,e);return console.assert(t!==this.object,"Duplicated object is original"),this.object.visible=!1,this._startPosition&&this.object.position.clone().copy(this._startPosition),this._startQuaternion&&this.object.quaternion.clone().copy(this._startQuaternion),t}};Cf([u(O)],Tu.prototype,"parent"),Cf([u(O)],Tu.prototype,"object"),Cf([u()],Tu.prototype,"limitCount");let Pf=Tu;var Ao=(o=>(o[o.PointerEnter=0]="PointerEnter",o[o.PointerExit=1]="PointerExit",o[o.PointerDown=2]="PointerDown",o[o.PointerUp=3]="PointerUp",o[o.PointerClick=4]="PointerClick",o[o.Drag=5]="Drag",o[o.Drop=6]="Drop",o[o.Scroll=7]="Scroll",o[o.UpdateSelected=8]="UpdateSelected",o[o.Select=9]="Select",o[o.Deselect=10]="Deselect",o[o.Move=11]="Move",o[o.InitializePotentialDrag=12]="InitializePotentialDrag",o[o.BeginDrag=13]="BeginDrag",o[o.EndDrag=14]="EndDrag",o[o.Submit=15]="Submit",o[o.Cancel=16]="Cancel",o))(Ao||{}),VR=Object.defineProperty,Of=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&VR(e,t,n),n};class kf{eventID;callback=new ce}Of([u()],kf.prototype,"eventID"),Of([u(ce)],kf.prototype,"callback");class Eu extends M{triggers=[];invoke(e){if(this.triggers)for(const t of this.triggers)t.eventID===e&&t.callback?.invoke()}hasTrigger(e){return this.triggers?.some(t=>t.eventID===e)??!1}shouldChangeCursor(){return this.hasTrigger(Ao.PointerClick)||this.hasTrigger(Ao.PointerDown)||this.hasTrigger(Ao.PointerUp)}onPointerClick(e){this.invoke(Ao.PointerClick)}onPointerEnter(e){this.shouldChangeCursor()&&this.context.input.setCursor("pointer"),this.invoke(Ao.PointerEnter)}onPointerExit(e){this.shouldChangeCursor()&&this.context.input.unsetCursor("pointer"),this.invoke(Ao.PointerExit)}onPointerDown(e){this.invoke(Ao.PointerDown)}onPointerUp(e){this.invoke(Ao.PointerUp)}}Of([u(kf)],Eu.prototype,"triggers");class Fw{writer;constructor(e){this.writer=e}writeNode(e){}}class $R extends Fw{beforeWriteNode(e,t){F.isGizmo(e)&&(t.keep=!1)}}class Uw extends Fw{beforeWriteTexture(e,t){e.isRenderTargetTexture&&(t.newTexture=Fg(new se(1,1,1,0)))}}function Mf(o){const e=Su.DontExport;return!(o.hideFlags&e)}const Rf=w("debugexr");class HR{get name(){return"EXT_texture_exr"}parser;constructor(e){this.parser=e,Rf&&console.log(e)}loadTexture(e){const t=this.name,i=this.parser,n=i.json.textures[e];if(Rf&&console.log("EXT_texture_exr.loadTexture",e,n),!n.extensions||!n.extensions[t])return null;const s=n.extensions[t],r=new mm(i.options.manager);return Rf&&console.log("EXT_texture_exr.loadTexture",s),i.loadTextureImage(e,s.source,r)}}typeof window<"u"&&window.addEventListener("unhandledrejection",o=>{});const Io=gt,Au="$___Export_Components",GR="NEEDLE_components";class qR{[hr]}class XR{node;nodeIndex;nodeDef;constructor(e,t,i){this.node=e,this.nodeIndex=t,this.nodeDef=i}}class zw{get name(){return GR}parser;nodeToObjectMap={};gltf=null;exportContext;objectToNodeMap={};context;writer;registerExport(e){e.register(t=>{if("serializeUserData"in t){const i=t.serializeUserData.bind(t);this.writer=t,t.serializeUserData=(n,s)=>{try{this.serializeUserData(n,s)&&(t.extensionsUsed[this.name]=!0),i(n,s)}finally{this.afterSerializeUserData(n,s)}}}return this})}beforeParse(){this.exportContext={},this.objectToNodeMap={}}serializeUserData(e,t){const i=e.userData?.components;return!i||i.length<=0?!1:(delete e.userData.components,e[Au]=i,!0)}afterSerializeUserData(e,t){if(e.type==="Scene"&&Io&&console.log("DONE",JSON.stringify(t)),e[Au]===void 0)return;const i=e[Au];delete e[Au],i!==null&&(e.userData.components=i)}writeNode(e,t){const i=this.writer.json.nodes.length;Io&&console.log(e.name,i,e.uuid);const n=new XR(e,i,t);this.exportContext[i]=n,this.objectToNodeMap[e.uuid]=i}afterParse(e){Io&&console.log("AFTER",e);for(const t in this.exportContext){const i=this.exportContext[t],n=i.node,s=i.nodeDef,r=i.nodeIndex,a=n.userData?.components;if(!a||a.length<=0)continue;const l=new qR;s.extensions=s.extensions||{},s.extensions[this.name]=l,this.context.object=n,this.context.nodeId=r,this.context.objectToNode=this.objectToNodeMap;const c=[];for(const h of a){this.context.target=h;const d=gn().writeBuiltinComponentData(h,this.context);d!==null&&c.push(d)}c.length>0&&(l[hr]=c,Io&&console.log("DID WRITE",n,"nodeIndex",r,c))}}beforeRoot(){return Io&&console.log("BEGIN LOAD"),this.nodeToObjectMap={},null}async afterRoot(e){this.gltf=e;const t=e.parser,i=t?.extensions;if(!i)return;const n=i[this.name];Io&&console.log("After root",e,this.parser,i);const s=[];if(n===!0){const r=t.json.nodes;if(r){for(let a=0;a<r.length;a++){const l=await t.getDependency("node",a);this.nodeToObjectMap[a]=l}for(let a=0;a<r.length;a++){const l=r[a],c=a,h=l.extensions;if(!h)continue;const d=h[this.name];if(!d)continue;Io&&console.log("NODE",l);const p=this.nodeToObjectMap[c];if(!p){console.error("Could not find object for node index: "+c,l,t);continue}Qd(p),s.push(this.createComponents(p,d))}}}await Promise.all(s);for(const r of t.associations.keys()){const a=t.associations.get(r);if(a?.materials!=null){const l="/materials/"+a.materials;fk(r,l)}}}async createComponents(e,t){if(!t)return;const i=t[hr];if(i){const n=new Array;Io&&console.log(e.name,i);for(const s in i){const r=i[s];Io&&console.log("Serialized data",JSON.parse(JSON.stringify(r))),r&&this.parser&&n.push(Pg(this.parser,r).catch(a=>console.error(`Error while resolving references (see console for details)
976
- `,a,e,r))),e.userData=e.userData||{},e.userData[hr]=e.userData[hr]||[],e.userData[hr].push(r)}await Promise.all(n).catch(s=>{console.error("Error while loading components",s)})}}}const Nw="NEEDLE_gameobject_data";class QR{get name(){return Nw}parser;constructor(e){this.parser=e}afterRoot(e){const t=[];for(let i=0;i<this.parser.json.nodes?.length;i++){const n=this.parser.json.nodes[i];if(n&&n.extensions){const s=n.extensions[Nw];if(s){const r=this.findAndApplyExtensionData(i,s);t.push(r)}}}return Promise.all(t).then(()=>null)}async findAndApplyExtensionData(e,t){const i=await this.parser.getDependency("node",e);i&&this.applyExtensionData(i,t)}applyExtensionData(e,t){t.layers===void 0&&(t.layers=0),e.userData.layer=t.layers,e.layers.disableAll(),e.layers.set(t.layers),e.userData.tag=t.tag??"none",e.hideFlags=0,e.userData.static=t.static??!1,e.visible=t.activeSelf??!0,e.guid=t.guid}}const Ww="NEEDLE_lighting_settings",Ya=w("debugenvlight");class YR{get name(){return Ww}parser;sourceId;context;constructor(e,t,i){this.parser=e,this.sourceId=t,this.context=i}afterRoot(e){const t=this.parser.json.extensions;if(t){const i=t[Ww];if(i){Ya&&console.log('Loaded "'+this.name+'", src: "'+this.sourceId+'"',i);let n;if(e.scene.children.length===1){const s=e.scene.children[0];n=x.addComponent(s,Iu,{},{callAwake:!1})}else{const s=new O;s.name="LightSettings "+this.sourceId,e.scene.add(s),n=x.addComponent(s,Iu,{},{callAwake:!1})}n.sourceId=this.sourceId,n.ambientIntensity=i.ambientIntensity,n.ambientLight=new ne().fromArray(i.ambientLight),Array.isArray(i.ambientTrilight)&&(n.ambientTrilight=i.ambientTrilight.map(s=>new ne().fromArray(s))),n.ambientMode=i.ambientMode,n.environmentReflectionSource=i.environmentReflectionSource}}return null}}ue.registerCallback(he.ContextCreated,o=>{const e=o.context,t=x.findObjectOfType(Iu,e);t?.sourceId&&(t.enabled=!0)});class Iu extends M{ambientMode=Ua.Skybox;ambientLight;ambientTrilight;ambientIntensity=1;environmentReflectionSource=ou.Skybox;_hasReflection=!1;_ambientLightObj;_hemisphereLightObj;awake(){if(this.sourceId){const t=this.environmentReflectionSource===ou.Skybox?zn.Skybox:zn.Reflection,i=this.context.lightmaps.tryGet(this.sourceId,t,0);this._hasReflection=i!=null,i&&this.context.sceneLighting.internalRegisterReflection(this.sourceId,i)}this.enabled=!1,this.context.sceneLighting.internalRegisterSceneLightSettings(this),Ya&&window.addEventListener("keydown",t=>{if(!this.destroyed)switch(t.key){case"l":this.enabled=!this.enabled;break}});const e=this.gameObject.userData?.components;if(e){const t=e.indexOf(this);e.splice(t,1),e.push(this)}}onDestroy(){this.context.sceneLighting.internalUnregisterSceneLightSettings(this)}calculateIntensityFactor(e){const t=Math.max(e.r,e.g,e.b);return 2.2*D.lerp(0,1.33,t)}onEnable(){if(Ya&&console.warn("\u{1F4A1}\u{1F7E1} >>> Enable lighting",this.sourceId,this.enabled,this),this.ambientMode==Ua.Flat){if(this.ambientLight&&!this._ambientLightObj){const e=this.calculateIntensityFactor(this.ambientLight);this._ambientLightObj=new vS(this.ambientLight,this.ambientIntensity*e),Ya&&console.log("Created ambient light",this.sourceId,this._ambientLightObj,this.ambientIntensity,e)}this._ambientLightObj&&this.gameObject.add(this._ambientLightObj)}else if(this.ambientMode===Ua.Trilight){if(this.ambientTrilight){const e=this.ambientTrilight[0],t=this.ambientTrilight[this.ambientTrilight.length-1],i=this.calculateIntensityFactor(t);this._hemisphereLightObj=new wS(t,e,this.ambientIntensity*i),this.gameObject.add(this._hemisphereLightObj),Ya&&console.log("Created hemisphere ambient light",this.sourceId,this._hemisphereLightObj,this.ambientIntensity,i)}}else this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._hemisphereLightObj&&this._hemisphereLightObj.removeFromParent();this.sourceId&&(this.context.domElement.getAttribute("environment-image")||this.context.sceneLighting.internalEnableReflection(this.sourceId))}onDisable(){Ya&&console.warn("\u{1F4A1}\u26AB <<< Disable lighting:",this.sourceId,this),this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._hemisphereLightObj&&this._hemisphereLightObj.removeFromParent(),this.sourceId&&this.context.sceneLighting.internalDisableReflection(this.sourceId)}}const Tf=w("debugstencil");function KR(o,e){return(o&1<<e.layer)!=0}const ZR=Symbol("stencils");class Ks{get name(){return"NEEDLE_render_objects"}static stencils={};static applyStencil(e){if(!e)return;const t=e.sourceId;if(Tf&&console.log(t,Ks.stencils),!t)return;const i=Ks.stencils[t];if(i)for(let n=i.length-1;n>=0;n--){const s=i[n];if(KR(s.layer,e)){Tf&&console.log(s),setTimeout(()=>{Wi()&&Kd(e.gameObject)&&(ge("Stencil not supported on instanced objects"),console.warn("Stencil not supported on instanced objects",e))},500);for(let r=0;r<e.sharedMaterials.length;r++){let a=e.sharedMaterials[r];a&&(a=a.clone(),a[ZR]=!0,a.stencilWrite=!0,a.stencilWriteMask=255,a.stencilFuncMask=255,a.stencilRef=s.value,a.stencilFunc=s.compareFunc,a.stencilZPass=s.passOp,a.stencilFail=s.failOp,a.stencilZFail=s.zFailOp,e.sharedMaterials[r]=a)}e.gameObject.renderOrder=s.event*1e3+s.index*50;break}}}parser;source;constructor(e,t){this.parser=e,this.source=t}afterRoot(e){const t=this.parser.json.extensions;if(t){const i=t[eT];if(i){Tf&&console.log(i);const n=i.stencil;if(n&&Array.isArray(n))for(const s of n){const r={...s};r.compareFunc=JR(r.compareFunc),r.passOp=Ef(r.passOp),r.failOp=Ef(r.failOp),r.zFailOp=Ef(r.zFailOp),Ks.stencils[this.source]||(Ks.stencils[this.source]=[]),Ks.stencils[this.source].push(r)}}}return null}}function Ef(o){switch(o){case 0:return DS;case 1:return jS;case 2:return LS;case 3:return IS;case 4:return AS;case 6:return ES;case 7:return TS;case 5:return RS}return 0}function JR(o){switch(o){case 1:return z0;case 2:return MS;case 3:return kS;case 4:return OS;case 5:return PS;case 6:return CS;case 7:return SS;case 8:return xS}return z0}const eT="NEEDLE_render_objects";var Vw=(o=>(o[o.INT=5124]="INT",o[o.FLOAT=5126]="FLOAT",o[o.FLOAT_VEC2=35664]="FLOAT_VEC2",o[o.FLOAT_VEC3=35665]="FLOAT_VEC3",o[o.FLOAT_VEC4=35666]="FLOAT_VEC4",o[o.INT_VEC2=35667]="INT_VEC2",o[o.INT_VEC3=35668]="INT_VEC3",o[o.INT_VEC4=35669]="INT_VEC4",o[o.BOOL=35670]="BOOL",o[o.BOOL_VEC2=35671]="BOOL_VEC2",o[o.BOOL_VEC3=35672]="BOOL_VEC3",o[o.BOOL_VEC4=35673]="BOOL_VEC4",o[o.FLOAT_MAT2=35674]="FLOAT_MAT2",o[o.FLOAT_MAT3=35675]="FLOAT_MAT3",o[o.FLOAT_MAT4=35676]="FLOAT_MAT4",o[o.SAMPLER_2D=35678]="SAMPLER_2D",o[o.SAMPLER_3D=35680]="SAMPLER_3D",o[o.SAMPLER_CUBE=35681]="SAMPLER_CUBE",o[o.UNKNOWN=0]="UNKNOWN",o))(Vw||{});const Yn=w("debugcustomshader"),Ka="NEEDLE_techniques_webgl";class tT{objectToWorldMatrix=new ee;worldToObjectMatrix=new ee;objectToWorld=new Array;worldToObject=new Array;updateFrom(e){this.objectToWorldMatrix.copy(e.matrixWorld),nu(this.objectToWorldMatrix,this.objectToWorld),this.worldToObjectMatrix.copy(e.matrixWorld).invert(),nu(this.worldToObjectMatrix,this.worldToObject)}}class Me extends N0{identifier;onBeforeRenderSceneCallback=this.onBeforeRenderScene.bind(this);clone(){const e=super.clone();return $w(e),e}constructor(e,...t){super(...t),this.identifier=e,Yn&&console.log(this),this.type="NEEDLE_CUSTOM_SHADER",this.uniforms[this._objToWorldName]||(this.uniforms[this._objToWorldName]={value:[]}),this.uniforms[this._worldToObjectName]||(this.uniforms[this._worldToObjectName]={value:[]}),this.uniforms[this._viewProjectionName]||(this.uniforms[this._viewProjectionName]={value:[]}),this.uniforms[this._sphericalHarmonicsName],(this.depthTextureUniform||this.opaqueTextureUniform)&&z.Current.pre_render_callbacks.push(this.onBeforeRenderSceneCallback)}dispose(){super.dispose();const e=z.Current.pre_render_callbacks.indexOf(this.onBeforeRenderSceneCallback);e>=0&&z.Current.pre_render_callbacks.splice(e,1)}_sphericalHarmonicsName="unity_SpecCube0";_objToWorldName="hlslcc_mtx4x4unity_ObjectToWorld";_worldToObjectName="hlslcc_mtx4x4unity_WorldToObject";static viewProjection=new ee;static _viewProjectionValues=[];_viewProjectionName="hlslcc_mtx4x4unity_MatrixVP";static viewMatrix=new ee;static _viewMatrixValues=[];_viewMatrixName="hlslcc_mtx4x4unity_MatrixV";static _worldSpaceCameraPosName="_WorldSpaceCameraPos";static _worldSpaceCameraPos=new b;static _mainLightColor=new pe;static _mainLightPosition=new b;static _lightData=new pe;_rendererData=new tT;get depthTextureUniform(){if(this.uniforms)return this.uniforms._CameraDepthTexture}get opaqueTextureUniform(){if(this.uniforms)return this.uniforms._CameraOpaqueTexture}onBeforeRenderScene(){this.opaqueTextureUniform&&z.Current.setRequireColor(!0),this.depthTextureUniform&&z.Current.setRequireDepth(!0)}onBeforeRender(e,t,i,n,s,r){n.attributes.tangent||n.computeTangents(),this.onUpdateUniforms(i,s)}onUpdateUniforms(e,t){const i=z.Current;if(e&&(Me.viewProjection&&this.uniforms[this._viewProjectionName]&&(Me.viewProjection.copy(e.projectionMatrix).multiply(e.matrixWorldInverse),nu(Me.viewProjection,Me._viewProjectionValues)),Me.viewMatrix&&this.uniforms[this._viewMatrixName]&&(Me.viewMatrix.copy(e.matrixWorldInverse),nu(Me.viewMatrix,Me._viewMatrixValues)),this.uniforms[Me._worldSpaceCameraPosName]&&Me._worldSpaceCameraPos.setFromMatrixPosition(e.matrixWorld)),this.uniforms._TimeParameters&&(this.uniforms._TimeParameters.value=i.sceneLighting.timeVec4),this.uniforms._Time){const a=this.uniforms._Time.value;a.x=i.sceneLighting.timeVec4.x/20,a.y=i.sceneLighting.timeVec4.x,a.z=i.sceneLighting.timeVec4.x*2,a.w=i.sceneLighting.timeVec4.x*3}if(this.uniforms._SinTime){const a=this.uniforms._SinTime.value;a.x=Math.sin(i.sceneLighting.timeVec4.x/8),a.y=Math.sin(i.sceneLighting.timeVec4.x/4),a.z=Math.sin(i.sceneLighting.timeVec4.x/2),a.w=Math.sin(i.sceneLighting.timeVec4.x)}if(this.uniforms._CosTime){const a=this.uniforms._CosTime.value;a.x=Math.cos(i.sceneLighting.timeVec4.x/8),a.y=Math.cos(i.sceneLighting.timeVec4.x/4),a.z=Math.cos(i.sceneLighting.timeVec4.x/2),a.w=Math.cos(i.sceneLighting.timeVec4.x)}if(this.uniforms.unity_DeltaTime){const a=this.uniforms.unity_DeltaTime.value;a.x=i.time.deltaTime,a.y=1/i.time.deltaTime,a.z=i.time.smoothedDeltaTime,a.w=1/i.time.smoothedDeltaTime}const n=i.mainLight;if(n){const a=Z(n.gameObject,Me._mainLightPosition);this.uniforms._MainLightPosition={value:a.normalize()},Me._mainLightColor.set(n.color.r,n.color.g,n.color.b,0),this.uniforms._MainLightColor={value:Me._mainLightColor};const l=n.intensity;Me._lightData.z=l,this.uniforms.unity_LightData={value:Me._lightData}}if(e&&(Me.viewProjection&&this.uniforms[this._viewProjectionName]&&(this.uniforms[this._viewProjectionName].value=Me._viewProjectionValues),Me.viewMatrix&&this.uniforms[this._viewMatrixName]&&(this.uniforms[this._viewMatrixName].value=Me._viewMatrixValues),this.uniforms[Me._worldSpaceCameraPosName]&&(this.uniforms[Me._worldSpaceCameraPosName]={value:Me._worldSpaceCameraPos}),i.mainCameraComponent)){if(this.uniforms._ProjectionParams){const a=this.uniforms._ProjectionParams.value;a.x=1,a.y=i.mainCameraComponent.nearClipPlane,a.z=i.mainCameraComponent.farClipPlane,a.w=1/a.z,this.uniforms._ProjectionParams.value=a}if(this.uniforms._ZBufferParams){const a=this.uniforms._ZBufferParams.value,l=i.mainCameraComponent;a.x=1-l.farClipPlane/l.nearClipPlane,a.y=l.farClipPlane/l.nearClipPlane,a.z=a.x/l.farClipPlane,a.w=a.y/l.farClipPlane,this.uniforms._ZBufferParams.value=a}if(this.uniforms._ScreenParams){const a=this.uniforms._ScreenParams.value;a.x=i.domWidth,a.y=i.domHeight,a.z=1+1/a.x,a.w=1+1/a.y,this.uniforms._ScreenParams.value=a}if(this.uniforms._ScaledScreenParams){const a=this.uniforms._ScaledScreenParams.value;a.x=i.domWidth,a.y=i.domHeight,a.z=1+1/a.x,a.w=1+1/a.y,this.uniforms._ScaledScreenParams.value=a}}const s=this.depthTextureUniform;s&&(s.value=i.depthTexture);const r=this.opaqueTextureUniform;if(r&&(r.value=i.opaqueColorTexture),t){const a=this._rendererData;a.updateFrom(t),this.uniforms[this._worldToObjectName].value=a.worldToObject,this.uniforms[this._objToWorldName].value=a.objectToWorld}this.uniformsNeedUpdate=!0}}class iT{get name(){return Ka}parser;identifier;constructor(e,t){this.parser=e,this.identifier=t}loadMaterial(e){const t=this.parser.json.materials[e];if(!t)return Yn&&console.log(e,this.parser.json.materials),null;if(!t.extensions||!t.extensions[Ka])return Yn&&console.log(`Material ${e} does not use NEEDLE_techniques_webgl`),null;Yn&&console.log(`Material ${e} uses NEEDLE_techniques_webgl`,t);const i=t.extensions[Ka].technique;if(i<0)return console.debug(`Material ${e} does not have a valid technique index`),null;const n=this.parser.json.extensions[Ka];if(!n)return Yn?console.error("Missing shader data",this.parser.json.extensions):console.debug("Missing custom shader data in parser.json.extensions"),null;Yn&&console.log(n);const s=n.techniques[i];return s?new Promise(async(r,a)=>{const l=await Yk(n,s.program),c=l?.fragmentShader,h=l?.vertexShader;if(!c||!h)return a();Yn&&console.log("loadMaterial",t,l);const d={},p=s.uniforms;(h.includes("_Time")||c.includes("_Time"))&&(d._Time={value:new pe(0,0,0,0)}),(h.includes("_SinTime")||c.includes("_SinTime"))&&(d._SinTime={value:new pe(0,0,0,0)}),(h.includes("_CosTime")||c.includes("_CosTime"))&&(d._CosTime={value:new pe(0,0,0,0)}),(h.includes("unity_DeltaTime")||c.includes("unity_DeltaTime"))&&(d.unity_DeltaTime={value:new pe(0,0,0,0)});for(const m in p){const y=m;switch(y){case"_TimeParameters":const _=new pe;d[y]={value:_};break;case"hlslcc_mtx4x4unity_MatrixV":case"hlslcc_mtx4x4unity_MatrixVP":d[y]={value:[]};break;case"_MainLightPosition":case"_MainLightColor":case"_WorldSpaceCameraPos":d[y]={value:[0,0,0,1]};break;case"unity_OrthoParams":break;case"unity_SpecCube0":d[y]={value:null};break;default:case"_ScreenParams":case"_ZBufferParams":case"_ProjectionParams":d[y]={value:[0,0,0,0]};break;case"_CameraOpaqueTexture":case"_CameraDepthTexture":d[y]={value:null};break}}let g=!1;if(t.extensions&&t.extensions[Ka]){const m=t.extensions[Ka];if(m.technique===i){Yn&&console.log(t.name,"Material Properties",m);for(const y in m.values){const _=m.values[y];if(typeof _=="string"){if(_.startsWith("/textures/")){const v=_.substring(10),P=Number.parseInt(v);if(P>=0){const R=await this.parser.getDependency("texture",P);R instanceof Re&&(R.colorSpace=po,R.needsUpdate=!0),d[y]={value:R};continue}}switch(y){case"alphaMode":_==="BLEND"&&(g=!0);continue}}if(Array.isArray(_)&&_.length===4){d[y]={value:new pe(_[0],_[1],_[2],_[3])};continue}d[y]={value:_}}}}const f=new Me(this.identifier,{name:t.name??"",uniforms:d,vertexShader:h,fragmentShader:c,lights:!1});switch(f.glslVersion=BS,f.vertexShader=f.vertexShader.replace("#version 300 es",""),f.fragmentShader=f.fragmentShader.replace("#version 300 es",""),d._Cull?.value){case 0:f.side=vi;break;case 1:f.side=ud;break;case 2:f.side=as;break;default:f.side=as;break}switch(d._ZTest?.value){case 3:f.depthTest=!0,f.depthFunc=$S;break;case 6:f.depthTest=!0,f.depthFunc=VS;break;case 2:f.depthTest=!0,f.depthFunc=WS;break;case 4:f.depthTest=!0,f.depthFunc=NS;break;case 5:f.depthTest=!0,f.depthFunc=zS;break;case 7:f.depthTest=!0,f.depthFunc=US;break;case 8:f.depthTest=!1,f.depthFunc=FS;break}f.transparent=g,g&&(f.depthWrite=!1),Xk(d),f.onUpdateUniforms();for(const m in p){const y=m,_=p[m].type;if(d[y]?.value===void 0)switch(_){case Vw.SAMPLER_2D:d[y]={value:Gk},console.warn("Missing/unassigned texture, fallback to white: "+y);break;default:y==="unity_OrthoParams"||console.warn("TODO: EXPECTED UNIFORM / fallback NOT SET: "+y,p[m]);break}}Yn&&console.log(f.uuid,d),$w(f),r(f)}):null}}function $w(o){if(o.uniforms){Yn&&console.log("Uniforms:",o.uniforms);for(const t in o.uniforms)switch(e(t,t),t){case"_Color":e("color",t);break}}function e(t,i){Object.getOwnPropertyDescriptor(o,t)||Object.defineProperty(o,t,{get:()=>o.uniforms[i].value,set:n=>{o.uniforms[i].value=n,o.needsUpdate=!0}})}}const nT=w("debugextensions");let Lu;const oT=import("./vendor-XJ9xiwrv.min.js").then(o=>o.index$2).then(async o=>(Lu=o.GLTFAnimationPointerExtension,Lu)).catch(o=>{console.warn("Failed to import GLTFLoaderAnimationPointer. Please use @needle-tools/three-animationpointer for full KHR_animation support",o)}),Lr=new Array;function sT(o){Lr.includes(o)||Lr.push(o)}function rT(o){const e=Lr.indexOf(o);e>=0&&Lr.splice(e,1)}function Af(o){if(o instanceof fo){const e=new zw;return o.register(t=>(e.parser=t,e)),e}return null}class aT{resolvePath(e){return e.includes("/extensions/builtin_components/")?e.replace("/extensions/builtin_components/","/userData/components/"):e.includes("extensions/builtin_components/")?e.replace("extensions/builtin_components/","/userData/components/"):e}}async function ju(o,e,t){const i=t.indexOf("?");i>=0&&(t=t.substring(0,i)),o.register(n=>new QR(n)),o.register(n=>new bk(n)),o.register(n=>new Wk(n,e.lightmaps,t)),o.register(n=>new YR(n,t,e)),o.register(n=>new iT(n,t)),o.register(n=>new Ks(n,t)),o.register(n=>new Ve(n)),o.register(n=>new HR(n)),j_()&&o.register(n=>new Al(n)),await oT.catch(n=>{}),o.register(n=>{if(Lu){const s=new Lu(n);return s.setAnimationPointerResolver.bind(s)(new aT),s}else return(nT||E())&&console.error("Missing KHR_animation_pointer extension..."),{name:"KHR_animation_pointer_NOT_AVAILABLE"}});for(const n of Lr)n.onImport&&n.onImport(o,t,e)}function If(o,e){for(const t of Lr)t.onExport&&t.onExport(o,e)}function Hw(o,e,t){for(const i of Lr)i.onLoaded&&i.onLoaded(o,e,t)}class Gw{constructor(e){this.writer=e,this.name="EXT_mesh_gpu_instancing"}writeNode(e,t){if(e.constructor.name!=="InstancedMesh")return;const i=this.writer,n=i.extensionsUsed,s={};t.extensions=t.extensions||{},t.extensions[this.name]=s;let r=new ee;const a=new Array,l=new Array,c=new Array;for(let g=0;g<e.count;g++){e.getMatrixAt(g,r);let f=new b,m=new U,y=new b;r.decompose(f,m,y),a.push(f.x,f.y,f.z),l.push(m.x,m.y,m.z,m.w),c.push(y.x,y.y,y.z)}const h=new Float32Array(a),d=new Float32Array(l),p=new Float32Array(c);s.attributes={TRANSLATION:i.processAccessor(new pt(h,3)),ROTATION:i.processAccessor(new pt(d,4)),SCALE:i.processAccessor(new pt(p,3))},n[this.name]=!0}}var lT=Object.defineProperty,qw=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&lT(e,t,n),n};const jc=w("debugreflectionprobe"),Xw=w("noreflectionprobe"),Lf=Symbol("reflectionProbeKey"),Qw=Symbol("original material"),jf=class Qo extends M{static _probes=new Map;static isUsingReflectionProbe(e){return!!(e[Lf]||e[Qw]?.[Lf])}static get(e,t,i,n){if(!e||e.isObject3D!==!0||Xw)return null;const s=Qo._probes.get(t);if(s){for(const r of s)if(r.__didAwake||r.__internalAwake(),r.activeAndEnabled){if(n){if(r.gameObject===n)return r}else if(r.isInBox(e))return jc&&console.log("Found reflection probe",e.name,r.name),r}}return jc&&console.debug("Did not find reflection probe",e.name,i,e),null}_texture;set texture(e){if(e&&!(e instanceof Re)){console.error("ReflectionProbe.texture must be a Texture",e);return}this._texture=e,e&&(e.mapping=mo,e.colorSpace=po,e.needsUpdate=!0)}get texture(){return this._texture}center;size;_boxHelper;isInBox(e){return this._boxHelper?.isInBox(e)}constructor(){super(),Qo._probes.has(this.context)||Qo._probes.set(this.context,[]),Qo._probes.get(this.context)?.push(this)}awake(){this._boxHelper=this.gameObject.addComponent(xt),this._boxHelper.updateBox(!0),jc&&this._boxHelper.showHelper(5592320,!0),this._texture&&(this._texture.mapping=mo,this._texture.colorSpace=po,this._texture.needsUpdate=!0)}start(){!this._texture&&E()&&(console.warn(`[ReflectionProbe] Missing texture. Please assign a custom cubemap texture. To use reflection probes assign them to your renderer's "anchor" property.`),ge("ReflectionProbe configuration hint: See browser console for details"))}onDestroy(){const e=Qo._probes.get(this.context);if(e){const t=e.indexOf(this);t>=0&&e.splice(t,1)}}static _rendererMaterialsCache=new Map;onSet(e){if(Xw||!this.enabled||e.sharedMaterials?.length<=0||!this.texture)return;let t=Qo._rendererMaterialsCache.get(e);t||(t=[],Qo._rendererMaterialsCache.set(e,t));for(let i=0;i<e.sharedMaterials.length;i++){const n=e.sharedMaterials[i];if(!n||n.envMap===void 0||n instanceof xe)continue;let s=t[i];const r=n===s?.copy,a=!s||s.material.uuid!==n.uuid||s.copy.version!==n.version;if(!r&&a){if(jc){let h="";s?s.material!==n?h="reference changed; cached instance?: "+r:s.copy.version!==n.version&&(h="version changed"):h="not cached",console.warn("Cloning material",n.name,n.version,"Reason:",h,`
975
+ Binary:`,i)}else console.debug("Could not determine file type from binary data");return"unknown"}var FR=Object.defineProperty,Qa=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&FR(e,t,n),n};const Ri=w("debugdroplistener");class UR extends CustomEvent{constructor(e){super("object-added",{detail:e})}}const zR="blob";class Eo extends M{dropArea;fitIntoVolume=!1;fitVolumeSize=new b(1,1,1);placeAtHitPosition=!0;useNetworking=!1;onDropped=new ce;loadFromURL(e,t){return this.addFromUrl(e,{screenposition:new J,point:t?.point,size:t?.size},!1)}forgetObjects(){this.removePreviouslyAddedObjects(!1)}onEnable(){this.context.renderer.domElement.addEventListener("dragover",this.onDrag),this.context.renderer.domElement.addEventListener("drop",this.onDrop),window.addEventListener("paste",this.handlePaste),this.context.connection.beginListen("droplistener",this.onNetworkEvent)}onDisable(){this.context.renderer.domElement.removeEventListener("dragover",this.onDrag),this.context.renderer.domElement.removeEventListener("drop",this.onDrop),window.removeEventListener("paste",this.handlePaste),this.context.connection.stopListen("droplistener",this.onNetworkEvent)}onNetworkEvent=e=>{if(!this.useNetworking){Ri&&console.debug("[DropListener] Ignoring networked event because networking is disabled",e);return}if(e.guid?.startsWith(this.guid)){const t=e.url;if(console.debug("[DropListener] Received networked event",e),t)if(Array.isArray(t))for(const i of t)this.addFromUrl(i,{screenposition:new J,point:e.point,size:e.size},!0);else this.addFromUrl(t,{screenposition:new J,point:e.point,size:e.size},!0)}};handlePaste=e=>{this.context.connection.allowEditing===!1||e.defaultPrevented||navigator.clipboard.readText().then(t=>{if(t&&(t.startsWith("http")||t.startsWith("https")||t.startsWith("blob"))){const i={screenposition:new J(this.context.input.mousePosition.x,this.context.input.mousePosition.y)};this.testIfIsInDropArea(i)&&this.addFromUrl(t,i,!1)}}).catch(console.warn)};onDrag=e=>{this.context.connection.allowEditing!==!1&&e.preventDefault()};onDrop=async e=>{if(this.context.connection.allowEditing===!1||(Ri&&console.log(e),!e?.dataTransfer)||e["droplistener:handled"])return;e.preventDefault();const t={screenposition:new J(e.offsetX,e.offsetY)};if(this.dropArea&&this.testIfIsInDropArea(t)===!1)return;e["droplistener:handled"]=!0;const i=e.dataTransfer.items;if(!i)return;const n=[];for(const s in i){const r=i[s];if(r.kind==="file"){const a=r.getAsFile();if(!a)continue;n.push(a)}else r.kind==="string"&&r.type=="text/plain"&&r.getAsString(a=>{this.addFromUrl(a,t,!1)})}n.length>0&&await this.addFromFiles(n,t)};async addFromUrl(e,t,i){Ri&&console.log("dropped url",e);try{if(e.startsWith("https://github.com/")){const r=e.split("/"),a=r[3],l=r[4],c=r[6],h=r.slice(7).join("/");e=`https://raw.githubusercontent.com/${a}/${l}/${c}/${h}`}else e.startsWith("https://polyhaven.com/a")&&(e=NR(e));if(!e)return null;const n=e.toLowerCase();if(n.endsWith(".hdr")||n.endsWith(".hdri")||n.endsWith(".exr")||n.endsWith(".png")||n.endsWith(".jpg")||n.endsWith(".jpeg"))return console.warn(`Fileformat is not supported: ${n}`),null;this.removePreviouslyAddedObjects();const s=await Ru.loadFileFromURL(new URL(e),{guid:this.guid,context:this.context,parent:this.gameObject,point:t.point,size:t.size});if(s&&this._addedObjects.length<=0)return t.url=e,this.onObjectLoaded(s,t,i)}catch{console.warn("String is not a valid URL",e)}return null}_abort=null;async addFromFiles(e,t){if(Ri&&console.log("Add files",e),!!Array.isArray(e)&&e.length){this.deleteDropEvent(),this.removePreviouslyAddedObjects(),zl(zR,null),this._abort?.abort("New files dropped"),this._abort=new AbortController;for(const i of e){if(!i)continue;if(i.type.startsWith("image/")){Ri&&console.warn("Ignoring dropped image file",i.name,i.type);continue}else if(i.name.endsWith(".bin")){Ri&&console.warn("Ignoring dropped binary file",i.name,i.type);continue}console.debug("Load file "+i.name+" + "+i.type);const n=await Ru.loadFile(i,this.context,{guid:this.guid});if(n){this.dispatchEvent(new CustomEvent("file-dropped",{detail:i})),t.file=i;const s=this.onObjectLoaded(n,t,!1);s&&this.context.connection.isConnected&&this.useNetworking&&(console.debug("Uploading dropped file to blob storage"),xr.upload(i,{abort:this._abort?.signal}).then(r=>{r?.download_url&&this._addedObjects.includes(s)&&this.sendDropEvent(r.download_url,s,n.contentMD5)}).catch(console.warn));break}}}}_addedObjects=new Array;_addedModels=new Array;removePreviouslyAddedObjects(e=!0){if(e)for(const t of this._addedObjects)t.parent===this.gameObject&&Ci(t,!0,!0);this._addedObjects.length=0,this._addedModels.length=0}onObjectLoaded(e,t,i){const{model:n,contentMD5:s}=e;if(Ri&&console.log(`Dropped ${this.gameObject.name}`,n),!n?.scene)return console.warn("No object specified to add to scene",n),null;this.removePreviouslyAddedObjects();const r=n.scene;this.gameObject.attach(r),r.position.set(0,0,0),r.quaternion.identity(),this._addedObjects.push(r),this._addedModels.push(n);const a=new bi().setFromCenterAndSize(new b(0,this.fitVolumeSize.y*.5,0).add(this.gameObject.worldPosition),this.fitVolumeSize);if(Ri&&F.DrawWireBox3(a,255,5),this.fitIntoVolume&&Vb(r,a,{position:!this.placeAtHitPosition}),this.placeAtHitPosition&&t&&t.screenposition){r.visible=!1;const c=this.context.physics.raycast({screenPoint:this.context.input.convertScreenspaceToRaycastSpace(t.screenposition.clone())});if(r.visible=!0,c&&c.length>0)for(const h of c){const d=h.point.clone();Ri&&console.log("Place object at hit",h),$b(r,d);break}}Ba.autoplayAnimations(n);const l=new UR({sender:this,gltf:n,model:n,object:r,contentMD5:s,dropped:t.file||(t.url?new URL(t.url):void 0)});return this.dispatchEvent(l),this.onDropped?.invoke(l.detail),!i&&t.url?.startsWith("http")&&this.context.connection.isConnected&&r&&this.sendDropEvent(t.url,r,s),r}async sendDropEvent(e,t,i){if(!this.useNetworking){Ri&&console.debug("[DropListener] Ignoring networked event because networking is disabled",e);return}if(this.context.connection.isConnected){console.debug('Sending drop event "'+t.name+'"',e);const n=Wt([t]),s={name:t.name,guid:this.guid,url:e,point:t.worldPosition.clone(),size:n.getSize(new b),contentMD5:i};this.context.connection.send("droplistener",s)}}deleteDropEvent(){this.context.connection.sendDeleteRemoteState(this.guid)}testIfIsInDropArea(e){if(this.dropArea){const t=this.context.input.convertScreenspaceToRaycastSpace(e.screenposition.clone());if(!this.context.physics.raycast({targets:[this.dropArea],screenPoint:t,recursive:!0,testObject:i=>!this._addedObjects.includes(i)}).length)return E()&&console.log(`Dropped outside of drop area for DropListener "${this.name}".`),!1}return!0}}Qa([u(O)],Eo.prototype,"dropArea"),Qa([u()],Eo.prototype,"fitIntoVolume"),Qa([u(b)],Eo.prototype,"fitVolumeSize"),Qa([u()],Eo.prototype,"placeAtHitPosition"),Qa([u()],Eo.prototype,"useNetworking"),Qa([u(ce)],Eo.prototype,"onDropped");function NR(o){if(!o.startsWith("https://polyhaven.com/"))return o;const e="https://dl.polyhaven.org/file/ph-assets/Models/gltf/4k/",t=new URL(o).pathname.split("/").pop(),i=`${e}${t}/${t}_4k.gltf`;return console.log("Resolved polyhaven asset url",o,"\u2192",i),i}var Ru;(o=>{async function e(i,n,s){const r=s.guid,a=new At(r),l=new Blob([i],{type:i.type||jw(i.name)||void 0}),c=URL.createObjectURL(l),h=await gn().loadSync(n,c,i.name,a).catch(d=>(console.error(`Failed to load file "${i.name}" (${i.type}):`,d),null));return URL.revokeObjectURL(c),h?new Promise((d,p)=>{const m=new FileReader;m.readAsArrayBuffer(i),m.onloadend=async f=>{const g=m.result,y=xr.hashMD5(g);return d({model:h,contentMD5:y})}}):(console.warn(`Failed to load "${i.name}" (${i.type})`),null)}o.loadFile=e;async function t(i,n){return new Promise(async(s,r)=>{const a=new At(n.guid),l=i.toString();Ri&&F.DrawWireSphere(n.point,.1,16711680,3);const c=Cs.addPreview({guid:n.guid,parent:n.parent,position:n?.point,size:n?.size}),h=await gn().loadSync(n.context,l,l,a,d=>{c.onProgress(d.loaded/d.total)}).catch(console.warn);if(h){const d=await fetch(l).then(m=>m.arrayBuffer()),p=xr.hashMD5(d);Ri?setTimeout(()=>Cs.removePreview(n.guid),3e3):Cs.removePreview(n.guid),s({model:h,contentMD5:p})}else Ri?setTimeout(()=>Cs.removePreview(n.guid),3e3):Cs.removePreview(n.guid),console.warn("Unsupported file type: "+i.toString())})}o.loadFileFromURL=t})(Ru||(Ru={}));var WR=Object.defineProperty,Cf=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&WR(e,t,n),n};const Tu=class V1 extends M{parent=null;object=null;limitCount=60;_currentCount=0;_startPosition=null;_startQuaternion=null;start(){if(this._currentCount=0,this._startPosition=null,this._startQuaternion=null,this.object||(this.object=this.gameObject),this.object){if(this.object===this.gameObject){const t=new At(this.guid);this.object=x.instantiate(this.object,{idProvider:t,keepWorldPosition:!1}),x.getComponent(this.object,V1)?.destroy();let i=this.object.getComponentInChildren(Ir);i||(i=this.object.addComponent(Ir,{dragMode:wf.SnapToSurfaces}),i.guid=t.generateUUID());let n=x.getComponent(i.gameObject,vn);n||(n=i.gameObject.addComponent(vn),n.guid=t.generateUUID())}this.object.visible=!1;const e=this.gameObject.getComponent(Ir);e&&(e.enabled=!1),this._startPosition=this.object.position?.clone()??new b(0,0,0),this._startQuaternion=this.object.quaternion?.clone()??new U(0,0,0,1)}this.gameObject.getComponentInParent(ki)||this.gameObject.addComponent(ki)}onEnable(){this.startCoroutine(this.cloneLimitIntervalFn())}_forwardPointerEvents=new Map;onPointerEnter(e){e.used||this.object&&this.context.connection.allowEditing&&e.button===0&&this.context.input.setCursor("pointer")}onPointerExit(e){e.used||this.object&&this.context.connection.allowEditing&&e.button===0&&this.context.input.unsetCursor("pointer")}onPointerDown(e){if(e.used||!this.object||!this.context.connection.allowEditing||e.button!==0)return;const t=this.handleDuplication();if(t){const i=x.getComponent(t,Ir);i?(i.onPointerDown(e),this._forwardPointerEvents.set(e.event.space,i)):E()&&console.warn(`Duplicated object (${t.name}) does not have DragControls`)}else this._currentCount>=this.limitCount?console.warn(`[Duplicatable] Limit of ${this.limitCount} objects created within a few seconds reached. Please wait a moment before creating more objects.`):console.warn("[Duplicatable] Could not duplicate object.")}onPointerUp(e){if(e.used)return;const t=this._forwardPointerEvents.get(e.event.space);t&&(t.onPointerUp(e),this._forwardPointerEvents.delete(e.event.space))}*cloneLimitIntervalFn(){for(;this.activeAndEnabled&&!this.destroyed;)this._currentCount>0?this._currentCount-=1:this._currentCount<0&&(this._currentCount=0),yield Dg(1)}handleDuplication(){if(!this.object||this.limitCount>0&&this._currentCount>=this.limitCount||this.object===this.gameObject)return null;if(x.isDestroyed(this.object))return this.object=null,null;this.object.visible=!0,this._startPosition&&this.object.position.copy(this._startPosition),this._startQuaternion&&this.object.quaternion.copy(this._startQuaternion);const e=new En;this.parent||(this.parent=this.gameObject.parent),this.parent&&(e.parent=this.parent.guid??this.parent.userData?.guid,e.keepWorldPosition=!0),e.position=this.worldPosition,e.rotation=this.worldQuaternion,e.context=this.context,this._currentCount+=1;const t=x.instantiateSynced(this.object,e);return console.assert(t!==this.object,"Duplicated object is original"),this.object.visible=!1,this._startPosition&&this.object.position.clone().copy(this._startPosition),this._startQuaternion&&this.object.quaternion.clone().copy(this._startQuaternion),t}};Cf([u(O)],Tu.prototype,"parent"),Cf([u(O)],Tu.prototype,"object"),Cf([u()],Tu.prototype,"limitCount");let Pf=Tu;var Ao=(o=>(o[o.PointerEnter=0]="PointerEnter",o[o.PointerExit=1]="PointerExit",o[o.PointerDown=2]="PointerDown",o[o.PointerUp=3]="PointerUp",o[o.PointerClick=4]="PointerClick",o[o.Drag=5]="Drag",o[o.Drop=6]="Drop",o[o.Scroll=7]="Scroll",o[o.UpdateSelected=8]="UpdateSelected",o[o.Select=9]="Select",o[o.Deselect=10]="Deselect",o[o.Move=11]="Move",o[o.InitializePotentialDrag=12]="InitializePotentialDrag",o[o.BeginDrag=13]="BeginDrag",o[o.EndDrag=14]="EndDrag",o[o.Submit=15]="Submit",o[o.Cancel=16]="Cancel",o))(Ao||{}),VR=Object.defineProperty,Of=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&VR(e,t,n),n};class kf{eventID;callback=new ce}Of([u()],kf.prototype,"eventID"),Of([u(ce)],kf.prototype,"callback");class Eu extends M{triggers=[];invoke(e){if(this.triggers)for(const t of this.triggers)t.eventID===e&&t.callback?.invoke()}hasTrigger(e){return this.triggers?.some(t=>t.eventID===e)??!1}shouldChangeCursor(){return this.hasTrigger(Ao.PointerClick)||this.hasTrigger(Ao.PointerDown)||this.hasTrigger(Ao.PointerUp)}onPointerClick(e){this.invoke(Ao.PointerClick)}onPointerEnter(e){this.shouldChangeCursor()&&this.context.input.setCursor("pointer"),this.invoke(Ao.PointerEnter)}onPointerExit(e){this.shouldChangeCursor()&&this.context.input.unsetCursor("pointer"),this.invoke(Ao.PointerExit)}onPointerDown(e){this.invoke(Ao.PointerDown)}onPointerUp(e){this.invoke(Ao.PointerUp)}}Of([u(kf)],Eu.prototype,"triggers");class Fw{writer;constructor(e){this.writer=e}writeNode(e){}}class $R extends Fw{beforeWriteNode(e,t){F.isGizmo(e)&&(t.keep=!1)}}class Uw extends Fw{beforeWriteTexture(e,t){e.isRenderTargetTexture&&(t.newTexture=Fg(new se(1,1,1,0)))}}function Mf(o){const e=Su.DontExport;return!(o.hideFlags&e)}const Rf=w("debugexr");class HR{get name(){return"EXT_texture_exr"}parser;constructor(e){this.parser=e,Rf&&console.log(e)}loadTexture(e){const t=this.name,i=this.parser,n=i.json.textures[e];if(Rf&&console.log("EXT_texture_exr.loadTexture",e,n),!n.extensions||!n.extensions[t])return null;const s=n.extensions[t],r=new mm(i.options.manager);return Rf&&console.log("EXT_texture_exr.loadTexture",s),i.loadTextureImage(e,s.source,r)}}typeof window<"u"&&window.addEventListener("unhandledrejection",o=>{});const Io=gt,Au="$___Export_Components",GR="NEEDLE_components";class qR{[hr]}class XR{node;nodeIndex;nodeDef;constructor(e,t,i){this.node=e,this.nodeIndex=t,this.nodeDef=i}}class zw{get name(){return GR}parser;nodeToObjectMap={};gltf=null;exportContext;objectToNodeMap={};context;writer;registerExport(e){e.register(t=>{if("serializeUserData"in t){const i=t.serializeUserData.bind(t);this.writer=t,t.serializeUserData=(n,s)=>{try{this.serializeUserData(n,s)&&(t.extensionsUsed[this.name]=!0),i(n,s)}finally{this.afterSerializeUserData(n,s)}}}return this})}beforeParse(){this.exportContext={},this.objectToNodeMap={}}serializeUserData(e,t){const i=e.userData?.components;return!i||i.length<=0?!1:(delete e.userData.components,e[Au]=i,!0)}afterSerializeUserData(e,t){if(e.type==="Scene"&&Io&&console.log("DONE",JSON.stringify(t)),e[Au]===void 0)return;const i=e[Au];delete e[Au],i!==null&&(e.userData.components=i)}writeNode(e,t){const i=this.writer.json.nodes.length;Io&&console.log(e.name,i,e.uuid);const n=new XR(e,i,t);this.exportContext[i]=n,this.objectToNodeMap[e.uuid]=i}afterParse(e){Io&&console.log("AFTER",e);for(const t in this.exportContext){const i=this.exportContext[t],n=i.node,s=i.nodeDef,r=i.nodeIndex,a=n.userData?.components;if(!a||a.length<=0)continue;const l=new qR;s.extensions=s.extensions||{},s.extensions[this.name]=l,this.context.object=n,this.context.nodeId=r,this.context.objectToNode=this.objectToNodeMap;const c=[];for(const h of a){this.context.target=h;const d=gn().writeBuiltinComponentData(h,this.context);d!==null&&c.push(d)}c.length>0&&(l[hr]=c,Io&&console.log("DID WRITE",n,"nodeIndex",r,c))}}beforeRoot(){return Io&&console.log("BEGIN LOAD"),this.nodeToObjectMap={},null}async afterRoot(e){this.gltf=e;const t=e.parser,i=t?.extensions;if(!i)return;const n=i[this.name];Io&&console.log("After root",e,this.parser,i);const s=[];if(n===!0){const r=t.json.nodes;if(r){for(let a=0;a<r.length;a++){const l=await t.getDependency("node",a);this.nodeToObjectMap[a]=l}for(let a=0;a<r.length;a++){const l=r[a],c=a,h=l.extensions;if(!h)continue;const d=h[this.name];if(!d)continue;Io&&console.log("NODE",l);const p=this.nodeToObjectMap[c];if(!p){console.error("Could not find object for node index: "+c,l,t);continue}Qd(p),s.push(this.createComponents(p,d))}}}await Promise.all(s);for(const r of t.associations.keys()){const a=t.associations.get(r);if(a?.materials!=null){const l="/materials/"+a.materials;fk(r,l)}}}async createComponents(e,t){if(!t)return;const i=t[hr];if(i){const n=new Array;Io&&console.log(e.name,i);for(const s in i){const r=i[s];Io&&console.log("Serialized data",JSON.parse(JSON.stringify(r))),r&&this.parser&&n.push(Pg(this.parser,r).catch(a=>console.error(`Error while resolving references (see console for details)
976
+ `,a,e,r))),e.userData=e.userData||{},e.userData[hr]=e.userData[hr]||[],e.userData[hr].push(r)}await Promise.all(n).catch(s=>{console.error("Error while loading components",s)})}}}const Nw="NEEDLE_gameobject_data";class QR{get name(){return Nw}parser;constructor(e){this.parser=e}afterRoot(e){const t=[];for(let i=0;i<this.parser.json.nodes?.length;i++){const n=this.parser.json.nodes[i];if(n&&n.extensions){const s=n.extensions[Nw];if(s){const r=this.findAndApplyExtensionData(i,s);t.push(r)}}}return Promise.all(t).then(()=>null)}async findAndApplyExtensionData(e,t){const i=await this.parser.getDependency("node",e);i&&this.applyExtensionData(i,t)}applyExtensionData(e,t){t.layers===void 0&&(t.layers=0),e.userData.layer=t.layers,e.layers.disableAll(),e.layers.set(t.layers),e.userData.tag=t.tag??"none",e.hideFlags=0,e.userData.static=t.static??!1,e.visible=t.activeSelf??!0,e.guid=t.guid}}const Ww="NEEDLE_lighting_settings",Ya=w("debugenvlight");class YR{get name(){return Ww}parser;sourceId;context;constructor(e,t,i){this.parser=e,this.sourceId=t,this.context=i}afterRoot(e){const t=this.parser.json.extensions;if(t){const i=t[Ww];if(i){Ya&&console.log('Loaded "'+this.name+'", src: "'+this.sourceId+'"',i);let n;if(e.scene.children.length===1){const s=e.scene.children[0];n=x.addComponent(s,Iu,{},{callAwake:!1})}else{const s=new O;s.name="LightSettings "+this.sourceId,e.scene.add(s),n=x.addComponent(s,Iu,{},{callAwake:!1})}n.sourceId=this.sourceId,n.ambientIntensity=i.ambientIntensity,n.ambientLight=new ne().fromArray(i.ambientLight),Array.isArray(i.ambientTrilight)&&(n.ambientTrilight=i.ambientTrilight.map(s=>new ne().fromArray(s))),n.ambientMode=i.ambientMode,n.environmentReflectionSource=i.environmentReflectionSource}}return null}}ue.registerCallback(he.ContextCreated,o=>{const e=o.context,t=x.findObjectOfType(Iu,e);t?.sourceId&&(t.enabled=!0)});class Iu extends M{ambientMode=Ua.Skybox;ambientLight;ambientTrilight;ambientIntensity=1;environmentReflectionSource=ou.Skybox;_hasReflection=!1;_ambientLightObj;_hemisphereLightObj;awake(){if(this.sourceId){const t=this.environmentReflectionSource===ou.Skybox?zn.Skybox:zn.Reflection,i=this.context.lightmaps.tryGet(this.sourceId,t,0);this._hasReflection=i!=null,i&&this.context.sceneLighting.internalRegisterReflection(this.sourceId,i)}this.enabled=!1,this.context.sceneLighting.internalRegisterSceneLightSettings(this),Ya&&window.addEventListener("keydown",t=>{if(!this.destroyed)switch(t.key){case"l":this.enabled=!this.enabled;break}});const e=this.gameObject.userData?.components;if(e){const t=e.indexOf(this);e.splice(t,1),e.push(this)}}onDestroy(){this.context.sceneLighting.internalUnregisterSceneLightSettings(this)}calculateIntensityFactor(e){const t=Math.max(e.r,e.g,e.b);return 2.2*D.lerp(0,1.33,t)}onEnable(){if(Ya&&console.warn("\u{1F4A1}\u{1F7E1} >>> Enable lighting",this.sourceId,this.enabled,this),this.ambientMode==Ua.Flat){if(this.ambientLight&&!this._ambientLightObj){const e=this.calculateIntensityFactor(this.ambientLight);this._ambientLightObj=new vS(this.ambientLight,this.ambientIntensity*e),Ya&&console.log("Created ambient light",this.sourceId,this._ambientLightObj,this.ambientIntensity,e)}this._ambientLightObj&&this.gameObject.add(this._ambientLightObj)}else if(this.ambientMode===Ua.Trilight){if(this.ambientTrilight){const e=this.ambientTrilight[0],t=this.ambientTrilight[this.ambientTrilight.length-1],i=this.calculateIntensityFactor(t);this._hemisphereLightObj=new wS(t,e,this.ambientIntensity*i),this.gameObject.add(this._hemisphereLightObj),Ya&&console.log("Created hemisphere ambient light",this.sourceId,this._hemisphereLightObj,this.ambientIntensity,i)}}else this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._hemisphereLightObj&&this._hemisphereLightObj.removeFromParent();this.sourceId&&(this.context.domElement.getAttribute("environment-image")||this.context.sceneLighting.internalEnableReflection(this.sourceId))}onDisable(){Ya&&console.warn("\u{1F4A1}\u26AB <<< Disable lighting:",this.sourceId,this),this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._hemisphereLightObj&&this._hemisphereLightObj.removeFromParent(),this.sourceId&&this.context.sceneLighting.internalDisableReflection(this.sourceId)}}const Tf=w("debugstencil");function KR(o,e){return(o&1<<e.layer)!=0}const ZR=Symbol("stencils");class Ks{get name(){return"NEEDLE_render_objects"}static stencils={};static applyStencil(e){if(!e)return;const t=e.sourceId;if(Tf&&console.log(t,Ks.stencils),!t)return;const i=Ks.stencils[t];if(i)for(let n=i.length-1;n>=0;n--){const s=i[n];if(KR(s.layer,e)){Tf&&console.log(s),setTimeout(()=>{Wi()&&Kd(e.gameObject)&&(ge("Stencil not supported on instanced objects"),console.warn("Stencil not supported on instanced objects",e))},500);for(let r=0;r<e.sharedMaterials.length;r++){let a=e.sharedMaterials[r];a&&(a=a.clone(),a[ZR]=!0,a.stencilWrite=!0,a.stencilWriteMask=255,a.stencilFuncMask=255,a.stencilRef=s.value,a.stencilFunc=s.compareFunc,a.stencilZPass=s.passOp,a.stencilFail=s.failOp,a.stencilZFail=s.zFailOp,e.sharedMaterials[r]=a)}e.gameObject.renderOrder=s.event*1e3+s.index*50;break}}}parser;source;constructor(e,t){this.parser=e,this.source=t}afterRoot(e){const t=this.parser.json.extensions;if(t){const i=t[eT];if(i){Tf&&console.log(i);const n=i.stencil;if(n&&Array.isArray(n))for(const s of n){const r={...s};r.compareFunc=JR(r.compareFunc),r.passOp=Ef(r.passOp),r.failOp=Ef(r.failOp),r.zFailOp=Ef(r.zFailOp),Ks.stencils[this.source]||(Ks.stencils[this.source]=[]),Ks.stencils[this.source].push(r)}}}return null}}function Ef(o){switch(o){case 0:return DS;case 1:return jS;case 2:return LS;case 3:return IS;case 4:return AS;case 6:return ES;case 7:return TS;case 5:return RS}return 0}function JR(o){switch(o){case 1:return z0;case 2:return MS;case 3:return kS;case 4:return OS;case 5:return PS;case 6:return CS;case 7:return SS;case 8:return xS}return z0}const eT="NEEDLE_render_objects";var Vw=(o=>(o[o.INT=5124]="INT",o[o.FLOAT=5126]="FLOAT",o[o.FLOAT_VEC2=35664]="FLOAT_VEC2",o[o.FLOAT_VEC3=35665]="FLOAT_VEC3",o[o.FLOAT_VEC4=35666]="FLOAT_VEC4",o[o.INT_VEC2=35667]="INT_VEC2",o[o.INT_VEC3=35668]="INT_VEC3",o[o.INT_VEC4=35669]="INT_VEC4",o[o.BOOL=35670]="BOOL",o[o.BOOL_VEC2=35671]="BOOL_VEC2",o[o.BOOL_VEC3=35672]="BOOL_VEC3",o[o.BOOL_VEC4=35673]="BOOL_VEC4",o[o.FLOAT_MAT2=35674]="FLOAT_MAT2",o[o.FLOAT_MAT3=35675]="FLOAT_MAT3",o[o.FLOAT_MAT4=35676]="FLOAT_MAT4",o[o.SAMPLER_2D=35678]="SAMPLER_2D",o[o.SAMPLER_3D=35680]="SAMPLER_3D",o[o.SAMPLER_CUBE=35681]="SAMPLER_CUBE",o[o.UNKNOWN=0]="UNKNOWN",o))(Vw||{});const Yn=w("debugcustomshader"),Ka="NEEDLE_techniques_webgl";class tT{objectToWorldMatrix=new ee;worldToObjectMatrix=new ee;objectToWorld=new Array;worldToObject=new Array;updateFrom(e){this.objectToWorldMatrix.copy(e.matrixWorld),nu(this.objectToWorldMatrix,this.objectToWorld),this.worldToObjectMatrix.copy(e.matrixWorld).invert(),nu(this.worldToObjectMatrix,this.worldToObject)}}class Me extends N0{identifier;onBeforeRenderSceneCallback=this.onBeforeRenderScene.bind(this);clone(){const e=super.clone();return $w(e),e}constructor(e,...t){super(...t),this.identifier=e,Yn&&console.log(this),this.type="NEEDLE_CUSTOM_SHADER",this.uniforms[this._objToWorldName]||(this.uniforms[this._objToWorldName]={value:[]}),this.uniforms[this._worldToObjectName]||(this.uniforms[this._worldToObjectName]={value:[]}),this.uniforms[this._viewProjectionName]||(this.uniforms[this._viewProjectionName]={value:[]}),this.uniforms[this._sphericalHarmonicsName],(this.depthTextureUniform||this.opaqueTextureUniform)&&z.Current.pre_render_callbacks.push(this.onBeforeRenderSceneCallback)}dispose(){super.dispose();const e=z.Current.pre_render_callbacks.indexOf(this.onBeforeRenderSceneCallback);e>=0&&z.Current.pre_render_callbacks.splice(e,1)}_sphericalHarmonicsName="unity_SpecCube0";_objToWorldName="hlslcc_mtx4x4unity_ObjectToWorld";_worldToObjectName="hlslcc_mtx4x4unity_WorldToObject";static viewProjection=new ee;static _viewProjectionValues=[];_viewProjectionName="hlslcc_mtx4x4unity_MatrixVP";static viewMatrix=new ee;static _viewMatrixValues=[];_viewMatrixName="hlslcc_mtx4x4unity_MatrixV";static _worldSpaceCameraPosName="_WorldSpaceCameraPos";static _worldSpaceCameraPos=new b;static _mainLightColor=new pe;static _mainLightPosition=new b;static _lightData=new pe;_rendererData=new tT;get depthTextureUniform(){if(this.uniforms)return this.uniforms._CameraDepthTexture}get opaqueTextureUniform(){if(this.uniforms)return this.uniforms._CameraOpaqueTexture}onBeforeRenderScene(){this.opaqueTextureUniform&&z.Current.setRequireColor(!0),this.depthTextureUniform&&z.Current.setRequireDepth(!0)}onBeforeRender(e,t,i,n,s,r){n.attributes.tangent||n.computeTangents(),this.onUpdateUniforms(i,s)}onUpdateUniforms(e,t){const i=z.Current;if(e&&(Me.viewProjection&&this.uniforms[this._viewProjectionName]&&(Me.viewProjection.copy(e.projectionMatrix).multiply(e.matrixWorldInverse),nu(Me.viewProjection,Me._viewProjectionValues)),Me.viewMatrix&&this.uniforms[this._viewMatrixName]&&(Me.viewMatrix.copy(e.matrixWorldInverse),nu(Me.viewMatrix,Me._viewMatrixValues)),this.uniforms[Me._worldSpaceCameraPosName]&&Me._worldSpaceCameraPos.setFromMatrixPosition(e.matrixWorld)),this.uniforms._TimeParameters&&(this.uniforms._TimeParameters.value=i.sceneLighting.timeVec4),this.uniforms._Time){const a=this.uniforms._Time.value;a.x=i.sceneLighting.timeVec4.x/20,a.y=i.sceneLighting.timeVec4.x,a.z=i.sceneLighting.timeVec4.x*2,a.w=i.sceneLighting.timeVec4.x*3}if(this.uniforms._SinTime){const a=this.uniforms._SinTime.value;a.x=Math.sin(i.sceneLighting.timeVec4.x/8),a.y=Math.sin(i.sceneLighting.timeVec4.x/4),a.z=Math.sin(i.sceneLighting.timeVec4.x/2),a.w=Math.sin(i.sceneLighting.timeVec4.x)}if(this.uniforms._CosTime){const a=this.uniforms._CosTime.value;a.x=Math.cos(i.sceneLighting.timeVec4.x/8),a.y=Math.cos(i.sceneLighting.timeVec4.x/4),a.z=Math.cos(i.sceneLighting.timeVec4.x/2),a.w=Math.cos(i.sceneLighting.timeVec4.x)}if(this.uniforms.unity_DeltaTime){const a=this.uniforms.unity_DeltaTime.value;a.x=i.time.deltaTime,a.y=1/i.time.deltaTime,a.z=i.time.smoothedDeltaTime,a.w=1/i.time.smoothedDeltaTime}const n=i.mainLight;if(n){const a=Z(n.gameObject,Me._mainLightPosition);this.uniforms._MainLightPosition={value:a.normalize()},Me._mainLightColor.set(n.color.r,n.color.g,n.color.b,0),this.uniforms._MainLightColor={value:Me._mainLightColor};const l=n.intensity;Me._lightData.z=l,this.uniforms.unity_LightData={value:Me._lightData}}if(e&&(Me.viewProjection&&this.uniforms[this._viewProjectionName]&&(this.uniforms[this._viewProjectionName].value=Me._viewProjectionValues),Me.viewMatrix&&this.uniforms[this._viewMatrixName]&&(this.uniforms[this._viewMatrixName].value=Me._viewMatrixValues),this.uniforms[Me._worldSpaceCameraPosName]&&(this.uniforms[Me._worldSpaceCameraPosName]={value:Me._worldSpaceCameraPos}),i.mainCameraComponent)){if(this.uniforms._ProjectionParams){const a=this.uniforms._ProjectionParams.value;a.x=1,a.y=i.mainCameraComponent.nearClipPlane,a.z=i.mainCameraComponent.farClipPlane,a.w=1/a.z,this.uniforms._ProjectionParams.value=a}if(this.uniforms._ZBufferParams){const a=this.uniforms._ZBufferParams.value,l=i.mainCameraComponent;a.x=1-l.farClipPlane/l.nearClipPlane,a.y=l.farClipPlane/l.nearClipPlane,a.z=a.x/l.farClipPlane,a.w=a.y/l.farClipPlane,this.uniforms._ZBufferParams.value=a}if(this.uniforms._ScreenParams){const a=this.uniforms._ScreenParams.value;a.x=i.domWidth,a.y=i.domHeight,a.z=1+1/a.x,a.w=1+1/a.y,this.uniforms._ScreenParams.value=a}if(this.uniforms._ScaledScreenParams){const a=this.uniforms._ScaledScreenParams.value;a.x=i.domWidth,a.y=i.domHeight,a.z=1+1/a.x,a.w=1+1/a.y,this.uniforms._ScaledScreenParams.value=a}}const s=this.depthTextureUniform;s&&(s.value=i.depthTexture);const r=this.opaqueTextureUniform;if(r&&(r.value=i.opaqueColorTexture),t){const a=this._rendererData;a.updateFrom(t),this.uniforms[this._worldToObjectName].value=a.worldToObject,this.uniforms[this._objToWorldName].value=a.objectToWorld}this.uniformsNeedUpdate=!0}}class iT{get name(){return Ka}parser;identifier;constructor(e,t){this.parser=e,this.identifier=t}loadMaterial(e){const t=this.parser.json.materials[e];if(!t)return Yn&&console.log(e,this.parser.json.materials),null;if(!t.extensions||!t.extensions[Ka])return Yn&&console.log(`Material ${e} does not use NEEDLE_techniques_webgl`),null;Yn&&console.log(`Material ${e} uses NEEDLE_techniques_webgl`,t);const i=t.extensions[Ka].technique;if(i<0)return console.debug(`Material ${e} does not have a valid technique index`),null;const n=this.parser.json.extensions[Ka];if(!n)return Yn?console.error("Missing shader data",this.parser.json.extensions):console.debug("Missing custom shader data in parser.json.extensions"),null;Yn&&console.log(n);const s=n.techniques[i];return s?new Promise(async(r,a)=>{const l=await Yk(n,s.program),c=l?.fragmentShader,h=l?.vertexShader;if(!c||!h)return a();Yn&&console.log("loadMaterial",t,l);const d={},p=s.uniforms;(h.includes("_Time")||c.includes("_Time"))&&(d._Time={value:new pe(0,0,0,0)}),(h.includes("_SinTime")||c.includes("_SinTime"))&&(d._SinTime={value:new pe(0,0,0,0)}),(h.includes("_CosTime")||c.includes("_CosTime"))&&(d._CosTime={value:new pe(0,0,0,0)}),(h.includes("unity_DeltaTime")||c.includes("unity_DeltaTime"))&&(d.unity_DeltaTime={value:new pe(0,0,0,0)});for(const g in p){const y=g;switch(y){case"_TimeParameters":const _=new pe;d[y]={value:_};break;case"hlslcc_mtx4x4unity_MatrixV":case"hlslcc_mtx4x4unity_MatrixVP":d[y]={value:[]};break;case"_MainLightPosition":case"_MainLightColor":case"_WorldSpaceCameraPos":d[y]={value:[0,0,0,1]};break;case"unity_OrthoParams":break;case"unity_SpecCube0":d[y]={value:null};break;default:case"_ScreenParams":case"_ZBufferParams":case"_ProjectionParams":d[y]={value:[0,0,0,0]};break;case"_CameraOpaqueTexture":case"_CameraDepthTexture":d[y]={value:null};break}}let m=!1;if(t.extensions&&t.extensions[Ka]){const g=t.extensions[Ka];if(g.technique===i){Yn&&console.log(t.name,"Material Properties",g);for(const y in g.values){const _=g.values[y];if(typeof _=="string"){if(_.startsWith("/textures/")){const v=_.substring(10),P=Number.parseInt(v);if(P>=0){const R=await this.parser.getDependency("texture",P);R instanceof Re&&(R.colorSpace=po,R.needsUpdate=!0),d[y]={value:R};continue}}switch(y){case"alphaMode":_==="BLEND"&&(m=!0);continue}}if(Array.isArray(_)&&_.length===4){d[y]={value:new pe(_[0],_[1],_[2],_[3])};continue}d[y]={value:_}}}}const f=new Me(this.identifier,{name:t.name??"",uniforms:d,vertexShader:h,fragmentShader:c,lights:!1});switch(f.glslVersion=BS,f.vertexShader=f.vertexShader.replace("#version 300 es",""),f.fragmentShader=f.fragmentShader.replace("#version 300 es",""),d._Cull?.value){case 0:f.side=vi;break;case 1:f.side=ud;break;case 2:f.side=as;break;default:f.side=as;break}switch(d._ZTest?.value){case 3:f.depthTest=!0,f.depthFunc=$S;break;case 6:f.depthTest=!0,f.depthFunc=VS;break;case 2:f.depthTest=!0,f.depthFunc=WS;break;case 4:f.depthTest=!0,f.depthFunc=NS;break;case 5:f.depthTest=!0,f.depthFunc=zS;break;case 7:f.depthTest=!0,f.depthFunc=US;break;case 8:f.depthTest=!1,f.depthFunc=FS;break}f.transparent=m,m&&(f.depthWrite=!1),Xk(d),f.onUpdateUniforms();for(const g in p){const y=g,_=p[g].type;if(d[y]?.value===void 0)switch(_){case Vw.SAMPLER_2D:d[y]={value:Gk},console.warn("Missing/unassigned texture, fallback to white: "+y);break;default:y==="unity_OrthoParams"||console.warn("TODO: EXPECTED UNIFORM / fallback NOT SET: "+y,p[g]);break}}Yn&&console.log(f.uuid,d),$w(f),r(f)}):null}}function $w(o){if(o.uniforms){Yn&&console.log("Uniforms:",o.uniforms);for(const t in o.uniforms)switch(e(t,t),t){case"_Color":e("color",t);break}}function e(t,i){Object.getOwnPropertyDescriptor(o,t)||Object.defineProperty(o,t,{get:()=>o.uniforms[i].value,set:n=>{o.uniforms[i].value=n,o.needsUpdate=!0}})}}const nT=w("debugextensions");let Lu;const oT=import("./vendor-XJ9xiwrv.min.js").then(o=>o.index$2).then(async o=>(Lu=o.GLTFAnimationPointerExtension,Lu)).catch(o=>{console.warn("Failed to import GLTFLoaderAnimationPointer. Please use @needle-tools/three-animationpointer for full KHR_animation support",o)}),Lr=new Array;function sT(o){Lr.includes(o)||Lr.push(o)}function rT(o){const e=Lr.indexOf(o);e>=0&&Lr.splice(e,1)}function Af(o){if(o instanceof fo){const e=new zw;return o.register(t=>(e.parser=t,e)),e}return null}class aT{resolvePath(e){return e.includes("/extensions/builtin_components/")?e.replace("/extensions/builtin_components/","/userData/components/"):e.includes("extensions/builtin_components/")?e.replace("extensions/builtin_components/","/userData/components/"):e}}async function ju(o,e,t){const i=t.indexOf("?");i>=0&&(t=t.substring(0,i)),o.register(n=>new QR(n)),o.register(n=>new bk(n)),o.register(n=>new Wk(n,e.lightmaps,t)),o.register(n=>new YR(n,t,e)),o.register(n=>new iT(n,t)),o.register(n=>new Ks(n,t)),o.register(n=>new Ve(n)),o.register(n=>new HR(n)),j_()&&o.register(n=>new Al(n)),await oT.catch(n=>{}),o.register(n=>{if(Lu){const s=new Lu(n);return s.setAnimationPointerResolver.bind(s)(new aT),s}else return(nT||E())&&console.error("Missing KHR_animation_pointer extension..."),{name:"KHR_animation_pointer_NOT_AVAILABLE"}});for(const n of Lr)n.onImport&&n.onImport(o,t,e)}function If(o,e){for(const t of Lr)t.onExport&&t.onExport(o,e)}function Hw(o,e,t){for(const i of Lr)i.onLoaded&&i.onLoaded(o,e,t)}class Gw{constructor(e){this.writer=e,this.name="EXT_mesh_gpu_instancing"}writeNode(e,t){if(e.constructor.name!=="InstancedMesh")return;const i=this.writer,n=i.extensionsUsed,s={};t.extensions=t.extensions||{},t.extensions[this.name]=s;let r=new ee;const a=new Array,l=new Array,c=new Array;for(let m=0;m<e.count;m++){e.getMatrixAt(m,r);let f=new b,g=new U,y=new b;r.decompose(f,g,y),a.push(f.x,f.y,f.z),l.push(g.x,g.y,g.z,g.w),c.push(y.x,y.y,y.z)}const h=new Float32Array(a),d=new Float32Array(l),p=new Float32Array(c);s.attributes={TRANSLATION:i.processAccessor(new pt(h,3)),ROTATION:i.processAccessor(new pt(d,4)),SCALE:i.processAccessor(new pt(p,3))},n[this.name]=!0}}var lT=Object.defineProperty,qw=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&lT(e,t,n),n};const jc=w("debugreflectionprobe"),Xw=w("noreflectionprobe"),Lf=Symbol("reflectionProbeKey"),Qw=Symbol("original material"),jf=class Qo extends M{static _probes=new Map;static isUsingReflectionProbe(e){return!!(e[Lf]||e[Qw]?.[Lf])}static get(e,t,i,n){if(!e||e.isObject3D!==!0||Xw)return null;const s=Qo._probes.get(t);if(s){for(const r of s)if(r.__didAwake||r.__internalAwake(),r.activeAndEnabled){if(n){if(r.gameObject===n)return r}else if(r.isInBox(e))return jc&&console.log("Found reflection probe",e.name,r.name),r}}return jc&&console.debug("Did not find reflection probe",e.name,i,e),null}_texture;set texture(e){if(e&&!(e instanceof Re)){console.error("ReflectionProbe.texture must be a Texture",e);return}this._texture=e,e&&(e.mapping=mo,e.colorSpace=po,e.needsUpdate=!0)}get texture(){return this._texture}center;size;_boxHelper;isInBox(e){return this._boxHelper?.isInBox(e)}constructor(){super(),Qo._probes.has(this.context)||Qo._probes.set(this.context,[]),Qo._probes.get(this.context)?.push(this)}awake(){this._boxHelper=this.gameObject.addComponent(xt),this._boxHelper.updateBox(!0),jc&&this._boxHelper.showHelper(5592320,!0),this._texture&&(this._texture.mapping=mo,this._texture.colorSpace=po,this._texture.needsUpdate=!0)}start(){!this._texture&&E()&&(console.warn(`[ReflectionProbe] Missing texture. Please assign a custom cubemap texture. To use reflection probes assign them to your renderer's "anchor" property.`),ge("ReflectionProbe configuration hint: See browser console for details"))}onDestroy(){const e=Qo._probes.get(this.context);if(e){const t=e.indexOf(this);t>=0&&e.splice(t,1)}}static _rendererMaterialsCache=new Map;onSet(e){if(Xw||!this.enabled||e.sharedMaterials?.length<=0||!this.texture)return;let t=Qo._rendererMaterialsCache.get(e);t||(t=[],Qo._rendererMaterialsCache.set(e,t));for(let i=0;i<e.sharedMaterials.length;i++){const n=e.sharedMaterials[i];if(!n||n.envMap===void 0||n instanceof xe)continue;let s=t[i];const r=n===s?.copy,a=!s||s.material.uuid!==n.uuid||s.copy.version!==n.version;if(!r&&a){if(jc){let h="";s?s.material!==n?h="reference changed; cached instance?: "+r:s.copy.version!==n.version&&(h="version changed"):h="not cached",console.warn("Cloning material",n.name,n.version,"Reason:",h,`
977
977
  `,n.uuid,`
978
978
  `,s?.copy.uuid,`
979
979
  `,e.name)}const c=n.clone();c.version=n.version,s?(s.copy=c,s.material=n):(s={material:n,copy:c},t.push(s)),c[Lf]=this,c[Qw]=n,jc&&console.log("Set reflection",e.name,e.guid)}s&&s.copy&&(s.copy.onBeforeCompile=n.onBeforeCompile);const l=s?.copy;l.envMap=this.texture,e.sharedMaterials[i]=l}}onUnset(e){const t=Qo._rendererMaterialsCache.get(e);if(t)for(let i=0;i<t.length;i++){const n=t[i];e.sharedMaterials[i]=n.material}}};qw([u(b)],jf.prototype,"center"),qw([u(b)],jf.prototype,"size");let Dc=jf;const li=w("debuginstancing");class la{static instance=new la;static getStartInstanceCount=e=>4;objs=[];setup(e,t,i,n,s,r=0){e.applySettings(t);const a=this.tryCreateOrAddInstance(t,i,s);if(a){n===null&&(n=[]),n.push(a),Ve.assignTextureLOD(a.renderer.material,0);for(let l=0;l<e.sharedMeshes.length;l++){const c=e.sharedMeshes[l],h=c.geometry;Ve.assignMeshLOD(c,0).then(d=>{d&&e.activeAndEnabled&&h!=d&&a.setGeometry(d)})}}else if(r<=0&&t.type!=="Mesh"){const l=r+1;for(const c of t.children)n=this.setup(e,c,i,n,s,l)}return r===0&&s.useMatrixWorldAutoUpdate&&n&&n.length>=0&&this.autoUpdateInstanceMatrix(t),n}tryCreateOrAddInstance(e,t,i){if(e.type==="Mesh"){const n=i.foundMeshes;if(i.foundMeshes+=1,!i.rend.enableInstancing)return null;if(i.rend.enableInstancing!==!0){if(n>=i.rend.enableInstancing.length)return li&&console.error("Something is wrong with instance setup",e,i.rend.enableInstancing,n),null;if(!i.rend.enableInstancing[n])return null}const s=e,r=s.material;for(const h of this.objs)if(!!h.canAdd(s.geometry,r))return h.addInstance(s);let a=la.getStartInstanceCount(e);(!a||a<0)&&(a=4);let l=e.name;l?.length||(l=fb());const c=new cT(l,s.geometry,r,a,t);return this.objs.push(c),c.addInstance(s)}return null}autoUpdateInstanceMatrix(e){const t=e.matrixWorld.multiplyMatrices.bind(e.matrixWorld),i=e.matrixWorld.clone(),n=(s,r)=>{const a=t(s,r);return(e[nc]||i.equals(a)===!1)&&(i.copy(a),e[nc]=!0),a};e.matrixWorld.multiplyMatrices=n}}class ua{static all=[];get name(){return this.object.name}get isActive(){return this.__instanceIndex>=0}get vertexCount(){return this.object.geometry.attributes.position.count}get maxVertexCount(){return Math.max(this.meshInformation.vertexCount,this.vertexCount)}get reservedVertexCount(){return this.__reservedVertexRange}get indexCount(){return this.object.geometry.index?this.object.geometry.index.count:0}get maxIndexCount(){return Math.max(this.meshInformation.indexCount,this.indexCount)}get reservedIndexCount(){return this.__reservedIndexRange}object;renderer;__instanceIndex=-1;__reservedVertexRange=0;__reservedIndexRange=0;__geometryIndex=-1;meshInformation;constructor(e,t){this.__instanceIndex=-1,this.object=e,this.renderer=t,e[N_]=t,this.meshInformation=jr(e.geometry),ua.all.push(this)}updateMeshInformation(){const e=jr(this.object.geometry),t=this.meshInformation.vertexCount,i=this.meshInformation.indexCount;return Object.assign(this.meshInformation,e),t!==this.meshInformation.vertexCount||i!==this.meshInformation.indexCount}updateInstanceMatrix(e=!1,t=!0){this.__instanceIndex<0||(t&&this.object.updateWorldMatrix(!0,e),this.renderer.updateInstance(this.object.matrixWorld,this.__instanceIndex))}setMatrix(e){this.__instanceIndex<0||this.renderer.updateInstance(e,this.__instanceIndex)}setGeometry(e){if(this.__geometryIndex<0)return!1;const t=this;if(this.vertexCount>this.__reservedVertexRange)return i(`Instancing: Can not update geometry (${this.name}), reserved vertex range is too small: ${this.__reservedVertexRange.toLocaleString()} < ${this.vertexCount.toLocaleString()} vertices for ${this.name}`);if(this.indexCount>this.__reservedIndexRange)return i(`Instancing: Can not update geometry (${this.name}), reserved index range is too small: ${this.__reservedIndexRange.toLocaleString()} < ${this.indexCount.toLocaleString()} indices for ${this.name}`);return this.renderer.updateGeometry(e,this.__geometryIndex);function i(n){return t.updateMeshInformation()&&(t.renderer.remove(t,!0),t.renderer.add(t))?!0:((E()||li)&&console.error(n),!1)}}add(){this.__instanceIndex>=0||(this.renderer.add(this),x.markAsInstancedRendered(this.object,!0))}remove(e){if(!(this.__instanceIndex<0)&&(this.renderer.remove(this,e),x.markAsInstancedRendered(this.object,!1),e)){const t=ua.all.indexOf(this);t>=0&&ua.all.splice(t,1)}}}class cT{get batchedMesh(){return this._batchedMesh}get visible(){return this._batchedMesh.visible}set visible(e){this._batchedMesh.visible=e}get castShadow(){return this._batchedMesh.castShadow}set castShadow(e){this._batchedMesh.castShadow=e}set receiveShadow(e){this._batchedMesh.receiveShadow=e}allowResize=!0;name="";geometry;material;get count(){return this._currentInstanceCount}updateBounds(e=!0,t=!0){if(this._needUpdateBounds=!1,e&&this._batchedMesh.computeBoundingBox(),t&&this._batchedMesh.computeBoundingSphere(),li&&this._batchedMesh.boundingSphere){const i=this._batchedMesh.boundingSphere;F.DrawWireSphere(i.center,i.radius,65280)}}_context;_batchedMesh;_handles=[];_geometryIds=new Map;_maxInstanceCount;_currentInstanceCount=0;_currentVertexCount=0;_currentIndexCount=0;_maxVertexCount;_maxIndexCount;static nullMatrix=new ee;canAdd(e,t){return this._maxVertexCount>1e7||t!==this.material||!this.validateGeometry(e)?!1:!!(!this.mustGrow(e)||this.allowResize)}_needUpdateBounds=!1;_debugMaterial=null;constructor(e,t,i,n,s){this.name=e,this.geometry=t,this.material=i,this._context=s,this._maxInstanceCount=Math.max(2,n),li&&(this._debugMaterial=Yw());const r=this.tryEstimateVertexCountSize(this._maxInstanceCount,[t],n);this._maxVertexCount=r.vertexCount,this._maxIndexCount=r.indexCount,this._batchedMesh=new W0(this._maxInstanceCount,this._maxVertexCount,this._maxIndexCount,this._debugMaterial??this.material),this._batchedMesh[oc]=!0,this._batchedMesh.visible=!0,this._context.scene.add(this._batchedMesh),i instanceof N0&&(i.defines.USE_INSTANCING=!0,i.needsUpdate=!0),s.pre_render_callbacks.push(this.onBeforeRender),s.post_render_callbacks.push(this.onAfterRender),li&&console.log(`Instanced renderer created with ${this._maxInstanceCount} instances, ${this._maxVertexCount} max vertices and ${this._maxIndexCount} max indices for "${e}"`)}dispose(){li&&console.warn("Dispose instanced renderer",this.name),this._context.scene.remove(this._batchedMesh),this._batchedMesh.dispose(),this._batchedMesh=null,this._handles=[]}addInstance(e){const t=new ua(e,this);e.castShadow===!0&&this._batchedMesh.castShadow===!1&&(this._batchedMesh.castShadow=!0),e.receiveShadow===!0&&this._batchedMesh.receiveShadow===!1&&(this._batchedMesh.receiveShadow=!0);try{this.add(t)}catch(i){if(console.error(`Failed adding mesh to instancing (object name: "${e.name}", instances: ${this._currentInstanceCount.toLocaleString()}/${this._maxInstanceCount.toLocaleString()}, vertices: ${this._currentVertexCount.toLocaleString()}/${this._maxVertexCount.toLocaleString()}, indices: ${this._currentIndexCount.toLocaleString()}/${this._maxIndexCount.toLocaleString()})
@@ -1023,7 +1023,7 @@ Texture:`,i),this.setLightmapDebugMaterial()):Za&&console.log("Use debuglightmap
1023
1023
  gl_FragColor = lightMapTexel;
1024
1024
  gl_FragColor.a = 1.;
1025
1025
  }
1026
- `,defines:{USE_LIGHTMAP:""}})}}var hT=Object.defineProperty,Lo=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&hT(e,t,n),n};const Ja=w("debugrenderer"),Kw=w("debugskinnedmesh"),Zw=w("noinstancing"),dT=w("wireframe");class Jw{path=null;asset=null;default}class uT{_renderer;_targets=[];_indexMapMaxIndex;_indexMap;_changed=!1;get changed(){return this._changed}set changed(e){e===!0&&Ja&&console.warn("SharedMaterials have changed: "+this._renderer.name,this),this._changed=e}is(e){return this._renderer===e}constructor(e,t){this._renderer=e;const i=this.setMaterial.bind(this),n=this.getMaterial.bind(this),s=e.gameObject;if(this._targets=[],s)switch(s.type){case"Group":this._targets=[...s.children];break;case"SkinnedMesh":case"Mesh":this._targets.push(s);break}let r=!1,a,l=0;for(let c=0;c<this._targets.length;c++){const h=this._targets[c];if(!h)continue;const d=h.material;if(d){d.shadowSide=d.side;for(let p=0;p<t.length;p++){const g=t[p];if(!g){r=!0;continue}if(d.name===g.name){a===void 0&&(a=new Map),a.set(p,c),l=Math.max(l,p);break}}}}if(r){this._indexMapMaxIndex=l,this._indexMap=a;const c=`Renderer ${e.name} was initialized with missing materials - this may lead to unexpected behaviour when trying to access sharedMaterials by index.`;console.warn(c),Wi()&&ge("Found renderer with missing materials: please check the console for details.")}return new Proxy(this,{get(c,h){if(typeof h=="string"){const d=parseInt(h);if(!isNaN(d))return n(d)}return c[h]},set(c,h,d){return typeof h=="string"&&i(d,Number.parseInt(h)),Reflect.set(c,h,d)?(d instanceof ve&&(c.changed=!0),!0):!1}})}get length(){return this._indexMapMaxIndex!==void 0?this._indexMapMaxIndex+1:this._targets.length}*[Symbol.iterator](){for(let e=0;e<this.length;e++)yield this.getMaterial(e)}resolveIndex(e){const t=this._indexMap;return t&&t.has(e)?t.get(e):e}setMaterial(e,t){if(t=this.resolveIndex(t),t<0||t>=this._targets.length)return;const i=this._targets[t];!i||i.material===void 0||(i.material=e,this.changed=!0)}getMaterial(e){if(e=this.resolveIndex(e),e<0)return null;const t=this._targets;if(e>=t.length)return null;const i=t[e];return i?i.material:null}}const Kn=class Gp extends M{static setInstanced(e,t){const i=cc(e,Gp);return i.setInstancingEnabled(t),i}static isInstanced(e){const t=br(e,Gp);return t?t.isInstancingActive:an.isUsingInstancing(e)}static setVisible(e,t){Co(e,t)}receiveShadows=!1;shadowCastingMode=0;lightmapIndex=-1;lightmapScaleOffset=new pe(1,1,0,0);enableInstancing=void 0;renderOrder=void 0;allowOcclusionWhenDynamic=!0;probeAnchor;reflectionProbeUsage=0;_lightmaps;get sharedMesh(){if(this.gameObject.type==="Mesh")return this.gameObject;if(this.gameObject.type==="SkinnesMesh")return this.gameObject;if(this.gameObject.type==="Group")return this.gameObject.children[0]}_sharedMeshes=[];get sharedMeshes(){if(this.destroyed||!this.gameObject)return this._sharedMeshes;if(this._sharedMeshes.length=0,this.gameObject.type==="Group")for(const e of this.gameObject.children)(e.type==="Mesh"||e.type==="SkinnedMesh")&&this._sharedMeshes.push(e);else(this.gameObject.type==="Mesh"||this.gameObject.type==="SkinnedMesh")&&this._sharedMeshes.push(this.gameObject);return this._sharedMeshes}get sharedMaterial(){return this.sharedMaterials[0]}set sharedMaterial(e){this.sharedMaterials[0]!==e&&(this.sharedMaterials[0]=e,this.applyLightmapping())}get material(){return this.sharedMaterials[0]}set material(e){this.sharedMaterial=e}_sharedMaterials;_originalMaterials;_probeAnchorLastFrame;set sharedMaterials(e){if(!this._originalMaterials)this._originalMaterials=e;else if(e){let t=!1;for(let i=0;i<this._sharedMaterials.length;i++){const n=i<e.length?e[i]:null;n&&n instanceof ve?this.sharedMaterials[i]=n:t||(t=!0,console.warn("Can not assign null as material: "+this.name,n))}}}get sharedMaterials(){return this.__didAwake?((!this._sharedMaterials||!this._sharedMaterials.is(this))&&(this._originalMaterials||(this._originalMaterials=[]),this._sharedMaterials=new uT(this,this._originalMaterials)),this._sharedMaterials):null}static get shouldSuppressInstancing(){return Zw}_lightmapTextureOverride=void 0;get lightmap(){return this._lightmaps?.length?this._lightmaps[0].lightmap:null}set lightmap(e){if(this._lightmapTextureOverride=e,e===void 0&&(e=this.context.lightmaps.tryGetLightmap(this.sourceId,this.lightmapIndex)),this._lightmaps?.length)for(const t of this._lightmaps)t.lightmap=e}get hasLightmap(){return this.lightmap!=null}allowProgressiveLoading=!0;_firstFrame=-1;registering(){this.enabled||this.setVisibility(!1)}awake(){if(this._firstFrame=this.context.time.frame,Ja&&console.log("Renderer ",this.name,this),this.clearInstancingState(),this.probeAnchor&&Ja&&this.probeAnchor.add(new _i(.2)),this._reflectionProbe=null,this.isMultiMaterialObject(this.gameObject)){for(const e of this.gameObject.children)this.context.addBeforeRenderListener(e,this.onBeforeRenderThree),e.layers.mask=this.gameObject.layers.mask;if(this.renderOrder!==void 0){let e=0;for(let t=0;t<this.gameObject.children.length;t++){const i=this.gameObject.children[t];if(!(!this.isMeshOrSkinnedMesh(i)||x.getComponent(i,Gp))){if(this.renderOrder.length<=e){console.warn("Incorrect renderOrder element count",this,this.renderOrder.length+" but expected "+this.gameObject.children.length,"Index: "+e,"ChildElement:",i);continue}i.renderOrder=this.renderOrder[e],e+=1}}}}else this.isMeshOrSkinnedMesh(this.gameObject)?(this.context.addBeforeRenderListener(this.gameObject,this.onBeforeRenderThree),this.renderOrder!==void 0&&this.renderOrder.length>0&&(this.gameObject.renderOrder=this.renderOrder[0])):this.context.addBeforeRenderListener(this.gameObject,this.onBeforeRenderThree);if(this.applyLightmapping(),dT)for(let e=0;e<this.sharedMaterials.length;e++){const t=this.sharedMaterials[e];t&&(t.wireframe=!0)}}applyLightmapping(){if(this.lightmapIndex>=0){const e=this.gameObject.type,t=this._lightmapTextureOverride!==void 0?this._lightmapTextureOverride:this.context.lightmaps.tryGetLightmap(this.sourceId,this.lightmapIndex);if(t){if(this._lightmaps||(this._lightmaps=[]),e==="Mesh"){const i=this.gameObject.material;if(i?.isMeshBasicMaterial)i&&console.warn("Lightmapping is not supported on MeshBasicMaterial",i.name);else{if(this._lightmaps.length<=0){const n=new Du(this.gameObject,this.context);this._lightmaps.push(n)}this._lightmaps[0].init(this.lightmapIndex,this.lightmapScaleOffset,t)}}else if(this.isMultiMaterialObject(this.gameObject)&&this.sharedMaterials.length>0)for(let i=0;i<this.gameObject.children.length;i++){const n=this.gameObject.children[i];if(!n.material?.isMeshBasicMaterial){let s;i>=this._lightmaps.length?(s=new Du(n,this.context),this._lightmaps.push(s)):s=this._lightmaps[i],s.init(this.lightmapIndex,this.lightmapScaleOffset,t)}}}else Ja&&console.warn("Lightmap not found",this.sourceId,this.lightmapIndex)}}_isInstancingEnabled=!1;_handles=void 0;get isInstancingActive(){return this._handles!=null&&this._handles.length>0&&this._isInstancingEnabled}get instances(){if(!this._handles||this._handles.length<=0)return null;if(this._handlesTempArray.length=0,this._handles)for(const e of this._handles)this._handlesTempArray.push(e);return this._handlesTempArray}_handlesTempArray=[];setInstancingEnabled(e){if(this._isInstancingEnabled===e)return e&&(this._handles===void 0||this._handles!=null&&this._handles.length>0);if(this._isInstancingEnabled=e,e){if(this.enableInstancing===void 0&&(this.enableInstancing=!0),this._handles===void 0){if(this._handles=la.instance.setup(this,this.gameObject,this.context,null,{rend:this,foundMeshes:0,useMatrixWorldAutoUpdate:this.useInstanceMatrixWorldAutoUpdate()}),this._handles)return x.markAsInstancedRendered(this.gameObject,!0),!0}else if(this._handles!==null){for(const t of this._handles)t.updateInstanceMatrix(!0),t.add();return x.markAsInstancedRendered(this.gameObject,!0),!0}}else{if(this._handles)for(const t of this._handles)t.remove(this.destroyed);return!0}return!1}clearInstancingState(){this._isInstancingEnabled=!1,this._handles=void 0}useInstanceMatrixWorldAutoUpdate(){return!0}start(){if(this.enableInstancing&&!Zw&&(this.setInstancingEnabled(!0),an.markDirty(this.gameObject)),this.gameObject.frustumCulled=this.allowOcclusionWhenDynamic,this.isMultiMaterialObject(this.gameObject))for(let e=0;e<this.gameObject.children.length;e++){const t=this.gameObject.children[e];t.frustumCulled=this.allowOcclusionWhenDynamic}}onEnable(){this.sharedMeshes,this.setVisibility(!0),this._isInstancingEnabled||this.enableInstancing==!0||Array.isArray(this.enableInstancing)&&this.enableInstancing.some(e=>e)?this.__internalDidAwakeAndStart&&this.setInstancingEnabled(!0):this.enabled&&this.applyStencil(),this.updateReflectionProbe()}onDisable(){this.setVisibility(!1),this._handles&&this._handles.length>0&&this.setInstancingEnabled(!1)}onDestroy(){if(this._handles=null,this.isMultiMaterialObject(this.gameObject))for(const e of this.gameObject.children)this.context.removeBeforeRenderListener(e,this.onBeforeRenderThree);else this.context.removeBeforeRenderListener(this.gameObject,this.onBeforeRenderThree)}onBeforeRender(){if(this.gameObject){if(this._probeAnchorLastFrame!==this.probeAnchor&&(this._reflectionProbe?.onUnset(this),this.updateReflectionProbe()),Ja==this.name&&this.gameObject instanceof H){this.gameObject.geometry.computeBoundingSphere();const e=$(this.gameObject.geometry.boundingSphere.center).applyMatrix4(this.gameObject.matrixWorld);F.DrawWireSphere(e,this.gameObject.geometry.boundingSphere.radius,56831)}if(this.isMultiMaterialObject(this.gameObject)&&this.gameObject.children?.length>0)for(const e of this.gameObject.children)this.applySettings(e);else this.applySettings(this.gameObject);if(this.sharedMaterials?.changed&&(this.sharedMaterials.changed=!1,this.applyLightmapping()),this._handles?.length&&this.gameObject[nc]===!0){this.gameObject[nc]=!1;for(let e=this._handles.length-1;e>=0;e--)this._handles[e].updateInstanceMatrix();this.gameObject.matrixWorldNeedsUpdate=!1}if(this._handles&&this._handles.length<=0&&x.markAsInstancedRendered(this.gameObject,!1),this._isInstancingEnabled&&this._handles)for(let e=0;e<this._handles.length;e++){const t=this._handles[e];Co(t.object,!1)}if(this.reflectionProbeUsage!==0&&this._reflectionProbe&&(this._lightmaps?.length||this._reflectionProbe.onSet(this)),this._sharedMaterials)for(const e of this._sharedMaterials)e&&"envMap"in e&&"envMapIntensity"in e&&!Dc.isUsingReflectionProbe(e)&&(e.envMap=this.context.scene.environment);else Ja&&console.warn("[Renderer] sharedMaterials not initialized yet: "+this.name)}}onBeforeRenderThree=(e,t,i,n,s,r)=>{if(s.envMapIntensity!==void 0){const a=this.hasLightmap?Math.PI:1,l=this.context.mainCameraComponent?.environmentIntensity??1;s.envMapIntensity=Math.max(0,l*this.context.sceneLighting.environmentIntensity/a)}if(this._lightmaps)for(const a of this._lightmaps)a.updateLightmapUniforms(s),a.applyLightmap()};onAfterRender(){if(this._isInstancingEnabled&&this._handles)for(let e=0;e<this._handles.length;e++){const t=this._handles[e];Co(t.object,!0)}this.reflectionProbeUsage!==0&&this._reflectionProbe&&this._reflectionProbe.onUnset(this),this.static&&this.gameObject.matrixAutoUpdate&&(this.gameObject.matrixAutoUpdate=!1)}applyStencil(){Ks.applyStencil(this)}applySettings(e){e.receiveShadow=this.receiveShadows,this.shadowCastingMode==1?e.castShadow=!0:e.castShadow=!1}_reflectionProbe=null;updateReflectionProbe(){this._reflectionProbe=null,this.reflectionProbeUsage!==0&&(this.startCoroutine(this._updateReflectionProbe(),we.LateUpdate),this._probeAnchorLastFrame=this.probeAnchor)}*_updateReflectionProbe(){const e=this.probeAnchor||this.gameObject,t=!!this.probeAnchor;this._reflectionProbe=Dc.get(e,this.context,t,this.probeAnchor)}setVisibility(e){if(!this.isMultiMaterialObject(this.gameObject))Co(this.gameObject,e);else for(const t of this.gameObject.children)this.isMeshOrSkinnedMesh(t)&&Co(t,e)}isMultiMaterialObject(e){return e.type==="Group"}isMeshOrSkinnedMesh(e){return e.type==="Mesh"||e.type==="SkinnedMesh"}};Lo([u()],Kn.prototype,"receiveShadows"),Lo([u()],Kn.prototype,"shadowCastingMode"),Lo([u()],Kn.prototype,"lightmapIndex"),Lo([u(pe)],Kn.prototype,"lightmapScaleOffset"),Lo([u()],Kn.prototype,"enableInstancing"),Lo([u()],Kn.prototype,"renderOrder"),Lo([u()],Kn.prototype,"allowOcclusionWhenDynamic"),Lo([u(O)],Kn.prototype,"probeAnchor"),Lo([u()],Kn.prototype,"reflectionProbeUsage");let Ti=Kn;class Bc extends Ti{}class Df extends Bc{_needUpdateBoundingSphere=!1;awake(){super.awake(),Kw&&console.log('SkinnedMeshRenderer for "'+this.name+'"',this),this.allowOcclusionWhenDynamic=!1;for(const e of this.sharedMeshes)e.parent?.updateWorldMatrix(!1,!0),this.markBoundsDirty()}onAfterRender(){if(super.onAfterRender(),this._needUpdateBoundingSphere){for(const e of this.sharedMeshes)if(e instanceof ss){this._needUpdateBoundingSphere=!1;try{const t=e.geometry,i=q0(e);i&&(e.geometry=i),e.computeBoundingSphere(),e.geometry=t}catch(t){console.error(`Error updating bounding sphere for ${e.name}`,t)}}}if(Kw){for(const e of this.sharedMeshes)if(e instanceof ss&&e.boundingSphere){const t=$(e.boundingSphere.center).applyMatrix4(e.matrixWorld);F.DrawWireSphere(t,e.boundingSphere.radius,"red")}}}markBoundsDirty(){this._needUpdateBoundingSphere=!0}}var pT=Object.defineProperty,ex=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&pT(e,t,n),n};const Bu=w("debuggltfexport");class Bf extends xt{sceneRoot}const Ff=class Ml extends M{binary=!0;objects=[];ext;async exportNow(e,t){Bu&&console.log("Exporting objects as glTF",this.objects),e||(e="scene"),(!this.objects||this.objects.length<=0)&&(this.objects=[this.context.scene]);const i={binary:this.binary,pivot:Ml.calculateCenter(this.objects),...t},n=await this.export(this.objects,i).catch(s=>(console.error(s),!1));return n===!1?!1:(this.binary?e.endsWith(".glb")||(e+=".glb"):e.endsWith(".gltf")||(e+=".gltf"),this.binary?Ml.saveArrayBuffer(n,e):Ml.saveJson(n,e),!0)}async export(e,t){if(!e||e.length<=0){console.warn("No objects set to export");return}const i=new K0;i.register(c=>new Gw(c)),i.register(c=>new Uw(c)),If(i,this.context),Ml.filterTopmostParent(e);const n={trs:!1,onlyVisible:!0,truncateDrawRange:!1,binary:!0,maxTextureSize:1/0,embedImages:!0,includeCustomExtensions:!0,animations:t?.animations||Ml.collectAnimations(e),...t},s=new Array,r=new O;t?.pivot&&r.position.sub(t.pivot),Bu&&console.log("EXPORT",e),e.forEach(c=>{c&&Mf(c)&&(r.children.push(c),c.matrixAutoUpdate=!1,c.matrix.copy(c.matrixWorld),x.getComponentsInChildren(c,Ti).forEach(h=>{x.isActiveInHierarchy(h.gameObject)&&h.setInstancingEnabled(!1)}),c.traverse(h=>{if(!Mf(h)){const d=h.parent;h.removeFromParent(),s.push(()=>{d&&d.add(h)})}}))});const a=new Mg(r);return t?.needleComponents&&(this.ext=new zw),this.ext&&(this.ext.registerExport(i),this.ext.context=a),new Promise((c,h)=>{Bu&&console.log("Starting glTF export.");try{i?.parse(r,d=>{l(),c(d)},d=>{l(),h(d)},n)}catch(d){console.error(d),h(d)}finally{s.forEach(d=>d()),Bu&&console.log("Finished glTF export.")}});function l(){e.forEach(c=>{c&&(c.matrixAutoUpdate=!0,x.getComponentsInChildren(c,Ti).forEach(h=>{x.isActiveInHierarchy(h.gameObject)&&h.setInstancingEnabled(!1)}))})}}static saveArrayBuffer(e,t){this.save(new Blob([e],{type:"application/octet-stream"}),t)}static saveJson(e,t){this.save("data: text/json;charset=utf-8,"+encodeURIComponent(JSON.stringify(e)),t)}static save(e,t){const i=document.createElement("a");i.style.display="none",document.body.appendChild(i),typeof e=="string"?i.href=e:i.href=URL.createObjectURL(e),i.download=t,i.click(),i.remove()}static collectAnimations(e,t){t=t||[];for(const i of e)i&&i.traverseVisible(n=>{n.animations&&n.animations.length>0&&t.push(...n.animations)});return t}static calculateCenter(e,t){const i=t||new b;return i.set(0,0,0),e.forEach(n=>{i.add(Z(n))}),i.divideScalar(e.length),i}static filterTopmostParent(e){if(!(e.length<=0))for(let t=0;t<e.length;t++){let i=e[t];if(!i){e.splice(t,1),t--;continue}for(;i.parent;){if(e.includes(i.parent)){e.splice(t,1),t--;break}i=i.parent}}}};ex([u()],Ff.prototype,"binary"),ex([u(O)],Ff.prototype,"objects");let Uf=Ff;typeof globalThis!==void 0&&!("OffscreenCanvas"in globalThis)&&(globalThis.OffscreenCanvas=class{canvas;constructor(o,e){return this.canvas=document.createElement("canvas"),this.canvas.width=o,this.canvas.height=e,this.canvas.convertToBlob=(t,i)=>new Promise(n=>{this.canvas.toBlob(n,t,i)}),this.canvas}});const mT=w("debugprogress");function tx(o){o=o||new Date;const e=o.getMonth()+1,t=o.getDate(),i=o.getHours(),n=o.getMinutes(),s=o.getSeconds(),r=(e<10?"0":"")+e,a=(t<10?"0":"")+t,l=(i<10?"0":"")+i,c=(n<10?"0":"")+n,h=(s<10?"0":"")+s;return o.getFullYear()+r+a+"-"+l+c+h}class re{static start(e,t){typeof t=="string"&&(t={parentScope:t});const i=new gT(e,t);Fc.set(e,i)}static report(e,t){const i=Fc.get(e);if(!i){console.warn("Reporting progress for non-existing scope",e);return}typeof t=="string"&&(t={message:t,autoStep:!0}),i.report(t)}static end(e){const t=Fc.get(e);t&&(t.end(),Fc.delete(e))}}const Fc=new Map;class gT{scopeLabel;parentScope;childScopes=[];parentDepth=0;lastStep=0;lastAutoStepWeight=1;lastTotalSteps=0;onProgress;showLogs=!1;selfProgress=0;totalProgress=0;selfReports=0;totalReports=0;constructor(e,t){this.parentScope=t?.parentScope?Fc.get(t.parentScope):void 0,this.parentScope&&(this.parentScope.childScopes.push(this),this.parentDepth=this.parentScope.parentDepth+1),this.scopeLabel=" ".repeat(this.parentDepth*2)+e,this.showLogs=t?.logTimings??!!mT,this.showLogs&&console.time(this.scopeLabel),this.onProgress=t?.onProgress}report(e,t=!1){if(e){if(e.totalSteps!==void 0&&(this.lastTotalSteps=e.totalSteps),e.currentStep!==void 0&&(this.lastStep=e.currentStep),e.autoStep!==void 0){if(e.currentStep===void 0){this.lastStep===void 0&&(this.lastStep=0);const n=typeof e.autoStep=="number"?e.autoStep:1;this.lastStep+=this.lastAutoStepWeight,this.lastAutoStepWeight=n,e.currentStep=this.lastStep}e.totalSteps=this.lastTotalSteps}e.progress!==void 0?this.selfProgress=e.progress:e.currentStep!==void 0&&e.totalSteps!==void 0&&(this.selfProgress=e.currentStep/e.totalSteps)}if(this.childScopes.length>0){let n=0,s=0;for(const a of this.childScopes)n+=a.selfProgress,s+=1;s>0&&(n/=s);const r=this.lastAutoStepWeight/(this.lastTotalSteps??1);this.totalProgress=this.selfProgress+n*r}else this.totalProgress=this.selfProgress;this.selfProgress=Math.min(1,this.selfProgress),this.totalProgress=Math.min(1,this.totalProgress);let i=(this.totalProgress*100).toFixed(3)+"%";this.childScopes.length>0&&(i+=" ("+(this.selfProgress*100).toFixed(3)+"% self)"),e?.message&&(i=e.message+" \u2013 "+i),this.lastStep!==void 0&&this.lastTotalSteps!==void 0&&(i="Step "+(this.lastStep+(this.lastAutoStepWeight!=1?"\u2013"+(this.lastStep+this.lastAutoStepWeight):"")+"/"+this.lastTotalSteps)+" "+i),t?this.totalReports++:(this.selfReports++,this.totalReports++),this.showLogs&&console.timeLog(this.scopeLabel,i),this.onProgress&&this.onProgress(this.totalProgress),this.parentScope&&this.parentScope.report(void 0,!0)}end(){this.report({progress:1,autoStep:!0},!0),this.showLogs&&(console.timeLog(this.scopeLabel,"Total reports: "+this.totalReports,"Self reports: "+this.selfReports),console.timeEnd(this.scopeLabel));let e=!1;for(const t of this.childScopes)if(!(t.selfProgress>=1)){e=!0;break}e&&console.warn("Progress end with child scopes that are still running",this),this.onProgress=void 0}}const De="</StageRoot/Materials";function fT(o,e,t){const i=new Map,n=m=>{const y=m.type___needle,_=i.get(y)||new Map;if(i.set(y,_),!_.has(m)){const v=`${y}${_.size?`_${_.size}`:""}`;_.set(m,v)}return _.get(m)},s=o.colorNode?Fu(o.colorNode):[],r=o.colorNode?`color3f inputs:diffuseColor.connect = ${De}/${e}/${n(s.values().next().value)}.outputs:out>`:"",a=o.roughnessNode?Fu(o.roughnessNode):[],l=o.roughnessNode?`float inputs:roughness.connect = ${De}/${e}/${n(a.values().next().value)}.outputs:out>`:"",c=o.normalNode?Fu(o.normalNode):[],h=o.normalNode?`float3 inputs:normal.connect = ${De}/${e}/${n(c.values().next().value)}.outputs:out>`:"",d=o.metalnessNode?Fu(o.metalnessNode):[],p=o.metalnessNode?`float inputs:metallic.connect = ${De}/${e}/${n(d.values().next().value)}.outputs:out>`:"",g=new Set([...s,...a,...c,...d]),f=_T(g,e,t,n);return console.debug(f),`
1026
+ `,defines:{USE_LIGHTMAP:""}})}}var hT=Object.defineProperty,Lo=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&hT(e,t,n),n};const Ja=w("debugrenderer"),Kw=w("debugskinnedmesh"),Zw=w("noinstancing"),dT=w("wireframe");class Jw{path=null;asset=null;default}class uT{_renderer;_targets=[];_indexMapMaxIndex;_indexMap;_changed=!1;get changed(){return this._changed}set changed(e){e===!0&&Ja&&console.warn("SharedMaterials have changed: "+this._renderer.name,this),this._changed=e}is(e){return this._renderer===e}constructor(e,t){this._renderer=e;const i=this.setMaterial.bind(this),n=this.getMaterial.bind(this),s=e.gameObject;if(this._targets=[],s)switch(s.type){case"Group":this._targets=[...s.children];break;case"SkinnedMesh":case"Mesh":this._targets.push(s);break}let r=!1,a,l=0;for(let c=0;c<this._targets.length;c++){const h=this._targets[c];if(!h)continue;const d=h.material;if(d){d.shadowSide=d.side;for(let p=0;p<t.length;p++){const m=t[p];if(!m){r=!0;continue}if(d.name===m.name){a===void 0&&(a=new Map),a.set(p,c),l=Math.max(l,p);break}}}}if(r){this._indexMapMaxIndex=l,this._indexMap=a;const c=`Renderer ${e.name} was initialized with missing materials - this may lead to unexpected behaviour when trying to access sharedMaterials by index.`;console.warn(c),Wi()&&ge("Found renderer with missing materials: please check the console for details.")}return new Proxy(this,{get(c,h){if(typeof h=="string"){const d=parseInt(h);if(!isNaN(d))return n(d)}return c[h]},set(c,h,d){return typeof h=="string"&&i(d,Number.parseInt(h)),Reflect.set(c,h,d)?(d instanceof ve&&(c.changed=!0),!0):!1}})}get length(){return this._indexMapMaxIndex!==void 0?this._indexMapMaxIndex+1:this._targets.length}*[Symbol.iterator](){for(let e=0;e<this.length;e++)yield this.getMaterial(e)}resolveIndex(e){const t=this._indexMap;return t&&t.has(e)?t.get(e):e}setMaterial(e,t){if(t=this.resolveIndex(t),t<0||t>=this._targets.length)return;const i=this._targets[t];!i||i.material===void 0||(i.material=e,this.changed=!0)}getMaterial(e){if(e=this.resolveIndex(e),e<0)return null;const t=this._targets;if(e>=t.length)return null;const i=t[e];return i?i.material:null}}const Kn=class Gp extends M{static setInstanced(e,t){const i=cc(e,Gp);return i.setInstancingEnabled(t),i}static isInstanced(e){const t=br(e,Gp);return t?t.isInstancingActive:an.isUsingInstancing(e)}static setVisible(e,t){Co(e,t)}receiveShadows=!1;shadowCastingMode=0;lightmapIndex=-1;lightmapScaleOffset=new pe(1,1,0,0);enableInstancing=void 0;renderOrder=void 0;allowOcclusionWhenDynamic=!0;probeAnchor;reflectionProbeUsage=0;_lightmaps;get sharedMesh(){if(this.gameObject.type==="Mesh")return this.gameObject;if(this.gameObject.type==="SkinnesMesh")return this.gameObject;if(this.gameObject.type==="Group")return this.gameObject.children[0]}_sharedMeshes=[];get sharedMeshes(){if(this.destroyed||!this.gameObject)return this._sharedMeshes;if(this._sharedMeshes.length=0,this.gameObject.type==="Group")for(const e of this.gameObject.children)(e.type==="Mesh"||e.type==="SkinnedMesh")&&this._sharedMeshes.push(e);else(this.gameObject.type==="Mesh"||this.gameObject.type==="SkinnedMesh")&&this._sharedMeshes.push(this.gameObject);return this._sharedMeshes}get sharedMaterial(){return this.sharedMaterials[0]}set sharedMaterial(e){this.sharedMaterials[0]!==e&&(this.sharedMaterials[0]=e,this.applyLightmapping())}get material(){return this.sharedMaterials[0]}set material(e){this.sharedMaterial=e}_sharedMaterials;_originalMaterials;_probeAnchorLastFrame;set sharedMaterials(e){if(!this._originalMaterials)this._originalMaterials=e;else if(e){let t=!1;for(let i=0;i<this._sharedMaterials.length;i++){const n=i<e.length?e[i]:null;n&&n instanceof ve?this.sharedMaterials[i]=n:t||(t=!0,console.warn("Can not assign null as material: "+this.name,n))}}}get sharedMaterials(){return this.__didAwake?((!this._sharedMaterials||!this._sharedMaterials.is(this))&&(this._originalMaterials||(this._originalMaterials=[]),this._sharedMaterials=new uT(this,this._originalMaterials)),this._sharedMaterials):null}static get shouldSuppressInstancing(){return Zw}_lightmapTextureOverride=void 0;get lightmap(){return this._lightmaps?.length?this._lightmaps[0].lightmap:null}set lightmap(e){if(this._lightmapTextureOverride=e,e===void 0&&(e=this.context.lightmaps.tryGetLightmap(this.sourceId,this.lightmapIndex)),this._lightmaps?.length)for(const t of this._lightmaps)t.lightmap=e}get hasLightmap(){return this.lightmap!=null}allowProgressiveLoading=!0;_firstFrame=-1;registering(){this.enabled||this.setVisibility(!1)}awake(){if(this._firstFrame=this.context.time.frame,Ja&&console.log("Renderer ",this.name,this),this.clearInstancingState(),this.probeAnchor&&Ja&&this.probeAnchor.add(new _i(.2)),this._reflectionProbe=null,this.isMultiMaterialObject(this.gameObject)){for(const e of this.gameObject.children)this.context.addBeforeRenderListener(e,this.onBeforeRenderThree),e.layers.mask=this.gameObject.layers.mask;if(this.renderOrder!==void 0){let e=0;for(let t=0;t<this.gameObject.children.length;t++){const i=this.gameObject.children[t];if(!(!this.isMeshOrSkinnedMesh(i)||x.getComponent(i,Gp))){if(this.renderOrder.length<=e){console.warn("Incorrect renderOrder element count",this,this.renderOrder.length+" but expected "+this.gameObject.children.length,"Index: "+e,"ChildElement:",i);continue}i.renderOrder=this.renderOrder[e],e+=1}}}}else this.isMeshOrSkinnedMesh(this.gameObject)?(this.context.addBeforeRenderListener(this.gameObject,this.onBeforeRenderThree),this.renderOrder!==void 0&&this.renderOrder.length>0&&(this.gameObject.renderOrder=this.renderOrder[0])):this.context.addBeforeRenderListener(this.gameObject,this.onBeforeRenderThree);if(this.applyLightmapping(),dT)for(let e=0;e<this.sharedMaterials.length;e++){const t=this.sharedMaterials[e];t&&(t.wireframe=!0)}}applyLightmapping(){if(this.lightmapIndex>=0){const e=this.gameObject.type,t=this._lightmapTextureOverride!==void 0?this._lightmapTextureOverride:this.context.lightmaps.tryGetLightmap(this.sourceId,this.lightmapIndex);if(t){if(this._lightmaps||(this._lightmaps=[]),e==="Mesh"){const i=this.gameObject.material;if(i?.isMeshBasicMaterial)i&&console.warn("Lightmapping is not supported on MeshBasicMaterial",i.name);else{if(this._lightmaps.length<=0){const n=new Du(this.gameObject,this.context);this._lightmaps.push(n)}this._lightmaps[0].init(this.lightmapIndex,this.lightmapScaleOffset,t)}}else if(this.isMultiMaterialObject(this.gameObject)&&this.sharedMaterials.length>0)for(let i=0;i<this.gameObject.children.length;i++){const n=this.gameObject.children[i];if(!n.material?.isMeshBasicMaterial){let s;i>=this._lightmaps.length?(s=new Du(n,this.context),this._lightmaps.push(s)):s=this._lightmaps[i],s.init(this.lightmapIndex,this.lightmapScaleOffset,t)}}}else Ja&&console.warn("Lightmap not found",this.sourceId,this.lightmapIndex)}}_isInstancingEnabled=!1;_handles=void 0;get isInstancingActive(){return this._handles!=null&&this._handles.length>0&&this._isInstancingEnabled}get instances(){if(!this._handles||this._handles.length<=0)return null;if(this._handlesTempArray.length=0,this._handles)for(const e of this._handles)this._handlesTempArray.push(e);return this._handlesTempArray}_handlesTempArray=[];setInstancingEnabled(e){if(this._isInstancingEnabled===e)return e&&(this._handles===void 0||this._handles!=null&&this._handles.length>0);if(this._isInstancingEnabled=e,e){if(this.enableInstancing===void 0&&(this.enableInstancing=!0),this._handles===void 0){if(this._handles=la.instance.setup(this,this.gameObject,this.context,null,{rend:this,foundMeshes:0,useMatrixWorldAutoUpdate:this.useInstanceMatrixWorldAutoUpdate()}),this._handles)return x.markAsInstancedRendered(this.gameObject,!0),!0}else if(this._handles!==null){for(const t of this._handles)t.updateInstanceMatrix(!0),t.add();return x.markAsInstancedRendered(this.gameObject,!0),!0}}else{if(this._handles)for(const t of this._handles)t.remove(this.destroyed);return!0}return!1}clearInstancingState(){this._isInstancingEnabled=!1,this._handles=void 0}useInstanceMatrixWorldAutoUpdate(){return!0}start(){if(this.enableInstancing&&!Zw&&(this.setInstancingEnabled(!0),an.markDirty(this.gameObject)),this.gameObject.frustumCulled=this.allowOcclusionWhenDynamic,this.isMultiMaterialObject(this.gameObject))for(let e=0;e<this.gameObject.children.length;e++){const t=this.gameObject.children[e];t.frustumCulled=this.allowOcclusionWhenDynamic}}onEnable(){this.sharedMeshes,this.setVisibility(!0),this._isInstancingEnabled||this.enableInstancing==!0||Array.isArray(this.enableInstancing)&&this.enableInstancing.some(e=>e)?this.__internalDidAwakeAndStart&&this.setInstancingEnabled(!0):this.enabled&&this.applyStencil(),this.updateReflectionProbe()}onDisable(){this.setVisibility(!1),this._handles&&this._handles.length>0&&this.setInstancingEnabled(!1)}onDestroy(){if(this._handles=null,this.isMultiMaterialObject(this.gameObject))for(const e of this.gameObject.children)this.context.removeBeforeRenderListener(e,this.onBeforeRenderThree);else this.context.removeBeforeRenderListener(this.gameObject,this.onBeforeRenderThree)}onBeforeRender(){if(this.gameObject){if(this._probeAnchorLastFrame!==this.probeAnchor&&(this._reflectionProbe?.onUnset(this),this.updateReflectionProbe()),Ja==this.name&&this.gameObject instanceof H){this.gameObject.geometry.computeBoundingSphere();const e=$(this.gameObject.geometry.boundingSphere.center).applyMatrix4(this.gameObject.matrixWorld);F.DrawWireSphere(e,this.gameObject.geometry.boundingSphere.radius,56831)}if(this.isMultiMaterialObject(this.gameObject)&&this.gameObject.children?.length>0)for(const e of this.gameObject.children)this.applySettings(e);else this.applySettings(this.gameObject);if(this.sharedMaterials?.changed&&(this.sharedMaterials.changed=!1,this.applyLightmapping()),this._handles?.length&&this.gameObject[nc]===!0){this.gameObject[nc]=!1;for(let e=this._handles.length-1;e>=0;e--)this._handles[e].updateInstanceMatrix();this.gameObject.matrixWorldNeedsUpdate=!1}if(this._handles&&this._handles.length<=0&&x.markAsInstancedRendered(this.gameObject,!1),this._isInstancingEnabled&&this._handles)for(let e=0;e<this._handles.length;e++){const t=this._handles[e];Co(t.object,!1)}if(this.reflectionProbeUsage!==0&&this._reflectionProbe&&(this._lightmaps?.length||this._reflectionProbe.onSet(this)),this._sharedMaterials)for(const e of this._sharedMaterials)e&&"envMap"in e&&"envMapIntensity"in e&&!Dc.isUsingReflectionProbe(e)&&(e.envMap=this.context.scene.environment);else Ja&&console.warn("[Renderer] sharedMaterials not initialized yet: "+this.name)}}onBeforeRenderThree=(e,t,i,n,s,r)=>{if(s.envMapIntensity!==void 0){const a=this.hasLightmap?Math.PI:1,l=this.context.mainCameraComponent?.environmentIntensity??1;s.envMapIntensity=Math.max(0,l*this.context.sceneLighting.environmentIntensity/a)}if(this._lightmaps)for(const a of this._lightmaps)a.updateLightmapUniforms(s),a.applyLightmap()};onAfterRender(){if(this._isInstancingEnabled&&this._handles)for(let e=0;e<this._handles.length;e++){const t=this._handles[e];Co(t.object,!0)}this.reflectionProbeUsage!==0&&this._reflectionProbe&&this._reflectionProbe.onUnset(this),this.static&&this.gameObject.matrixAutoUpdate&&(this.gameObject.matrixAutoUpdate=!1)}applyStencil(){Ks.applyStencil(this)}applySettings(e){e.receiveShadow=this.receiveShadows,this.shadowCastingMode==1?e.castShadow=!0:e.castShadow=!1}_reflectionProbe=null;updateReflectionProbe(){this._reflectionProbe=null,this.reflectionProbeUsage!==0&&(this.startCoroutine(this._updateReflectionProbe(),we.LateUpdate),this._probeAnchorLastFrame=this.probeAnchor)}*_updateReflectionProbe(){const e=this.probeAnchor||this.gameObject,t=!!this.probeAnchor;this._reflectionProbe=Dc.get(e,this.context,t,this.probeAnchor)}setVisibility(e){if(!this.isMultiMaterialObject(this.gameObject))Co(this.gameObject,e);else for(const t of this.gameObject.children)this.isMeshOrSkinnedMesh(t)&&Co(t,e)}isMultiMaterialObject(e){return e.type==="Group"}isMeshOrSkinnedMesh(e){return e.type==="Mesh"||e.type==="SkinnedMesh"}};Lo([u()],Kn.prototype,"receiveShadows"),Lo([u()],Kn.prototype,"shadowCastingMode"),Lo([u()],Kn.prototype,"lightmapIndex"),Lo([u(pe)],Kn.prototype,"lightmapScaleOffset"),Lo([u()],Kn.prototype,"enableInstancing"),Lo([u()],Kn.prototype,"renderOrder"),Lo([u()],Kn.prototype,"allowOcclusionWhenDynamic"),Lo([u(O)],Kn.prototype,"probeAnchor"),Lo([u()],Kn.prototype,"reflectionProbeUsage");let Ti=Kn;class Bc extends Ti{}class Df extends Bc{_needUpdateBoundingSphere=!1;awake(){super.awake(),Kw&&console.log('SkinnedMeshRenderer for "'+this.name+'"',this),this.allowOcclusionWhenDynamic=!1;for(const e of this.sharedMeshes)e.parent?.updateWorldMatrix(!1,!0),this.markBoundsDirty()}onAfterRender(){if(super.onAfterRender(),this._needUpdateBoundingSphere){for(const e of this.sharedMeshes)if(e instanceof ss){this._needUpdateBoundingSphere=!1;try{const t=e.geometry,i=q0(e);i&&(e.geometry=i),e.computeBoundingSphere(),e.geometry=t}catch(t){console.error(`Error updating bounding sphere for ${e.name}`,t)}}}if(Kw){for(const e of this.sharedMeshes)if(e instanceof ss&&e.boundingSphere){const t=$(e.boundingSphere.center).applyMatrix4(e.matrixWorld);F.DrawWireSphere(t,e.boundingSphere.radius,"red")}}}markBoundsDirty(){this._needUpdateBoundingSphere=!0}}var pT=Object.defineProperty,ex=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&pT(e,t,n),n};const Bu=w("debuggltfexport");class Bf extends xt{sceneRoot}const Ff=class Ml extends M{binary=!0;objects=[];ext;async exportNow(e,t){Bu&&console.log("Exporting objects as glTF",this.objects),e||(e="scene"),(!this.objects||this.objects.length<=0)&&(this.objects=[this.context.scene]);const i={binary:this.binary,pivot:Ml.calculateCenter(this.objects),...t},n=await this.export(this.objects,i).catch(s=>(console.error(s),!1));return n===!1?!1:(this.binary?e.endsWith(".glb")||(e+=".glb"):e.endsWith(".gltf")||(e+=".gltf"),this.binary?Ml.saveArrayBuffer(n,e):Ml.saveJson(n,e),!0)}async export(e,t){if(!e||e.length<=0){console.warn("No objects set to export");return}const i=new K0;i.register(c=>new Gw(c)),i.register(c=>new Uw(c)),If(i,this.context),Ml.filterTopmostParent(e);const n={trs:!1,onlyVisible:!0,truncateDrawRange:!1,binary:!0,maxTextureSize:1/0,embedImages:!0,includeCustomExtensions:!0,animations:t?.animations||Ml.collectAnimations(e),...t},s=new Array,r=new O;t?.pivot&&r.position.sub(t.pivot),Bu&&console.log("EXPORT",e),e.forEach(c=>{c&&Mf(c)&&(r.children.push(c),c.matrixAutoUpdate=!1,c.matrix.copy(c.matrixWorld),x.getComponentsInChildren(c,Ti).forEach(h=>{x.isActiveInHierarchy(h.gameObject)&&h.setInstancingEnabled(!1)}),c.traverse(h=>{if(!Mf(h)){const d=h.parent;h.removeFromParent(),s.push(()=>{d&&d.add(h)})}}))});const a=new Mg(r);return t?.needleComponents&&(this.ext=new zw),this.ext&&(this.ext.registerExport(i),this.ext.context=a),new Promise((c,h)=>{Bu&&console.log("Starting glTF export.");try{i?.parse(r,d=>{l(),c(d)},d=>{l(),h(d)},n)}catch(d){console.error(d),h(d)}finally{s.forEach(d=>d()),Bu&&console.log("Finished glTF export.")}});function l(){e.forEach(c=>{c&&(c.matrixAutoUpdate=!0,x.getComponentsInChildren(c,Ti).forEach(h=>{x.isActiveInHierarchy(h.gameObject)&&h.setInstancingEnabled(!1)}))})}}static saveArrayBuffer(e,t){this.save(new Blob([e],{type:"application/octet-stream"}),t)}static saveJson(e,t){this.save("data: text/json;charset=utf-8,"+encodeURIComponent(JSON.stringify(e)),t)}static save(e,t){const i=document.createElement("a");i.style.display="none",document.body.appendChild(i),typeof e=="string"?i.href=e:i.href=URL.createObjectURL(e),i.download=t,i.click(),i.remove()}static collectAnimations(e,t){t=t||[];for(const i of e)i&&i.traverseVisible(n=>{n.animations&&n.animations.length>0&&t.push(...n.animations)});return t}static calculateCenter(e,t){const i=t||new b;return i.set(0,0,0),e.forEach(n=>{i.add(Z(n))}),i.divideScalar(e.length),i}static filterTopmostParent(e){if(!(e.length<=0))for(let t=0;t<e.length;t++){let i=e[t];if(!i){e.splice(t,1),t--;continue}for(;i.parent;){if(e.includes(i.parent)){e.splice(t,1),t--;break}i=i.parent}}}};ex([u()],Ff.prototype,"binary"),ex([u(O)],Ff.prototype,"objects");let Uf=Ff;typeof globalThis!==void 0&&!("OffscreenCanvas"in globalThis)&&(globalThis.OffscreenCanvas=class{canvas;constructor(o,e){return this.canvas=document.createElement("canvas"),this.canvas.width=o,this.canvas.height=e,this.canvas.convertToBlob=(t,i)=>new Promise(n=>{this.canvas.toBlob(n,t,i)}),this.canvas}});const mT=w("debugprogress");function tx(o){o=o||new Date;const e=o.getMonth()+1,t=o.getDate(),i=o.getHours(),n=o.getMinutes(),s=o.getSeconds(),r=(e<10?"0":"")+e,a=(t<10?"0":"")+t,l=(i<10?"0":"")+i,c=(n<10?"0":"")+n,h=(s<10?"0":"")+s;return o.getFullYear()+r+a+"-"+l+c+h}class re{static start(e,t){typeof t=="string"&&(t={parentScope:t});const i=new gT(e,t);Fc.set(e,i)}static report(e,t){const i=Fc.get(e);if(!i){console.warn("Reporting progress for non-existing scope",e);return}typeof t=="string"&&(t={message:t,autoStep:!0}),i.report(t)}static end(e){const t=Fc.get(e);t&&(t.end(),Fc.delete(e))}}const Fc=new Map;class gT{scopeLabel;parentScope;childScopes=[];parentDepth=0;lastStep=0;lastAutoStepWeight=1;lastTotalSteps=0;onProgress;showLogs=!1;selfProgress=0;totalProgress=0;selfReports=0;totalReports=0;constructor(e,t){this.parentScope=t?.parentScope?Fc.get(t.parentScope):void 0,this.parentScope&&(this.parentScope.childScopes.push(this),this.parentDepth=this.parentScope.parentDepth+1),this.scopeLabel=" ".repeat(this.parentDepth*2)+e,this.showLogs=t?.logTimings??!!mT,this.showLogs&&console.time(this.scopeLabel),this.onProgress=t?.onProgress}report(e,t=!1){if(e){if(e.totalSteps!==void 0&&(this.lastTotalSteps=e.totalSteps),e.currentStep!==void 0&&(this.lastStep=e.currentStep),e.autoStep!==void 0){if(e.currentStep===void 0){this.lastStep===void 0&&(this.lastStep=0);const n=typeof e.autoStep=="number"?e.autoStep:1;this.lastStep+=this.lastAutoStepWeight,this.lastAutoStepWeight=n,e.currentStep=this.lastStep}e.totalSteps=this.lastTotalSteps}e.progress!==void 0?this.selfProgress=e.progress:e.currentStep!==void 0&&e.totalSteps!==void 0&&(this.selfProgress=e.currentStep/e.totalSteps)}if(this.childScopes.length>0){let n=0,s=0;for(const a of this.childScopes)n+=a.selfProgress,s+=1;s>0&&(n/=s);const r=this.lastAutoStepWeight/(this.lastTotalSteps??1);this.totalProgress=this.selfProgress+n*r}else this.totalProgress=this.selfProgress;this.selfProgress=Math.min(1,this.selfProgress),this.totalProgress=Math.min(1,this.totalProgress);let i=(this.totalProgress*100).toFixed(3)+"%";this.childScopes.length>0&&(i+=" ("+(this.selfProgress*100).toFixed(3)+"% self)"),e?.message&&(i=e.message+" \u2013 "+i),this.lastStep!==void 0&&this.lastTotalSteps!==void 0&&(i="Step "+(this.lastStep+(this.lastAutoStepWeight!=1?"\u2013"+(this.lastStep+this.lastAutoStepWeight):"")+"/"+this.lastTotalSteps)+" "+i),t?this.totalReports++:(this.selfReports++,this.totalReports++),this.showLogs&&console.timeLog(this.scopeLabel,i),this.onProgress&&this.onProgress(this.totalProgress),this.parentScope&&this.parentScope.report(void 0,!0)}end(){this.report({progress:1,autoStep:!0},!0),this.showLogs&&(console.timeLog(this.scopeLabel,"Total reports: "+this.totalReports,"Self reports: "+this.selfReports),console.timeEnd(this.scopeLabel));let e=!1;for(const t of this.childScopes)if(!(t.selfProgress>=1)){e=!0;break}e&&console.warn("Progress end with child scopes that are still running",this),this.onProgress=void 0}}const De="</StageRoot/Materials";function fT(o,e,t){const i=new Map,n=g=>{const y=g.type___needle,_=i.get(y)||new Map;if(i.set(y,_),!_.has(g)){const v=`${y}${_.size?`_${_.size}`:""}`;_.set(g,v)}return _.get(g)},s=o.colorNode?Fu(o.colorNode):[],r=o.colorNode?`color3f inputs:diffuseColor.connect = ${De}/${e}/${n(s.values().next().value)}.outputs:out>`:"",a=o.roughnessNode?Fu(o.roughnessNode):[],l=o.roughnessNode?`float inputs:roughness.connect = ${De}/${e}/${n(a.values().next().value)}.outputs:out>`:"",c=o.normalNode?Fu(o.normalNode):[],h=o.normalNode?`float3 inputs:normal.connect = ${De}/${e}/${n(c.values().next().value)}.outputs:out>`:"",d=o.metalnessNode?Fu(o.metalnessNode):[],p=o.metalnessNode?`float inputs:metallic.connect = ${De}/${e}/${n(d.values().next().value)}.outputs:out>`:"",m=new Set([...s,...a,...c,...d]),f=_T(m,e,t,n);return console.debug(f),`
1027
1027
 
1028
1028
  def Material "${e}" ${o.name?`(
1029
1029
  displayName = "${o.name}"
@@ -1043,7 +1043,7 @@ Texture:`,i),this.setLightmapDebugMaterial()):Za&&console.log("Use debuglightmap
1043
1043
 
1044
1044
  ${f}
1045
1045
 
1046
- }`}function Fu(o){const e=m=>{if(m.nodeType)return m.nodeType;switch(m.type){case"TimerNode":return"float";case"TextureNode":return;case"ConvertNode":return m.convertTo;default:return}},t=m=>{const y=new Set,_=v=>{if(!(!v.isNode||y.has(v))){v.nodeType___needle||(v.nodeType___needle=e(v)),v.shaderNode?(v.type___needle="ShaderCallNodeInternal",v.shaderNodeLayoutName___needle=v.shaderNode.layout.name.slice(3)):v.type___needle=v.type,y.add(v);for(const P in v)v[P]?.isNode&&(_(v[P]),v.nodeType___needle||=v[P].nodeType___needle),Array.isArray(v[P])&&v[P].forEach(R=>{R.isNode&&(_(R),v.nodeType___needle||=R.nodeType___needle)})}};return _(m),y},i=m=>{if(m.type==="ConvertNode"){if(m.convertTo===m.node.nodeType___needle)return!0;if(m.node.type==="ConstNode"){if(m.convertTo==="vec4"&&m.node.value.isVector4||m.convertTo==="vec3"&&m.node.value.isVector3||m.convertTo==="vec2"&&m.node.value.isVector2||m.convertTo==="color"&&m.node.value.isColor||m.convertTo==="float"&&typeof m.node.value=="number")return!0}else if(m.node.type=="SplitNode"&&m.convertTo=="float"&&m.node.components.length===1)return!0}return!1},n=m=>{for(;s(m);)!m.node&&m.shaderNode?m=m.inputNodes[0]:m=m.node??m.aNode??m.bNode??m.cNode;return m},s=m=>{const y=["UniformNode","UniformGroupNode","ShaderNodeInternal"];return!m||i(m)||y.includes(m.type___needle)||m.type___needle===void 0},r=(m,y)=>{for(const _ of y)for(const v in _){if(_[v]?.isNode&&_[v]===m)return{parent:_,label:v};if(Array.isArray(_[v])&&_[v].find(P=>P.isNode&&P===m))return{parent:_,label:v}}return null},a=(m,y)=>{if(m.shaderNode)m.inputNodes[0]=n(m.inputNodes[0]);else if(Array.isArray(m.nodes))for(let _=0;_<m.nodes.length;_++)m.nodes[_]&&s(m.nodes[_])&&(m.nodes[_]=n(m.nodes[_]));else y.forEach(_=>{m[_]&&s(m[_])&&(m[_]=n(m[_]))})},l=m=>{m.type==="MathNode"&&m.method==="mix"&&(m.cNode.nodeType___needle="float",m.cNode.type==="ConvertNode"&&(m.cNode.convertTo="float"))},c=(m,y)=>{y.label==="cNode"&&y.parent.type==="MathNode"&&y.parent.method==="mix"||(y.parent.type==="JoinNode"?m.nodeType___needle="float":m.nodeType___needle=y.parent.nodeType___needle)},h=m=>m?.type==="ConvertNode"&&m.nodeType___needle==="color"&&m.node.nodeType___needle==="vec4",d=(m,y)=>{m.convertTo="vec3",m.nodeType___needle="vec3";const _={type:"ConvertNode",convertTo:"color",node:m,isNode:!0,nodeType___needle:"color",type___needle:"ConvertNode"},v=r(m,y);return v?.parent&&(v.parent[v.label]=_),_},p=m=>m?.type==="ConvertNode"&&m.node.type==="TextureNode"&&m.nodeType___needle!==m.node.nodeType___needle,g=m=>{const y=new Set;for(let _ of m)if(!s(_)){if(l(_),_.type=="SplitNode"){const v=r(_,m);if(_.components.length===1)_.nodeType___needle="float";else if(v)_.nodeType___needle=v.parent.nodeType___needle;else throw new Error("SplitNode without parent found, this should not happen")}if(a(_,["node","aNode","bNode","cNode"]),_.type=="ConstNode"&&_.nodeType==null&&c(_,r(_,m)),h(_)&&y.add(d(_,m)),p(_)){_.node.nodeType___needle=_.convertTo;const v=r(_,m);v?.parent&&(v.parent[v.label]=_.node),_=_.node}y.add(_)}return y},f=t(o);return g(f)}function yT(o,e){switch(e){case"float4":return o.isVector4?`(${o.x}, ${o.y}, ${o.z}, ${o.w})`:`(${o}, ${o}, ${o}, ${o})`;case"float3":return o.isVector3?`(${o.x}, ${o.y}, ${o.z})`:`(${o}, ${o}, ${o})`;case"float2":return o.isVector2?`(${o.x}, ${o.y})`:`(${o}, ${o})`;case"color3f":return o.isColor?`(${o.r}, ${o.g}, ${o.b})`:`(${o}, ${o}, ${o})`;default:return o.isVector4||o.isVector3||o.isVector2?`${o.x}`:o.isColor?`${o.r}`:`${o}`}}function bT(o,e,t,i){const n=" ",s=g=>({float:"float",vec2:"vector2",vec3:"vector3",vec4:"vector4",color:"color3"})[g]||"float",r=g=>({float:"float",vec2:"float2",vec3:"float3",vec4:"float4",color:"color3f"})[g]||"float",a=o.type___needle,l=o.nodeType___needle,c=s(l);let h=r(l),d="";const p=new Array;switch(a){case"UniformGroupNode":case"UniformNode":return"";case"TimerNode":d="time_float";break;case"ConstNode":d="constant_"+c,p.push(`${h} inputs:value = ${yT(o.value,h)}`);break;case"JoinNode":d="combine"+o.nodes.length+"_"+c;let g=1;for(const v of o.nodes)p.push(`float inputs:in${g++}.connect = ${De}/${e}/${t(v)}.outputs:out>`);break;case"ConvertNode":d="convert_"+s(o.node.nodeType___needle)+"_"+c,o.node&&p.push(`${r(o.node.nodeType___needle)} inputs:in.connect = ${De}/${e}/${t(o.node)}.outputs:out>`);break;case"MathNode":d=o.method+"_"+c,o.aNode&&!o.bNode&&p.push(`${r(o.aNode.nodeType___needle)} inputs:in.connect = ${De}/${e}/${t(o.aNode)}.outputs:out>`),o.aNode&&o.bNode&&!o.cNode&&(p.push(`${r(o.aNode.nodeType___needle)} inputs:in1.connect = ${De}/${e}/${t(o.aNode)}.outputs:out>`),p.push(`${r(o.bNode.nodeType___needle)} inputs:in2.connect = ${De}/${e}/${t(o.bNode)}.outputs:out>`)),o.aNode&&o.bNode&&o.cNode&&o.method=="clamp"&&(p.push(`${r(o.aNode.nodeType___needle)} inputs:in.connect = ${De}/${e}/${t(o.aNode)}.outputs:out>`),p.push(`${r(o.bNode.nodeType___needle)} inputs:low.connect = ${De}/${e}/${t(o.bNode)}.outputs:out>`),p.push(`${r(o.cNode.nodeType___needle)} inputs:high.connect = ${De}/${e}/${t(o.cNode)}.outputs:out>`)),o.aNode&&o.bNode&&o.cNode&&o.method=="mix"&&(p.push(`${r(o.aNode.nodeType___needle)} inputs:fg.connect = ${De}/${e}/${t(o.bNode)}.outputs:out>`),p.push(`${r(o.bNode.nodeType___needle)} inputs:bg.connect = ${De}/${e}/${t(o.aNode)}.outputs:out>`),p.push(`float inputs:mix.connect = ${De}/${e}/${t(o.cNode)}.outputs:out>`));break;case"OperatorNode":let f="";switch(o.op){case"*":f="multiply";break;case"/":f="divide";break;case"+":f="add";break;case"-":f="subtract";break}if(d=f+"_"+c,o.aNode&&!o.bNode&&p.push(`${r(o.aNode.nodeType___needle)} inputs:in.connect = ${De}/${e}/${t(o.aNode)}.outputs:out>`),o.aNode&&o.bNode){const v=r(o.aNode.nodeType___needle),P=r(o.bNode.nodeType___needle);(v==="color3f"&&P==="float"||P==="float"&&P==="color3f")&&(d=f+"_color3FA"),p.push(`${v} inputs:in1.connect = ${De}/${e}/${t(o.aNode)}.outputs:out>`),p.push(`${P} inputs:in2.connect = ${De}/${e}/${t(o.bNode)}.outputs:out>`)}break;case"TextureNode":o.uvNode?(d="tiledimage_"+c,p.push(`float2 inputs:texcoord.connect = ${De}/${e}/${t(o.uvNode)}.outputs:out>`)):d="image_"+c;const m=o._value,y=qf.includes(m.format),_=vT(m);p.push(`asset inputs:file = @textures/${_}.${y?"png":"jpg"}@`),i[_]={texture:m,scale:void 0};break;case"NormalMapNode":h="float3",d="normalmap",p.push(`${h} inputs:in.connect = ${De}/${e}/${t(o.node)}.outputs:out>`);break;case"AttributeNode":d="geompropvalue_"+c,p.push('string inputs:geomprop = "st"');break;case"ShaderCallNodeInternal":d=o.shaderNodeLayoutName___needle+"_"+c,p.push(`${h} inputs:in.connect = ${De}/${e}/${t(o.inputNodes[0])}.outputs:out>`);break;case"SplitNode":d="swizzle_"+s(o.node.nodeType___needle)+"_"+c,p.push(`${r(o.node.nodeType___needle)} inputs:in.connect = ${De}/${e}/${t(o.node)}.outputs:out>`),p.push(`string inputs:channels = "${o.components}"`);break}return`
1046
+ }`}function Fu(o){const e=g=>{if(g.nodeType)return g.nodeType;switch(g.type){case"TimerNode":return"float";case"TextureNode":return;case"ConvertNode":return g.convertTo;default:return}},t=g=>{const y=new Set,_=v=>{if(!(!v.isNode||y.has(v))){v.nodeType___needle||(v.nodeType___needle=e(v)),v.shaderNode?(v.type___needle="ShaderCallNodeInternal",v.shaderNodeLayoutName___needle=v.shaderNode.layout.name.slice(3)):v.type___needle=v.type,y.add(v);for(const P in v)v[P]?.isNode&&(_(v[P]),v.nodeType___needle||=v[P].nodeType___needle),Array.isArray(v[P])&&v[P].forEach(R=>{R.isNode&&(_(R),v.nodeType___needle||=R.nodeType___needle)})}};return _(g),y},i=g=>{if(g.type==="ConvertNode"){if(g.convertTo===g.node.nodeType___needle)return!0;if(g.node.type==="ConstNode"){if(g.convertTo==="vec4"&&g.node.value.isVector4||g.convertTo==="vec3"&&g.node.value.isVector3||g.convertTo==="vec2"&&g.node.value.isVector2||g.convertTo==="color"&&g.node.value.isColor||g.convertTo==="float"&&typeof g.node.value=="number")return!0}else if(g.node.type=="SplitNode"&&g.convertTo=="float"&&g.node.components.length===1)return!0}return!1},n=g=>{for(;s(g);)!g.node&&g.shaderNode?g=g.inputNodes[0]:g=g.node??g.aNode??g.bNode??g.cNode;return g},s=g=>{const y=["UniformNode","UniformGroupNode","ShaderNodeInternal"];return!g||i(g)||y.includes(g.type___needle)||g.type___needle===void 0},r=(g,y)=>{for(const _ of y)for(const v in _){if(_[v]?.isNode&&_[v]===g)return{parent:_,label:v};if(Array.isArray(_[v])&&_[v].find(P=>P.isNode&&P===g))return{parent:_,label:v}}return null},a=(g,y)=>{if(g.shaderNode)g.inputNodes[0]=n(g.inputNodes[0]);else if(Array.isArray(g.nodes))for(let _=0;_<g.nodes.length;_++)g.nodes[_]&&s(g.nodes[_])&&(g.nodes[_]=n(g.nodes[_]));else y.forEach(_=>{g[_]&&s(g[_])&&(g[_]=n(g[_]))})},l=g=>{g.type==="MathNode"&&g.method==="mix"&&(g.cNode.nodeType___needle="float",g.cNode.type==="ConvertNode"&&(g.cNode.convertTo="float"))},c=(g,y)=>{y.label==="cNode"&&y.parent.type==="MathNode"&&y.parent.method==="mix"||(y.parent.type==="JoinNode"?g.nodeType___needle="float":g.nodeType___needle=y.parent.nodeType___needle)},h=g=>g?.type==="ConvertNode"&&g.nodeType___needle==="color"&&g.node.nodeType___needle==="vec4",d=(g,y)=>{g.convertTo="vec3",g.nodeType___needle="vec3";const _={type:"ConvertNode",convertTo:"color",node:g,isNode:!0,nodeType___needle:"color",type___needle:"ConvertNode"},v=r(g,y);return v?.parent&&(v.parent[v.label]=_),_},p=g=>g?.type==="ConvertNode"&&g.node.type==="TextureNode"&&g.nodeType___needle!==g.node.nodeType___needle,m=g=>{const y=new Set;for(let _ of g)if(!s(_)){if(l(_),_.type=="SplitNode"){const v=r(_,g);if(_.components.length===1)_.nodeType___needle="float";else if(v)_.nodeType___needle=v.parent.nodeType___needle;else throw new Error("SplitNode without parent found, this should not happen")}if(a(_,["node","aNode","bNode","cNode"]),_.type=="ConstNode"&&_.nodeType==null&&c(_,r(_,g)),h(_)&&y.add(d(_,g)),p(_)){_.node.nodeType___needle=_.convertTo;const v=r(_,g);v?.parent&&(v.parent[v.label]=_.node),_=_.node}y.add(_)}return y},f=t(o);return m(f)}function yT(o,e){switch(e){case"float4":return o.isVector4?`(${o.x}, ${o.y}, ${o.z}, ${o.w})`:`(${o}, ${o}, ${o}, ${o})`;case"float3":return o.isVector3?`(${o.x}, ${o.y}, ${o.z})`:`(${o}, ${o}, ${o})`;case"float2":return o.isVector2?`(${o.x}, ${o.y})`:`(${o}, ${o})`;case"color3f":return o.isColor?`(${o.r}, ${o.g}, ${o.b})`:`(${o}, ${o}, ${o})`;default:return o.isVector4||o.isVector3||o.isVector2?`${o.x}`:o.isColor?`${o.r}`:`${o}`}}function bT(o,e,t,i){const n=" ",s=m=>({float:"float",vec2:"vector2",vec3:"vector3",vec4:"vector4",color:"color3"})[m]||"float",r=m=>({float:"float",vec2:"float2",vec3:"float3",vec4:"float4",color:"color3f"})[m]||"float",a=o.type___needle,l=o.nodeType___needle,c=s(l);let h=r(l),d="";const p=new Array;switch(a){case"UniformGroupNode":case"UniformNode":return"";case"TimerNode":d="time_float";break;case"ConstNode":d="constant_"+c,p.push(`${h} inputs:value = ${yT(o.value,h)}`);break;case"JoinNode":d="combine"+o.nodes.length+"_"+c;let m=1;for(const v of o.nodes)p.push(`float inputs:in${m++}.connect = ${De}/${e}/${t(v)}.outputs:out>`);break;case"ConvertNode":d="convert_"+s(o.node.nodeType___needle)+"_"+c,o.node&&p.push(`${r(o.node.nodeType___needle)} inputs:in.connect = ${De}/${e}/${t(o.node)}.outputs:out>`);break;case"MathNode":d=o.method+"_"+c,o.aNode&&!o.bNode&&p.push(`${r(o.aNode.nodeType___needle)} inputs:in.connect = ${De}/${e}/${t(o.aNode)}.outputs:out>`),o.aNode&&o.bNode&&!o.cNode&&(p.push(`${r(o.aNode.nodeType___needle)} inputs:in1.connect = ${De}/${e}/${t(o.aNode)}.outputs:out>`),p.push(`${r(o.bNode.nodeType___needle)} inputs:in2.connect = ${De}/${e}/${t(o.bNode)}.outputs:out>`)),o.aNode&&o.bNode&&o.cNode&&o.method=="clamp"&&(p.push(`${r(o.aNode.nodeType___needle)} inputs:in.connect = ${De}/${e}/${t(o.aNode)}.outputs:out>`),p.push(`${r(o.bNode.nodeType___needle)} inputs:low.connect = ${De}/${e}/${t(o.bNode)}.outputs:out>`),p.push(`${r(o.cNode.nodeType___needle)} inputs:high.connect = ${De}/${e}/${t(o.cNode)}.outputs:out>`)),o.aNode&&o.bNode&&o.cNode&&o.method=="mix"&&(p.push(`${r(o.aNode.nodeType___needle)} inputs:fg.connect = ${De}/${e}/${t(o.bNode)}.outputs:out>`),p.push(`${r(o.bNode.nodeType___needle)} inputs:bg.connect = ${De}/${e}/${t(o.aNode)}.outputs:out>`),p.push(`float inputs:mix.connect = ${De}/${e}/${t(o.cNode)}.outputs:out>`));break;case"OperatorNode":let f="";switch(o.op){case"*":f="multiply";break;case"/":f="divide";break;case"+":f="add";break;case"-":f="subtract";break}if(d=f+"_"+c,o.aNode&&!o.bNode&&p.push(`${r(o.aNode.nodeType___needle)} inputs:in.connect = ${De}/${e}/${t(o.aNode)}.outputs:out>`),o.aNode&&o.bNode){const v=r(o.aNode.nodeType___needle),P=r(o.bNode.nodeType___needle);(v==="color3f"&&P==="float"||P==="float"&&P==="color3f")&&(d=f+"_color3FA"),p.push(`${v} inputs:in1.connect = ${De}/${e}/${t(o.aNode)}.outputs:out>`),p.push(`${P} inputs:in2.connect = ${De}/${e}/${t(o.bNode)}.outputs:out>`)}break;case"TextureNode":o.uvNode?(d="tiledimage_"+c,p.push(`float2 inputs:texcoord.connect = ${De}/${e}/${t(o.uvNode)}.outputs:out>`)):d="image_"+c;const g=o._value,y=qf.includes(g.format),_=vT(g);p.push(`asset inputs:file = @textures/${_}.${y?"png":"jpg"}@`),i[_]={texture:g,scale:void 0};break;case"NormalMapNode":h="float3",d="normalmap",p.push(`${h} inputs:in.connect = ${De}/${e}/${t(o.node)}.outputs:out>`);break;case"AttributeNode":d="geompropvalue_"+c,p.push('string inputs:geomprop = "st"');break;case"ShaderCallNodeInternal":d=o.shaderNodeLayoutName___needle+"_"+c,p.push(`${h} inputs:in.connect = ${De}/${e}/${t(o.inputNodes[0])}.outputs:out>`);break;case"SplitNode":d="swizzle_"+s(o.node.nodeType___needle)+"_"+c,p.push(`${r(o.node.nodeType___needle)} inputs:in.connect = ${De}/${e}/${t(o.node)}.outputs:out>`),p.push(`string inputs:channels = "${o.components}"`);break}return`
1047
1047
  ${n}def Shader "${t(o)}"
1048
1048
  ${n}{
1049
1049
  ${n}uniform token info:id = "ND_${d}"
@@ -1074,8 +1074,8 @@ Texture:`,i),this.setLightmapDebugMaterial()):Za&&console.log("Use debuglightmap
1074
1074
  ${c}
1075
1075
  )
1076
1076
  `}}const el=`
1077
- `,Xt="</StageRoot/Materials";class sx{str;indent;constructor(){this.str="",this.indent=0}clear(){this.str="",this.indent=0}beginBlock(e=void 0,t="{",i=!0){e!==void 0?(e=this.applyIndent(e),this.str+=e,i?(this.str+=el,this.str+=this.applyIndent(t)):this.str+=" "+t):this.str+=this.applyIndent(t),this.str+=el,this.indent+=1}closeBlock(e="}"){this.indent-=1,this.str+=this.applyIndent(e)+el}beginArray(e){e=this.applyIndent(e+" = ["),this.str+=e,this.str+=el,this.indent+=1}closeArray(){this.indent-=1,this.str+=this.applyIndent("]")+el}appendLine(e=""){e=this.applyIndent(e),this.str+=e,this.str+=el}toString(){return this.str}applyIndent(e){let t="";for(let i=0;i<this.indent;i++)t+=" ";return t+e}}class CT{root;exporter;extensions=[];quickLookCompatible;exportInvisible;materials;textures;files;document;output;animations;constructor(e,t,i){this.root=e,this.exporter=t,this.quickLookCompatible=i.quickLookCompatible,this.exportInvisible=i.exportInvisible,i.extensions&&(this.extensions=i.extensions),this.materials=new Map,this.textures={},this.files={},this.document=new zf,this.output="",this.animations=[]}}class Nf{ar={anchoring:{type:"plane"},planeAnchoring:{alignment:"horizontal"}};quickLookCompatible=!1;extensions=[];maxTextureSize=4096;exportInvisible=!1}let rx=class{debug;pruneUnusedNodes;sceneAnchoringOptions=new Nf;extensions=[];keepObject;beforeWritingDocument;constructor(){this.debug=!1,this.pruneUnusedNodes=!0}async parse(o,e=new Nf){e=Object.assign(new Nf,e),this.sceneAnchoringOptions=e;const t=new CT(o,this,e);this.extensions=t.extensions;const i=t.files,n="model.usda";i[n]=null;const s=t.materials,r=t.textures;re.report("export-usdz","Invoking onBeforeBuildDocument"),await Uu(t,"onBeforeBuildDocument"),re.report("export-usdz","Done onBeforeBuildDocument"),re.report("export-usdz","Reparent bones to common ancestor");const a=[],l=new Set;o?.traverse(m=>{if(!(!e.exportInvisible&&!m.visible)&&m instanceof ss){const y=m.skeleton.bones,_=nx(y);if(_){const v={object:m,originalParent:m.parent,newParent:_};a.push(v),l.add(v.object.uuid),v.newParent&&l.add(v.newParent.uuid),v.originalParent&&l.add(v.originalParent.uuid)}}});for(const m of a){const{object:y,originalParent:_,newParent:v}=m;v.add(y)}re.report("export-usdz","Traversing hierarchy"),o&&ax(o,t.document,t,this.keepObject),re.report("export-usdz","Invoking onAfterBuildDocument"),await Uu(t,"onAfterBuildDocument");const c=t.extensions.find(m=>m.extensionName==="Behaviour")?.getAllTargetUuids()??new Set;if(this.pruneUnusedNodes){const m={allBehaviorTargets:c,debug:!1,boneReparentings:l,quickLookCompatible:t.quickLookCompatible};this.debug&&lx(t.document,"Hierarchy BEFORE pruning",m),cx(t.document,m),this.debug&&lx(t.document,"Hierarchy AFTER pruning")}else this.debug&&console.log("Pruning of empty nodes is disabled. This may result in a larger USDZ file.");re.report("export-usdz",{message:"Parsing document",autoStep:10}),await PT(t,()=>(re.report("export-usdz","Building materials"),IT(s,r,e.quickLookCompatible))),re.report("export-usdz","Invoking onAfterSerialize"),await Uu(t,"onAfterSerialize");for(const m of a){const{object:y,originalParent:_,newParent:v}=m;_&&_.add(y)}t.exporter?.beforeWritingDocument?.();const h=t.document.buildHeader(t)+`
1078
- `+t.output;this.debug&&console.log(h),i[n]=Z0(h),t.output="",re.report("export-usdz",{message:"Exporting textures",autoStep:10}),re.start("export-usdz-textures",{parentScope:"export-usdz",logTimings:!1});const d=new er({antialias:!1,alpha:!0,premultipliedAlpha:!1,preserveDrawingBuffer:!0}),p=Object.keys(r).length;re.report("export-usdz-textures",{totalSteps:p*3,currentStep:0});const g=async m=>{const y=r[m],_=y.texture,v=qf.includes(_.format);let P={imageData:_.image};re.report("export-usdz-textures",{message:"read back texture",autoStep:!0});const R=y.scale!==void 0&&y.scale.x!==1&&y.scale.y!==1&&y.scale.z!==1&&y.scale.w!==1;(_.isCompressedTexture||_.isRenderTargetTexture||R)&&(P=await dx(_,e.maxTextureSize,d,y.scale)),re.report("export-usdz-textures",{message:"convert texture to canvas",autoStep:!0});const k=await kT(P.imageBitmap||P.imageData,e.maxTextureSize).catch(A=>{console.error("Error converting texture to canvas",_,A)});if(k){re.report("export-usdz-textures",{message:"convert canvas to blob",autoStep:!0});const A=await k.convertToBlob({type:v?"image/png":"image/jpeg",quality:.95});i[`textures/${m}.${v?"png":"jpg"}`]=new Uint8Array(await A.arrayBuffer())}else console.warn("Can`t export texture: ",_)};for(const m in r)await g(m);d.dispose(),re.end("export-usdz-textures");let f=0;for(const m in i){const y=i[m],_=34+m.length;f+=_;const v=f&63;if(v!==4){const P=64-v,R=new Uint8Array(P);i[m]=[y,{extra:{12345:R}}]}f=y.length}return re.report("export-usdz","zip archive"),CC(i,{level:0})}};function ax(o,e,t,i){if(!t.exportInvisible&&!o.visible)return;let n,s,r;const a={position:o.position,quaternion:o.quaternion,scale:o.scale};if(o.position.x===0&&o.position.y===0&&o.position.z===0&&(a.position=null),o.quaternion.x===0&&o.quaternion.y===0&&o.quaternion.z===0&&o.quaternion.w===1&&(a.quaternion=null),o.scale.x===1&&o.scale.y===1&&o.scale.z===1&&(a.scale=null),(o instanceof H||o instanceof ss)&&(s=o.geometry,r=o.material),i&&!i(o)&&(s=void 0,r=void 0),(o instanceof H||o instanceof ss)&&r&&typeof r=="object"&&(r instanceof ut||r instanceof xe||r.isMeshPhysicalNodeMaterial||r instanceof ve&&r.type==="MeshLineMaterial")){const l=Wu(o),c=o instanceof ss?o:null;n=new it(o.uuid,l,a,s,r,void 0,c,o.animations)}else if(o instanceof de||o instanceof nd){const l=Wu(o);n=new it(o.uuid,l,a,void 0,void 0,o)}else{const l=Wu(o);n=new it(o.uuid,l,a,void 0,void 0,void 0,void 0,o.animations)}if(n){if(n.displayName=o.userData?.name||o.name,n.visibility=o.visible?void 0:"invisible",e&&e.add(n),e=n,t.extensions)for(const l of t.extensions)l.onExportObject&&l.onExportObject.call(l,o,n,t)}else{const l=Wu(o),c=new it(o.uuid,l,{position:o.position,quaternion:o.quaternion,scale:o.scale});e&&e.add(c),e=c}for(const l of o.children)ax(l,e,t,i)}function lx(o,e,...t){const i={};let n=0;function s(r,a){n++;let l=r.displayName||r.name;l+=" ("+r.uuid+")",(r.geometry||r.material||r.camera||r.skinnedMesh)&&(l+=" ("+(r.geometry?"geo, ":"")+(r.material?"mat, ":"")+(r.camera?"cam, ":"")+(r.skinnedMesh?"skin, ":"")+")"),a[l]={};const c={object:r};r.material&&(c.mat=!0),r.geometry&&(c.geo=!0),r.camera&&(c.cam=!0),r.skinnedMesh&&(c.skin=!0),a[l]._self=c;for(const h of r.children)h&&s(h,a[l])}s(o,i),console.log(e+" ("+n+" nodes)",i,...t)}function cx(o,e){let t=!0;const i=new Array,n=new Array;if(o.children.length===0)t=!0;else{const c=[...o.children];for(const h of c)if(h){const d=cx(h,e);e.debug&&(d?i.push(h):n.push(h)),t=t&&d}}const s=e.allBehaviorTargets.has(o.uuid),r=o.geometry||o.material||o.camera&&!e.quickLookCompatible||o.skinnedMesh||!1,a=e.boneReparentings.has(o.uuid),l=t&&!s&&!r&&!a;return l?(e.debug&&console.log("Pruned object:",(o.displayName||o.name)+" ("+o.uuid+")",{isVisible:r,isBehaviorSourceOrTarget:s,allChildsWerePruned:t,isBoneReparenting:a,object:o,prunedChilds:i,keptChilds:n}),o.parent?.remove(o)):e.debug&&console.log("Kept object:",(o.displayName||o.name)+" ("+o.uuid+")",{isVisible:r,isBehaviorSourceOrTarget:s,allChildsWerePruned:t,isBoneReparenting:a,object:o,prunedChilds:i,keptChilds:n}),l}async function PT(o,e){re.start("export-usdz-resources","export-usdz");const t=[];for(const l of o.document.children)hx(l,o,t);const i=t.length;for(let l=0;l<i;l++)re.report("export-usdz-resources",{totalSteps:i,currentStep:l}),await new Promise((c,h)=>{t[l](),c()});re.end("export-usdz-resources");const n=new sx,s=o.exporter.sceneAnchoringOptions.ar;n.beginBlock(`def Xform "${o.document.name}"`),n.beginBlock(`def Scope "Scenes" (
1077
+ `,Xt="</StageRoot/Materials";class sx{str;indent;constructor(){this.str="",this.indent=0}clear(){this.str="",this.indent=0}beginBlock(e=void 0,t="{",i=!0){e!==void 0?(e=this.applyIndent(e),this.str+=e,i?(this.str+=el,this.str+=this.applyIndent(t)):this.str+=" "+t):this.str+=this.applyIndent(t),this.str+=el,this.indent+=1}closeBlock(e="}"){this.indent-=1,this.str+=this.applyIndent(e)+el}beginArray(e){e=this.applyIndent(e+" = ["),this.str+=e,this.str+=el,this.indent+=1}closeArray(){this.indent-=1,this.str+=this.applyIndent("]")+el}appendLine(e=""){e=this.applyIndent(e),this.str+=e,this.str+=el}toString(){return this.str}applyIndent(e){let t="";for(let i=0;i<this.indent;i++)t+=" ";return t+e}}class CT{root;exporter;extensions=[];quickLookCompatible;exportInvisible;materials;textures;files;document;output;animations;constructor(e,t,i){this.root=e,this.exporter=t,this.quickLookCompatible=i.quickLookCompatible,this.exportInvisible=i.exportInvisible,i.extensions&&(this.extensions=i.extensions),this.materials=new Map,this.textures={},this.files={},this.document=new zf,this.output="",this.animations=[]}}class Nf{ar={anchoring:{type:"plane"},planeAnchoring:{alignment:"horizontal"}};quickLookCompatible=!1;extensions=[];maxTextureSize=4096;exportInvisible=!1}let rx=class{debug;pruneUnusedNodes;sceneAnchoringOptions=new Nf;extensions=[];keepObject;beforeWritingDocument;constructor(){this.debug=!1,this.pruneUnusedNodes=!0}async parse(o,e=new Nf){e=Object.assign(new Nf,e),this.sceneAnchoringOptions=e;const t=new CT(o,this,e);this.extensions=t.extensions;const i=t.files,n="model.usda";i[n]=null;const s=t.materials,r=t.textures;re.report("export-usdz","Invoking onBeforeBuildDocument"),await Uu(t,"onBeforeBuildDocument"),re.report("export-usdz","Done onBeforeBuildDocument"),re.report("export-usdz","Reparent bones to common ancestor");const a=[],l=new Set;o?.traverse(g=>{if(!(!e.exportInvisible&&!g.visible)&&g instanceof ss){const y=g.skeleton.bones,_=nx(y);if(_){const v={object:g,originalParent:g.parent,newParent:_};a.push(v),l.add(v.object.uuid),v.newParent&&l.add(v.newParent.uuid),v.originalParent&&l.add(v.originalParent.uuid)}}});for(const g of a){const{object:y,originalParent:_,newParent:v}=g;v.add(y)}re.report("export-usdz","Traversing hierarchy"),o&&ax(o,t.document,t,this.keepObject),re.report("export-usdz","Invoking onAfterBuildDocument"),await Uu(t,"onAfterBuildDocument");const c=t.extensions.find(g=>g.extensionName==="Behaviour")?.getAllTargetUuids()??new Set;if(this.pruneUnusedNodes){const g={allBehaviorTargets:c,debug:!1,boneReparentings:l,quickLookCompatible:t.quickLookCompatible};this.debug&&lx(t.document,"Hierarchy BEFORE pruning",g),cx(t.document,g),this.debug&&lx(t.document,"Hierarchy AFTER pruning")}else this.debug&&console.log("Pruning of empty nodes is disabled. This may result in a larger USDZ file.");re.report("export-usdz",{message:"Parsing document",autoStep:10}),await PT(t,()=>(re.report("export-usdz","Building materials"),IT(s,r,e.quickLookCompatible))),re.report("export-usdz","Invoking onAfterSerialize"),await Uu(t,"onAfterSerialize");for(const g of a){const{object:y,originalParent:_,newParent:v}=g;_&&_.add(y)}t.exporter?.beforeWritingDocument?.();const h=t.document.buildHeader(t)+`
1078
+ `+t.output;this.debug&&console.log(h),i[n]=Z0(h),t.output="",re.report("export-usdz",{message:"Exporting textures",autoStep:10}),re.start("export-usdz-textures",{parentScope:"export-usdz",logTimings:!1});const d=new er({antialias:!1,alpha:!0,premultipliedAlpha:!1,preserveDrawingBuffer:!0}),p=Object.keys(r).length;re.report("export-usdz-textures",{totalSteps:p*3,currentStep:0});const m=async g=>{const y=r[g],_=y.texture,v=qf.includes(_.format);let P={imageData:_.image};re.report("export-usdz-textures",{message:"read back texture",autoStep:!0});const R=y.scale!==void 0&&y.scale.x!==1&&y.scale.y!==1&&y.scale.z!==1&&y.scale.w!==1;(_.isCompressedTexture||_.isRenderTargetTexture||R)&&(P=await dx(_,e.maxTextureSize,d,y.scale)),re.report("export-usdz-textures",{message:"convert texture to canvas",autoStep:!0});const k=await kT(P.imageBitmap||P.imageData,e.maxTextureSize).catch(A=>{console.error("Error converting texture to canvas",_,A)});if(k){re.report("export-usdz-textures",{message:"convert canvas to blob",autoStep:!0});const A=await k.convertToBlob({type:v?"image/png":"image/jpeg",quality:.95});i[`textures/${g}.${v?"png":"jpg"}`]=new Uint8Array(await A.arrayBuffer())}else console.warn("Can`t export texture: ",_)};for(const g in r)await m(g);d.dispose(),re.end("export-usdz-textures");let f=0;for(const g in i){const y=i[g],_=34+g.length;f+=_;const v=f&63;if(v!==4){const P=64-v,R=new Uint8Array(P);i[g]=[y,{extra:{12345:R}}]}f=y.length}return re.report("export-usdz","zip archive"),CC(i,{level:0})}};function ax(o,e,t,i){if(!t.exportInvisible&&!o.visible)return;let n,s,r;const a={position:o.position,quaternion:o.quaternion,scale:o.scale};if(o.position.x===0&&o.position.y===0&&o.position.z===0&&(a.position=null),o.quaternion.x===0&&o.quaternion.y===0&&o.quaternion.z===0&&o.quaternion.w===1&&(a.quaternion=null),o.scale.x===1&&o.scale.y===1&&o.scale.z===1&&(a.scale=null),(o instanceof H||o instanceof ss)&&(s=o.geometry,r=o.material),i&&!i(o)&&(s=void 0,r=void 0),(o instanceof H||o instanceof ss)&&r&&typeof r=="object"&&(r instanceof ut||r instanceof xe||r.isMeshPhysicalNodeMaterial||r instanceof ve&&r.type==="MeshLineMaterial")){const l=Wu(o),c=o instanceof ss?o:null;n=new it(o.uuid,l,a,s,r,void 0,c,o.animations)}else if(o instanceof de||o instanceof nd){const l=Wu(o);n=new it(o.uuid,l,a,void 0,void 0,o)}else{const l=Wu(o);n=new it(o.uuid,l,a,void 0,void 0,void 0,void 0,o.animations)}if(n){if(n.displayName=o.userData?.name||o.name,n.visibility=o.visible?void 0:"invisible",e&&e.add(n),e=n,t.extensions)for(const l of t.extensions)l.onExportObject&&l.onExportObject.call(l,o,n,t)}else{const l=Wu(o),c=new it(o.uuid,l,{position:o.position,quaternion:o.quaternion,scale:o.scale});e&&e.add(c),e=c}for(const l of o.children)ax(l,e,t,i)}function lx(o,e,...t){const i={};let n=0;function s(r,a){n++;let l=r.displayName||r.name;l+=" ("+r.uuid+")",(r.geometry||r.material||r.camera||r.skinnedMesh)&&(l+=" ("+(r.geometry?"geo, ":"")+(r.material?"mat, ":"")+(r.camera?"cam, ":"")+(r.skinnedMesh?"skin, ":"")+")"),a[l]={};const c={object:r};r.material&&(c.mat=!0),r.geometry&&(c.geo=!0),r.camera&&(c.cam=!0),r.skinnedMesh&&(c.skin=!0),a[l]._self=c;for(const h of r.children)h&&s(h,a[l])}s(o,i),console.log(e+" ("+n+" nodes)",i,...t)}function cx(o,e){let t=!0;const i=new Array,n=new Array;if(o.children.length===0)t=!0;else{const c=[...o.children];for(const h of c)if(h){const d=cx(h,e);e.debug&&(d?i.push(h):n.push(h)),t=t&&d}}const s=e.allBehaviorTargets.has(o.uuid),r=o.geometry||o.material||o.camera&&!e.quickLookCompatible||o.skinnedMesh||!1,a=e.boneReparentings.has(o.uuid),l=t&&!s&&!r&&!a;return l?(e.debug&&console.log("Pruned object:",(o.displayName||o.name)+" ("+o.uuid+")",{isVisible:r,isBehaviorSourceOrTarget:s,allChildsWerePruned:t,isBoneReparenting:a,object:o,prunedChilds:i,keptChilds:n}),o.parent?.remove(o)):e.debug&&console.log("Kept object:",(o.displayName||o.name)+" ("+o.uuid+")",{isVisible:r,isBehaviorSourceOrTarget:s,allChildsWerePruned:t,isBoneReparenting:a,object:o,prunedChilds:i,keptChilds:n}),l}async function PT(o,e){re.start("export-usdz-resources","export-usdz");const t=[];for(const l of o.document.children)hx(l,o,t);const i=t.length;for(let l=0;l<i;l++)re.report("export-usdz-resources",{totalSteps:i,currentStep:l}),await new Promise((c,h)=>{t[l](),c()});re.end("export-usdz-resources");const n=new sx,s=o.exporter.sceneAnchoringOptions.ar;n.beginBlock(`def Xform "${o.document.name}"`),n.beginBlock(`def Scope "Scenes" (
1079
1079
  kind = "sceneLibrary"
1080
1080
  )`),n.beginBlock('def Xform "Scene"',"(",!1),n.appendLine('apiSchemas = ["Preliminary_AnchoringAPI"]'),n.appendLine("customData = {"),n.appendLine(" bool preliminary_collidesWithEnvironment = 0"),n.appendLine(' string sceneName = "Scene"'),n.appendLine("}"),n.appendLine('sceneName = "Scene"'),n.closeBlock(")"),n.beginBlock(),n.appendLine(`token preliminary:anchoring:type = "${s.anchoring.type}"`),s.anchoring.type==="plane"&&n.appendLine(`token preliminary:planeAnchoring:alignment = "${s.planeAnchoring.alignment}"`),s.anchoring.type==="image"&&n.appendLine(`rel preliminary:imageAnchoring:referenceImage = </${o.document.name}/Scenes/Scene/AnchoringReferenceImage>`),n.appendLine();const r=l=>{if(!l)return 0;let c=1;for(const h of l.children)c+=r(h);return c},a=r(o.document);re.start("export-usdz-xforms","export-usdz"),re.report("export-usdz-xforms",{totalSteps:a,currentStep:1});for(const l of o.document.children)mx(l,n,o);re.end("export-usdz-xforms"),re.report("export-usdz","invoke onAfterHierarchy"),await Uu(o,"onAfterHierarchy",n),n.closeBlock(),n.closeBlock(),n.appendLine(e()),n.closeBlock(),re.report("export-usdz","write to string"),o.output+=n.toString()}function hx(o,e,t){if(!o)return;const i=o.geometry,n=o.material;if(i)if(n&&("isMeshStandardMaterial"in n&&n.isMeshStandardMaterial||"isMeshBasicMaterial"in n&&n.isMeshBasicMaterial||n.type==="MeshLineMaterial")){const s="geometries/"+Vf(i,o.name)+".usda";if(!(s in e.files)){const r=()=>{const a=TT(i,o.skinnedMesh?.skeleton?.bones,e.quickLookCompatible);e.files[s]=RT(a)};t.push(r)}}else console.warn("NeedleUSDZExporter: Unsupported material type (USDZ only supports MeshStandardMaterial)",n?.name);n&&(n.uuid in e.materials||(e.materials[n.uuid]=n));for(const s of o.children)hx(s,e,t)}async function Uu(o,e,t=null){if(o.extensions){for(const i of o.extensions)if(i&&typeof i[e]=="function"){const n=i[e].call(i,o,t);n instanceof Promise&&await n}}}let zu=null,Qt=null,Wf,tl,Nu;async function dx(o,e=1/0,t=null,i=void 0){Wf||(Wf=new In(2,2,1,1)),tl||(tl=new Ln({uniforms:{blitTexture:new Ni(o),flipY:new Ni(!1),scale:new Ni(new pe(1,1,1,1))},vertexShader:`
1081
1081
  varying vec2 vUv;
@@ -1100,7 +1100,7 @@ ${c}
1100
1100
  #endif
1101
1101
 
1102
1102
  gl_FragColor.rgba *= scale.rgba;
1103
- }`}));const n=tl.uniforms;n.blitTexture.value=o,n.flipY.value=!1,n.scale.value=new pe(1,1,1,1),i!==void 0&&n.scale.value.copy(i),tl.defines.IS_SRGB=o.colorSpace==go,tl.needsUpdate=!0,Nu||(Nu=new H(Wf,tl),Nu.frustumCulled=!1);const s=new de,r=new yi;r.add(Nu),t||(t=zu=new er({antialias:!1,alpha:!0,premultipliedAlpha:!1,preserveDrawingBuffer:!0}));const a=Math.min(o.image.width,e),l=Math.min(o.image.height,e);Qt&&(Qt.width!==a||Qt.height!==l)&&(Qt.dispose(),Qt=null),Qt||(Qt=new jn(a,l,{format:ad,type:HS,minFilter:pd,magFilter:pd})),t.setRenderTarget(Qt),t.setSize(a,l),t.clear(),t.render(r,s),zu&&(zu.dispose(),zu=null);const c=new Uint8ClampedArray(Qt.width*Qt.height*4);t.readRenderTargetPixels(Qt,0,0,Qt.width,Qt.height,c);const h=new ImageData(c,Qt.width,Qt.height,void 0),d=await createImageBitmap(h,{premultiplyAlpha:"none"});return{imageData:h,imageBitmap:d}}function OT(o){return typeof HTMLImageElement<"u"&&o instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&o instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&o instanceof OffscreenCanvas||typeof ImageBitmap<"u"&&o instanceof ImageBitmap}async function kT(o,e=4096){const t=e/Math.max(o.width,o.height),i=o.width*Math.min(1,t),n=o.height*Math.min(1,t),s=new OffscreenCanvas(i,n),r={premultiplyAlpha:"none"};o.width!==i&&(r.resizeWidth=i),o.height!==n&&(r.resizeHeight=n);const a=await createImageBitmap(o,r),l=s.getContext("bitmaprenderer");return l&&l.transferFromImageBitmap(a),s}async function ux(o,e=void 0,t=!1,i=4096){if(OT(o)){const n=i/Math.max(o.width,o.height),s=new OffscreenCanvas(o.width*Math.min(1,n),o.height*Math.min(1,n)),r=s.getContext("2d",{alpha:!0,premultipliedAlpha:!1});if(!r)throw new Error("Could not get canvas 2D context");if(t===!0&&(r.translate(0,s.height),r.scale(1,-1)),r.drawImage(o,0,0,s.width,s.height),e!==void 0){const a=e.x,l=e.y,c=e.z,h=e.w,d=r.getImageData(0,0,s.width,s.height),p=d.data;for(let g=0;g<p.length;g+=4)p[g+0]=p[g+0]*a,p[g+1]=p[g+1]*l,p[g+2]=p[g+2]*c,p[g+3]=p[g+3]*h;r.putImageData(d,0,0)}return s}else throw new Error("NeedleUSDZExporter: No valid image data found. Unable to process texture.")}const Oe=7;function MT(){return`#usda 1.0
1103
+ }`}));const n=tl.uniforms;n.blitTexture.value=o,n.flipY.value=!1,n.scale.value=new pe(1,1,1,1),i!==void 0&&n.scale.value.copy(i),tl.defines.IS_SRGB=o.colorSpace==go,tl.needsUpdate=!0,Nu||(Nu=new H(Wf,tl),Nu.frustumCulled=!1);const s=new de,r=new yi;r.add(Nu),t||(t=zu=new er({antialias:!1,alpha:!0,premultipliedAlpha:!1,preserveDrawingBuffer:!0}));const a=Math.min(o.image.width,e),l=Math.min(o.image.height,e);Qt&&(Qt.width!==a||Qt.height!==l)&&(Qt.dispose(),Qt=null),Qt||(Qt=new jn(a,l,{format:ad,type:HS,minFilter:pd,magFilter:pd})),t.setRenderTarget(Qt),t.setSize(a,l),t.clear(),t.render(r,s),zu&&(zu.dispose(),zu=null);const c=new Uint8ClampedArray(Qt.width*Qt.height*4);t.readRenderTargetPixels(Qt,0,0,Qt.width,Qt.height,c);const h=new ImageData(c,Qt.width,Qt.height,void 0),d=await createImageBitmap(h,{premultiplyAlpha:"none"});return{imageData:h,imageBitmap:d}}function OT(o){return typeof HTMLImageElement<"u"&&o instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&o instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&o instanceof OffscreenCanvas||typeof ImageBitmap<"u"&&o instanceof ImageBitmap}async function kT(o,e=4096){const t=e/Math.max(o.width,o.height),i=o.width*Math.min(1,t),n=o.height*Math.min(1,t),s=new OffscreenCanvas(i,n),r={premultiplyAlpha:"none"};o.width!==i&&(r.resizeWidth=i),o.height!==n&&(r.resizeHeight=n);const a=await createImageBitmap(o,r),l=s.getContext("bitmaprenderer");return l&&l.transferFromImageBitmap(a),s}async function ux(o,e=void 0,t=!1,i=4096){if(OT(o)){const n=i/Math.max(o.width,o.height),s=new OffscreenCanvas(o.width*Math.min(1,n),o.height*Math.min(1,n)),r=s.getContext("2d",{alpha:!0,premultipliedAlpha:!1});if(!r)throw new Error("Could not get canvas 2D context");if(t===!0&&(r.translate(0,s.height),r.scale(1,-1)),r.drawImage(o,0,0,s.width,s.height),e!==void 0){const a=e.x,l=e.y,c=e.z,h=e.w,d=r.getImageData(0,0,s.width,s.height),p=d.data;for(let m=0;m<p.length;m+=4)p[m+0]=p[m+0]*a,p[m+1]=p[m+1]*l,p[m+2]=p[m+2]*c,p[m+3]=p[m+3]*h;r.putImageData(d,0,0)}return s}else throw new Error("NeedleUSDZExporter: No valid image data found. Unable to process texture.")}const Oe=7;function MT(){return`#usda 1.0
1104
1104
  (
1105
1105
  customLayerData = {
1106
1106
  string creator = "Needle Engine USDZExporter"
@@ -1108,10 +1108,10 @@ ${c}
1108
1108
  metersPerUnit = 1
1109
1109
  upAxis = "Y"
1110
1110
  )
1111
- `}function RT(o,e){let t=MT();return t+=o,Z0(t)}function Wu(o){return o.name.replace(/[-<>\(\)\[\]§$%&\/\\\=\?\,\;]/g,"")+"_"+o.id}function px(o){return Zi(o.name||"bone_"+o.uuid)}function Vf(o,e){return Zi(o.name||"Geometry")+"_"+o.id}function Vu(o){return Zi(o.name||"Material")+"_"+o.id}function il(o,e){let t=px(o),i=o.parent;for(;i&&i!==e;)t=px(i)+"/"+t,i=i.parent;return t}function mx(o,e,t){if(o==null)return;re.report("export-usdz-xforms",{message:"buildXform "+o.displayName||o.name,autoStep:!0});const i=o.transform,n=o.geometry,s=o.material,r=o.camera,a=o.name;if(o.animations)for(const g of o.animations)t.animations.push(g);const l=n&&n.isBufferGeometry&&n.attributes.skinIndex!==void 0&&n.attributes.skinIndex.count>0,c=l?"SkelRoot":"Xform",h=new Array,d=s&&s instanceof xe&&s.color&&s.color.r===1&&s.color.g===1&&s.color.b===1&&!s.map&&s.opacity===1&&n?.attributes.color;if(n?.attributes.color&&!d&&console.warn("NeedleUSDZExporter: Geometry has vertex colors. Vertex colors will only be shown in QuickLook for unlit materials with white color and no texture. Otherwise, they will be ignored.",o.displayName),e.appendLine(),n?(e.beginBlock(`def ${c} "${a}"`,"(",!1),t.quickLookCompatible&&s&&s.side===vi&&!l?e.appendLine(`prepend references = @./geometries/${Vf(n)}.usda@</Geometry_doubleSided>`):e.appendLine(`prepend references = @./geometries/${Vf(n)}.usda@</Geometry>`),d||h.push("MaterialBindingAPI"),l&&h.push("SkelBindingAPI")):r&&!t.quickLookCompatible?e.beginBlock(`def Camera "${a}"`,"(",!1):o.type!==void 0?e.beginBlock(`def ${o.type} "${a}"`):e.beginBlock(`def Xform "${a}"`,"(",!1),o.type===void 0&&(o.extraSchemas?.length&&h.push(...o.extraSchemas),h.length&&e.appendLine(`prepend apiSchemas = [${h.map(g=>`"${g}"`).join(", ")}]`)),o.displayName&&e.appendLine(`displayName = "${ix(o.displayName)}"`),(r||o.type===void 0)&&(e.closeBlock(")"),e.beginBlock()),n&&s){if(!d){const g=Vu(s);e.appendLine(`rel material:binding = </StageRoot/Materials/${g}>`)}!t.quickLookCompatible&&s.side===vi&&(e.beginBlock('over "Geometry" '),e.appendLine("uniform bool doubleSided = 1"),e.closeBlock())}let p=!1;if(l?(e.appendLine("rel skel:skeleton = <Rig>"),e.appendLine("rel skel:animationSource = <Rig/_anim>"),p=!1):o.type===void 0&&i&&(p=p||i.position!==null||i.quaternion!==null||i.scale!==null,i.position&&(o.needsTranslate=!0,e.appendLine(`double3 xformOp:translate = (${ae(i.position.x)}, ${ae(i.position.y)}, ${ae(i.position.z)})`)),i.quaternion&&(o.needsOrient=!0,e.appendLine(`quatf xformOp:orient = (${ae(i.quaternion.w)}, ${ae(i.quaternion.x)}, ${ae(i.quaternion.y)}, ${ae(i.quaternion.z)})`)),i.scale&&(o.needsScale=!0,e.appendLine(`double3 xformOp:scale = (${ae(i.scale.x)}, ${ae(i.scale.y)}, ${ae(i.scale.z)})`))),o.visibility!==void 0&&e.appendLine(`token visibility = "${o.visibility}"`),r&&!t.quickLookCompatible&&("isOrthographicCamera"in r&&r.isOrthographicCamera?(e.appendLine(`float2 clippingRange = (${r.near}, ${r.far})`),e.appendLine(`float horizontalAperture = ${((Math.abs(r.left)+Math.abs(r.right))*10).toPrecision(Oe)}`),e.appendLine(`float verticalAperture = ${((Math.abs(r.top)+Math.abs(r.bottom))*10).toPrecision(Oe)}`),e.appendLine('token projection = "orthographic"')):"isPerspectiveCamera"in r&&r.isPerspectiveCamera&&(e.appendLine(`float2 clippingRange = (${r.near.toPrecision(Oe)}, ${r.far.toPrecision(Oe)})`),e.appendLine(`float focalLength = ${r.getFocalLength().toPrecision(Oe)}`),e.appendLine(`float focusDistance = ${r.focus.toPrecision(Oe)}`),e.appendLine(`float horizontalAperture = ${r.getFilmWidth().toPrecision(Oe)}`),e.appendLine('token projection = "perspective"'),e.appendLine(`float verticalAperture = ${r.getFilmHeight().toPrecision(Oe)}`))),o.onSerialize&&o.onSerialize(e,t),o.type===void 0){const g=new Array;o.needsTranslate&&g.push('"xformOp:translate"'),o.needsOrient&&g.push('"xformOp:orient"'),o.needsScale&&g.push('"xformOp:scale"'),g.length&&e.appendLine(`uniform token[] xformOpOrder = [${g.join(", ")}]`)}if(o.children){e.appendLine();for(const g of o.children)mx(g,e,t)}e.closeBlock()}function ae(o){return Number.isInteger(o)?o.toString():o.toFixed(10)}function gx(o){const e=o.elements;return`( ${$u(e,0)}, ${$u(e,4)}, ${$u(e,8)}, ${$u(e,12)} )`}function $u(o,e){return`(${ae(o[e+0])}, ${ae(o[e+1])}, ${ae(o[e+2])}, ${ae(o[e+3])})`}function TT(o,e=[],t=!0){return`
1111
+ `}function RT(o,e){let t=MT();return t+=o,Z0(t)}function Wu(o){return o.name.replace(/[-<>\(\)\[\]§$%&\/\\\=\?\,\;]/g,"")+"_"+o.id}function px(o){return Zi(o.name||"bone_"+o.uuid)}function Vf(o,e){return Zi(o.name||"Geometry")+"_"+o.id}function Vu(o){return Zi(o.name||"Material")+"_"+o.id}function il(o,e){let t=px(o),i=o.parent;for(;i&&i!==e;)t=px(i)+"/"+t,i=i.parent;return t}function mx(o,e,t){if(o==null)return;re.report("export-usdz-xforms",{message:"buildXform "+o.displayName||o.name,autoStep:!0});const i=o.transform,n=o.geometry,s=o.material,r=o.camera,a=o.name;if(o.animations)for(const m of o.animations)t.animations.push(m);const l=n&&n.isBufferGeometry&&n.attributes.skinIndex!==void 0&&n.attributes.skinIndex.count>0,c=l?"SkelRoot":"Xform",h=new Array,d=s&&s instanceof xe&&s.color&&s.color.r===1&&s.color.g===1&&s.color.b===1&&!s.map&&s.opacity===1&&n?.attributes.color;if(n?.attributes.color&&!d&&console.warn("NeedleUSDZExporter: Geometry has vertex colors. Vertex colors will only be shown in QuickLook for unlit materials with white color and no texture. Otherwise, they will be ignored.",o.displayName),e.appendLine(),n?(e.beginBlock(`def ${c} "${a}"`,"(",!1),t.quickLookCompatible&&s&&s.side===vi&&!l?e.appendLine(`prepend references = @./geometries/${Vf(n)}.usda@</Geometry_doubleSided>`):e.appendLine(`prepend references = @./geometries/${Vf(n)}.usda@</Geometry>`),d||h.push("MaterialBindingAPI"),l&&h.push("SkelBindingAPI")):r&&!t.quickLookCompatible?e.beginBlock(`def Camera "${a}"`,"(",!1):o.type!==void 0?e.beginBlock(`def ${o.type} "${a}"`):e.beginBlock(`def Xform "${a}"`,"(",!1),o.type===void 0&&(o.extraSchemas?.length&&h.push(...o.extraSchemas),h.length&&e.appendLine(`prepend apiSchemas = [${h.map(m=>`"${m}"`).join(", ")}]`)),o.displayName&&e.appendLine(`displayName = "${ix(o.displayName)}"`),(r||o.type===void 0)&&(e.closeBlock(")"),e.beginBlock()),n&&s){if(!d){const m=Vu(s);e.appendLine(`rel material:binding = </StageRoot/Materials/${m}>`)}!t.quickLookCompatible&&s.side===vi&&(e.beginBlock('over "Geometry" '),e.appendLine("uniform bool doubleSided = 1"),e.closeBlock())}let p=!1;if(l?(e.appendLine("rel skel:skeleton = <Rig>"),e.appendLine("rel skel:animationSource = <Rig/_anim>"),p=!1):o.type===void 0&&i&&(p=p||i.position!==null||i.quaternion!==null||i.scale!==null,i.position&&(o.needsTranslate=!0,e.appendLine(`double3 xformOp:translate = (${ae(i.position.x)}, ${ae(i.position.y)}, ${ae(i.position.z)})`)),i.quaternion&&(o.needsOrient=!0,e.appendLine(`quatf xformOp:orient = (${ae(i.quaternion.w)}, ${ae(i.quaternion.x)}, ${ae(i.quaternion.y)}, ${ae(i.quaternion.z)})`)),i.scale&&(o.needsScale=!0,e.appendLine(`double3 xformOp:scale = (${ae(i.scale.x)}, ${ae(i.scale.y)}, ${ae(i.scale.z)})`))),o.visibility!==void 0&&e.appendLine(`token visibility = "${o.visibility}"`),r&&!t.quickLookCompatible&&("isOrthographicCamera"in r&&r.isOrthographicCamera?(e.appendLine(`float2 clippingRange = (${r.near}, ${r.far})`),e.appendLine(`float horizontalAperture = ${((Math.abs(r.left)+Math.abs(r.right))*10).toPrecision(Oe)}`),e.appendLine(`float verticalAperture = ${((Math.abs(r.top)+Math.abs(r.bottom))*10).toPrecision(Oe)}`),e.appendLine('token projection = "orthographic"')):"isPerspectiveCamera"in r&&r.isPerspectiveCamera&&(e.appendLine(`float2 clippingRange = (${r.near.toPrecision(Oe)}, ${r.far.toPrecision(Oe)})`),e.appendLine(`float focalLength = ${r.getFocalLength().toPrecision(Oe)}`),e.appendLine(`float focusDistance = ${r.focus.toPrecision(Oe)}`),e.appendLine(`float horizontalAperture = ${r.getFilmWidth().toPrecision(Oe)}`),e.appendLine('token projection = "perspective"'),e.appendLine(`float verticalAperture = ${r.getFilmHeight().toPrecision(Oe)}`))),o.onSerialize&&o.onSerialize(e,t),o.type===void 0){const m=new Array;o.needsTranslate&&m.push('"xformOp:translate"'),o.needsOrient&&m.push('"xformOp:orient"'),o.needsScale&&m.push('"xformOp:scale"'),m.length&&e.appendLine(`uniform token[] xformOpOrder = [${m.join(", ")}]`)}if(o.children){e.appendLine();for(const m of o.children)mx(m,e,t)}e.closeBlock()}function ae(o){return Number.isInteger(o)?o.toString():o.toFixed(10)}function gx(o){const e=o.elements;return`( ${$u(e,0)}, ${$u(e,4)}, ${$u(e,8)}, ${$u(e,12)} )`}function $u(o,e){return`(${ae(o[e+0])}, ${ae(o[e+1])}, ${ae(o[e+2])}, ${ae(o[e+3])})`}function TT(o,e=[],t=!0){return`
1112
1112
  def "Geometry"
1113
1113
  ${ET(o,e,t)}
1114
- `}function ET(o,e=[],t=!0){const i="Geometry",n=o.attributes,s=n.position.count,r=e&&e.length>0,a=[],l=[];let c=new Array,h=n.skinIndex;if(r){const p=[];for(const y of e)a.push({bone:y,index:e.indexOf(y)}),p.push(y.uuid);let g=1e4;for(;p.length<e.length&&g-- >0;)for(const y of a){const _=y.bone.children;for(const v of _)p.indexOf(v.uuid)===-1&&e.indexOf(v)!==-1&&(a.push({bone:v,index:e.indexOf(v)}),p.push(v.uuid))}g<=0&&console.error("Failed to sort bones in skinned mesh",a,e,p);for(const y of ox(e))a.push({bone:y,index:a.length});const f=a[0].bone.parent;a.sort((y,_)=>il(y.bone,f)>il(_.bone,f)?1:-1),a.map(y=>'"'+il(y.bone,f)+'"').join(", ");for(const y in a)l[a[y].index]=parseInt(y);const m=n.skinIndex;c=new Array;for(let y=0;y<m.count;y++){const _=m.getX(y),v=m.getY(y),P=m.getZ(y),R=m.getW(y);c.push(l[_],l[v],l[P],l[R])}h=new pt(new Uint16Array(c),4)}const d=n.skinWeight&&n.skinIndex;return`
1114
+ `}function ET(o,e=[],t=!0){const i="Geometry",n=o.attributes,s=n.position.count,r=e&&e.length>0,a=[],l=[];let c=new Array,h=n.skinIndex;if(r){const p=[];for(const y of e)a.push({bone:y,index:e.indexOf(y)}),p.push(y.uuid);let m=1e4;for(;p.length<e.length&&m-- >0;)for(const y of a){const _=y.bone.children;for(const v of _)p.indexOf(v.uuid)===-1&&e.indexOf(v)!==-1&&(a.push({bone:v,index:e.indexOf(v)}),p.push(v.uuid))}m<=0&&console.error("Failed to sort bones in skinned mesh",a,e,p);for(const y of ox(e))a.push({bone:y,index:a.length});const f=a[0].bone.parent;a.sort((y,_)=>il(y.bone,f)>il(_.bone,f)?1:-1),a.map(y=>'"'+il(y.bone,f)+'"').join(", ");for(const y in a)l[a[y].index]=parseInt(y);const g=n.skinIndex;c=new Array;for(let y=0;y<g.count;y++){const _=g.getX(y),v=g.getY(y),P=g.getZ(y),R=g.getW(y);c.push(l[_],l[v],l[P],l[R])}h=new pt(new Uint16Array(c),4)}const d=n.skinWeight&&n.skinIndex;return`
1115
1115
  {
1116
1116
  def Mesh "${i}" ${d?`(
1117
1117
  prepend apiSchemas = ["SkelBindingAPI"]
@@ -1171,7 +1171,7 @@ def "${i}_doubleSided" (
1171
1171
  def "Materials"
1172
1172
  {
1173
1173
  ${i.join("")}
1174
- }`}function Ji(o){return Zi(o.name)+"_"+(o.source?.id??o.id)}function Ps(o,e,t,i,n,s,r=void 0,a=void 0){const l=Ji(o),c=l+(a!==void 0&&a!==1?"_"+a:""),h=t&&a!==void 0&&a!==1,d=h?new pe(1,1,1,a):void 0;a===void 0&&(a=1),h&&(a=1),d&&d.w<=.05&&(d.w=.05),i[c]={texture:o,scale:d};const p=o.channel>0?"st"+o.channel:"st";s.add(o.channel);const g=qf.includes(o.format),f={1e3:"repeat",1001:"clamp",1002:"mirror"},m=o.repeat.clone(),y=o.offset.clone(),_=o.rotation,v=Math.sin(_),P=Math.cos(_);y.y=1-y.y-m.y,t?(m.x===0&&(m.x=1e-4),m.y===0&&(m.y=1e-4),y.x=y.x/m.x,y.y=y.y/m.y,y.x+=v/m.x,y.y+=P-1):(y.x+=v*m.x,y.y+=(1-P)*m.y);const R=Vu(n),k=m.x!=1||m.y!=1||y.x!=0||y.y!=0||_!=0,A=`${Xt}/${R}/${"uvReader_"+p}.outputs:result>`,L=`${Xt}/${R}/Transform2d_${e}.outputs:result>`,N=e!=="normal"&&r&&(r.r!==1||r.g!==1||r.b!==1||a!==1)||!1,j=e==="normal",q=n instanceof ut&&n.normalScale?n.normalScale.x*2:2,Y=q.toFixed(Oe),I=(-1*(q/2)).toFixed(Oe),V=(1-q).toFixed(Oe);return`
1174
+ }`}function Ji(o){return Zi(o.name)+"_"+(o.source?.id??o.id)}function Ps(o,e,t,i,n,s,r=void 0,a=void 0){const l=Ji(o),c=l+(a!==void 0&&a!==1?"_"+a:""),h=t&&a!==void 0&&a!==1,d=h?new pe(1,1,1,a):void 0;a===void 0&&(a=1),h&&(a=1),d&&d.w<=.05&&(d.w=.05),i[c]={texture:o,scale:d};const p=o.channel>0?"st"+o.channel:"st";s.add(o.channel);const m=qf.includes(o.format),f={1e3:"repeat",1001:"clamp",1002:"mirror"},g=o.repeat.clone(),y=o.offset.clone(),_=o.rotation,v=Math.sin(_),P=Math.cos(_);y.y=1-y.y-g.y,t?(g.x===0&&(g.x=1e-4),g.y===0&&(g.y=1e-4),y.x=y.x/g.x,y.y=y.y/g.y,y.x+=v/g.x,y.y+=P-1):(y.x+=v*g.x,y.y+=(1-P)*g.y);const R=Vu(n),k=g.x!=1||g.y!=1||y.x!=0||y.y!=0||_!=0,A=`${Xt}/${R}/${"uvReader_"+p}.outputs:result>`,L=`${Xt}/${R}/Transform2d_${e}.outputs:result>`,N=e!=="normal"&&r&&(r.r!==1||r.g!==1||r.b!==1||a!==1)||!1,j=e==="normal",q=n instanceof ut&&n.normalScale?n.normalScale.x*2:2,Y=q.toFixed(Oe),I=(-1*(q/2)).toFixed(Oe),V=(1-q).toFixed(Oe);return`
1175
1175
  ${k?`def Shader "Transform2d_${e}" (
1176
1176
  sdrMetadata = {
1177
1177
  string role = "math"
@@ -1180,7 +1180,7 @@ ${i.join("")}
1180
1180
  {
1181
1181
  uniform token info:id = "UsdTransform2d"
1182
1182
  float2 inputs:in.connect = ${A}
1183
- float2 inputs:scale = ${_x(m)}
1183
+ float2 inputs:scale = ${_x(g)}
1184
1184
  float2 inputs:translation = ${_x(y)}
1185
1185
  float inputs:rotation = ${(_/Math.PI*180).toFixed(Oe)}
1186
1186
  float2 outputs:result
@@ -1189,7 +1189,7 @@ ${i.join("")}
1189
1189
  def Shader "${l}_${e}"
1190
1190
  {
1191
1191
  uniform token info:id = "UsdUVTexture"
1192
- asset inputs:file = @textures/${c}.${g?"png":"jpg"}@
1192
+ asset inputs:file = @textures/${c}.${m?"png":"jpg"}@
1193
1193
  token inputs:sourceColorSpace = "${o.colorSpace==="srgb"?"sRGB":"raw"}"
1194
1194
  float2 inputs:st.connect = ${k?L:A}
1195
1195
  ${N?`
@@ -1256,21 +1256,21 @@ ${a.has(1)?`
1256
1256
  `:""}
1257
1257
  ${r.join(`
1258
1258
  `)}`:""}
1259
- }`}function bx(o){return`(${o.r}, ${o.g}, ${o.b})`}function _x(o){return`(${o.x}, ${o.y})`}const qf=[1023,33777,33778,33779,35842,35843,37496,37808,37809,37810,37811,37812,37813,37814,37815,37816,37817,37818,37819,37820,37821,36492];w("debugusdz");class Et{static global_id=0;id;trigger;action;exclusive=!1;makeExclusive(e){return this.exclusive=e,this}constructor(e,t,i){this.id="Behavior_"+Zi(e)+"_"+Et.global_id++,this.trigger=t,this.action=i}writeTo(e,t,i){if(!this.trigger||!this.action)return;i.beginBlock(`def Preliminary_Behavior "${this.id}"`);let n="";if(Array.isArray(this.trigger)){n="[";for(let s=0;s<this.trigger.length;s++){const r=this.trigger[s];n+="<"+r.id+">",s+1<this.trigger.length&&(n+=", ")}n+="]"}else n=`<${this.trigger.id}>`;if(i.appendLine(`rel triggers = ${n}`),i.appendLine(`rel actions = <${this.action.id}>`),i.appendLine(`uniform bool exclusive = ${this.exclusive?1:0}`),i.appendLine(),Array.isArray(this.trigger))for(const s of this.trigger)s.writeTo(t,i),i.appendLine();else this.trigger.writeTo(t,i);i.appendLine(),this.action.writeTo(t,i),i.closeBlock()}}const nl=new Set;function Xf(o,e){let t="";if(Array.isArray(o)){nl.clear();let i="[ ";for(let n=0;n<o.length;n++){let s=o[n];if(!s){console.warn("Invalid target object in behavior",o+". Is the object exported?");continue}if(typeof s=="string"){if(nl.has(s))continue;i+=s,nl.add(s)}else if(typeof s=="object"){if(s.isObject3D&&(s=e.findById(s.uuid),!s)){console.warn("Invalid target object in behavior",o+". Is the object exported?");continue}const r=s.getPath?.call(s);if(nl.has(r))continue;i+=r,nl.add(r)}n+1<o.length&&(i+=", ")}i+=" ]",t=i,nl.clear()}else if(typeof o=="object"){const i=o;if(i.isObject3D&&(o=e.findById(i.uuid)),!o)throw console.error("Invalid target object in behavior, the target object is likely missing from USDZ export. Is the object exported?",i),new Error(`Invalid target object in behavior, the target object is likely missing from USDZ export. Please report a bug. uuid: ${i.uuid}.`);t=o.getPath?.call(o)}return t}class Xs{static global_id=0;id;targetId;tokenId;type;distance;constructor(e,t){e&&(this.targetId=e),t?this.id=t:this.id="Trigger_"+Xs.global_id++}writeTo(e,t){t.beginBlock(`def Preliminary_Trigger "${this.id}"`),this.targetId&&(typeof this.targetId!="string"&&(this.targetId=Xf(this.targetId,e)),t.appendLine("rel affectedObjects = "+this.targetId)),this.tokenId&&t.appendLine(`token info:id = "${this.tokenId}"`),this.type&&t.appendLine(`token type = "${this.type}"`),typeof this.distance=="number"&&t.appendLine(`double distance = ${this.distance}`),t.closeBlock()}}function vx(o,e={direct:!0,indirect:!0}){const t=it.createEmpty();t.name="InputTarget_"+t.name,t.displayName=void 0,t.type="RealityKitComponent",t.onSerialize=i=>{i.appendLine("bool allowsDirectInput = "+(e.direct?1:0)),i.appendLine("bool allowsIndirectInput = "+(e.indirect?1:0)),i.appendLine('uniform token info:id = "RealityKit.InputTarget"')},o.add(t)}class jt{static __sceneStartTrigger;static sceneStartTrigger(){if(this.__sceneStartTrigger!==void 0)return this.__sceneStartTrigger;const e=new Xs(void 0,"SceneStart");return e.tokenId="SceneTransition",e.type="enter",this.__sceneStartTrigger=e,e}static tapTrigger(e,t={direct:!0,indirect:!0}){const i=new Xs(e);if(Array.isArray(e)&&e.length>1)for(const n of e)n instanceof it&&vx(n,t);else e instanceof it&&vx(e,t);return i.tokenId="TapGesture",i}static isTapTrigger(e){return e?.tokenId==="TapGesture"}static proximityToCameraTrigger(e,t){const i=new Xs(e);return i.tokenId="ProximityToCamera",i.distance=t,i}}class Dr{static global_id=0;static getId(){return this.global_id++}id;actions;loops=0;performCount=1;type="serial";multiplePerformOperation=void 0;constructor(e,t){this.id=e,this.actions=t}addAction(e){return this.actions.push(e),this}makeParallel(){return this.type="parallel",this}makeSequence(){return this.type="serial",this}makeLooping(){return this.loops=1,this.performCount=0,this}makeRepeat(e){return this.performCount=e,this}writeTo(e,t){t.beginBlock(`def Preliminary_Action "${this.id}"`),t.beginArray("rel actions");for(const i of this.actions){if(!i)continue;const n=i===this.actions[this.actions.length-1];t.appendLine("<"+i.id+">"+(n?"":", "))}t.closeArray(),t.appendLine(),t.appendLine('token info:id = "Group"'),t.appendLine(`bool loops = ${this.loops}`),t.appendLine(`int performCount = ${this.loops>0?0:Math.max(0,this.performCount)}`),t.appendLine(`token type = "${this.type}"`),typeof this.multiplePerformOperation=="string"&&t.appendLine(`token multiplePerformOperation = "${this.multiplePerformOperation}"`),t.appendLine();for(const i of this.actions)i&&(i.writeTo(e,t),t.appendLine());t.closeBlock()}}class fi{static global_id=0;id;tokenId;affectedObjects;easeType;motionType=void 0;duration;moveDistance;style;type;front;up;start;animationSpeed;reversed;pingPong;xFormTarget;audio;gain;auralMode;multiplePerformOperation;velocity;comment;animationName;clone(){const e=new fi,t=e.id;return Object.assign(e,this),e.id=t,e}constructor(e,t){e&&(this.affectedObjects=e),t?this.id=t:this.id="Action",this.id+="_"+fi.global_id++}writeTo(e,t){t.beginBlock(`def Preliminary_Action "${this.id}"`),this.comment&&t.appendLine(`# ${this.comment}`),this.affectedObjects&&(typeof this.affectedObjects!="string"&&(this.affectedObjects=Xf(this.affectedObjects,e)),t.appendLine("rel affectedObjects = "+this.affectedObjects)),typeof this.duration=="number"&&(typeof this.animationSpeed=="number"&&this.animationSpeed!==1?t.appendLine(`double duration = ${this.duration/this.animationSpeed} `):t.appendLine(`double duration = ${this.duration} `)),this.easeType&&t.appendLine(`token easeType = "${this.easeType}"`),this.tokenId&&t.appendLine(`token info:id = "${this.tokenId}"`),this.tokenId==="ChangeScene"&&t.appendLine("rel scene = </StageRoot/Scenes/Scene>"),this.motionType!==void 0&&t.appendLine(`token motionType = "${this.motionType}"`),typeof this.moveDistance=="number"&&t.appendLine(`double moveDistance = ${this.moveDistance} `),this.style&&t.appendLine(`token style = "${this.style}"`),this.type&&t.appendLine(`token type = "${this.type}"`),this.front&&t.appendLine(`vector3d front = (${this.front.x}, ${this.front.y}, ${this.front.z})`),this.up&&t.appendLine(`vector3d upVector = (${this.up.x}, ${this.up.y}, ${this.up.z})`),typeof this.start=="number"&&t.appendLine(`double start = ${this.start} `),typeof this.animationSpeed=="number"&&t.appendLine(`double animationSpeed = ${this.animationSpeed.toFixed(2)} `),typeof this.reversed=="boolean"&&t.appendLine(`bool reversed = ${this.reversed}`),typeof this.pingPong=="boolean"&&t.appendLine(`bool reverses = ${this.pingPong}`),this.xFormTarget&&(typeof this.xFormTarget!="string"&&(this.xFormTarget=Xf(this.xFormTarget,e)),t.appendLine(`rel xformTarget = ${this.xFormTarget}`)),typeof this.audio=="string"&&t.appendLine(`asset audio = @${this.audio}@`),typeof this.gain=="number"&&t.appendLine(`double gain = ${this.gain}`),typeof this.auralMode=="string"&&t.appendLine(`token auralMode = "${this.auralMode}"`),typeof this.multiplePerformOperation=="string"&&t.appendLine(`token multiplePerformOperation = "${this.multiplePerformOperation}"`),typeof this.velocity=="object"&&t.appendLine(`vector3d velocity = (${this.velocity.x}, ${this.velocity.y}, ${this.velocity.z})`),t.closeBlock()}}class hn{x=0;y=0;z=0;constructor(e,t,i){this.x=e,this.y=t,this.z=i}static get up(){return new hn(0,1,0)}static get right(){return new hn(1,0,0)}static get forward(){return new hn(0,0,1)}static get back(){return new hn(0,0,-1)}static get zero(){return new hn(0,0,0)}}class me{static sequence(...e){return new Dr("Group_"+Dr.getId(),e).makeSequence()}static parallel(...e){return new Dr("Group_"+Dr.getId(),e).makeParallel()}static fadeAction(e,t,i){const n=new fi(e);return n.tokenId="Visibility",n.type=i?"show":"hide",n.duration=t,n.style="basic",n.motionType="none",n.moveDistance=0,n.easeType="none",n}static startAnimationAction(e,t,i=!1,n=!1){const s=new fi(e);s.tokenId="StartAnimation";const r=t.start,a=t.duration,l=t.speed,c=t.clipName;if(s.comment=`Animation: ${c}, start=${r*60}, length=${a*60}, end=${(r+a)*60}`,s.animationName=c,s.start=r,s.duration=a,s.animationSpeed=l,s.reversed=i,s.pingPong=n,s.multiplePerformOperation="allow",i&&(s.start-=a),n){s.pingPong=!1;const h=s.clone();return h.reversed=!i,h.start=s.start,h.reversed&&(h.start-=a),me.sequence(s,h)}return s}static waitAction(e){const t=new fi;return t.tokenId="Wait",t.duration=e,t.motionType=void 0,t}static lookAtCameraAction(e,t,i,n){const s=new fi(e);return s.tokenId="LookAtCamera",s.duration=t===void 0?9999999999999:t,s.front=i??hn.forward,s.up=n??hn.up,s}static emphasize(e,t,i="bounce",n=1,s="basic"){const r=new fi(e);return r.tokenId="Emphasize",r.duration=t,r.style=s??"basic",r.motionType=i,r.moveDistance=n,r}static transformAction(e,t,i,n,s="inout"){const r=new fi(e);return r.tokenId="Transform",r.duration=i,r.duration=Math.max(1e-6,i),r.type=n,r.easeType=i>0?s:"none",Array.isArray(t)&&console.error("Transform target must not be an array",t),r.xFormTarget=t,r}static playAudioAction(e,t,i="play",n=1,s="spatial"){const r=new fi(e);return r.tokenId="Audio",r.type=i,r.audio=t,r.gain=n,r.auralMode=s,r.multiplePerformOperation="allow",r}static impulseAction(e,t){const i=new fi(e);return i.tokenId="Impulse",i.velocity=t,i}}class jT{get id(){return this.object.uuid}object;model;constructor(e){this.object=e}apply(e){if(!this.model&&(this.model=e.findById(this.object.uuid),!this.model)){console.error("could not find model with id "+this.object.uuid);return}this.onApply(e)}}class Qf extends jT{constructor(e,t,i,n){super(e),this.matrix=t,this.material=i,this.geometry=n}matrix;material;geometry;onApply(e){const t=this.model;if(!t)return;t.parent?.isDynamic||it.createEmptyParent(t);const i=t.clone();this.matrix&&i.setMatrix(this.matrix),this.material&&(i.material=this.material),this.geometry&&(i.geometry=this.geometry),t.parent?.add(i)}_enableAction;_disableAction;enable(){return this._enableAction?this._enableAction:(this._enableAction=me.fadeAction(this.object,0,!0),this._enableAction)}disable(){return this._disableAction?this._disableAction:(this._disableAction=me.fadeAction(this.object,0,!1),this._disableAction)}}class wx{actions;sortedActions;constructor(e){this.actions=[...e]}organize(){this.sortedActions={};for(const e of this.actions){const t=e.id;this.sortedActions[t]||(this.sortedActions[t]=[]),this.sortedActions[t].push(e)}}getActions(e){return this.sortedActions||this.organize(),this.sortedActions[e.uuid]}}const Zn=w("debugusdzanimation"),Yf=w("debugusdzanimationserialization");class Js{_start;get start(){return this._start===void 0&&(this._start=this.ext.getStartTimeByClip(this.clip)),this._start}get duration(){return this.clip?.duration??Ne.restPoseClipDuration}get nearestAnimatedRoot(){return this._nearestAnimatedRoot}get clipName(){return this.clip?.name??"rest"}ext;root;_nearestAnimatedRoot=void 0;clip;speed;constructor(e,t,i){this.ext=e,this.root=t,this.clip=i,this._nearestAnimatedRoot=this.getNearestAnimatedRoot()}static isDescendantOf(e,t){let i=t;if(!i||!e)return!1;for(;i;){if(!i)return!1;if(i===e)return!0;i=i.parent}return!1}getNearestAnimatedRoot(){let e;try{for(const t of this.clip?.tracks??[]){const i=fa.parseTrackName(t.name);let n=fa.findNode(this.root,i.nodeName);if(n)if(!e)e=n;else{if(n===e||Js.isDescendantOf(e,n))continue;if(!Js.isDescendantOf(n,e)){for(;!Js.isDescendantOf(n,e)&&n.parent;)n=n.parent;Js.isDescendantOf(n,e)||console.error("USDZExporter: Animation clip targets multiple roots that are not parent/child. Please report a bug",this.root,this.clip,e,n)}e=n}}}catch(t){console.error("USDZExporter: Exception when trying to find nearest animated root. Please report a bug",t),e=void 0}return e}}class Ne{clip;pos;rot;scale;root;target;duration=0;useRootMotion=!1;static frameRate=60;static animationDurationPadding=6/60;static restPoseClipDuration=6/60;constructor(e,t,i){if(this.root=e,this.target=t,this.clip=i,i?this.duration=i.duration:this.duration=Ne.restPoseClipDuration,i&&i.tracks){const s=Math.max(...i.tracks.map(r=>r.times[r.times.length-1]));s!==this.duration&&(console.warn("USDZExporter: Animation clip duration does not match the maximum time value in the tracks.",i,s,this.duration),this.duration=s)}const n=x.getComponent(e,ft);n&&(this.useRootMotion=n.applyRootMotion)}addTrack(e){if(!this.clip){console.error("This is a rest clip but you're trying to add tracks to it \u2013 this is likely a bug");return}e.name.endsWith("position")?this.pos=e:e.name.endsWith("quaternion")?this.rot=e:e.name.endsWith("scale")?this.scale=e:(e.name.endsWith("activeSelf")?console.warn("[USDZ] Animation of enabled/disabled state is not supported for USDZ export and will NOT be exported: "+e.name+" on "+(this.root?.name??this.target.name)+". Animate scale 0/1 instead."):console.warn("[USDZ] Animation track type not supported for USDZ export and will NOT be exported: "+e.name+" on "+(this.root?.name??this.target.name)+". Only .position, .rotation, .scale are supported."),E()&&ge("[USDZ] Some animations can't be exported. See console for details."))}getFrames(){return this.clip?Math.max(this.pos?.times?.length??0,this.rot?.times?.length??0,this.scale?.times?.length??0):2}getDuration(){return this.duration}getSortedTimesArray(e=!0,t=!0,i=!0){if(!this.clip)return[0,this.duration];const n=this.pos?.times,s=this.rot?.times,r=this.scale?.times,a=[];if(e&&n)for(const l of n)a.push(l);if(t&&s)for(const l of s)a.push(l);if(i&&r)for(const l of r)a.push(l);return a.includes(0)||a.push(0),a.sort((l,c)=>l-c),[...new Set(a)]}*getValues(e,t=!0,i=!0,n=!0){const s=new b,r=new U,a=new b(1,1,1),l=this.target,c=t?this.pos?.createInterpolant():void 0,h=i?this.rot?.createInterpolant():void 0,d=n?this.scale?.createInterpolant():void 0;c||s.set(l.position.x,l.position.y,l.position.z),h||r.set(l.quaternion.x,l.quaternion.y,l.quaternion.z,l.quaternion.w),d||a.set(l.scale.x,l.scale.y,l.scale.z),c&&c.valueSize!==3&&(c.valueSize=3),h&&h.valueSize!==4&&(h.valueSize=4),d&&d.valueSize!==3&&(d.valueSize=3);const p=0;for(let g=0-p;g<e.length+p;g++){let f=0,m=0;if(g<0?(f=e[0],m=f-Ne.animationDurationPadding/2+1/60):g>=e.length?(f=e[e.length-1],m=f+Ne.animationDurationPadding/2-1/60):(f=e[g],m=f),c){const y=c.evaluate(f);s.set(y[0],y[1],y[2])}if(h){const y=h.evaluate(f);r.set(y[0],y[1],y[2],y[3])}if(d){const y=d.evaluate(f);a.set(y[0],y[1],y[2])}if(this.useRootMotion&&l===this.root){const y=new ee;y.compose(s,r,a),y.multiply(l.matrix),y.decompose(s,r,a)}yield{time:m,translation:s,rotation:r,scale:a,index:g}}}}class Gu{get extensionName(){return"animation"}get animationData(){return this.dict}get registeredClips(){return this.clipToStartTime.keys()}get animatedRoots(){return this.rootTargetMap.keys()}get holdClipMap(){return this.clipToHoldClip}dict=new Map;rootTargetMap=new Map;rootAndClipToRegisteredAnimationMap=new Map;rootToRegisteredClip=new Map;lastClipEndTime=0;clipToStartTime=new Map;clipToHoldClip=new Map;serializers=[];injectRestPoses=!1;injectImplicitBehaviours=!1;constructor(e){this.injectRestPoses=e,this.injectImplicitBehaviours=e}getStartTimeCode(){return!this.injectRestPoses||this.rootAndClipToRegisteredAnimationMap.size===0?0:(Ne.restPoseClipDuration+Ne.animationDurationPadding)*60}getEndTimeCode(){let e=0;for(const[t,i]of this.rootAndClipToRegisteredAnimationMap){const n=i.start+i.duration;n>e&&(e=n)}return e*60}getClipCount(e){return this.rootToRegisteredClip.get(e)?.length??0??0}getStartTimeByClip(e){return e?this.clipToStartTime.has(e)?this.clipToStartTime.get(e):(console.error("USDZExporter: Missing start time for clip \u2013 please report a bug.",e),0):0}registerAnimation(e,t){if(!e)return null;this.rootTargetMap.has(e)||this.rootTargetMap.set(e,[]);const i=e.uuid+(t?.uuid??"-rest");if(this.rootAndClipToRegisteredAnimationMap.has(i))return this.rootAndClipToRegisteredAnimationMap.get(i);Zn&&console.log("registerAnimation",e,t);const n=this.injectRestPoses?1:0,s=(this.rootToRegisteredClip.get(e)?.length??0)+n,r=this.rootTargetMap.get(e),a=new Set(r);if(t&&t.tracks)for(const c of t.tracks){const h=fa.parseTrackName(c.name),d=fa.findNode(e,h.nodeName);if(!d){console.warn("no object found for track",c.name,"using "+e.name+" instead");continue}this.dict.has(d)||this.dict.set(d,[]);const p=this.dict.get(d);if(!p){console.warn("no transform data found for target ",d,"at slot "+s+", this is likely a bug");continue}a.delete(d),this.injectRestPoses&&!p[0]&&(console.log("Injecting rest pose",d,t,"at slot",s),p[0]=new Ne(null,d,null));let g=p[s];g||(g=new Ne(e,d,t),p[s]=g),g.addTrack(c),r?.includes(d)||r?.push(d)}Zn&&console.log("Unregistered nodes for this clip",a,"clip",t,"at slot",s,"for root",e,"targets",r);for(const c of a){const h=this.dict.get(c);if(!h)continue;if(this.injectRestPoses&&!h[0]){console.warn("Adding rest pose for ",c,t,"at slot",s,"This is likely a bug, should have been added earlier.");const p=new Ne(null,c,null);h[0]=p}let d=h[s];d||(Zn&&console.log("Adding padding clip for ",c,t,"at slot",s),d=new Ne(e,c,t),h[s]=d)}const l=new Js(this,e,t);if(this.rootAndClipToRegisteredAnimationMap.set(i,l),Zn&&console.log({root:e,clip:t,info:l}),t){const c=this.rootToRegisteredClip.get(e);if(c?c.push(t):this.rootToRegisteredClip.set(e,[t]),!this.clipToStartTime.get(t)){this.lastClipEndTime==null&&(this.lastClipEndTime=Ne.restPoseClipDuration);let h=this.lastClipEndTime+Ne.animationDurationPadding,d=h+t.duration;const p=Math.round(h*60)/60,g=Math.round(d*60)/60;Math.abs(p-h)<.01&&(h=p),Math.abs(g-d)<.01&&(d=g),h=Math.ceil(h),d=h+t.duration,this.clipToStartTime.set(t,h),this.lastClipEndTime=d}}return l}onAfterHierarchy(e){Zn&&console.log("Animation clips per animation target node",this.dict)}onAfterBuildDocument(e){Zn&&console.log("Animation data",{dict:this.dict,rootTargetMap:this.rootTargetMap,rootToRegisteredClip:this.rootToRegisteredClip});for(const t of this.rootTargetMap.keys()){const i=this.rootTargetMap.get(t);if(!i)continue;let n;const s=[];for(const r of i){const a=this.dict.get(r);if(!a){console.error("No data found for target on USDZ export \u2013 please report a bug!",r);continue}n===void 0&&(n=a?.length),n!==a?.length&&console.error("Different array lengths for targets \u2013 please report a bug!",a);for(let l=0;l<a.length;l++){let c=a[l];if(!c){const d=l-(this.injectRestPoses?1:0);a[l]=new Ne(null,r,this.rootToRegisteredClip.get(t)[d]),c=a[l]}const h=c.getDuration();if(s[l]===void 0)s[l]=h;else if(s[l]!==h){console.error("Error during UDSZ export: Encountered different animation durations for animated targets. Please report a bug!",{datas:a,target:r}),s[l]=h;continue}}}}for(const t of this.serializers){const i=t.model?.parent,n=i?.isDynamic===!0;Yf&&console.log(n,t.model?.parent),n&&t.registerCallback(i)}}onExportObject(e,t,i){x.foreachComponent(e,s=>{const r=s;typeof r.createAnimation=="function"&&r.createAnimation(this,t,i)},!1);const n=new DT(e,this);this.serializers.push(n),n.registerCallback(t)}}class DT{model=void 0;object;animationData;ext;callback;constructor(e,t){this.object=e,this.animationData=t.animationData,this.ext=t}registerCallback(e){this.model&&this.callback&&this.model.removeEventListener("serialize",this.callback),this.callback||(this.callback=this.onSerialize.bind(this)),Yf&&console.log("REPARENT",e),this.model=e,this.callback&&this.model.addEventListener("serialize",this.callback)}skinnedMeshExport(e,t,i){const n=this.model,s=this.animationData;if(n&&n.skinnedMesh){let r=function(I){const V=[];for(const[W,oe]of I){let le=`${W} : [`;const ye=[];for(const Se of oe)ye.push(`(${ae(Se.x)}, ${ae(Se.y)}, ${ae(Se.z)})`);le=le.concat(ye.join(", ")),le=le.concat("],"),V.push(le)}return V},a=function(I){const V=[];for(const[W,oe]of I){let le=`${W} : [`;const ye=[];for(const Se of oe)ye.push(`(${ae(Se.w)}, ${ae(Se.x)}, ${ae(Se.y)}, ${ae(Se.z)})`);le=le.concat(ye.join(", ")),le=le.concat("],"),V.push(le)}return V},l=function(I){let V,W=!0;const oe=new Map;for(const[ye,Se]of I){V===void 0&&(V=Se.length),V!==Se.length&&(W=!1);let St=0;for(const zi of Se)St++,zi||(oe.has(ye)||oe.set(ye,[]),oe.get(ye).push(St))}Zn&&console.log("Bone count: ",I.size,"TransformData entries per bone: ",V,"Undefined bone entries: ",oe),console.assert(W,"All bones should have the same number of TransformData entries",I),console.assert(oe.size===0,"All TransformData entries should be set",oe);const le=[];for(const[ye,Se]of I)for(let St=0;St<Se.length;St++){const zi=Se[St],id=i.getStartTimeByClip(zi.clip);le.length<=St&&le.push({pos:[],rot:[],scale:[],timeOffset:id});const ts=le[St];ts.pos.push(...zi.getSortedTimesArray(!0,!1,!1)),ts.rot.push(...zi.getSortedTimesArray(!1,!0,!1)),ts.scale.push(...zi.getSortedTimesArray(!1,!1,!0))}for(const ye of le)ye.pos.sort((Se,St)=>Se-St),ye.rot.sort((Se,St)=>Se-St),ye.scale.sort((Se,St)=>Se-St),ye.pos=[...new Set(ye.pos)],ye.rot=[...new Set(ye.rot)],ye.scale=[...new Set(ye.scale)];return le},c=function(I,V,W){const oe=new Map,le=new Map,ye=new Map,Se=V.length;for(const St of W){const zi=I.get(St);let id;zi?console.assert(zi.length===Se,"We should have the same number of TransformData entries for each bone",zi,V):id=new Ne(null,St,null);for(let ts=0;ts<Se;ts++){const Zp=zi?zi[ts]:id,pa=V[ts];for(const{time:Dl,translation:Bl}of Zp.getValues(pa.pos,!0,!1,!1)){const dn=(Dl+pa.timeOffset)*60;oe.has(dn)||oe.set(dn,new Array),oe.get(dn).push(Bl.clone())}for(const{time:Dl,rotation:Bl}of Zp.getValues(pa.rot,!1,!0,!1)){const dn=(Dl+pa.timeOffset)*60;le.has(dn)||le.set(dn,new Array),le.get(dn).push(Bl.clone())}for(const{time:Dl,scale:Bl}of Zp.getValues(pa.scale,!1,!1,!0)){const dn=(Dl+pa.timeOffset)*60;ye.has(dn)||ye.set(dn,new Array),ye.get(dn).push(Bl.clone())}}}return{position:oe.size==0?void 0:oe,quaternion:le.size==0?void 0:le,scale:ye.size==0?void 0:ye}},h=function(I){const V=[];for(const W of I)V.push(`(${ae(W.x)}, ${ae(W.y)}, ${ae(W.z)})`);return V.join(", ")},d=function(I){const V=[];for(const W of I)V.push(`(${ae(W.w)}, ${ae(W.x)}, ${ae(W.y)}, ${ae(W.z)})`);return V.join(", ")},p=function(I){const V=new Map;if(Zn){const W=new Array;for(const[oe,le]of s)W.push(oe.uuid+": "+le.length+" "+le.map(ye=>ye.clip?.uuid.substring(0,6)).join(" "));console.log(`getPerBoneTransformData
1259
+ }`}function bx(o){return`(${o.r}, ${o.g}, ${o.b})`}function _x(o){return`(${o.x}, ${o.y})`}const qf=[1023,33777,33778,33779,35842,35843,37496,37808,37809,37810,37811,37812,37813,37814,37815,37816,37817,37818,37819,37820,37821,36492];w("debugusdz");class Et{static global_id=0;id;trigger;action;exclusive=!1;makeExclusive(e){return this.exclusive=e,this}constructor(e,t,i){this.id="Behavior_"+Zi(e)+"_"+Et.global_id++,this.trigger=t,this.action=i}writeTo(e,t,i){if(!this.trigger||!this.action)return;i.beginBlock(`def Preliminary_Behavior "${this.id}"`);let n="";if(Array.isArray(this.trigger)){n="[";for(let s=0;s<this.trigger.length;s++){const r=this.trigger[s];n+="<"+r.id+">",s+1<this.trigger.length&&(n+=", ")}n+="]"}else n=`<${this.trigger.id}>`;if(i.appendLine(`rel triggers = ${n}`),i.appendLine(`rel actions = <${this.action.id}>`),i.appendLine(`uniform bool exclusive = ${this.exclusive?1:0}`),i.appendLine(),Array.isArray(this.trigger))for(const s of this.trigger)s.writeTo(t,i),i.appendLine();else this.trigger.writeTo(t,i);i.appendLine(),this.action.writeTo(t,i),i.closeBlock()}}const nl=new Set;function Xf(o,e){let t="";if(Array.isArray(o)){nl.clear();let i="[ ";for(let n=0;n<o.length;n++){let s=o[n];if(!s){console.warn("Invalid target object in behavior",o+". Is the object exported?");continue}if(typeof s=="string"){if(nl.has(s))continue;i+=s,nl.add(s)}else if(typeof s=="object"){if(s.isObject3D&&(s=e.findById(s.uuid),!s)){console.warn("Invalid target object in behavior",o+". Is the object exported?");continue}const r=s.getPath?.call(s);if(nl.has(r))continue;i+=r,nl.add(r)}n+1<o.length&&(i+=", ")}i+=" ]",t=i,nl.clear()}else if(typeof o=="object"){const i=o;if(i.isObject3D&&(o=e.findById(i.uuid)),!o)throw console.error("Invalid target object in behavior, the target object is likely missing from USDZ export. Is the object exported?",i),new Error(`Invalid target object in behavior, the target object is likely missing from USDZ export. Please report a bug. uuid: ${i.uuid}.`);t=o.getPath?.call(o)}return t}class Xs{static global_id=0;id;targetId;tokenId;type;distance;constructor(e,t){e&&(this.targetId=e),t?this.id=t:this.id="Trigger_"+Xs.global_id++}writeTo(e,t){t.beginBlock(`def Preliminary_Trigger "${this.id}"`),this.targetId&&(typeof this.targetId!="string"&&(this.targetId=Xf(this.targetId,e)),t.appendLine("rel affectedObjects = "+this.targetId)),this.tokenId&&t.appendLine(`token info:id = "${this.tokenId}"`),this.type&&t.appendLine(`token type = "${this.type}"`),typeof this.distance=="number"&&t.appendLine(`double distance = ${this.distance}`),t.closeBlock()}}function vx(o,e={direct:!0,indirect:!0}){const t=it.createEmpty();t.name="InputTarget_"+t.name,t.displayName=void 0,t.type="RealityKitComponent",t.onSerialize=i=>{i.appendLine("bool allowsDirectInput = "+(e.direct?1:0)),i.appendLine("bool allowsIndirectInput = "+(e.indirect?1:0)),i.appendLine('uniform token info:id = "RealityKit.InputTarget"')},o.add(t)}class jt{static __sceneStartTrigger;static sceneStartTrigger(){if(this.__sceneStartTrigger!==void 0)return this.__sceneStartTrigger;const e=new Xs(void 0,"SceneStart");return e.tokenId="SceneTransition",e.type="enter",this.__sceneStartTrigger=e,e}static tapTrigger(e,t={direct:!0,indirect:!0}){const i=new Xs(e);if(Array.isArray(e)&&e.length>1)for(const n of e)n instanceof it&&vx(n,t);else e instanceof it&&vx(e,t);return i.tokenId="TapGesture",i}static isTapTrigger(e){return e?.tokenId==="TapGesture"}static proximityToCameraTrigger(e,t){const i=new Xs(e);return i.tokenId="ProximityToCamera",i.distance=t,i}}class Dr{static global_id=0;static getId(){return this.global_id++}id;actions;loops=0;performCount=1;type="serial";multiplePerformOperation=void 0;constructor(e,t){this.id=e,this.actions=t}addAction(e){return this.actions.push(e),this}makeParallel(){return this.type="parallel",this}makeSequence(){return this.type="serial",this}makeLooping(){return this.loops=1,this.performCount=0,this}makeRepeat(e){return this.performCount=e,this}writeTo(e,t){t.beginBlock(`def Preliminary_Action "${this.id}"`),t.beginArray("rel actions");for(const i of this.actions){if(!i)continue;const n=i===this.actions[this.actions.length-1];t.appendLine("<"+i.id+">"+(n?"":", "))}t.closeArray(),t.appendLine(),t.appendLine('token info:id = "Group"'),t.appendLine(`bool loops = ${this.loops}`),t.appendLine(`int performCount = ${this.loops>0?0:Math.max(0,this.performCount)}`),t.appendLine(`token type = "${this.type}"`),typeof this.multiplePerformOperation=="string"&&t.appendLine(`token multiplePerformOperation = "${this.multiplePerformOperation}"`),t.appendLine();for(const i of this.actions)i&&(i.writeTo(e,t),t.appendLine());t.closeBlock()}}class fi{static global_id=0;id;tokenId;affectedObjects;easeType;motionType=void 0;duration;moveDistance;style;type;front;up;start;animationSpeed;reversed;pingPong;xFormTarget;audio;gain;auralMode;multiplePerformOperation;velocity;comment;animationName;clone(){const e=new fi,t=e.id;return Object.assign(e,this),e.id=t,e}constructor(e,t){e&&(this.affectedObjects=e),t?this.id=t:this.id="Action",this.id+="_"+fi.global_id++}writeTo(e,t){t.beginBlock(`def Preliminary_Action "${this.id}"`),this.comment&&t.appendLine(`# ${this.comment}`),this.affectedObjects&&(typeof this.affectedObjects!="string"&&(this.affectedObjects=Xf(this.affectedObjects,e)),t.appendLine("rel affectedObjects = "+this.affectedObjects)),typeof this.duration=="number"&&(typeof this.animationSpeed=="number"&&this.animationSpeed!==1?t.appendLine(`double duration = ${this.duration/this.animationSpeed} `):t.appendLine(`double duration = ${this.duration} `)),this.easeType&&t.appendLine(`token easeType = "${this.easeType}"`),this.tokenId&&t.appendLine(`token info:id = "${this.tokenId}"`),this.tokenId==="ChangeScene"&&t.appendLine("rel scene = </StageRoot/Scenes/Scene>"),this.motionType!==void 0&&t.appendLine(`token motionType = "${this.motionType}"`),typeof this.moveDistance=="number"&&t.appendLine(`double moveDistance = ${this.moveDistance} `),this.style&&t.appendLine(`token style = "${this.style}"`),this.type&&t.appendLine(`token type = "${this.type}"`),this.front&&t.appendLine(`vector3d front = (${this.front.x}, ${this.front.y}, ${this.front.z})`),this.up&&t.appendLine(`vector3d upVector = (${this.up.x}, ${this.up.y}, ${this.up.z})`),typeof this.start=="number"&&t.appendLine(`double start = ${this.start} `),typeof this.animationSpeed=="number"&&t.appendLine(`double animationSpeed = ${this.animationSpeed.toFixed(2)} `),typeof this.reversed=="boolean"&&t.appendLine(`bool reversed = ${this.reversed}`),typeof this.pingPong=="boolean"&&t.appendLine(`bool reverses = ${this.pingPong}`),this.xFormTarget&&(typeof this.xFormTarget!="string"&&(this.xFormTarget=Xf(this.xFormTarget,e)),t.appendLine(`rel xformTarget = ${this.xFormTarget}`)),typeof this.audio=="string"&&t.appendLine(`asset audio = @${this.audio}@`),typeof this.gain=="number"&&t.appendLine(`double gain = ${this.gain}`),typeof this.auralMode=="string"&&t.appendLine(`token auralMode = "${this.auralMode}"`),typeof this.multiplePerformOperation=="string"&&t.appendLine(`token multiplePerformOperation = "${this.multiplePerformOperation}"`),typeof this.velocity=="object"&&t.appendLine(`vector3d velocity = (${this.velocity.x}, ${this.velocity.y}, ${this.velocity.z})`),t.closeBlock()}}class hn{x=0;y=0;z=0;constructor(e,t,i){this.x=e,this.y=t,this.z=i}static get up(){return new hn(0,1,0)}static get right(){return new hn(1,0,0)}static get forward(){return new hn(0,0,1)}static get back(){return new hn(0,0,-1)}static get zero(){return new hn(0,0,0)}}class me{static sequence(...e){return new Dr("Group_"+Dr.getId(),e).makeSequence()}static parallel(...e){return new Dr("Group_"+Dr.getId(),e).makeParallel()}static fadeAction(e,t,i){const n=new fi(e);return n.tokenId="Visibility",n.type=i?"show":"hide",n.duration=t,n.style="basic",n.motionType="none",n.moveDistance=0,n.easeType="none",n}static startAnimationAction(e,t,i=!1,n=!1){const s=new fi(e);s.tokenId="StartAnimation";const r=t.start,a=t.duration,l=t.speed,c=t.clipName;if(s.comment=`Animation: ${c}, start=${r*60}, length=${a*60}, end=${(r+a)*60}`,s.animationName=c,s.start=r,s.duration=a,s.animationSpeed=l,s.reversed=i,s.pingPong=n,s.multiplePerformOperation="allow",i&&(s.start-=a),n){s.pingPong=!1;const h=s.clone();return h.reversed=!i,h.start=s.start,h.reversed&&(h.start-=a),me.sequence(s,h)}return s}static waitAction(e){const t=new fi;return t.tokenId="Wait",t.duration=e,t.motionType=void 0,t}static lookAtCameraAction(e,t,i,n){const s=new fi(e);return s.tokenId="LookAtCamera",s.duration=t===void 0?9999999999999:t,s.front=i??hn.forward,s.up=n??hn.up,s}static emphasize(e,t,i="bounce",n=1,s="basic"){const r=new fi(e);return r.tokenId="Emphasize",r.duration=t,r.style=s??"basic",r.motionType=i,r.moveDistance=n,r}static transformAction(e,t,i,n,s="inout"){const r=new fi(e);return r.tokenId="Transform",r.duration=i,r.duration=Math.max(1e-6,i),r.type=n,r.easeType=i>0?s:"none",Array.isArray(t)&&console.error("Transform target must not be an array",t),r.xFormTarget=t,r}static playAudioAction(e,t,i="play",n=1,s="spatial"){const r=new fi(e);return r.tokenId="Audio",r.type=i,r.audio=t,r.gain=n,r.auralMode=s,r.multiplePerformOperation="allow",r}static impulseAction(e,t){const i=new fi(e);return i.tokenId="Impulse",i.velocity=t,i}}class jT{get id(){return this.object.uuid}object;model;constructor(e){this.object=e}apply(e){if(!this.model&&(this.model=e.findById(this.object.uuid),!this.model)){console.error("could not find model with id "+this.object.uuid);return}this.onApply(e)}}class Qf extends jT{constructor(e,t,i,n){super(e),this.matrix=t,this.material=i,this.geometry=n}matrix;material;geometry;onApply(e){const t=this.model;if(!t)return;t.parent?.isDynamic||it.createEmptyParent(t);const i=t.clone();this.matrix&&i.setMatrix(this.matrix),this.material&&(i.material=this.material),this.geometry&&(i.geometry=this.geometry),t.parent?.add(i)}_enableAction;_disableAction;enable(){return this._enableAction?this._enableAction:(this._enableAction=me.fadeAction(this.object,0,!0),this._enableAction)}disable(){return this._disableAction?this._disableAction:(this._disableAction=me.fadeAction(this.object,0,!1),this._disableAction)}}class wx{actions;sortedActions;constructor(e){this.actions=[...e]}organize(){this.sortedActions={};for(const e of this.actions){const t=e.id;this.sortedActions[t]||(this.sortedActions[t]=[]),this.sortedActions[t].push(e)}}getActions(e){return this.sortedActions||this.organize(),this.sortedActions[e.uuid]}}const Zn=w("debugusdzanimation"),Yf=w("debugusdzanimationserialization");class Js{_start;get start(){return this._start===void 0&&(this._start=this.ext.getStartTimeByClip(this.clip)),this._start}get duration(){return this.clip?.duration??Ne.restPoseClipDuration}get nearestAnimatedRoot(){return this._nearestAnimatedRoot}get clipName(){return this.clip?.name??"rest"}ext;root;_nearestAnimatedRoot=void 0;clip;speed;constructor(e,t,i){this.ext=e,this.root=t,this.clip=i,this._nearestAnimatedRoot=this.getNearestAnimatedRoot()}static isDescendantOf(e,t){let i=t;if(!i||!e)return!1;for(;i;){if(!i)return!1;if(i===e)return!0;i=i.parent}return!1}getNearestAnimatedRoot(){let e;try{for(const t of this.clip?.tracks??[]){const i=fa.parseTrackName(t.name);let n=fa.findNode(this.root,i.nodeName);if(n)if(!e)e=n;else{if(n===e||Js.isDescendantOf(e,n))continue;if(!Js.isDescendantOf(n,e)){for(;!Js.isDescendantOf(n,e)&&n.parent;)n=n.parent;Js.isDescendantOf(n,e)||console.error("USDZExporter: Animation clip targets multiple roots that are not parent/child. Please report a bug",this.root,this.clip,e,n)}e=n}}}catch(t){console.error("USDZExporter: Exception when trying to find nearest animated root. Please report a bug",t),e=void 0}return e}}class Ne{clip;pos;rot;scale;root;target;duration=0;useRootMotion=!1;static frameRate=60;static animationDurationPadding=6/60;static restPoseClipDuration=6/60;constructor(e,t,i){if(this.root=e,this.target=t,this.clip=i,i?this.duration=i.duration:this.duration=Ne.restPoseClipDuration,i&&i.tracks){const s=Math.max(...i.tracks.map(r=>r.times[r.times.length-1]));s!==this.duration&&(console.warn("USDZExporter: Animation clip duration does not match the maximum time value in the tracks.",i,s,this.duration),this.duration=s)}const n=x.getComponent(e,ft);n&&(this.useRootMotion=n.applyRootMotion)}addTrack(e){if(!this.clip){console.error("This is a rest clip but you're trying to add tracks to it \u2013 this is likely a bug");return}e.name.endsWith("position")?this.pos=e:e.name.endsWith("quaternion")?this.rot=e:e.name.endsWith("scale")?this.scale=e:(e.name.endsWith("activeSelf")?console.warn("[USDZ] Animation of enabled/disabled state is not supported for USDZ export and will NOT be exported: "+e.name+" on "+(this.root?.name??this.target.name)+". Animate scale 0/1 instead."):console.warn("[USDZ] Animation track type not supported for USDZ export and will NOT be exported: "+e.name+" on "+(this.root?.name??this.target.name)+". Only .position, .rotation, .scale are supported."),E()&&ge("[USDZ] Some animations can't be exported. See console for details."))}getFrames(){return this.clip?Math.max(this.pos?.times?.length??0,this.rot?.times?.length??0,this.scale?.times?.length??0):2}getDuration(){return this.duration}getSortedTimesArray(e=!0,t=!0,i=!0){if(!this.clip)return[0,this.duration];const n=this.pos?.times,s=this.rot?.times,r=this.scale?.times,a=[];if(e&&n)for(const l of n)a.push(l);if(t&&s)for(const l of s)a.push(l);if(i&&r)for(const l of r)a.push(l);return a.includes(0)||a.push(0),a.sort((l,c)=>l-c),[...new Set(a)]}*getValues(e,t=!0,i=!0,n=!0){const s=new b,r=new U,a=new b(1,1,1),l=this.target,c=t?this.pos?.createInterpolant():void 0,h=i?this.rot?.createInterpolant():void 0,d=n?this.scale?.createInterpolant():void 0;c||s.set(l.position.x,l.position.y,l.position.z),h||r.set(l.quaternion.x,l.quaternion.y,l.quaternion.z,l.quaternion.w),d||a.set(l.scale.x,l.scale.y,l.scale.z),c&&c.valueSize!==3&&(c.valueSize=3),h&&h.valueSize!==4&&(h.valueSize=4),d&&d.valueSize!==3&&(d.valueSize=3);const p=0;for(let m=0-p;m<e.length+p;m++){let f=0,g=0;if(m<0?(f=e[0],g=f-Ne.animationDurationPadding/2+1/60):m>=e.length?(f=e[e.length-1],g=f+Ne.animationDurationPadding/2-1/60):(f=e[m],g=f),c){const y=c.evaluate(f);s.set(y[0],y[1],y[2])}if(h){const y=h.evaluate(f);r.set(y[0],y[1],y[2],y[3])}if(d){const y=d.evaluate(f);a.set(y[0],y[1],y[2])}if(this.useRootMotion&&l===this.root){const y=new ee;y.compose(s,r,a),y.multiply(l.matrix),y.decompose(s,r,a)}yield{time:g,translation:s,rotation:r,scale:a,index:m}}}}class Gu{get extensionName(){return"animation"}get animationData(){return this.dict}get registeredClips(){return this.clipToStartTime.keys()}get animatedRoots(){return this.rootTargetMap.keys()}get holdClipMap(){return this.clipToHoldClip}dict=new Map;rootTargetMap=new Map;rootAndClipToRegisteredAnimationMap=new Map;rootToRegisteredClip=new Map;lastClipEndTime=0;clipToStartTime=new Map;clipToHoldClip=new Map;serializers=[];injectRestPoses=!1;injectImplicitBehaviours=!1;constructor(e){this.injectRestPoses=e,this.injectImplicitBehaviours=e}getStartTimeCode(){return!this.injectRestPoses||this.rootAndClipToRegisteredAnimationMap.size===0?0:(Ne.restPoseClipDuration+Ne.animationDurationPadding)*60}getEndTimeCode(){let e=0;for(const[t,i]of this.rootAndClipToRegisteredAnimationMap){const n=i.start+i.duration;n>e&&(e=n)}return e*60}getClipCount(e){return this.rootToRegisteredClip.get(e)?.length??0??0}getStartTimeByClip(e){return e?this.clipToStartTime.has(e)?this.clipToStartTime.get(e):(console.error("USDZExporter: Missing start time for clip \u2013 please report a bug.",e),0):0}registerAnimation(e,t){if(!e)return null;this.rootTargetMap.has(e)||this.rootTargetMap.set(e,[]);const i=e.uuid+(t?.uuid??"-rest");if(this.rootAndClipToRegisteredAnimationMap.has(i))return this.rootAndClipToRegisteredAnimationMap.get(i);Zn&&console.log("registerAnimation",e,t);const n=this.injectRestPoses?1:0,s=(this.rootToRegisteredClip.get(e)?.length??0)+n,r=this.rootTargetMap.get(e),a=new Set(r);if(t&&t.tracks)for(const c of t.tracks){const h=fa.parseTrackName(c.name),d=fa.findNode(e,h.nodeName);if(!d){console.warn("no object found for track",c.name,"using "+e.name+" instead");continue}this.dict.has(d)||this.dict.set(d,[]);const p=this.dict.get(d);if(!p){console.warn("no transform data found for target ",d,"at slot "+s+", this is likely a bug");continue}a.delete(d),this.injectRestPoses&&!p[0]&&(console.log("Injecting rest pose",d,t,"at slot",s),p[0]=new Ne(null,d,null));let m=p[s];m||(m=new Ne(e,d,t),p[s]=m),m.addTrack(c),r?.includes(d)||r?.push(d)}Zn&&console.log("Unregistered nodes for this clip",a,"clip",t,"at slot",s,"for root",e,"targets",r);for(const c of a){const h=this.dict.get(c);if(!h)continue;if(this.injectRestPoses&&!h[0]){console.warn("Adding rest pose for ",c,t,"at slot",s,"This is likely a bug, should have been added earlier.");const p=new Ne(null,c,null);h[0]=p}let d=h[s];d||(Zn&&console.log("Adding padding clip for ",c,t,"at slot",s),d=new Ne(e,c,t),h[s]=d)}const l=new Js(this,e,t);if(this.rootAndClipToRegisteredAnimationMap.set(i,l),Zn&&console.log({root:e,clip:t,info:l}),t){const c=this.rootToRegisteredClip.get(e);if(c?c.push(t):this.rootToRegisteredClip.set(e,[t]),!this.clipToStartTime.get(t)){this.lastClipEndTime==null&&(this.lastClipEndTime=Ne.restPoseClipDuration);let h=this.lastClipEndTime+Ne.animationDurationPadding,d=h+t.duration;const p=Math.round(h*60)/60,m=Math.round(d*60)/60;Math.abs(p-h)<.01&&(h=p),Math.abs(m-d)<.01&&(d=m),h=Math.ceil(h),d=h+t.duration,this.clipToStartTime.set(t,h),this.lastClipEndTime=d}}return l}onAfterHierarchy(e){Zn&&console.log("Animation clips per animation target node",this.dict)}onAfterBuildDocument(e){Zn&&console.log("Animation data",{dict:this.dict,rootTargetMap:this.rootTargetMap,rootToRegisteredClip:this.rootToRegisteredClip});for(const t of this.rootTargetMap.keys()){const i=this.rootTargetMap.get(t);if(!i)continue;let n;const s=[];for(const r of i){const a=this.dict.get(r);if(!a){console.error("No data found for target on USDZ export \u2013 please report a bug!",r);continue}n===void 0&&(n=a?.length),n!==a?.length&&console.error("Different array lengths for targets \u2013 please report a bug!",a);for(let l=0;l<a.length;l++){let c=a[l];if(!c){const d=l-(this.injectRestPoses?1:0);a[l]=new Ne(null,r,this.rootToRegisteredClip.get(t)[d]),c=a[l]}const h=c.getDuration();if(s[l]===void 0)s[l]=h;else if(s[l]!==h){console.error("Error during UDSZ export: Encountered different animation durations for animated targets. Please report a bug!",{datas:a,target:r}),s[l]=h;continue}}}}for(const t of this.serializers){const i=t.model?.parent,n=i?.isDynamic===!0;Yf&&console.log(n,t.model?.parent),n&&t.registerCallback(i)}}onExportObject(e,t,i){x.foreachComponent(e,s=>{const r=s;typeof r.createAnimation=="function"&&r.createAnimation(this,t,i)},!1);const n=new DT(e,this);this.serializers.push(n),n.registerCallback(t)}}class DT{model=void 0;object;animationData;ext;callback;constructor(e,t){this.object=e,this.animationData=t.animationData,this.ext=t}registerCallback(e){this.model&&this.callback&&this.model.removeEventListener("serialize",this.callback),this.callback||(this.callback=this.onSerialize.bind(this)),Yf&&console.log("REPARENT",e),this.model=e,this.callback&&this.model.addEventListener("serialize",this.callback)}skinnedMeshExport(e,t,i){const n=this.model,s=this.animationData;if(n&&n.skinnedMesh){let r=function(I){const V=[];for(const[W,oe]of I){let le=`${W} : [`;const ye=[];for(const Se of oe)ye.push(`(${ae(Se.x)}, ${ae(Se.y)}, ${ae(Se.z)})`);le=le.concat(ye.join(", ")),le=le.concat("],"),V.push(le)}return V},a=function(I){const V=[];for(const[W,oe]of I){let le=`${W} : [`;const ye=[];for(const Se of oe)ye.push(`(${ae(Se.w)}, ${ae(Se.x)}, ${ae(Se.y)}, ${ae(Se.z)})`);le=le.concat(ye.join(", ")),le=le.concat("],"),V.push(le)}return V},l=function(I){let V,W=!0;const oe=new Map;for(const[ye,Se]of I){V===void 0&&(V=Se.length),V!==Se.length&&(W=!1);let St=0;for(const zi of Se)St++,zi||(oe.has(ye)||oe.set(ye,[]),oe.get(ye).push(St))}Zn&&console.log("Bone count: ",I.size,"TransformData entries per bone: ",V,"Undefined bone entries: ",oe),console.assert(W,"All bones should have the same number of TransformData entries",I),console.assert(oe.size===0,"All TransformData entries should be set",oe);const le=[];for(const[ye,Se]of I)for(let St=0;St<Se.length;St++){const zi=Se[St],id=i.getStartTimeByClip(zi.clip);le.length<=St&&le.push({pos:[],rot:[],scale:[],timeOffset:id});const ts=le[St];ts.pos.push(...zi.getSortedTimesArray(!0,!1,!1)),ts.rot.push(...zi.getSortedTimesArray(!1,!0,!1)),ts.scale.push(...zi.getSortedTimesArray(!1,!1,!0))}for(const ye of le)ye.pos.sort((Se,St)=>Se-St),ye.rot.sort((Se,St)=>Se-St),ye.scale.sort((Se,St)=>Se-St),ye.pos=[...new Set(ye.pos)],ye.rot=[...new Set(ye.rot)],ye.scale=[...new Set(ye.scale)];return le},c=function(I,V,W){const oe=new Map,le=new Map,ye=new Map,Se=V.length;for(const St of W){const zi=I.get(St);let id;zi?console.assert(zi.length===Se,"We should have the same number of TransformData entries for each bone",zi,V):id=new Ne(null,St,null);for(let ts=0;ts<Se;ts++){const Zp=zi?zi[ts]:id,pa=V[ts];for(const{time:Dl,translation:Bl}of Zp.getValues(pa.pos,!0,!1,!1)){const dn=(Dl+pa.timeOffset)*60;oe.has(dn)||oe.set(dn,new Array),oe.get(dn).push(Bl.clone())}for(const{time:Dl,rotation:Bl}of Zp.getValues(pa.rot,!1,!0,!1)){const dn=(Dl+pa.timeOffset)*60;le.has(dn)||le.set(dn,new Array),le.get(dn).push(Bl.clone())}for(const{time:Dl,scale:Bl}of Zp.getValues(pa.scale,!1,!1,!0)){const dn=(Dl+pa.timeOffset)*60;ye.has(dn)||ye.set(dn,new Array),ye.get(dn).push(Bl.clone())}}}return{position:oe.size==0?void 0:oe,quaternion:le.size==0?void 0:le,scale:ye.size==0?void 0:ye}},h=function(I){const V=[];for(const W of I)V.push(`(${ae(W.x)}, ${ae(W.y)}, ${ae(W.z)})`);return V.join(", ")},d=function(I){const V=[];for(const W of I)V.push(`(${ae(W.w)}, ${ae(W.x)}, ${ae(W.y)}, ${ae(W.z)})`);return V.join(", ")},p=function(I){const V=new Map;if(Zn){const W=new Array;for(const[oe,le]of s)W.push(oe.uuid+": "+le.length+" "+le.map(ye=>ye.clip?.uuid.substring(0,6)).join(" "));console.log(`getPerBoneTransformData
1260
1260
  `+W.join(`
1261
- `))}for(const W of I){const oe=s.get(W);oe&&V.set(W,oe)}return V},g=function(I){const V=p(I),W=l(V);return c(V,W,I)};const f=n.skinnedMesh.skeleton,m=new Array,y=[],_=[];for(const I of f.bones){y.push(I),_.push(I.uuid);const V=f.boneInverses[f.bones.indexOf(I)];m.push({bone:I,inverse:V})}let v=1e4;for(;_.length<f.bones.length&&v-- >0;)for(const I of y){const V=I.children;for(const W of V)if(_.indexOf(W.uuid)===-1&&f.bones.indexOf(W)!==-1){y.push(W),_.push(W.uuid);const oe=f.boneInverses[f.bones.indexOf(W)];m.push({bone:W,inverse:oe})}}v<=0&&console.error("Failed to sort bones in skinned mesh",n.skinnedMesh,f.bones,_);for(const I of ox(f.bones))m.push({bone:I,inverse:I.matrixWorld.clone().invert()});const P=m[0].bone.parent;P||console.error("No bone parent found for skinned mesh during USDZ export",n.skinnedMesh),m.sort((I,V)=>il(I.bone,P)>il(V.bone,P)?1:-1);const R=t.quickLookCompatible,k=[],A=[],L=[],N=[];for(const{bone:I}of m){if(R){const V=I.scale;V.x==0&&(V.x=1e-5),V.y==0&&(V.y=1e-5),V.z==0&&(V.z=1e-5),k.push(new ee().compose(I.position,I.quaternion,I.scale))}else k.push(I.matrix.clone());A.push(I.position),L.push(I.quaternion),N.push(I.scale)}const j=m.map(I=>'"'+il(I.bone,P)+'"').join(", "),q=m.map(I=>gx(I.inverse.clone().invert())).join(", ");e.beginBlock('def Skeleton "Rig"'),e.appendLine(`uniform matrix4d[] bindTransforms = [${q}]`),e.appendLine(`uniform token[] joints = [${j}]`),e.appendLine('uniform token purpose = "guide"'),e.appendLine(`uniform matrix4d[] restTransforms = [${k.map(I=>gx(I)).join(", ")}]`);const Y=g(m.map(I=>I.bone));if(Zn){let I=1e7,V=0;for(const W of Y.position?.keys()??[])I=Math.min(I,W),V=Math.max(V,W);console.log("Time samples",I,V,Y)}if(e.beginBlock('def SkelAnimation "_anim"'),e.appendLine(`uniform token[] joints = [${j}]`),e.appendLine(`quatf[] rotations = [${d(L)}]`),Y&&Y.quaternion){e.beginBlock("quatf[] rotations.timeSamples = {","");const I=a(Y.quaternion);for(const V of I)e.appendLine(V);e.closeBlock()}if(e.appendLine(`half3[] scales = [${h(N)}]`),Y&&Y.scale){e.beginBlock("half3[] scales.timeSamples = {","");const I=r(Y.scale);for(const V of I)e.appendLine(V);e.closeBlock()}if(e.appendLine(`float3[] translations = [${h(A)}]`),Y&&Y.position){e.beginBlock("float3[] translations.timeSamples = {","");const I=r(Y.position);for(const V of I)e.appendLine(V);e.closeBlock()}e.closeBlock(),e.closeBlock()}}onSerialize(e,t){if(!this.model)return;const i=this.animationData.get(this.object);if(i)for(let h=0;h<i.length;h++)i[h]===void 0&&(i[h]=new Ne(null,this.object,null));const n=this.ext;this.skinnedMeshExport(e,t,n);const s=this.object,r=this.model,a=this.animationData.get(s);if(!a||s.isSkinnedMesh)return;Yf&&console.log("SERIALIZE",this.model.name,this.object.type,a);const l=Intl.NumberFormat("en-US",{maximumFractionDigits:3,minimumFractionDigits:0,useGrouping:!1});function c(h,d){if(h.some(p=>p&&{position:p.pos,rotation:p.rot,scale:p.scale}[d])){switch(d){case"position":r.needsTranslate=!0,e.beginBlock("double3 xformOp:translate.timeSamples = {","");break;case"rotation":r.needsOrient=!0,e.beginBlock("quatf xformOp:orient.timeSamples = {","");break;case"scale":r.needsScale=!0,e.beginBlock("double3 xformOp:scale.timeSamples = {","");break}for(let p=0;p<h.length;p++){const g=h[p];if(!g)continue;const f=n.getStartTimeByClip(g.clip),m=g.getSortedTimesArray(d==="position",d==="rotation",d==="scale");if(!m||m.length===0){console.error("got an animated object but no time values?",s,g);continue}const y=!g.clip,_=d==="position"&&(g.pos||y),v=d==="rotation"&&(g.rot||y),P=d==="scale"&&(g.scale||y);if(_||v||P){const R=g.clip?.name??"rest",k=g.getDuration();Zn&&console.log("Write .timeSamples:",R,f,k,h),e.appendLine("# "+R+": start="+l.format(f*Ne.frameRate)+", length="+l.format(k*Ne.frameRate)+", frames="+g.getFrames())}if(_)for(const{time:R,translation:k}of g.getValues(m,!0,!1,!1)){const A=`${l.format((f+R)*Ne.frameRate)}: (${ae(k.x)}, ${ae(k.y)}, ${ae(k.z)}),`;e.appendLine(A)}if(v)for(const{time:R,rotation:k}of g.getValues(m,!1,!0,!1)){const A=`${l.format((f+R)*Ne.frameRate)}: (${ae(k.w)}, ${ae(k.x)}, ${ae(k.y)}, ${ae(k.z)}),`;e.appendLine(A)}if(P)for(const{time:R,scale:k}of g.getValues(m,!1,!1,!0)){const A=`${l.format((f+R)*Ne.frameRate)}: (${ae(k.x)}, ${ae(k.y)}, ${ae(k.z)}),`;e.appendLine(A)}}e.closeBlock()}}c(a,"position"),c(a,"rotation"),c(a,"scale")}}const BT=w("debugusdz");class aa{static getName(e){const t=e.split(".").pop();let i=e.split(".").slice(0,-1).join(".").split("/").pop()?.replace(".","_");return i||(i="Audio_"+Math.random().toString(36).substring(2,15)),Zi(i)+"."+t}get extensionName(){return"Audio"}files=new Array;onExportObject(e,t,i){const n=x.getComponents(e,Mi);if(n.length)for(const s of n){if(!s.clip||typeof s.clip!="string"||!s.playOnAwake)continue;const r=s.clip.split("/").pop()||"Audio",a=aa.getName(s.clip),l=Zi(a);if(!this.files.some(c=>c.path===s.clip)){this.files.push({path:s.clip,name:a});const c=a.toLowerCase();i.quickLookCompatible&&!c.endsWith(".mp3")&&!c.endsWith(".wav")&&!c.endsWith(".m4a")&&console.error("Audio file "+s.clip+" from "+s.name+" is not an MP3 or WAV file. QuickLook may not support playing it.")}i.quickLookCompatible||t.addEventListener("serialize",(c,h)=>{c.appendLine(),c.beginBlock(`def SpatialAudio "${l}"`,"(",!1),c.appendLine(`displayName = "${r}"`),c.closeBlock(")"),c.beginBlock(),c.appendLine(`uniform asset filePath = @audio/${a}@`),c.appendLine(`uniform token auralMode = "${s.spatialBlend>0?"spatial":"nonSpatial"}"`),c.appendLine(`uniform token playbackMode = "${s.loop?"loopFromStage":"onceFromStart"}"`),c.appendLine(`uniform float gain = ${s.volume}`),c.closeBlock()})}}async onAfterSerialize(e){for(const t of this.files){const i="audio/"+t.name;if(e.files[i]){BT&&console.warn("Audio file with name "+i+" already exists in the context. Skipping.");continue}const n=await(await(await fetch(t.path)).blob()).arrayBuffer(),s=new Uint8Array(n);e.files[i]=s}}}var FT=Object.defineProperty,Be=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&FT(e,t,n),n};const xx=w("debugusdzbehaviours");function Uc(o){o&&(o.getComponentInParent(Wa)||(E()&&console.debug('Raycaster on "'+o.name+'" was automatically added, because no raycaster was found in the parent hierarchy.'),o.addComponent(ki)))}class Br extends M{object;target;duration=1;relativeMotion=!1;coroutine=null;targetPos=new b;targetRot=new U;targetScale=new b;start(){Uc(this.gameObject)}onPointerClick(e){e.use(),this.coroutine&&this.stopCoroutine(this.coroutine),this.relativeMotion?this.coroutine=this.startCoroutine(this.moveRelative()):this.coroutine=this.startCoroutine(this.moveToTarget())}*moveToTarget(){if(!this.target||!this.object)return;const e=Z(this.object).clone(),t=Z(this.target).clone(),i=be(this.object).clone(),n=be(this.target).clone(),s=$e(this.object).clone(),r=$e(this.target).clone(),a=e.distanceTo(t),l=i.angleTo(n),c=s.distanceTo(r);if(a<.01&&l<.01&&c<.01){mt(this.object,t),pn(this.object,n),wa(this.object,r),this.coroutine=null;return}let h=0,d=0;for(;h<1;)h+=this.context.time.deltaTime/this.duration,h>1&&(h=1),d=h<.5?4*h*h*h:1-Math.pow(-2*h+2,3)/2,this.targetPos.lerpVectors(e,t,d),this.targetRot.slerpQuaternions(i,n,d),this.targetScale.lerpVectors(s,r,d),mt(this.object,this.targetPos),pn(this.object,this.targetRot),wa(this.object,this.targetScale),yield;this.coroutine=null}*moveRelative(){if(!this.target||!this.object)return;const e=this.object.position.clone(),t=this.object.quaternion.clone(),i=this.object.scale.clone(),n=this.target.position.clone(),s=this.target.quaternion.clone(),r=this.target.scale.clone();n.applyQuaternion(this.object.quaternion),this.targetPos.copy(this.object.position).add(n),this.targetRot.copy(this.object.quaternion).multiply(s),this.targetScale.copy(this.object.scale).multiply(r);let a=0,l=0;for(;a<1;)a+=this.context.time.deltaTime/this.duration,a>1&&(a=1),l=a<.5?4*a*a*a:1-Math.pow(-2*a+2,3)/2,this.object.position.lerpVectors(e,this.targetPos,l),this.object.quaternion.slerpQuaternions(t,this.targetRot,l),this.object.scale.lerpVectors(i,this.targetScale,l),yield;this.coroutine=null}beforeCreateDocument(e){if(this.target&&this.object&&this.gameObject){const t=new Et("Move to "+this.target?.name,jt.tapTrigger(this.gameObject),me.transformAction(this.object,this.target,this.duration,this.relativeMotion?"relative":"absolute"));e.addBehavior(t)}}}Be([u(O)],Br.prototype,"object"),Be([u(O)],Br.prototype,"target"),Be([u()],Br.prototype,"duration"),Be([u()],Br.prototype,"relativeMotion");const qu=class Zt extends M{materialToSwitch;variantMaterial;fadeDuration=0;start(){this._objectsWithThisMaterial=this.objectsWithThisMaterial,Uc(this.gameObject),E()&&this._objectsWithThisMaterial.length<=0&&console.warn('ChangeMaterialOnClick: No objects found with material "'+this.materialToSwitch?.name+'"')}onPointerEnter(e){this.context.input.setCursor("pointer")}onPointerExit(e){this.context.input.unsetCursor("pointer")}onPointerClick(e){if(e.use(),!!this.variantMaterial)for(let t=0;t<this.objectsWithThisMaterial.length;t++){const i=this.objectsWithThisMaterial[t];i.material=this.variantMaterial}}_objectsWithThisMaterial=null;get objectsWithThisMaterial(){return this._objectsWithThisMaterial!=null?this._objectsWithThisMaterial:(this._objectsWithThisMaterial=[],this.variantMaterial&&this.materialToSwitch&&this.context.scene.traverse(e=>{if(e instanceof H)if(Array.isArray(e.material)){for(const t of e.material)if(t===this.materialToSwitch){this.objectsWithThisMaterial.push(e);break}}else e.material===this.materialToSwitch?this.objectsWithThisMaterial.push(e):iv(e.material,this.materialToSwitch)&&this.objectsWithThisMaterial.push(e)}),this._objectsWithThisMaterial)}selfModel;targetModels;static _materialTriggersPerId={};static _startHiddenBehaviour=null;static _parallelStartHiddenActions=[];async beforeCreateDocument(e,t){this.targetModels=[],Zt._materialTriggersPerId={},Zt.variantSwitchIndex=0,this.materialToSwitch&&await Ve.assignTextureLOD(this.materialToSwitch,0),this.variantMaterial&&await Ve.assignTextureLOD(this.variantMaterial,0)}createBehaviours(e,t,i){this.objectsWithThisMaterial.find(n=>n.uuid===t.uuid)&&this.targetModels.push(t),this.gameObject.uuid===t.uuid&&(this.selfModel=t,this.materialToSwitch&&(Zt._materialTriggersPerId[this.materialToSwitch.uuid]||(Zt._materialTriggersPerId[this.materialToSwitch.uuid]=[]),Zt._materialTriggersPerId[this.materialToSwitch.uuid].push(this)))}afterCreateDocument(e,t){if(!this.materialToSwitch)return;const i=Zt._materialTriggersPerId[this.materialToSwitch.uuid];if(i){const n={};for(const s of i){const r=s.createVariants();r&&r.length>0&&(n[s.selfModel.uuid]=r)}for(const s of i){const r=[];for(const a in n)a!==s.selfModel.uuid&&r.push(...n[a]);s.createAndAttachBehaviors(e,n[s.selfModel.uuid],r)}}delete Zt._materialTriggersPerId[this.materialToSwitch.uuid]}createAndAttachBehaviors(e,t,i){const n=[],s=Math.max(0,this.fadeDuration);n.push(me.fadeAction([...this.targetModels,...i],s,!1)),n.push(me.fadeAction(t,s,!0)),e.addBehavior(new Et("Select_"+this.selfModel.name,jt.tapTrigger(this.selfModel),me.parallel(...n))),Zt._parallelStartHiddenActions.push(...t),Zt._startHiddenBehaviour||(Zt._startHiddenBehaviour=new Et("StartHidden_"+this.selfModel.name,jt.sceneStartTrigger(),me.fadeAction(Zt._parallelStartHiddenActions,s,!1)),e.addBehavior(Zt._startHiddenBehaviour))}static getMaterialName(e){return Zi(e.name||"Material")+"_"+e.id}static variantSwitchIndex=0;createVariants(){if(!this.variantMaterial)return null;const e=[];for(const t of this.targetModels){const i=t.clone();i.name+="_Variant_"+Zt.variantSwitchIndex+++"_"+Zt.getMaterialName(this.variantMaterial),i.displayName=i.displayName+": Variant with material "+this.variantMaterial.name,i.material=this.variantMaterial,i.geometry=t.geometry,i.transform=t.transform,(!t.parent||!t.parent.isEmpty())&&it.createEmptyParent(t),t.parent&&t.parent.add(i),e.push(i)}return e}};Be([u(ve)],qu.prototype,"materialToSwitch"),Be([u(ve)],qu.prototype,"variantMaterial"),Be([u()],qu.prototype,"fadeDuration");let Kf=qu;const zc=class ze extends M{target;toggleOnClick=!1;targetState=!0;hideSelf=!0;start(){Uc(this.gameObject)}onPointerClick(e){e.use(),!this.toggleOnClick&&this.hideSelf&&(this.gameObject.visible=!1),this.target&&(this.target.visible=this.toggleOnClick?!this.target.visible:this.targetState)}selfModel;selfModelClone;targetModel;toggleModel;createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&(this.selfModel=t,this.selfModelClone=t.clone())}stateBeforeCreatingDocument=!1;targetStateBeforeCreatingDocument=!1;static clonedToggleIndex=0;static wasVisible=Symbol("usdz_SetActiveOnClick_wasVisible");static toggleClone=Symbol("clone for toggling");static reverseToggleClone=Symbol("clone for reverse toggling");beforeCreateDocument(){this.target&&(this.gameObject[ze.wasVisible]===void 0&&(this.gameObject[ze.wasVisible]=this.gameObject.activeSelf),this.target[ze.wasVisible]===void 0&&(this.target[ze.wasVisible]=this.target.activeSelf),this.stateBeforeCreatingDocument=this.gameObject[ze.wasVisible],this.targetStateBeforeCreatingDocument=this.target[ze.wasVisible],this.gameObject.visible=!0,this.target.visible=!0)}afterCreateDocument(e,t){if(!this.target)return;this.targetModel=t.document.findById(this.target.uuid);const i=this.selfModel;if(this.selfModel&&this.targetModel){let n=this.selfModel,s=this.targetState;if(this.toggleOnClick)if(s=!this.targetStateBeforeCreatingDocument,!this.selfModelClone.geometry)(!this.selfModel.parent||this.selfModel.parent.isEmpty())&&zf.createEmptyParent(this.selfModel),this.toggleModel=this.selfModel.deepClone(),this.toggleModel.name+="_toggle",this.selfModel.parent.add(this.toggleModel);else{if(!this.gameObject[ze.toggleClone]){const l=this.selfModelClone.clone();l.setMatrix(new ee),l.name+="_toggle"+ze.clonedToggleIndex++,i.add(l),this.gameObject[ze.toggleClone]=l,console.warn("USDZExport: Toggle "+this.gameObject.name+" doesn't have geometry. It will be deep cloned and nested behaviours will likely not work.")}const a=this.gameObject[ze.toggleClone];if(!this.gameObject[ze.reverseToggleClone]){const l=this.selfModelClone.clone();l.setMatrix(new ee),l.name+="_toggleReverse"+ze.clonedToggleIndex++,i.add(l),this.gameObject[ze.reverseToggleClone]=l}this.toggleModel=this.gameObject[ze.reverseToggleClone],(!this.toggleModel.geometry||!a.geometry)&&console.error("triggers without childs and without geometry won't work!",this,i.geometry),n=a,i.geometry=null,i.material=null}if(this.toggleModel){if(this.toggleOnClick){const a=[];a.push(me.fadeAction(n,0,!1)),a.push(me.fadeAction(this.toggleModel,0,!0)),a.push(me.fadeAction(this.targetModel,0,s)),e.addBehavior(new Et("Toggle_"+n.name+"_ToggleTo"+(s?"On":"Off"),jt.tapTrigger(n),me.parallel(...a)));const l=[];l.push(me.fadeAction(this.toggleModel,0,!1)),l.push(me.fadeAction(n,0,!0)),l.push(me.fadeAction(this.targetModel,0,!s)),e.addBehavior(new Et("Toggle_"+n.name+"_ToggleTo"+(s?"Off":"On"),jt.tapTrigger(this.toggleModel),me.parallel(...l)))}}else{const a=[];this.hideSelf&&a.push(me.fadeAction(n,0,!1)),a.push(me.fadeAction(this.targetModel,0,s)),e.addBehavior(new Et("Toggle_"+n.name+"_ToggleTo"+(s?"On":"Off"),jt.tapTrigger(n),a.length>1?me.parallel(...a):a[0]))}const r=new Array;this.targetStateBeforeCreatingDocument||r.push(this.targetModel),this.stateBeforeCreatingDocument||r.push(i),this.toggleModel&&r.push(this.toggleModel),cn.add(r,e)}}afterSerialize(e,t){this.gameObject[ze.wasVisible]!==void 0&&(this.gameObject.visible=this.gameObject[ze.wasVisible],delete this.gameObject[ze.wasVisible]),this.target&&this.target[ze.wasVisible]!==void 0&&(this.target.visible=this.target[ze.wasVisible],delete this.target[ze.wasVisible]),delete this.gameObject[ze.toggleClone],delete this.gameObject[ze.reverseToggleClone]}};Be([u(O)],zc.prototype,"target"),Be([u()],zc.prototype,"toggleOnClick"),Be([u()],zc.prototype,"targetState"),Be([u()],zc.prototype,"hideSelf");let Zf=zc;class cn extends M{static _fadeBehaviour;static _fadeObjects=[];static add(e,t){const i=Array.isArray(e)?e:[e];for(const n of i)cn._fadeObjects.includes(n)||(console.log("adding hide on start",n),cn._fadeObjects.push(n));cn._fadeBehaviour===void 0&&(cn._fadeBehaviour=new Et("HideOnStart",jt.sceneStartTrigger(),me.fadeAction(cn._fadeObjects,0,!1)),t.addBehavior(cn._fadeBehaviour))}start(){x.setActive(this.gameObject,!1)}createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&(this.wasVisible||cn.add(t,e))}wasVisible=!1;beforeCreateDocument(){this.wasVisible=x.isActiveSelf(this.gameObject)}}class ol extends M{target;duration=.5;motionType="bounce";beforeCreateDocument(){}createBehaviours(e,t,i){if(this.target&&t.uuid===this.gameObject.uuid){const n=new Et("emphasize "+this.name,jt.tapTrigger(this.gameObject),me.emphasize(this.target,this.duration,this.motionType,void 0,"basic"));e.addBehavior(n)}}afterCreateDocument(e,t){}}Be([u()],ol.prototype,"target"),Be([u()],ol.prototype,"duration"),Be([u()],ol.prototype,"motionType");class Os extends M{target;clip="";toggleOnClick=!1;trigger="tap";start(){Uc(this.gameObject)}ensureAudioSource(){if(!this.target){const e=this.gameObject.addComponent(Mi);e&&(this.target=e,e.spatialBlend=1,e.volume=1,e.loop=!1,e.preload=!0)}}onPointerClick(e){e.use(),!(!this.target?.clip&&!this.clip)&&(this.ensureAudioSource(),this.target&&(this.target.isPlaying&&this.toggleOnClick?this.target.stop():(!this.toggleOnClick&&this.target.isPlaying&&this.target.stop(),this.clip?this.target.play(this.clip):this.target.play())))}createBehaviours(e,t,i){if(!(!this.target&&!this.clip)&&t.uuid===this.gameObject.uuid){const n=this.clip?this.clip:this.target?this.target.clip:void 0;if(!n||typeof n!="string")return;const s=this.target?this.target.gameObject:this.gameObject;aa.getName(n);const r=this.target?this.target.volume:1,a=this.target&&this.target.spatialBlend==0?"nonSpatial":"spatial";let l=!1;this.gameObject.traverse(p=>{p instanceof H&&p.visible&&(l=!0)}),l=!0;const c=e.addAudioClip(n);let h=me.playAudioAction(s,c,"play",r,a);this.target&&this.target.loop&&(h=me.sequence(h).makeLooping());const d=this.name?"_"+this.name:"";if(l&&this.trigger==="tap"){this.toggleOnClick&&(h.multiplePerformOperation="stop");const p=new Et("playAudio"+d,jt.tapTrigger(t),h);e.addBehavior(p)}if(this.target&&this.target.playOnAwake&&this.target.enabled)if(l&&this.trigger==="tap")console.warn("USDZExport: Audio sources that are played on tap can't also auto-play at scene start due to a QuickLook bug.");else{const p=new Et("playAudioOnStart"+d,jt.sceneStartTrigger(),h);e.addBehavior(p)}}}}Be([u(Mi)],Os.prototype,"target"),Be([u(URL)],Os.prototype,"clip"),Be([u()],Os.prototype,"toggleOnClick");const Jf=class lo extends M{animator;stateName;trigger="tap";animation;get target(){return this.animator?.gameObject||this.animation?.gameObject}start(){Uc(this.gameObject)}onPointerClick(e){e.use(),this.target&&this.stateName&&this.animator?.play(this.stateName,0,0,.1)}selfModel;stateAnimationModel;animationSequence=new Array;animationLoopAfterSequence=new Array;randomOffsetNormalized=0;createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&(this.selfModel=t)}static animationActions=[];static rootsWithExclusivePlayback=new Set;afterSerialize(){if(lo.rootsWithExclusivePlayback.size>1){const e='Multiple root objects targeted by more than one animation. To work around QuickLook bug FB13410767, animations will be set as "exclusive" and activating them will stop other animations being marked as exclusive.';E()&&ge(e),console.warn(e,...lo.rootsWithExclusivePlayback)}lo.animationActions=[],lo.rootsWithExclusivePlayback=new Set}afterCreateDocument(e,t){if(this.animationSequence===void 0&&this.animationLoopAfterSequence===void 0||!this.stateAnimationModel||!this.target)return;const i=t.document,n=t.extensions.find(a=>a instanceof Gu);if(!n)return;const s=n.getClipCount(this.target)>1;s&&(E()&&console.warn("Setting exclusive playback for "+this.target.name+"@"+this.stateName+" because it has "+n.getClipCount(this.target)+" animations. This works around QuickLook bug FB13410767."),lo.rootsWithExclusivePlayback.add(this.target));const r=this.name?this.name:"";i.traverse(a=>{if(a.uuid===this.target?.uuid){const l=lo.getActionForSequences(i,a,this.animationSequence,this.animationLoopAfterSequence,this.randomOffsetNormalized),c=new Et(this.trigger+"_"+r+"_toPlayAnimation_"+this.stateName+"_on_"+this.target?.name,this.trigger=="tap"?jt.tapTrigger(this.selfModel):jt.sceneStartTrigger(),l);s&&c.makeExclusive(!0),e.addBehavior(c)}})}static getActionForSequences(e,t,i,n,s){const r=(l,c)=>{let h=lo.animationActions.find(d=>d.affectedObjects==l&&d.start==c.start&&d.duration==c.duration&&d.animationSpeed==c.speed);return h||(h=me.startAnimationAction(l,c),lo.animationActions.push(h)),h},a=me.sequence();if(i&&i.length>0)for(const l of i)a.addAction(r(t,l));if(n&&n.length>0){const l=a.actions.length==0?a:me.sequence();for(const c of n)l.addAction(r(t,c));l.makeLooping(),a!==l&&a.addAction(l)}return s&&s>0&&a.actions.unshift(me.waitAction(s)),a}static getAndRegisterAnimationSequences(e,t,i){if(!t)return;const n=t.getComponent(ft),s=t.getComponent(Ht);if(!n&&!s)return;if(n&&!i)throw new Error("PlayAnimationOnClick: No stateName specified for animator "+n.name+" on "+t.name);let r=[],a=[];if(s){const f=e.registerAnimation(t,s.clip);f&&(s.loop?a.push(f):r.push(f));let m=0;if(s.minMaxOffsetNormalized){const y=s.minMaxOffsetNormalized.x,_=s.minMaxOffsetNormalized.y;m=(s.clip?.duration||1)*(y+Math.random()*(_-y))}return{animationSequence:r,animationLoopAfterSequence:a,randomTimeOffset:m}}const l=n?.runtimeAnimatorController;let c=l?.findState(i),h=[],d=[];if(l&&c){const f=new Array;f.push(c);let m=!1;for(;f.length<100;){if(!c||c===null||!c.transitions||c.transitions.length===0){c.motion?.isLooping&&(m=!0);break}const y=c.transitions.find(v=>v.conditions.length===0),_=y?l.getState(y.destinationState,0):null;if(_&&f.includes(_)){c=_,m=!0;break}else if(y){if(c=_,!c)break;f.push(c)}else{m=c.motion?.isLooping??!1;break}}if(m&&c){const y=f.indexOf(c);h=f.slice(0,y),d=f.slice(y),xx&&console.log("found loop from "+i,"states until loop",h,"states looping",d)}else h=f,d=[],xx&&console.log("found no loop from "+i,"states",h);if(!d.length){const y=h[h.length-1],_=y.motion?.clip;if(_){let v;if(e.holdClipMap.has(_))v=e.holdClipMap.get(_);else{const P=y.name+"_hold";v=_.clone(),v.duration=1,v.name=P;const R=_.duration;v.tracks=_.tracks.map(k=>{const A=k.clone();A.times=new Float32Array([0,R]);const L=k.values.length,N=k.getValueSize(),j=k.values.slice(L-N,L);return A.values=new Float32Array(2*N),A.values.set(j,0),A.values.set(j,N),A}),v.name=P,e.holdClipMap.set(_,v)}if(v){const P={name:v.name,motion:{clip:v,isLooping:!1,name:v.name},speed:1,transitions:[],behaviours:[],hash:y.hash+1};d.push(P)}}}}if(h.length===1&&(!h[0].motion?.clip||h[0].motion?.clip.tracks?.length===0)){r=new Array;const f=e.registerAnimation(t,null);f&&r.push(f);return}if(h=h.filter(f=>f.motion?.clip&&f.motion?.clip.tracks?.length>0),d=d.filter(f=>f.motion?.clip&&f.motion?.clip.tracks?.length>0),h.length===0&&d.length===0){console.warn("No clips found for state "+i+" on "+n?.name+", can't export animation data");return}const p=(f,m)=>{if(!t)return;const y=e.registerAnimation(t,f.motion.clip??null);y?(y.speed=f.speed,m.push(y)):console.warn("Couldn't register animation for state "+f.name+" on "+n?.name)};if(h.length>0){r=new Array;for(const f of h)p(f,r)}if(d.length>0){a=new Array;for(const f of d)p(f,a)}let g=0;if(n&&l&&n.minMaxOffsetNormalized){const f=n.minMaxOffsetNormalized.x,m=n.minMaxOffsetNormalized.y;g=((h.length?h[0]:d.length?d[0]:null)?.motion.clip?.duration||1)*(f+Math.random()*(m-f))}return{animationSequence:r,animationLoopAfterSequence:a,randomTimeOffset:g}}createAnimation(e,t,i){if(!this.target||!this.animator&&!this.animation)return;const n=lo.getAndRegisterAnimationSequences(e,this.target,this.stateName);n&&(this.animationSequence=n.animationSequence,this.animationLoopAfterSequence=n.animationLoopAfterSequence,this.randomOffsetNormalized=n.randomTimeOffset,this.stateAnimationModel=t)}};Be([u(ft)],Jf.prototype,"animator"),Be([u()],Jf.prototype,"stateName");let Nc=Jf;class sl extends M{getType(){}target;getDuration(){}}Be([u(O)],sl.prototype,"target");class Wc extends M{target}Be([u(sl)],Wc.prototype,"target");class Vc extends sl{type=1;duration=1;getType(){switch(this.type){case 1:return"hide";case 0:return"show"}}getDuration(){return this.duration}}Be([u()],Vc.prototype,"type"),Be([u()],Vc.prototype,"duration");class ey extends Wc{}class Qs{static _instance;static create(){return new Qs}static getOrCreate(){return this._instance||(this._instance=this.create()),this._instance}get isSecureConnection(){return window.location.protocol==="https:"}get quicklookButton(){return this._quicklookButton}_quicklookButton;get arButton(){return this._arButton}_arButton;get vrButton(){return this._vrButton}_vrButton;get sendToQuestButton(){return this._sendToQuestButton}_sendToQuestButton;get qrButton(){return An.getOrCreate().createQRCode()}createQuicklookButton(){if(this._quicklookButton)return this._quicklookButton;const e=document.createElement("button");this._quicklookButton=e,e.dataset.needle="quicklook-button";const t=G.supportsQuickLookAR();e.innerText="View in AR",e.prepend(Ct("view_in_ar"));let i=!1,n=null;return e.addEventListener("click",()=>{n=pc(to),n||(i=!0,n=new to),i&&(n.objectToExport=z.Current.scene),n?(e.classList.add("this-mode-is-requested"),n.exportAndOpen().then(()=>{e.classList.remove("this-mode-is-requested")}).catch(s=>{e.classList.remove("this-mode-is-requested"),console.error(s)})):console.warn("No USDZExporter component found in the scene")}),this.hideElementDuringXRSession(e),e}createARButton(e){if(this._arButton)return this._arButton;const t="immersive-ar",i=document.createElement("button");return this._arButton=i,i.classList.add("webxr-button"),i.dataset.needle="webxr-ar-button",i.innerText="Enter AR",i.prepend(Ct("view_in_ar")),i.title="Click to start an AR session",i.addEventListener("click",()=>K.start(t,e)),this.updateSessionSupported(i,t),this.listenToXRSessionState(i,t),this.hideElementDuringXRSession(i),this.isSecureConnection||(i.disabled=!0,i.title="WebXR requires a secure connection (HTTPS)"),G.isMozillaXR()||navigator.xr?.addEventListener("devicechange",()=>this.updateSessionSupported(i,t)),i}createVRButton(e){if(this._vrButton)return this._vrButton;const t="immersive-vr",i=document.createElement("button");return this._vrButton=i,i.classList.add("webxr-button"),i.dataset.needle="webxr-vr-button",i.innerText="Enter VR",i.prepend(Ct("panorama_photosphere")),i.title="Click to start a VR session",i.addEventListener("click",()=>K.start(t,e)),this.updateSessionSupported(i,t),this.listenToXRSessionState(i,t),this.hideElementDuringXRSession(i),this.isSecureConnection||(i.disabled=!0,i.title="WebXR requires a secure connection (HTTPS)"),G.isMozillaXR()||navigator.xr?.addEventListener("devicechange",()=>this.updateSessionSupported(i,t)),i}createSendToQuestButton(){if(this._sendToQuestButton)return this._sendToQuestButton;const e="https://oculus.com/open_url/?url=",t=document.createElement("button");return this._sendToQuestButton=t,t.dataset.needle="webxr-sendtoquest-button",t.innerText="Open on Quest",t.prepend(Ct("share_windows")),t.title="Click to send this page to the Oculus Browser on your Quest",t.addEventListener("click",()=>{const i=encodeURIComponent(window.location.href),n=e+i;window.open(n)==null&&Te("This page doesn't allow popups. Please paste "+n+" into your browser.")}),this.listenToXRSessionState(t),this.hideElementDuringXRSession(t),G.isMozillaXR()||navigator.xr?.addEventListener("devicechange",()=>{navigator.xr?.isSessionSupported("immersive-vr")?t.style.display="none":t.style.display=""}),t}createQRCode(){return An.getOrCreate().createQRCode()}updateSessionSupported(e,t){if(!("xr"in navigator)){e.style.display="none";return}K.isSessionSupported(t).then(i=>{e.style.display=i?"":"none",E()&&!i&&console.log('[WebXR] "'+t+'" is not supported on this device \u2013 make sure your server runs using HTTPS and you have a device connected that supports '+t)})}hideElementDuringXRSession(e){Md(t=>{e["previous-display"]=e.style.display,e.style.display="none"}),Xm(t=>{e["previous-display"]!=null&&(e.style.display=e["previous-display"])})}listenToXRSessionState(e,t){t&&(K.onSessionRequestStart(i=>{i.mode===t?e.classList.add("this-mode-is-requested"):(e["was-disabled"]=e.disabled,e.disabled=!0,e.classList.add("other-mode-is-requested"))}),K.onSessionRequestEnd(i=>{e.classList.remove("this-mode-is-requested"),e.classList.remove("other-mode-is-requested"),e.disabled=e["was-disabled"]}))}}var UT=Object.defineProperty,zT=Object.getOwnPropertyDescriptor,bt=(o,e,t,i)=>{for(var n=i>1?void 0:i?zT(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&UT(e,t,n),n};const $c=w("debugspriterenderer"),NT=w("wireframe");class ca{static cache={};static getOrCreateGeometry(e){if(e.__cached_geometry)return e.__cached_geometry;if(e.guid&&ca.cache[e.guid])return $c&&console.log("Take cached geometry for sprite",e.guid),ca.cache[e.guid];const t=new un;e.__cached_geometry=t;const i=new Float32Array(e.triangles.length*3),n=new Float32Array(e.triangles.length*2);for(let s=0;s<e.triangles.length;s+=1){const r=e.triangles[s];i[s*3]=-e.vertices[r].x,i[s*3+1]=e.vertices[r].y,i[s*3+2]=0;const a=e.uv[r];n[s*2]=a.x,n[s*2+1]=1-a.y}return t.setAttribute("position",new pt(i,3)),t.setAttribute("uv",new pt(n,2)),e.guid&&(this.cache[e.guid]=t),$c&&console.log("Built sprite geometry",e,t),t}}class WT{x;y}function Sx(o){o&&(o.colorSpace!=go&&(o.colorSpace=go,o.needsUpdate=!0),o.minFilter==dd&&o.magFilter==dd&&(o.anisotropy=1,o.needsUpdate=!0))}let jo=class{constructor(o){o&&(this.texture=o,this.triangles=[0,1,2,0,2,3],this.uv=[{x:0,y:0},{x:1,y:0},{x:1,y:1},{x:0,y:1}],this.vertices=[{x:-.5,y:-.5},{x:.5,y:-.5},{x:.5,y:.5},{x:-.5,y:.5}])}guid;texture;triangles;uv;vertices;__cached_geometry;get mesh(){return this._mesh||(this._mesh=new H(ca.getOrCreateGeometry(this),this.material)),this._mesh}_mesh;get material(){return this._material||(this.texture&&Sx(this.texture),this._material=new xe({map:this.texture,color:16777215,side:vi,transparent:!0})),this._material}_material;getGeometry(){return ca.getOrCreateGeometry(this)}};bt([u()],jo.prototype,"guid",2),bt([u(Re)],jo.prototype,"texture",2),bt([Qe()],jo.prototype,"triangles",2),bt([Qe()],jo.prototype,"uv",2),bt([Qe()],jo.prototype,"vertices",2);const ty=Symbol("spriteOwner");class rl{sprites;constructor(){this.sprites=[]}}bt([u(jo)],rl.prototype,"sprites",2);const iy=class k0{static create(){const e=new k0;return e.spriteSheet=new rl,e}constructor(){}clone(){const e=new k0;return e.index=this.index,e.spriteSheet=this.spriteSheet,e}set sprite(e){e&&(this.spriteSheet?((this.index===null||this.index===void 0)&&(this.index=0),this.spriteSheet.sprites[this.index]=e):(this.spriteSheet=new rl,this.spriteSheet.sprites=[e],this.index=0))}get sprite(){if(this.spriteSheet)return this.spriteSheet.sprites[this.index]}spriteSheet;index=0;update(e){if(!this.spriteSheet)return;const t=this.index;if(t<0||t>=this.spriteSheet.sprites.length)return;const i=this.spriteSheet.sprites[t],n=i?.texture;if(n&&(Sx(n),!i.__hasLoadedProgressive)){i.__hasLoadedProgressive=!0;const s=n;Ve.assignTextureLOD(n,0).then(r=>{r instanceof Re&&(i.texture=r,e?.map===s&&(e.map=r,e.needsUpdate=!0))})}}};bt([u(rl)],iy.prototype,"spriteSheet",2),bt([u()],iy.prototype,"index",2);let al=iy;class ci extends M{drawMode=0;size={x:1,y:1};color;sharedMaterial;transparent=!0;cutoutThreshold=0;castShadows=!1;renderOrder=0;toneMapped=!0;set texture(e){if(!this._spriteSheet)return;const t=this._spriteSheet.spriteSheet?.sprites[this.spriteIndex];t&&(t.texture=e,this.updateSprite())}addSprite(e,t=!1){if(this._spriteSheet||(this._spriteSheet=al.create()),!this._spriteSheet.spriteSheet)return-1;this._spriteSheet.spriteSheet?.sprites.push(e);const i=this._spriteSheet.spriteSheet?.sprites.length-1;return t&&(this.spriteIndex=i),i}get sprite(){return this._spriteSheet}set sprite(e){if(e!==this._spriteSheet)if(typeof e=="number"){const t=Math.round(e);$c&&console.log("[SpriteSheet] Set index to "+t+" (was "+this.spriteIndex+")",e),this.spriteIndex=t}else e instanceof jo?(this._spriteSheet||(this._spriteSheet=al.create()),this._spriteSheet.sprite!=e&&(this._spriteSheet.sprite=e),this.updateSprite()):e!=this._spriteSheet&&(this._spriteSheet=e,this.updateSprite())}set spriteIndex(e){this._spriteSheet&&(this._spriteSheet.index=e,this.updateSprite())}get spriteIndex(){return this._spriteSheet?.index??0}get spriteFrames(){return this._spriteSheet?.spriteSheet?.sprites.length??0}_spriteSheet;_currentSprite;awake(){this._currentSprite=void 0,this._spriteSheet?this._spriteSheet=this._spriteSheet.clone():this._spriteSheet=al.create(),$c&&console.log("Awake",this.name,this,this.sprite)}start(){this._currentSprite?this.gameObject&&this.gameObject.add(this._currentSprite):this.updateSprite()}updateSprite(e=!1){if(!this.__didAwake&&!e)return!1;const t=this._spriteSheet;if(!t?.spriteSheet?.sprites)return console.warn("SpriteRenderer has no data or spritesheet assigned..."),!1;const i=t.spriteSheet.sprites[this.spriteIndex];if(!i)return $c&&console.warn("Sprite not found",this.spriteIndex,t.spriteSheet.sprites),!1;if(this._currentSprite)this._currentSprite.geometry=ca.getOrCreateGeometry(i),this._currentSprite.material.map=i.texture;else{const n=new xe({color:16777215,side:vi});if(NT&&(n.wireframe=!0),this.color&&(n.color||(n.color=new ne),n.color.copy(this.color),n.opacity=this.color.alpha),n.transparent=!0,n.toneMapped=this.toneMapped,n.depthWrite=!1,i.texture&&!n.wireframe){let s=i.texture;s[ty]!==void 0&&s[ty]!==this&&this.spriteFrames>1&&(s=i.texture=s.clone()),s[ty]=this,n.map=s}this.sharedMaterial=n,this._currentSprite=new H(ca.getOrCreateGeometry(i),n),this._currentSprite.renderOrder=Math.round(this.renderOrder),Ve.assignTextureLOD(n,0)}return this._currentSprite.parent!==this.gameObject&&(this.drawMode===2&&this._currentSprite.scale.set(this.size.x,this.size.y,1),this.gameObject&&this.gameObject.add(this._currentSprite)),this._currentSprite&&this._currentSprite.layers.set(this.layer),this.sharedMaterial&&(this.sharedMaterial.alphaTest=this.cutoutThreshold,this.sharedMaterial.transparent=this.transparent),this._currentSprite.castShadow=this.castShadows,t?.update(this.sharedMaterial),!0}}bt([u()],ci.prototype,"drawMode",2),bt([u(WT)],ci.prototype,"size",2),bt([u(se)],ci.prototype,"color",2),bt([u(ve)],ci.prototype,"sharedMaterial",2),bt([u()],ci.prototype,"transparent",2),bt([u()],ci.prototype,"cutoutThreshold",2),bt([u()],ci.prototype,"castShadows",2),bt([u()],ci.prototype,"renderOrder",2),bt([u()],ci.prototype,"toneMapped",2),bt([u(al)],ci.prototype,"sprite",1);const Cx=w("debugwebxr"),VT=new ee().makeRotationY(Math.PI);class Ui extends M{static _eventListeners={};static onPlaced(e){const t="placed";return this._eventListeners[t]||(this._eventListeners[t]=[]),this._eventListeners[t].push(e),()=>{const i=this._eventListeners[t].indexOf(e);i>=0&&this._eventListeners[t].splice(i,1)}}static _hasPlaced=!1;static get hasPlaced(){return this._hasPlaced}get arScale(){return this._arScale}set arScale(e){this._arScale=Math.max(1e-6,e),this.onSetScale()}_arScale=1;invertForward=!1;customReticle;arTouchTransform=!0;autoPlace=!1;autoCenter=!1;useXRAnchor=!1;_isPlacing=!0;_startOffset=new ee;_createdPlacementObject=null;_reparentedComponents=[];_placementScene=new yi;_reticle=[];_hits=[];_placementStartTime=-1;_rigPlacementMatrix;_anchor=null;userInput;onEnable(){this.customReticle?.preload()}supportsXR(e){return e==="immersive-ar"}onEnterXR(e){Cx&&console.log("ENTER WEBXR: SessionRoot start..."),this._anchor=null,Ui._hasPlaced=!1,this.gameObject.updateMatrixWorld(),this._startOffset.copy(this.gameObject.matrixWorld);const t=new O;this._createdPlacementObject=t,t.name="AR Session Root",this._placementScene.name="AR Placement Scene",this._placementScene.children.length=0;for(let i=this.context.scene.children.length-1;i>=0;i--){const n=this.context.scene.children[i];this._placementScene.add(n)}if(this.context.scene.add(t),this.autoCenter){const i=Wt(this._placementScene.children),n=i.getCenter(new b),s=i.getSize(new b),r=new ee;r.makeTranslation(n.x,n.y-s.y*.5,n.z),this._startOffset.multiply(r)}this._reparentedComponents.length=0,this._reparentedComponents.push({comp:this,originalObject:this.gameObject}),x.addComponent(t,this);for(const i of this._reticle)Ci(i);this._reticle.length=0,this._isPlacing=!0,this.context.input.addEventListener("pointerup",this.onPlaceScene,{queue:ii.Early})}onLeaveXR(){this.context.input.removeEventListener("pointerup",this.onPlaceScene,{queue:ii.Early}),this.onRevertSceneChanges(),this._anchor=null,Ui._hasPlaced=!1,this._rigPlacementMatrix=void 0}onUpdateXR(e){if(e.xr.isTrackingImages){for(const t of this._reticle)t.visible=!1;return}if(this._isPlacing){const t=e.xr.rig?.gameObject;t&&t.parent!==this.context.scene&&this.context.scene.add(t);let i=!1;if(e.xr.isPassThrough&&e.xr.controllers.length>0&&!this.autoPlace)for(const n of e.xr.controllers){const s=n.getHitTest();s&&(i=!0,this.updateReticleAndHits(e.xr,n.index,s,e.xr.rigScale))}if(!i){const n=e.xr.getHitTest();n&&this.updateReticleAndHits(e.xr,0,n,e.xr.rigScale)}}else{if(this._anchor&&e.xr.referenceSpace){const t=e.xr.frame.getPose(this._anchor.anchorSpace,e.xr.referenceSpace);if(t&&this.context.time.frame%20===0){const i=e.xr.convertSpace(t.transform),n=this._reticle[0];n&&(n.position.copy(i.position),n.quaternion.copy(i.quaternion),this.onApplyPose(n))}}if(this.arTouchTransform?(this.userInput||(this.userInput=new Kp(this.context)),this.userInput?.enable()):this.userInput?.disable(),this.arTouchTransform&&this.userInput?.hasChanged){if(e.xr.rig){const t=e.xr.rig.gameObject;this.userInput.applyMatrixTo(t.matrix,!0),t.matrix.decompose(t.position,t.quaternion,t.scale),this.userInput.factor=t.scale.x}this.userInput.reset()}}}updateReticleAndHits(e,t,i,n){this._hits[t]=i.hit;let s=this._reticle[t];if(!s){if(this.customReticle)if(this.customReticle.asset)s=Da(this.customReticle.asset);else{this.customReticle.loadAssetAsync();return}else s=new H(new GS(.07,.09,32).rotateX(-Math.PI/2),new xe({side:vi,depthTest:!1,depthWrite:!1,transparent:!0,opacity:1,color:15658734})),s.name="AR Placement Reticle";if(Cx){const r=new _i(1);r.position.y+=.01,s.add(r)}this._reticle[t]=s,s.matrixAutoUpdate=!1,s.visible=!1}if(s.lastPos=s.lastPos||i.position.clone(),s.lastQuat=s.lastQuat||i.quaternion.clone(),s.position.copy(s.lastPos.lerp(i.position,this.context.time.deltaTime/.1)),s.lastPos.copy(s.position),s.quaternion.copy(s.lastQuat.slerp(i.quaternion,this.context.time.deltaTime/.05)),s.lastQuat.copy(s.quaternion),s.scale.set(n,n,n),this.customReticle&&this.applyViewBasedTransform(s),s.updateMatrix(),s.visible=!0,s.parent!==this.context.scene&&this.context.scene.add(s),this._placementStartTime<0&&(this._placementStartTime=this.context.time.realtimeSinceStartup),this.autoPlace)if(this.upVec.set(0,1,0).applyQuaternion(s.quaternion),this.upVec.dot($(0,1,0))>.9){let r=s["autoplace:timer"]||0;r>=1?(s.visible=!1,this.onPlaceScene(null)):(r+=this.context.time.deltaTime,s["autoplace:timer"]=r)}else s["autoplace:timer"]=0}onPlaceScene=e=>{if(this._isPlacing==!1||e?.used)return;let t=this._reticle[0];if(!t){console.warn("No reticle to place...");return}if(!t.visible&&!this.autoPlace){console.warn("Reticle is not visible (can not place)");return}if(K.active?.isTrackingImages){console.warn("Scene Placement is disabled while images are being tracked");return}let i=this._hits[0];if(e&&e.origin instanceof Qm){const n=this._reticle[e.origin.index];n&&(t=n,i=this._hits[e.origin.index])}if(e&&(e.stopImmediatePropagation(),e.stopPropagation(),e.use()),this._isPlacing=!1,this.context.input.removeEventListener("pointerup",this.onPlaceScene),this.onRevertSceneChanges(),t.position.copy(t.lastPos),t.quaternion.copy(t.lastQuat),this.onApplyPose(t),Ui._hasPlaced=!0,this.useXRAnchor&&this.onCreateAnchor(K.active,i),this.context.xr)for(const n of this.context.xr.controllers)n.cancelHitTestSource()};onSetScale(){if(!Ui._hasPlaced)return;const e=K.active?.rig?.gameObject;if(e){const t=K.active?.rigScale||1,i=1/this._arScale*t,n=new ee().makeScale(i,i,i).invert();e.matrix.premultiply(n),e.matrix.decompose(e.position,e.quaternion,e.scale)}}onRevertSceneChanges(){for(const e of this._reticle)e&&(e.visible=!1,e?.removeFromParent());this._reticle.length=0;for(let e=this._placementScene.children.length-1;e>=0;e--){const t=this._placementScene.children[e];this.context.scene.add(t)}this._createdPlacementObject?.removeFromParent();for(const e of this._reparentedComponents)x.addComponent(e.originalObject,e.comp)}async onCreateAnchor(e,t){if(t.createAnchor===void 0){console.warn("Hit does not support creating an anchor",t),E()&&ge("Hit does not support creating an anchor");return}else{const i=await t.createAnchor(e.viewerPose.transform);e.running&&i&&(this._anchor=i)}}upVec=new b(0,1,0);lookPoint=new b;worldUpVec=new b(0,1,0);applyViewBasedTransform(e){const t=this.context.mainCamera,i=e,n=t.worldPosition,s=i.worldPosition;this.upVec.set(0,1,0).applyQuaternion(e.quaternion);const r=t.worldPosition;r&&e.position.clone().sub(r).angleTo(this.upVec)<Math.PI/2&&this.upVec.negate();const a=this.upVec.angleTo(this.worldUpVec)*180/Math.PI,l=30;a>l&&a<180-l||a<-l&&a>-180+l?(this.lookPoint.copy(e.position).add(this.upVec),this.lookPoint.y=e.position.y,e.lookAt(this.lookPoint)):(n.y=s.y,e.lookAt(n))}onApplyPose(e){const t=K.active?.rig?.gameObject;if(!t){console.warn("No rig object to place");return}const i=t.parent||this.context.scene;this._rigPlacementMatrix?this._rigPlacementMatrix?.decompose(t.position,t.quaternion,t.scale):this._rigPlacementMatrix=t.matrix.clone(),this.applyViewBasedTransform(e),e.updateMatrix(),this.context.scene.add(e),e.attach(t),e.removeFromParent(),t.scale.set(this.arScale,this.arScale,this.arScale),t.position.multiplyScalar(this.arScale),t.updateMatrix(),this.invertForward&&t.matrix.premultiply(VT),t.matrix.premultiply(this._startOffset),t.matrix.decompose(t.position,t.quaternion,t.scale),i.add(t)}}class Kp{static up=new b(0,1,0);static zero=new b(0,0,0);static one=new b(1,1,1);oneFingerDrag=!0;twoFingerRotate=!0;twoFingerScale=!0;factor=1;context;offset;plane;_scale=1;_hasChanged=!1;get scale(){return this._scale}constructor(e){this.context=e,this.offset=new ee,this.plane=new tr,this.plane.setFromNormalAndCoplanarPoint(Kp.up,Kp.zero)}_enabled=!1;reset(){this._scale=1,this.offset.identity(),this._hasChanged=!0}get hasChanged(){return this._hasChanged}applyMatrixTo(e,t){this._hasChanged=!1,t?(this.offset.invert(),e.premultiply(this.offset)):e.multiply(this.offset)}currentlyUsedPointerIds=new Set;currentlyUnusedPointerIds=new Set;get isActive(){return this.currentlyUsedPointerIds.size<=0&&this.currentlyUnusedPointerIds.size>0}enable(){this._enabled||(this._enabled=!0,this.context.input.addEventListener("pointerdown",this.onPointerDownEarly,{queue:ii.Early}),this.context.input.addEventListener("pointerdown",this.onPointerDownLate,{queue:ii.Late}),this.context.input.addEventListener("pointerup",this.onPointerUpEarly,{queue:ii.Early}),window.addEventListener("touchstart",this.touchStart,{passive:!1}),window.addEventListener("touchmove",this.touchMove,{passive:!1}),window.addEventListener("touchend",this.touchEnd,{passive:!1}))}disable(){this._enabled&&(this._enabled=!1,this.context.input.removeEventListener("pointerdown",this.onPointerDownEarly,{queue:ii.Early}),this.context.input.removeEventListener("pointerdown",this.onPointerDownLate,{queue:ii.Late}),this.context.input.removeEventListener("pointerup",this.onPointerUpEarly,{queue:ii.Early}),window.removeEventListener("touchstart",this.touchStart),window.removeEventListener("touchmove",this.touchMove),window.removeEventListener("touchend",this.touchEnd))}onPointerDownEarly=e=>{this.isActive&&e.stopPropagation()};onPointerDownLate=e=>{e.used?this.currentlyUsedPointerIds.add(e.pointerId):this.currentlyUsedPointerIds.size<=0&&this.currentlyUnusedPointerIds.add(e.pointerId)};onPointerUpEarly=e=>{this.currentlyUsedPointerIds.delete(e.pointerId),this.currentlyUnusedPointerIds.delete(e.pointerId)};prev=new Map;_didMultitouch=!1;touchStart=e=>{if(!e.defaultPrevented)for(let t=0;t<e.changedTouches.length;t++){const i=e.changedTouches[t],n=G.isAndroidDevice()&&i.clientY<window.innerHeight*.1;this.prev.has(i.identifier)||this.prev.set(i.identifier,{ignore:n,x:0,z:0,screenx:0,screeny:0});const s=this.prev.get(i.identifier);if(s){const r=this.getPositionOnPlane(i.clientX,i.clientY);s.x=r.x,s.z=r.z,s.screenx=i.clientX,s.screeny=i.clientY}}};touchEnd=e=>{e.touches.length<=0&&(this._didMultitouch=!1);for(let t=0;t<e.changedTouches.length;t++){const i=e.changedTouches[t];this.prev.delete(i.identifier)}};touchMove=e=>{if(!e.defaultPrevented&&this.isActive){if(e.touches.length===1){if(this._didMultitouch)return;const t=e.touches[0],i=this.prev.get(t.identifier);if(!i||i.ignore)return;const n=this.getPositionOnPlane(t.clientX,t.clientY),s=n.x-i.x,r=n.z-i.z;if(s===0&&r===0)return;this.oneFingerDrag&&this.addMovement(s,r),i.x=n.x,i.z=n.z,i.screenx=t.clientX,i.screeny=t.clientY;return}else if(e.touches.length===2){this._didMultitouch=!0;const t=e.touches[0],i=e.touches[1],n=this.prev.get(t.identifier),s=this.prev.get(i.identifier);if(!n||!s)return;if(this.twoFingerRotate){const r=Math.atan2(t.clientY-i.clientY,t.clientX-i.clientX),a=Math.atan2(n.screeny-s.screeny,n.screenx-s.screenx),l=r-a;Math.abs(l)>.001&&this.addRotation(l)}if(this.twoFingerScale){const r=t.clientX-i.clientX,a=t.clientY-i.clientY,l=Math.sqrt(r*r+a*a),c=n.screenx-s.screenx,h=n.screeny-s.screeny,d=Math.sqrt(c*c+h*h),p=l-d;Math.abs(p)>2&&this.addScale(p)}n.screenx=t.clientX,n.screeny=t.clientY,s.screenx=i.clientX,s.screeny=i.clientY}}};_raycaster=new sd;_intersection=new b;_screenPos=new b;getPositionOnPlane(e,t){const i=this.context.mainCamera;return this._screenPos.x=e/window.innerWidth*2-1,this._screenPos.y=-(t/window.innerHeight)*2+1,this._screenPos.z=1,this._screenPos.unproject(i),this._raycaster.set(i.position,this._screenPos.sub(i.position)),this._raycaster.ray.intersectPlane(this.plane,this._intersection),this._intersection}addMovement(e,t){e/=this._scale,t/=this._scale,e*=this.factor,t*=this.factor,this.offset.elements[12]+=e,this.offset.elements[14]+=t,(e!==0||t!==0)&&(this._hasChanged=!0)}_tempMatrix=new ee;addScale(e){e/=window.innerWidth,e*=-1,this._scale*=1+e,this._tempMatrix.makeScale(1-e,1-e,1-e),this.offset.premultiply(this._tempMatrix),e!==0&&(this._hasChanged=!0)}addRotation(e){e*=-1,this._tempMatrix.makeRotationY(e),this.offset.premultiply(this._tempMatrix),e!==0&&(this._hasChanged=!0)}}const ks=w("debugautosync"),ny=Symbol("syncerId");class $T{_syncers={};getOrCreateSyncer(e){if(!e.guid)return null;if(this._syncers[e.guid])return this._syncers[e.guid];const t=new HT(e);return t[ny]=e.guid,this._syncers[t[ny]]=t,t}removeSyncer(e){delete this._syncers[e[ny]]}}const oy=new $T;class HT{comp;constructor(e){this.comp=e}hasChanges=!1;changedProperties={};get networkingKey(){return this.comp.guid}_isReceiving=!1;_isInit=!1;init(e){if(this._isInit)return;this._isInit=!0,this.comp=e,this.comp.context.post_render_callbacks.push(this.onHandleSending),this.comp.context.connection.beginListen(this.networkingKey,this.onHandleReceiving);const t=this.comp.context.connection.tryGetState(this.comp.guid);t&&this.onHandleReceiving(t)}destroy(){this._isInit&&(this.comp.context.post_render_callbacks.splice(this.comp.context.post_render_callbacks.indexOf(this.onHandleSending),1),this.comp.context.connection.stopListen(this.networkingKey,this.onHandleReceiving),this.comp=null,this._isInit=!1)}notifyChanged(e,t){this._isReceiving||(ks&&console.log("Property changed: "+e,t),this.hasChanges=!0,this.changedProperties[e]=t)}onHandleSending=()=>{if(!this.hasChanges)return;this.hasChanges=!1;const e=this.comp.context.connection;if(!e||!e.isConnected||!e.isInRoom){for(const t in this.changedProperties)delete this.changedProperties[t];return}for(const t in this.changedProperties){const i=this.changedProperties[t];ks&&console.log("SEND",this.comp.guid,this.networkingKey),e.send(this.networkingKey,{guid:this.comp.guid,property:t,data:i},fn.Queued),delete this.changedProperties[t]}};onHandleReceiving=e=>{if(ks&&console.log("SYNCFIELD RECEIVE",this.comp.name,this.comp.guid,e),!!this._isInit&&this.comp&&e.guid===this.comp.guid)try{this._isReceiving=!0,this.comp[e.property]=e.data}catch(t){console.error(t)}finally{this._isReceiving=!1}}}function GT(o,e){let t=e!==o;return!t&&o&&e&&(Array.isArray(o)&&Array.isArray(e)||typeof o=="object"&&typeof e=="object")&&(t=!0),t}const Hc=Symbol("AutoSyncHandler");function qT(o){if(o[Hc])return o[Hc];const e=oy.getOrCreateSyncer(o);return e?.init(o),o[Hc]=e,e}function XT(o){const e=o[Hc];e&&(oy.removeSyncer(e),e.destroy(),delete o[Hc])}const sy=function(o=null){return function(e,t){let i="";typeof t=="string"?i=t:i=t.name;let n=null,s;typeof o=="string"?s=e[o]:typeof o=="function"&&(s=o),s==null&&(E()||ks)&&o!=null&&console.warn('syncField: no callback function found for property "'+i+'"','"'+o+'"');const r=e,a=r.__internalAwake;if(typeof a!="function"){(ks||E())&&console.error('@syncField can currently only used on Needle Engine Components, custom object of type "'+e?.constructor?.name+'" is not supported',e);return}ks&&console.log(i);const l=Symbol(i);r.__internalAwake=function(){if(this[l]===void 0){if(this[l]=this[i],n=oy.getOrCreateSyncer(this),Object.getOwnPropertyDescriptor(this,i)?.set===void 0){let h=!1;Object.defineProperty(this,i,{set:function(d){const p=this[l];if(this[l]=d,h){(E()||ks)&&console.warn("Recursive call detected",i);return}h=!0;try{const g=GT(d,p);ks&&console.log("SyncField assignment",i,"changed?",g,d,s),g&&s?.call(this,d,p)!==!1&&qT(this)?.notifyChanged(i,d)}finally{h=!1}},get:function(){return this[l]},configurable:!0,enumerable:!0})}n?.init(this),a.call(this)}};const c=r.__internalDestroy;r.__internalDestroy=function(){XT(this),c.call(this)}}};var QT=Object.defineProperty,Xu=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&QT(e,t,n),n};const Yt=w("debugplayersync"),Qu=class $1 extends M{static async setupFrom(e,t){const i=ie.getOrCreateFromUrl(e);if(!i.asset){const r=await i.loadAssetAsync();r&&x.getOrAddComponent(r,xn)}const n=new $1;n._internalInit(t),n.asset=i;const s=new O;return s.guid=e,x.addComponent(s,n),n}autoSync=!0;asset;onPlayerSpawned;_localInstance;awake(){this.watchTabVisible(),this.onPlayerSpawned||(this.onPlayerSpawned=new ce)}onEnable(){this.context.connection.beginListen(te.RoomStateSent,this.onJoinedRoom),this.context.connection.beginListen(te.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(te.LeftRoom,this.destroyInstance),this.context.connection.isInRoom&&this.onJoinedRoom()}onDisable(){this.context.connection.stopListen(te.RoomStateSent,this.onJoinedRoom),this.context.connection.stopListen(te.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(te.LeftRoom,this.destroyInstance)}onJoinedRoom=()=>{Yt&&console.log("PlayerSync.joinedRoom. autoSync is set to "+this.autoSync),this.autoSync&&this.getInstance()};async getInstance(){if(this._localInstance)return this._localInstance;if(Yt&&console.log("PlayerSync.createInstance",this.asset?.url),!this.asset?.asset&&!this.asset?.url)return console.error('PlayerSync: can not create an instance because "asset" is not set and or has no URL!'),null;this.gameObject.guid||console.warn("PlayerSync: gameObject has no guid! This might cause issues with syncing the player state."),this._localInstance=this.asset?.instantiateSynced({parent:this.gameObject,deleteOnDisconnect:!0},!0);const e=await this._localInstance;if(e){const t=x.getComponentsInChildren(e,xn);if(Yt&&console.log(`PlayerSync.createInstance: found ${t?.length} PlayerState components. Owner: ${this.context.connection.connectionId}`),t?.length){for(const i of t)i.owner=this.context.connection.connectionId;this.onPlayerSpawned?.invoke(e)}else this._localInstance=void 0,console.error("<strong>Failed finding PlayerState on "+this.asset?.url+"</strong>: please make sure the asset has a PlayerState component!"),x.destroySynced(e)}else this._localInstance=void 0,console.warn("PlayerSync: failed instantiating asset!");return this._localInstance}destroyInstance=()=>{this._localInstance?.then(e=>{Yt&&console.log("PlayerSync.destroyInstance",e),ac(e,this.context.connection,!0,{saveInRoom:!1})}),this._localInstance=void 0};watchTabVisible(){window.addEventListener("visibilitychange",e=>{if(document.visibilityState==="visible")for(let t=xn.all.length-1;t>=0;t--){const i=xn.all[t];(!i.owner||!this.context.connection.userIsInRoom(i.owner))&&i.doDestroy()}})}};Xu([u()],Qu.prototype,"autoSync"),Xu([u(ie)],Qu.prototype,"asset"),Xu([u(ce)],Qu.prototype,"onPlayerSpawned");let ry=Qu;var Px=(o=>(o.OwnerChanged="ownerChanged",o))(Px||{});const ay=class Rt extends M{static _all=[];static get all(){return Rt._all}static _local=[];static get local(){return Rt._local}static getFor(e){if(e instanceof O)return x.getComponentInParent(e,Rt);if(e instanceof M)return x.getComponentInParent(e.gameObject,Rt)}static isLocalPlayer(e){return Rt.getFor(e)?.isLocalPlayer??!1}static _callbacks={};static addEventListener(e,t){return this._callbacks[e]||(this._callbacks[e]=[]),this._callbacks[e].push(t),t}static removeEventListener(e,t){if(!this._callbacks[e])return;const i=this._callbacks[e].indexOf(t);i>=0&&this._callbacks[e].splice(i,1)}static dispatchEvent(e,t){if(this._callbacks[e])for(const i of this._callbacks[e])i(t)}onOwnerChangeEvent=new ce;onFirstOwnerChangeEvent=new ce;hasOwner=!1;owner;dontDestroy=!1;get isLocalPlayer(){return this.owner===this.context.connection.connectionId}onOwnerChange(e,t){Yt&&console.log(`PlayerSync.onOwnerChange: ${t} \u2192 ${e} (me: ${this.context.connection.connectionId})`);const i=Rt._local.indexOf(this);i>=0&&Rt._local.splice(i,1);const n={playerState:this,oldValue:t,newValue:e};if(this.hasOwner||(this.hasOwner=!0,this.onFirstOwnerChangeEvent?.invoke(n)),this.onOwnerChangeEvent?.invoke(n),this.owner===this.context.connection.connectionId){Rt._local.push(this);const r=new CustomEvent("local-owner-changed",{detail:n});this.dispatchEvent(r)}const s=new CustomEvent("owner-changed",{detail:n});this.dispatchEvent(s),Rt.dispatchEvent("ownerChanged",s)}awake(){Rt.all.push(this),Yt&&console.log("Registered new PlayerState",this.guid,Rt.all.length-1,Rt.all),this.context.connection.beginListen(te.UserLeftRoom,this.onUserLeftRoom)}async start(){Yt&&console.log("PLAYERSTATE.START, owner: "+this.owner,this.context.connection.usersInRoom([])),this.owner?(this.context.connection.isInRoom||await Dn(300),this.context.connection.userIsInRoom(this.owner)==!1&&(Yt&&console.log(`PlayerSync.start \u2192 doDestroy "${this.name}" because user "${this.owner}" is not in room anymore...`,"Currently in room:",...this.context.connection.usersInRoom()),this.doDestroy())):this.owner||(Yt&&console.warn("PlayerState.start \u2192 owner is undefined!",this.name),setTimeout(()=>{!this.destroyed&&!this.owner?this.dontDestroy?Yt&&console.warn("PlayerState.start \u2192 owner is still undefined but dontDestroy is set to true",this.name):(Yt&&console.warn(`PlayerState.start \u2192 owner is still undefined: destroying "${this.name}" instance now`),this.doDestroy()):Yt&&console.log("PlayerState.start \u2192 owner is assigned",this.owner)},2e3))}doDestroy(){Yt&&console.log("PlayerSync.doDestroy \u2192 syncDestroy",this.name),ac(this.gameObject,this.context.connection,!0,{saveInRoom:!1})}onDestroy(){if(Yt&&console.warn("PlayerState.onDestroy",this.owner),this.context.connection.stopListen(te.UserLeftRoom,this.onUserLeftRoom),Rt.all.splice(Rt.all.indexOf(this),1),this.isLocalPlayer){const e=Rt._local.indexOf(this);e>=0&&Rt._local.splice(e,1)}}onUserLeftRoom=e=>{if(e.userId===this.owner){Yt&&console.log("PLAYERSYNC LEFT",this.owner),this.doDestroy();return}}};Xu([sy(ay.prototype.onOwnerChange)],ay.prototype,"owner");let xn=ay;var YT=Object.defineProperty,ll=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&YT(e,t,n),n};class Jn extends M{position="bottom";showNeedleLogo=!1;showSpatialMenu;createFullscreenButton;createMuteButton;createQRCodeButton;onEnable(){this.applyOptions()}applyOptions(){this.context.menu.setPosition(this.position),this.context.menu.showNeedleLogo(this.showNeedleLogo),this.createFullscreenButton===!0&&this.context.menu.showFullscreenOption(!0),this.createMuteButton===!0&&this.context.menu.showAudioPlaybackOption(!0),this.showSpatialMenu===!0&&this.context.menu.showSpatialMenu(this.showSpatialMenu),this.createQRCodeButton===!0&&(G.isMobileDevice()||this.context.menu.showQRCodeButton(!0))}}ll([u()],Jn.prototype,"position"),ll([u()],Jn.prototype,"showNeedleLogo"),ll([u()],Jn.prototype,"showSpatialMenu"),ll([u()],Jn.prototype,"createFullscreenButton"),ll([u()],Jn.prototype,"createMuteButton"),ll([u()],Jn.prototype,"createQRCodeButton");var KT=Object.defineProperty,ly=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&KT(e,t,n),n};const Gc=w("debugwebxr"),Ox=new U().setFromAxisAngle(new b(0,1,0),Math.PI);class Ms extends M{head;leftHand;rightHand;_leftHandMeshes;_rightHandMeshes;_syncTransforms;async onEnterXR(e){if(!this.activeAndEnabled)return;Gc&&console.warn("AVATAR ENTER XR",this.guid,this.sourceId,this,this.activeAndEnabled),this._syncTransforms&&(this._syncTransforms.length=0),await this.prepareAvatar();const t=xn.getFor(this);if(t?.owner){const i=this.gameObject.addComponent(Le);i.avatar=this.gameObject,i.connectionId=t.owner}else this.context.connection.isConnected?console.error("No player state found for avatar",this):t&&!this.context.connection.isConnected&&(t.dontDestroy=!0)}onLeaveXR(e){const t=this.gameObject.getComponent(Le);t&&t.destroy()}onUpdateXR(e){if(!this.activeAndEnabled)return;const t=xn.isLocalPlayer(this);if(!t)return;const i=e.xr;if(i.rig&&i.rig.gameObject!==this.gameObject.parent&&(this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),this.gameObject.scale.set(1,1,1),i.rig.gameObject.add(this.gameObject)),this._syncTransforms&&t)for(const l of this._syncTransforms)l.fastMode=!0,l.isOwned()||l.requestOwnership();if(this.head&&this.context.mainCamera){const l=this.head.asset;if(l.position.copy(this.context.mainCamera.position),l.position.x*=-1,l.position.z*=-1,l.quaternion.copy(this.context.mainCamera.quaternion),l.quaternion.x*=-1,this.context.time.frameCount%10===0&&this.head.asset){const c=x.getComponentsInChildren(this.head.asset,Ki);for(const h of c)h.enabled=!1,h.gameObject.visible=!1}}const n=e.xr.leftController,s=this.leftHand?.asset;n&&s?(s.position.copy(n.gripPosition),s.quaternion.copy(n.gripQuaternion),s.quaternion.multiply(Ox),s.visible=n.isTracking,this.updateHandVisibility(n,s,this._leftHandMeshes)):s&&s.visible&&(s.visible=!1);const r=e.xr.rightController,a=this.rightHand?.asset;r&&a?(a.position.copy(r.gripPosition),a.quaternion.copy(r.gripQuaternion),a.quaternion.multiply(Ox),a.visible=r.isTracking,this.updateHandVisibility(r,a,this._rightHandMeshes)):a&&a.visible&&(a.visible=!1)}onBeforeRender(){this.context.xr&&this.context.time.frame%10===0&&this.updateRemoteAvatarVisibility()}updateHandVisibility(e,t,i){if(i){const n=e.model&&e.model.visible&&e.model!==t;i.forEach(s=>{Co(s,!n)})}}updateRemoteAvatarVisibility(){if(this.context.connection.isConnected){const e=xn.getFor(this);if(e&&e.isLocalPlayer==!1){const t=K.getXRSync(this.context);if(t&&t.hasState(e.owner)){this.tryFindAvatarObjectsIfMissing();const i=this.leftHand?.asset;i&&(i.visible=t?.isTracking(e.owner,"left")??!1);const n=this.rightHand?.asset;n&&(n.visible=t?.isTracking(e.owner,"right")??!1)}if(this.head?.asset){const i=x.getComponentsInChildren(this.head.asset,Ki);for(const n of i)n.enabled=!1,n.gameObject.visible=!0}}}}tryFindAvatarObjectsIfMissing(){if(!this.head||!this.leftHand||!this.rightHand){const e={head:this.head,leftHand:this.leftHand,rightHand:this.rightHand};k_.tryFindAvatarObjects(this.gameObject,this.sourceId||"",e),e.head&&(this.head=e.head),e.leftHand&&(this.leftHand=e.leftHand),e.rightHand&&(this.rightHand=e.rightHand)}}async prepareAvatar(){if(this.tryFindAvatarObjectsIfMissing(),this.head)this.head instanceof O&&(this.head=new ie("",this.sourceId,this.head));else{const e=new O;e.name="Head";const t=pr.createPrimitive(ur.Cube);e.add(t),this.gameObject.add(e),this.head=new ie("",this.sourceId,e),Gc&&console.log("Create head",e)}if(this.rightHand)this.rightHand instanceof O&&(this.rightHand=new ie("",this.sourceId,this.rightHand));else{const e=new O;e.name="Right Hand",this.gameObject.add(e),this.rightHand=new ie("",this.sourceId,e),Gc&&console.log("Create right hand",e)}if(this.leftHand)this.leftHand instanceof O&&(this.leftHand=new ie("",this.sourceId,this.leftHand));else{const e=new O;e.name="Left Hand",this.gameObject.add(e),this.leftHand=new ie("",this.sourceId,e),Gc&&console.log("Create left hand",e)}await this.loadAvatarObjects(this.head,this.leftHand,this.rightHand),this._leftHandMeshes=[],this.leftHand.asset?.traverse(e=>{e?.isMesh&&this._leftHandMeshes.push(e)}),this._rightHandMeshes=[],this.rightHand.asset?.traverse(e=>{e?.isMesh&&this._rightHandMeshes.push(e)}),xn.isLocalPlayer(this.gameObject)&&(this._syncTransforms=x.getComponentsInChildren(this.gameObject,vn))}async loadAvatarObjects(e,t,i){const n=e.loadAssetAsync(),s=t.loadAssetAsync(),r=i.loadAssetAsync(),a=new Array;n&&a.push(n),s&&a.push(s),r&&a.push(r);const l=await Pm(a);Gc&&console.log("Avatar loaded results:",l)}}ly([u(ie)],Ms.prototype,"head"),ly([u(ie)],Ms.prototype,"leftHand"),ly([u(ie)],Ms.prototype,"rightHand");var ZT=Object.defineProperty,Yu=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&ZT(e,t,n),n};const Rs=w("debugwebxr"),Ts=new Array;class Do extends M{createControllerModel=!0;createHandModel=!0;customLeftHand;customRightHand;static factory=new PC;supportsXR(e){return e==="immersive-vr"||e==="immersive-ar"}_models=new Array;async onXRControllerAdded(e){if(!(e.xr.isVR||e.xr.isPassThrough))return;console.debug("XR Controller Added",e.controller.side,e.controller.index);const{controller:t}=e;if(this.createControllerModel||this.createHandModel){if(t.hand){if(this.createHandModel){const i=await this.loadHandModel(this,t);if(!i||!t.connected||!t.isHand){i?.handObject&&ja(i.handObject,!1),i?.handObject?.destroy();return}this._models.push({controller:t,model:i.handObject,handmesh:i.handmesh}),this._models.sort((n,s)=>n.controller.index-s.controller.index),this.scene.add(i.handObject),t.model=i.handObject}}else if(this.createControllerModel){const i=await t.getModelUrl();if(i){const n=await this.loadModel(t,i);if(!n||!t.connected||t.isHand)return;this._models.push({controller:t,model:n}),this._models.sort((s,r)=>s.controller.index-r.controller.index),this.scene.add(n),n.traverse(s=>{s.layers.set(2),s.matrixAutoUpdate=!1,s.updateMatrix()}),t.model=n}else t.targetRayMode!=="transient-pointer"&&console.warn("XRControllerModel: no model found for "+t.side)}}}onXRControllerRemoved(e){console.debug("XR Controller Removed",e.controller.side,e.controller.index);const t=this._models.findIndex(n=>n.controller===e.controller),i=this._models[t];i&&(this._models.splice(t,1),i.model&&(ja(i.model,!1),i.model.destroy(),i.model=void 0))}onBeforeXR(e,t){this.createHandModel&&(this.customLeftHand||this.customRightHand)&&(t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.includes("hand-tracking")||t.optionalFeatures.push("hand-tracking"))}onLeaveXR(e){for(const t of this._models)t&&(t.model&&(ja(t.model,!1),t.model.destroy(),t.model=void 0),t.controller.model===t.model&&(t.controller.model=null));this._models.length=0}onBeforeRender(){if(K.active&&(Rs&&(Ts[0]=Date.now()),this.updateRendering(K.active),Rs)){const e=Date.now()-Ts[0];Ts.push(e),Ts.length>=30&&(Ts[0]=0,Ts.reduce((t,i)=>t+i,0)/Ts.length,Ts.length=0)}}updateRendering(e){for(let t=0;t<this._models.length;t++){const i=this._models[t];if(!i)continue;const n=i.controller;if(!n.connected){Rs&&console.warn("XRControllerModel.onUpdateXR: controller is not connected anymore",n.side,n.hand);continue}if(i.model&&!i.handmesh)i.model.matrixAutoUpdate=!1,i.model.matrix.copy(n.gripMatrix),i.model.visible=n.isTracking,e.rig?.gameObject.add(i.model);else if(n.inputSource.hand&&i.handmesh){const s=e.referenceSpace,r=this.context.renderer.xr.getHand(n.index);if(s&&e.frame.getJointPose){for(const a of n.inputSource.hand.values()){const l=r.joints[a.jointName];if(l){const c=n.getHandJointPose(a);if(c){const h=c.transform.position,d=c.transform.orientation;l.position.copy(h),l.quaternion.copy(d),l.matrixAutoUpdate=!1}l.visible=c!=null}}i.model&&(i.model.visible=n.isTracking,i.model.visible&&i.model.parent!==e.rig?.gameObject&&e.rig?.gameObject.add(i.model)),i.model?.visible&&(i.handmesh?.updateMesh(),i.model.matrixAutoUpdate=!1,i.model.matrix.identity(),i.model.applyMatrix4(Pa))}}}}async loadModel(e,t){if(!e.connected)return console.warn("XRControllerModel.onXRControllerAdded: controller is not connected anymore",e.side),null;const i=await ie.getOrCreate("",t).instantiate();return ja(i),K.active?.isPassThrough&&i.traverseVisible(n=>{this.makeOccluder(n)}),i}async loadHandModel(e,t){const i=this.context,n=i.renderer.xr.getHand(t.index);n||(Rs?F.DrawLabel(t.rayWorldPosition,"No hand found for index "+t.index,.05,5):console.warn("No hand found for index "+t.index));const s=new fo;Yg(s,i),await ju(s,i,this.sourceId??"");const r=Af(s);let a="";const l=t.side==="left"?this.customLeftHand:this.customRightHand;l?(a=l.url.split(".").slice(0,-1).join("."),s.setPath("")):(a=t.inputSource.handedness==="left"?"left":"right",s.setPath("https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/"));const c=new O;ja(c);const h=new OC(c,n,s.path,a,s,d=>{const p=r?.gltf;p?.scene.children?.length===0&&(p.scene.children[0]=d),r?.gltf&&gn().createBuiltinComponents(e.context,e.sourceId||a,r.gltf,null,r),d.traverse(g=>{g.layers.set(2),K.active?.isPassThrough&&!l&&this.makeOccluder(g),g instanceof H&&Ve.assignMeshLOD(g,0)}),t.connected||(Rs&&F.DrawLabel(t.rayWorldPosition,"Hand is loaded but not connected anymore",.05,5),d.removeFromParent())});if(Rs&&c.add(new _i(.5)),t.inputSource.hand){Rs&&console.log(t.inputSource.hand);for(const d of t.inputSource.hand.values())if(n.joints[d.jointName]===void 0){const p=new os;p.matrixAutoUpdate=!1,p.visible=!0,n.joints[d.jointName]=p,n.add(p)}}else Rs&&F.DrawLabel(t.rayWorldPosition,"No inputSource.hand found for index "+t.index,.05,5);return{handObject:c,handmesh:h}}makeOccluder(e){if(e instanceof H){let t=e.material;t instanceof ve&&(t=e.material=t.clone(),t.depthWrite=!0,t.depthTest=!0,t.colorWrite=!1,e.receiveShadow=!1,e.renderOrder=-100)}}}Yu([u()],Do.prototype,"createControllerModel"),Yu([u()],Do.prototype,"createHandModel"),Yu([u(ie)],Do.prototype,"customLeftHand"),Yu([u(ie)],Do.prototype,"customRightHand");class Ku extends M{}var JT=Object.defineProperty,Es=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&JT(e,t,n),n};const cy=w("debugwebxr");class Ei extends M{movementSpeed=1.5;rotationStep=30;useTeleport=!0;usePinchToTeleport=!0;useTeleportTarget=!1;useTeleportFade=!1;showRays=!0;showHits=!0;isXRMovementHandler=!0;xrSessionMode="immersive-vr";_didApplyRotation=!1;_didTeleport=!1;onUpdateXR(e){const t=e.xr.rig;if(!t?.gameObject||e.xr.isPassThrough)return;const i=e.xr.leftController,n=e.xr.rightController;i&&this.onHandleMovement(i,t.gameObject),n&&(this.onHandleRotation(n,t.gameObject),this.useTeleport&&this.onHandleTeleport(n,t.gameObject))}onLeaveXR(e){for(const t of this._lines)t.removeFromParent();for(const t of this._hitDiscs)t?.removeFromParent()}onBeforeRender(){this.context.xr?.running&&(this.showRays&&this.renderRays(this.context.xr),this.showHits&&this.renderHits(this.context.xr))}onHandleMovement(e,t){const i=e.getStick("xr-standard-thumbstick");if(i.x!=0||i.y!=0){const n=$(i.x,0,i.y);n.multiplyScalar(this.context.time.deltaTimeUnscaled*this.movementSpeed);const s=$e(t);n.multiplyScalar(s.x),n.applyQuaternion(e.xr.poseOrientation),n.y=0,n.applyQuaternion(t.worldQuaternion),E()&&Number.isNaN(n.x)&&console.error("Stick movement resulted in NaN",{stick:i,vec:n}),t.position.add(n),t.updateWorldMatrix(!1,!1);for(const r of t.children)r.updateWorldMatrix(!1,!1)}}onHandleRotation(e,t){if(e._isMxInk)return;const i=e.getStick("xr-standard-thumbstick").x;if(this._didApplyRotation)Math.abs(i)<.3&&(this._didApplyRotation=!1);else if(Math.abs(i)>.5){this._didApplyRotation=!0;const n=i>0?1:-1,s=Z(this.context.mainCamera).clone();t.rotateY(n*D.toRadians(this.rotationStep));const r=Z(this.context.mainCamera).clone().sub(s);r.y=0,t.position.sub(r)}}_teleportBuffer=new Array;onHandleTeleport(e,t){let i=0;if(e.hand&&this.usePinchToTeleport&&e.isTeleportGesture){const n=e.getPointerId("primary");if(n!=null&&this.context.input.getIsPointerIdInUse(n))return;const s=e.getGesture("pinch");s&&(i=s.value)}else i=e.getStick("xr-standard-thumbstick")?.y;if(this._didTeleport)i>=0&&i<.4?this._didTeleport=!1:i<0&&i>-.4&&(this._didTeleport=!1);else if(i>.8){this._didTeleport=!0;const n=this.context.physics.raycastFromRay(e.ray)[0];if(n&&n.object instanceof ba){const r=n.normal?.dot($(0,1,0));if(r!==void 0&&r<.4)return}let s=n?.point;if(!s&&!this.useTeleportTarget){this._plane||(this._plane=new tr(new b(0,1,0),0));const r=t.worldPosition;this._plane.setFromNormalAndCoplanarPoint(new b(0,1,0),r);const a=e.ray;s=r.clone(),this._plane.intersectLine(new qS(a.origin,$(a.direction).multiplyScalar(1e4).add(a.origin)),s),s.distanceTo(r)>t.scale.x*10&&(s=null)}if(s){if(this.useTeleportTarget&&!x.getComponentInParent(n.object,Ku))return;const r=s.clone();if(cy&&F.DrawSphere(s,.025,16711680,5),this.context.mainCamera?.position){const a=this.context.xr?.getUserOffsetInRig();a&&(a.y=0,r.sub(a),cy&&F.DrawWireSphere(a.add(r),.025,65280,5))}this._teleportBuffer.push(t.matrix.clone()),this._teleportBuffer.length>10&&this._teleportBuffer.shift(),this.useTeleportFade?e.xr.fadeTransition()?.then(()=>{t.worldPosition=r}):t.worldPosition=r}}else if(i<-.8&&(this._didTeleport=!0,this._teleportBuffer.length>0)){const n=this._teleportBuffer.pop();n&&n.decompose(t.position,t.quaternion,t.scale)}}_plane=null;_lines=[];_hitDiscs=[];_hitDistances=[];_lastHitDistances=[];renderRays(e){for(let t=0;t<this._lines.length;t++){const i=this._lines[t];i&&(i.visible=!1)}for(let t=0;t<e.controllers.length;t++){const i=e.controllers[t];let n=this._lines[t];if(!i.connected||!i.isTracking||!i.ray||i.targetRayMode==="transient-pointer"||!i.hasSelectEvent){n&&(n.visible=!1);continue}n||(n=this.createRayLineObject(),n.scale.z=.5,this._lines[t]=n),i.updateRayWorldPosition(),i.updateRayWorldQuaternion();const s=i.rayWorldPosition,r=i.rayWorldQuaternion;n.position.copy(s),n.quaternion.copy(r);const a=e.rigScale,l=this.usePinchToTeleport&&i.isTeleportGesture,c=this._lastHitDistances[t],h=this._hitDistances[t]!=null,d=c??a;n.scale.set(a,a,d),n.visible=!0,n.layers.disableAll(),n.layers.enable(2);let p=n.material.opacity;l?p=1:this.showHits&&d<e.rigScale*.5?p=0:i.getButton("primary")?.pressed?p=.5:p=h?.2:.1,n.material.opacity=D.lerp(n.material.opacity,p,this.context.time.deltaTimeUnscaled/.1),n.parent!==this.context.scene&&this.context.scene.add(n)}}renderHits(e){for(const t of this._hitDiscs){if(!t)continue;const i=t.controller;if(!i||!i.connected||!i.isTracking){t.visible=!1;continue}}for(let t=0;t<e.controllers.length;t++){const i=e.controllers[t];if(!i.connected||!i.isTracking||!i.ray||!i.hasSelectEvent)continue;let n=this._hitDiscs[t],s=!0;const r=i.getPointerId("primary");r!=null&&this.context.input.getIsPointerIdInUse(r)&&(n&&(n.visible=!1),this._hitDistances[t]=null,this._lastHitDistances[t]=0,s=!1);const a=this.context.time.smoothedFps>=59?1:10;if((this.context.time.frame+i.index)%a!==0&&(s=!1),!s){const h=this._hitDiscs[t];h&&h.visible&&h.hit&&this.updateHitPointerPosition(i,h,h.hit.distance);continue}const l=this.context.physics.raycastFromRay(i.ray,{testObject:this.hitPointRaycastFilter,precise:!1});let c=l.find(h=>this.usePinchToTeleport&&i.isTeleportGesture?!0:this.isObjectWithInteractiveComponent(h.object));if(c||(c=l[0]),n&&(n.controller=i,n.hit=c),this._hitDistances[t]=c?.distance||null,c){this._lastHitDistances[t]=c.distance;const h=e.rigScale??1;cy&&(F.DrawWireSphere(c.point,.025*h,16711680),F.DrawLabel($(0,.2,0).add(c.point),c.object.name,.02,0)),n||(n=this.createHitPointObject(),this._hitDiscs[t]=n),n.hit=c,n.visible=c.distance>h*.05;let d=.01*(h+c.distance);const p=i.getButton("primary")?.pressed;p&&(d*=1.1),n.scale.set(d,d,d),n.layers.set(2);let g=n.material.opacity;if(p?g=1:g=c.distance<.15*h?.2:.6,n.material.opacity=D.lerp(n.material.opacity,g,this.context.time.deltaTimeUnscaled/.1),n.visible){if(c.normal){this.updateHitPointerPosition(i,n,c.distance);const f=c.normal.applyQuaternion(be(c.object));n.quaternion.setFromUnitVectors(eE,f)}else this.updateHitPointerPosition(i,n,c.distance);n.parent!==this.context.scene&&this.context.scene.add(n)}}else this._hitDiscs[t]&&(this._hitDiscs[t].visible=!1)}}isObjectWithInteractiveComponent(e,t=0){return fu(e)||e.isUI===!0?!0:e.isScene?!1:e.parent?this.isObjectWithInteractiveComponent(e.parent,t+1):!1}updateHitPointerPosition(e,t,i){const n=$(e.rayWorldPosition);n.add($(0,0,i-.01).applyQuaternion(e.rayWorldQuaternion)),t.position.lerp(n,this.context.time.deltaTimeUnscaled/.05)}hitPointRaycastFilter=e=>e.type==="SkinnedMesh"?"continue in children":!0;createHitPointObject(){const e=new H(new od(.3,6,6),new xe({color:15658734,opacity:.7,transparent:!0,depthTest:!1,depthWrite:!1,side:vi}));return e.layers.disableAll(),e.layers.enable(2),e}createRayLineObject(){const e=new kC;e.layers.disableAll(),e.layers.enable(2);const t=new MC;e.geometry=t;const i=new Float32Array(9);i.set([0,0,.02,0,0,.4,0,0,1]),t.setPositions(i);const n=new Float32Array(9);n.set([1,1,1,.1,.1,.1,0,0,0]),t.setColors(n);const s=new RC({color:16777215,vertexColors:!0,worldUnits:!0,linewidth:.004,transparent:!0,depthWrite:!1,blending:V0,dashed:!1});return e.material=s,e}}Es([u()],Ei.prototype,"movementSpeed"),Es([u()],Ei.prototype,"rotationStep"),Es([u()],Ei.prototype,"useTeleport"),Es([u()],Ei.prototype,"usePinchToTeleport"),Es([u()],Ei.prototype,"useTeleportTarget"),Es([u()],Ei.prototype,"useTeleportFade"),Es([u()],Ei.prototype,"showRays"),Es([u()],Ei.prototype,"showHits");const eE=new b(0,1,0);var tE=Object.defineProperty,_t=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&tE(e,t,n),n};const qc=w("debugwebxr"),iE=w("debugusdz"),rt=class Rl extends M{createVRButton=!0;createARButton=!0;createSendToQuestButton=!0;createQRCode=!0;useDefaultControls=!0;showControllerModels=!0;showHandModels=!0;usePlacementReticle=!0;customARPlacementReticle;usePlacementAdjustment=!0;arScale=1;useXRAnchor=!1;autoPlace=!1;autoCenter=!1;useQuicklookExport=!1;useDepthSensing=!1;useSpatialGrab=!0;defaultAvatar;_playerSync;_createdComponentsInSession=[];_usdzExporter;static activeWebXRComponent=null;awake(){K.getXRSync(this.context)}onEnable(){window.location.protocol!=="https:"&&ge('<a href="https://developer.mozilla.org/en-US/docs/Web/API/WebXR_Device_API" target="_blank">WebXR</a> only works on secure connections (https).'),this.useQuicklookExport&&(x.findObjectOfType(to)||(qc&&console.log("WebXR: Adding USDZExporter"),this._usdzExporter=x.addComponent(this.gameObject,to),this._usdzExporter.objectToExport=this.context.scene,this._usdzExporter.autoExportAnimations=!0,this._usdzExporter.autoExportAudioSources=!0)),this.handleCreatingHTML(),this.handleOfferSession(),this.defaultAvatar===!0&&(qc&&console.warn("WebXR: No default avatar set, using static default avatar"),this.defaultAvatar=new ie("https://cdn.needle.tools/static/avatars/DefaultAvatar.glb")),this.defaultAvatar&&(this._playerSync=this.gameObject.getOrAddComponent(ry),this._playerSync.autoSync=!1),this._playerSync&&typeof this.defaultAvatar!="boolean"&&(this._playerSync.asset=this.defaultAvatar,this._playerSync.onPlayerSpawned?.removeEventListener(this.onAvatarSpawned),this._playerSync.onPlayerSpawned?.addEventListener(this.onAvatarSpawned))}onDisable(){this._usdzExporter?.destroy(),this.removeButtons()}async handleOfferSession(){return this.createVRButton&&await K.isVRSupported()&&this.createVRButton?K.offerSession("immersive-vr","default",this.context):this.createARButton&&await K.isARSupported()&&this.createARButton?K.offerSession("immersive-ar","default",this.context):!1}get session(){return K.active??null}get sessionMode(){return K.activeMode??null}get arSessionRoot(){return this._activeWebARSessionRoot}async enterVR(e){return K.start("immersive-vr",e,this.context)}async enterAR(e){return K.start("immersive-ar",e,this.context)}exitXR(){K.stop()}_exitXRMenuButton;_previousXRState=0;_spatialGrabRaycaster;_activeWebARSessionRoot=null;get isActiveWebXR(){return!Rl.activeWebXRComponent||Rl.activeWebXRComponent===this}onBeforeXR(e,t){if(!this.isActiveWebXR){console.warn(`WebXR: another WebXR component is already active (${Rl.activeWebXRComponent?.name}). This is ignored: ${this.name}`);return}Rl.activeWebXRComponent=this,e=="immersive-ar"&&this.useDepthSensing&&(t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.push("depth-sensing"))}async onEnterXR(e){if(!this.isActiveWebXR)return;qc&&console.log("WebXR onEnterXR"),this._previousXRState=Jt.Global.Mask;const t=e.xr.isVR;if(Jt.Global.Set(t?Xn.VR:Xn.AR),e.xr.isAR){let i=x.findObjectOfType(Ui);if(!i)if(this.usePlacementReticle){const n=new O;for(const s of this.context.scene.children)n.add(s);this.context.scene.add(n),i=x.addComponent(n,Ui),this._createdComponentsInSession.push(i)}else(qc||E())&&console.warn("WebXR: No WebARSessionRoot found in scene and usePlacementReticle is disabled in WebXR component.");this._activeWebARSessionRoot=i,i&&(i.customReticle=this.customARPlacementReticle,i.arScale=this.arScale,i.arTouchTransform=this.usePlacementAdjustment,i.autoPlace=this.autoPlace,i.autoCenter=this.autoCenter,i.useXRAnchor=this.useXRAnchor)}this.useDefaultControls&&this.setDefaultMovementEnabled(!0),(this.showControllerModels||this.showHandModels)&&this.setDefaultControllerRenderingEnabled(!0),this.useSpatialGrab&&(this._spatialGrabRaycaster=x.findObjectOfType(ra)??void 0,this._spatialGrabRaycaster||(this._spatialGrabRaycaster=this.gameObject.addComponent(ra))),this.createLocalAvatar(e.xr),e.xr.isScreenBasedAR||(this._exitXRMenuButton=this.context.menu.appendChild({label:"Quit XR",onClick:()=>this.exitXR(),icon:"exit_to_app",priority:2e4}))}onUpdateXR(e){this.isActiveWebXR&&this._spatialGrabRaycaster&&(this._spatialGrabRaycaster.enabled=this.useSpatialGrab)}onLeaveXR(e){if(this._exitXRMenuButton?.remove(),!!this.isActiveWebXR){Jt.Global.Set(this._previousXRState),this._playerSync?.destroyInstance();for(const t of this._createdComponentsInSession)t.destroy();this._createdComponentsInSession.length=0,this._activeWebARSessionRoot=null,this.handleOfferSession(),Wl(1).then(()=>Rl.activeWebXRComponent=null)}}setDefaultMovementEnabled(e){let t=this.gameObject.getComponent(Ei);return!t&&e&&(t=this.gameObject.addComponent(Ei),this._createdComponentsInSession.push(t)),t&&(t.enabled=e),t}setDefaultControllerRenderingEnabled(e){let t=this.gameObject.getComponent(Do);return!t&&e&&(t=this.gameObject.addComponent(Do),this._createdComponentsInSession.push(t),t.createControllerModel=this.showControllerModels,t.createHandModel==this.showHandModels),t&&(t.enabled=e),t}async createLocalAvatar(e){this._playerSync&&e.running&&typeof this.defaultAvatar!="boolean"&&(this._playerSync.asset=this.defaultAvatar,await this._playerSync.getInstance())}onAvatarSpawned=e=>{qc&&console.log("WebXR.onAvatarSpawned",e);let t=x.getComponentInChildren(e,Ms);t??=x.addComponent(e,Ms)};getButtonsContainer(){return this.getButtonsFactory()}getButtonsFactory(){return this._buttonFactory||(this._buttonFactory=Qs.getOrCreate()),this._buttonFactory}_buttonFactory;handleCreatingHTML(){if(this.createARButton||this.createVRButton||this.useQuicklookExport){if((G.isiOS()&&G.isSafari()||iE)&&this.useQuicklookExport){const e=x.findObjectOfType(to);if(!e||e&&e.allowCreateQuicklookButton){const t=this.getButtonsFactory().createQuicklookButton();this.addButton(t,50)}}if(this.createARButton){const e=this.getButtonsFactory().createARButton();this.addButton(e,50)}if(this.createVRButton){const e=this.getButtonsFactory().createVRButton();this.addButton(e,50)}}if(this.createSendToQuestButton&&!G.isQuest()&&K.isVRSupported().then(e=>{if(!e){const t=this.getButtonsFactory().createSendToQuestButton();this.addButton(t,50)}}),this.createQRCode){const e=pc(Jn);if(e&&e.createQRCodeButton===!1)E()&&console.warn("WebXR: QRCode button is disabled in the Needle Menu component");else if(!G.isMobileDevice()){const t=An.getOrCreate().createQRCode();this.addButton(t,50)}}}_buttons=[];addButton(e,t){this._buttons.push(e),e.setAttribute("priority",t.toString()),this.context.menu.appendChild(e)}removeButtons(){for(const e of this._buttons)e.remove();this._buttons.length=0}};_t([u()],rt.prototype,"createVRButton"),_t([u()],rt.prototype,"createARButton"),_t([u()],rt.prototype,"createSendToQuestButton"),_t([u()],rt.prototype,"createQRCode"),_t([u()],rt.prototype,"useDefaultControls"),_t([u()],rt.prototype,"showControllerModels"),_t([u()],rt.prototype,"showHandModels"),_t([u()],rt.prototype,"usePlacementReticle"),_t([u(ie)],rt.prototype,"customARPlacementReticle"),_t([u()],rt.prototype,"usePlacementAdjustment"),_t([u()],rt.prototype,"arScale"),_t([u()],rt.prototype,"useXRAnchor"),_t([u()],rt.prototype,"autoPlace"),_t([u()],rt.prototype,"autoCenter"),_t([u()],rt.prototype,"useQuicklookExport"),_t([u()],rt.prototype,"useDepthSensing"),_t([u()],rt.prototype,"useSpatialGrab"),_t([u(ie)],rt.prototype,"defaultAvatar");let Zu=rt;const Ju=w("debugusdzbehaviours");class hy{get extensionName(){return"Behaviour"}behaviours=[];addBehavior(e){this.behaviours.push(e)}addAudioClip(e){if(!e||typeof e!="string")return"";const t="audio/"+aa.getName(e);return this.audioClips.push({clipUrl:e,filesKey:t}),t}behaviourComponents=[];behaviourComponentsCopy=[];audioClips=[];audioClipsCopy=[];targetUuids=new Set;getAllTargetUuids(){return this.targetUuids}onBeforeBuildDocument(e){if(!e.root)return Promise.resolve();const t=[];return e.root.traverse(i=>{x.foreachComponent(i,n=>{const s=n;if(typeof s.createBehaviours=="function"||typeof s.beforeCreateDocument=="function"||typeof s.afterCreateDocument=="function"||typeof s.afterSerialize=="function"){this.behaviourComponents.push(s);const r=s.beforeCreateDocument?.call(s,this,e);r instanceof Promise&&t.push(r)}},!1)}),Ju&&console.log("onBeforeBuildDocument: all components",this.behaviourComponents),Promise.all(t)}onExportObject(e,t,i){for(const n of this.behaviourComponents)n.createBehaviours?.call(n,this,t,i)}onAfterBuildDocument(e){for(const d of this.behaviourComponents)typeof d.afterCreateDocument=="function"&&d.afterCreateDocument(this,e);this.behaviourComponentsCopy=this.behaviourComponents.slice(),this.behaviourComponents.length=0,this.audioClipsCopy=this.audioClips.slice(),this.audioClips.length=0;const t=new Set,i=new Set,n=new Set,s=new Set,r=Ju;let a=`graph LR
1261
+ `))}for(const W of I){const oe=s.get(W);oe&&V.set(W,oe)}return V},m=function(I){const V=p(I),W=l(V);return c(V,W,I)};const f=n.skinnedMesh.skeleton,g=new Array,y=[],_=[];for(const I of f.bones){y.push(I),_.push(I.uuid);const V=f.boneInverses[f.bones.indexOf(I)];g.push({bone:I,inverse:V})}let v=1e4;for(;_.length<f.bones.length&&v-- >0;)for(const I of y){const V=I.children;for(const W of V)if(_.indexOf(W.uuid)===-1&&f.bones.indexOf(W)!==-1){y.push(W),_.push(W.uuid);const oe=f.boneInverses[f.bones.indexOf(W)];g.push({bone:W,inverse:oe})}}v<=0&&console.error("Failed to sort bones in skinned mesh",n.skinnedMesh,f.bones,_);for(const I of ox(f.bones))g.push({bone:I,inverse:I.matrixWorld.clone().invert()});const P=g[0].bone.parent;P||console.error("No bone parent found for skinned mesh during USDZ export",n.skinnedMesh),g.sort((I,V)=>il(I.bone,P)>il(V.bone,P)?1:-1);const R=t.quickLookCompatible,k=[],A=[],L=[],N=[];for(const{bone:I}of g){if(R){const V=I.scale;V.x==0&&(V.x=1e-5),V.y==0&&(V.y=1e-5),V.z==0&&(V.z=1e-5),k.push(new ee().compose(I.position,I.quaternion,I.scale))}else k.push(I.matrix.clone());A.push(I.position),L.push(I.quaternion),N.push(I.scale)}const j=g.map(I=>'"'+il(I.bone,P)+'"').join(", "),q=g.map(I=>gx(I.inverse.clone().invert())).join(", ");e.beginBlock('def Skeleton "Rig"'),e.appendLine(`uniform matrix4d[] bindTransforms = [${q}]`),e.appendLine(`uniform token[] joints = [${j}]`),e.appendLine('uniform token purpose = "guide"'),e.appendLine(`uniform matrix4d[] restTransforms = [${k.map(I=>gx(I)).join(", ")}]`);const Y=m(g.map(I=>I.bone));if(Zn){let I=1e7,V=0;for(const W of Y.position?.keys()??[])I=Math.min(I,W),V=Math.max(V,W);console.log("Time samples",I,V,Y)}if(e.beginBlock('def SkelAnimation "_anim"'),e.appendLine(`uniform token[] joints = [${j}]`),e.appendLine(`quatf[] rotations = [${d(L)}]`),Y&&Y.quaternion){e.beginBlock("quatf[] rotations.timeSamples = {","");const I=a(Y.quaternion);for(const V of I)e.appendLine(V);e.closeBlock()}if(e.appendLine(`half3[] scales = [${h(N)}]`),Y&&Y.scale){e.beginBlock("half3[] scales.timeSamples = {","");const I=r(Y.scale);for(const V of I)e.appendLine(V);e.closeBlock()}if(e.appendLine(`float3[] translations = [${h(A)}]`),Y&&Y.position){e.beginBlock("float3[] translations.timeSamples = {","");const I=r(Y.position);for(const V of I)e.appendLine(V);e.closeBlock()}e.closeBlock(),e.closeBlock()}}onSerialize(e,t){if(!this.model)return;const i=this.animationData.get(this.object);if(i)for(let h=0;h<i.length;h++)i[h]===void 0&&(i[h]=new Ne(null,this.object,null));const n=this.ext;this.skinnedMeshExport(e,t,n);const s=this.object,r=this.model,a=this.animationData.get(s);if(!a||s.isSkinnedMesh)return;Yf&&console.log("SERIALIZE",this.model.name,this.object.type,a);const l=Intl.NumberFormat("en-US",{maximumFractionDigits:3,minimumFractionDigits:0,useGrouping:!1});function c(h,d){if(h.some(p=>p&&{position:p.pos,rotation:p.rot,scale:p.scale}[d])){switch(d){case"position":r.needsTranslate=!0,e.beginBlock("double3 xformOp:translate.timeSamples = {","");break;case"rotation":r.needsOrient=!0,e.beginBlock("quatf xformOp:orient.timeSamples = {","");break;case"scale":r.needsScale=!0,e.beginBlock("double3 xformOp:scale.timeSamples = {","");break}for(let p=0;p<h.length;p++){const m=h[p];if(!m)continue;const f=n.getStartTimeByClip(m.clip),g=m.getSortedTimesArray(d==="position",d==="rotation",d==="scale");if(!g||g.length===0){console.error("got an animated object but no time values?",s,m);continue}const y=!m.clip,_=d==="position"&&(m.pos||y),v=d==="rotation"&&(m.rot||y),P=d==="scale"&&(m.scale||y);if(_||v||P){const R=m.clip?.name??"rest",k=m.getDuration();Zn&&console.log("Write .timeSamples:",R,f,k,h),e.appendLine("# "+R+": start="+l.format(f*Ne.frameRate)+", length="+l.format(k*Ne.frameRate)+", frames="+m.getFrames())}if(_)for(const{time:R,translation:k}of m.getValues(g,!0,!1,!1)){const A=`${l.format((f+R)*Ne.frameRate)}: (${ae(k.x)}, ${ae(k.y)}, ${ae(k.z)}),`;e.appendLine(A)}if(v)for(const{time:R,rotation:k}of m.getValues(g,!1,!0,!1)){const A=`${l.format((f+R)*Ne.frameRate)}: (${ae(k.w)}, ${ae(k.x)}, ${ae(k.y)}, ${ae(k.z)}),`;e.appendLine(A)}if(P)for(const{time:R,scale:k}of m.getValues(g,!1,!1,!0)){const A=`${l.format((f+R)*Ne.frameRate)}: (${ae(k.x)}, ${ae(k.y)}, ${ae(k.z)}),`;e.appendLine(A)}}e.closeBlock()}}c(a,"position"),c(a,"rotation"),c(a,"scale")}}const BT=w("debugusdz");class aa{static getName(e){const t=e.split(".").pop();let i=e.split(".").slice(0,-1).join(".").split("/").pop()?.replace(".","_");return i||(i="Audio_"+Math.random().toString(36).substring(2,15)),Zi(i)+"."+t}get extensionName(){return"Audio"}files=new Array;onExportObject(e,t,i){const n=x.getComponents(e,Mi);if(n.length)for(const s of n){if(!s.clip||typeof s.clip!="string"||!s.playOnAwake)continue;const r=s.clip.split("/").pop()||"Audio",a=aa.getName(s.clip),l=Zi(a);if(!this.files.some(c=>c.path===s.clip)){this.files.push({path:s.clip,name:a});const c=a.toLowerCase();i.quickLookCompatible&&!c.endsWith(".mp3")&&!c.endsWith(".wav")&&!c.endsWith(".m4a")&&console.error("Audio file "+s.clip+" from "+s.name+" is not an MP3 or WAV file. QuickLook may not support playing it.")}i.quickLookCompatible||t.addEventListener("serialize",(c,h)=>{c.appendLine(),c.beginBlock(`def SpatialAudio "${l}"`,"(",!1),c.appendLine(`displayName = "${r}"`),c.closeBlock(")"),c.beginBlock(),c.appendLine(`uniform asset filePath = @audio/${a}@`),c.appendLine(`uniform token auralMode = "${s.spatialBlend>0?"spatial":"nonSpatial"}"`),c.appendLine(`uniform token playbackMode = "${s.loop?"loopFromStage":"onceFromStart"}"`),c.appendLine(`uniform float gain = ${s.volume}`),c.closeBlock()})}}async onAfterSerialize(e){for(const t of this.files){const i="audio/"+t.name;if(e.files[i]){BT&&console.warn("Audio file with name "+i+" already exists in the context. Skipping.");continue}const n=await(await(await fetch(t.path)).blob()).arrayBuffer(),s=new Uint8Array(n);e.files[i]=s}}}var FT=Object.defineProperty,Be=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&FT(e,t,n),n};const xx=w("debugusdzbehaviours");function Uc(o){o&&(o.getComponentInParent(Wa)||(E()&&console.debug('Raycaster on "'+o.name+'" was automatically added, because no raycaster was found in the parent hierarchy.'),o.addComponent(ki)))}class Br extends M{object;target;duration=1;relativeMotion=!1;coroutine=null;targetPos=new b;targetRot=new U;targetScale=new b;start(){Uc(this.gameObject)}onPointerClick(e){e.use(),this.coroutine&&this.stopCoroutine(this.coroutine),this.relativeMotion?this.coroutine=this.startCoroutine(this.moveRelative()):this.coroutine=this.startCoroutine(this.moveToTarget())}*moveToTarget(){if(!this.target||!this.object)return;const e=Z(this.object).clone(),t=Z(this.target).clone(),i=be(this.object).clone(),n=be(this.target).clone(),s=$e(this.object).clone(),r=$e(this.target).clone(),a=e.distanceTo(t),l=i.angleTo(n),c=s.distanceTo(r);if(a<.01&&l<.01&&c<.01){mt(this.object,t),pn(this.object,n),wa(this.object,r),this.coroutine=null;return}let h=0,d=0;for(;h<1;)h+=this.context.time.deltaTime/this.duration,h>1&&(h=1),d=h<.5?4*h*h*h:1-Math.pow(-2*h+2,3)/2,this.targetPos.lerpVectors(e,t,d),this.targetRot.slerpQuaternions(i,n,d),this.targetScale.lerpVectors(s,r,d),mt(this.object,this.targetPos),pn(this.object,this.targetRot),wa(this.object,this.targetScale),yield;this.coroutine=null}*moveRelative(){if(!this.target||!this.object)return;const e=this.object.position.clone(),t=this.object.quaternion.clone(),i=this.object.scale.clone(),n=this.target.position.clone(),s=this.target.quaternion.clone(),r=this.target.scale.clone();n.applyQuaternion(this.object.quaternion),this.targetPos.copy(this.object.position).add(n),this.targetRot.copy(this.object.quaternion).multiply(s),this.targetScale.copy(this.object.scale).multiply(r);let a=0,l=0;for(;a<1;)a+=this.context.time.deltaTime/this.duration,a>1&&(a=1),l=a<.5?4*a*a*a:1-Math.pow(-2*a+2,3)/2,this.object.position.lerpVectors(e,this.targetPos,l),this.object.quaternion.slerpQuaternions(t,this.targetRot,l),this.object.scale.lerpVectors(i,this.targetScale,l),yield;this.coroutine=null}beforeCreateDocument(e){if(this.target&&this.object&&this.gameObject){const t=new Et("Move to "+this.target?.name,jt.tapTrigger(this.gameObject),me.transformAction(this.object,this.target,this.duration,this.relativeMotion?"relative":"absolute"));e.addBehavior(t)}}}Be([u(O)],Br.prototype,"object"),Be([u(O)],Br.prototype,"target"),Be([u()],Br.prototype,"duration"),Be([u()],Br.prototype,"relativeMotion");const qu=class Zt extends M{materialToSwitch;variantMaterial;fadeDuration=0;start(){this._objectsWithThisMaterial=this.objectsWithThisMaterial,Uc(this.gameObject),E()&&this._objectsWithThisMaterial.length<=0&&console.warn('ChangeMaterialOnClick: No objects found with material "'+this.materialToSwitch?.name+'"')}onPointerEnter(e){this.context.input.setCursor("pointer")}onPointerExit(e){this.context.input.unsetCursor("pointer")}onPointerClick(e){if(e.use(),!!this.variantMaterial)for(let t=0;t<this.objectsWithThisMaterial.length;t++){const i=this.objectsWithThisMaterial[t];i.material=this.variantMaterial}}_objectsWithThisMaterial=null;get objectsWithThisMaterial(){return this._objectsWithThisMaterial!=null?this._objectsWithThisMaterial:(this._objectsWithThisMaterial=[],this.variantMaterial&&this.materialToSwitch&&this.context.scene.traverse(e=>{if(e instanceof H)if(Array.isArray(e.material)){for(const t of e.material)if(t===this.materialToSwitch){this.objectsWithThisMaterial.push(e);break}}else e.material===this.materialToSwitch?this.objectsWithThisMaterial.push(e):iv(e.material,this.materialToSwitch)&&this.objectsWithThisMaterial.push(e)}),this._objectsWithThisMaterial)}selfModel;targetModels;static _materialTriggersPerId={};static _startHiddenBehaviour=null;static _parallelStartHiddenActions=[];async beforeCreateDocument(e,t){this.targetModels=[],Zt._materialTriggersPerId={},Zt.variantSwitchIndex=0,this.materialToSwitch&&await Ve.assignTextureLOD(this.materialToSwitch,0),this.variantMaterial&&await Ve.assignTextureLOD(this.variantMaterial,0)}createBehaviours(e,t,i){this.objectsWithThisMaterial.find(n=>n.uuid===t.uuid)&&this.targetModels.push(t),this.gameObject.uuid===t.uuid&&(this.selfModel=t,this.materialToSwitch&&(Zt._materialTriggersPerId[this.materialToSwitch.uuid]||(Zt._materialTriggersPerId[this.materialToSwitch.uuid]=[]),Zt._materialTriggersPerId[this.materialToSwitch.uuid].push(this)))}afterCreateDocument(e,t){if(!this.materialToSwitch)return;const i=Zt._materialTriggersPerId[this.materialToSwitch.uuid];if(i){const n={};for(const s of i){const r=s.createVariants();r&&r.length>0&&(n[s.selfModel.uuid]=r)}for(const s of i){const r=[];for(const a in n)a!==s.selfModel.uuid&&r.push(...n[a]);s.createAndAttachBehaviors(e,n[s.selfModel.uuid],r)}}delete Zt._materialTriggersPerId[this.materialToSwitch.uuid]}createAndAttachBehaviors(e,t,i){const n=[],s=Math.max(0,this.fadeDuration);n.push(me.fadeAction([...this.targetModels,...i],s,!1)),n.push(me.fadeAction(t,s,!0)),e.addBehavior(new Et("Select_"+this.selfModel.name,jt.tapTrigger(this.selfModel),me.parallel(...n))),Zt._parallelStartHiddenActions.push(...t),Zt._startHiddenBehaviour||(Zt._startHiddenBehaviour=new Et("StartHidden_"+this.selfModel.name,jt.sceneStartTrigger(),me.fadeAction(Zt._parallelStartHiddenActions,s,!1)),e.addBehavior(Zt._startHiddenBehaviour))}static getMaterialName(e){return Zi(e.name||"Material")+"_"+e.id}static variantSwitchIndex=0;createVariants(){if(!this.variantMaterial)return null;const e=[];for(const t of this.targetModels){const i=t.clone();i.name+="_Variant_"+Zt.variantSwitchIndex+++"_"+Zt.getMaterialName(this.variantMaterial),i.displayName=i.displayName+": Variant with material "+this.variantMaterial.name,i.material=this.variantMaterial,i.geometry=t.geometry,i.transform=t.transform,(!t.parent||!t.parent.isEmpty())&&it.createEmptyParent(t),t.parent&&t.parent.add(i),e.push(i)}return e}};Be([u(ve)],qu.prototype,"materialToSwitch"),Be([u(ve)],qu.prototype,"variantMaterial"),Be([u()],qu.prototype,"fadeDuration");let Kf=qu;const zc=class ze extends M{target;toggleOnClick=!1;targetState=!0;hideSelf=!0;start(){Uc(this.gameObject)}onPointerClick(e){e.use(),!this.toggleOnClick&&this.hideSelf&&(this.gameObject.visible=!1),this.target&&(this.target.visible=this.toggleOnClick?!this.target.visible:this.targetState)}selfModel;selfModelClone;targetModel;toggleModel;createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&(this.selfModel=t,this.selfModelClone=t.clone())}stateBeforeCreatingDocument=!1;targetStateBeforeCreatingDocument=!1;static clonedToggleIndex=0;static wasVisible=Symbol("usdz_SetActiveOnClick_wasVisible");static toggleClone=Symbol("clone for toggling");static reverseToggleClone=Symbol("clone for reverse toggling");beforeCreateDocument(){this.target&&(this.gameObject[ze.wasVisible]===void 0&&(this.gameObject[ze.wasVisible]=this.gameObject.activeSelf),this.target[ze.wasVisible]===void 0&&(this.target[ze.wasVisible]=this.target.activeSelf),this.stateBeforeCreatingDocument=this.gameObject[ze.wasVisible],this.targetStateBeforeCreatingDocument=this.target[ze.wasVisible],this.gameObject.visible=!0,this.target.visible=!0)}afterCreateDocument(e,t){if(!this.target)return;this.targetModel=t.document.findById(this.target.uuid);const i=this.selfModel;if(this.selfModel&&this.targetModel){let n=this.selfModel,s=this.targetState;if(this.toggleOnClick)if(s=!this.targetStateBeforeCreatingDocument,!this.selfModelClone.geometry)(!this.selfModel.parent||this.selfModel.parent.isEmpty())&&zf.createEmptyParent(this.selfModel),this.toggleModel=this.selfModel.deepClone(),this.toggleModel.name+="_toggle",this.selfModel.parent.add(this.toggleModel);else{if(!this.gameObject[ze.toggleClone]){const l=this.selfModelClone.clone();l.setMatrix(new ee),l.name+="_toggle"+ze.clonedToggleIndex++,i.add(l),this.gameObject[ze.toggleClone]=l,console.warn("USDZExport: Toggle "+this.gameObject.name+" doesn't have geometry. It will be deep cloned and nested behaviours will likely not work.")}const a=this.gameObject[ze.toggleClone];if(!this.gameObject[ze.reverseToggleClone]){const l=this.selfModelClone.clone();l.setMatrix(new ee),l.name+="_toggleReverse"+ze.clonedToggleIndex++,i.add(l),this.gameObject[ze.reverseToggleClone]=l}this.toggleModel=this.gameObject[ze.reverseToggleClone],(!this.toggleModel.geometry||!a.geometry)&&console.error("triggers without childs and without geometry won't work!",this,i.geometry),n=a,i.geometry=null,i.material=null}if(this.toggleModel){if(this.toggleOnClick){const a=[];a.push(me.fadeAction(n,0,!1)),a.push(me.fadeAction(this.toggleModel,0,!0)),a.push(me.fadeAction(this.targetModel,0,s)),e.addBehavior(new Et("Toggle_"+n.name+"_ToggleTo"+(s?"On":"Off"),jt.tapTrigger(n),me.parallel(...a)));const l=[];l.push(me.fadeAction(this.toggleModel,0,!1)),l.push(me.fadeAction(n,0,!0)),l.push(me.fadeAction(this.targetModel,0,!s)),e.addBehavior(new Et("Toggle_"+n.name+"_ToggleTo"+(s?"Off":"On"),jt.tapTrigger(this.toggleModel),me.parallel(...l)))}}else{const a=[];this.hideSelf&&a.push(me.fadeAction(n,0,!1)),a.push(me.fadeAction(this.targetModel,0,s)),e.addBehavior(new Et("Toggle_"+n.name+"_ToggleTo"+(s?"On":"Off"),jt.tapTrigger(n),a.length>1?me.parallel(...a):a[0]))}const r=new Array;this.targetStateBeforeCreatingDocument||r.push(this.targetModel),this.stateBeforeCreatingDocument||r.push(i),this.toggleModel&&r.push(this.toggleModel),cn.add(r,e)}}afterSerialize(e,t){this.gameObject[ze.wasVisible]!==void 0&&(this.gameObject.visible=this.gameObject[ze.wasVisible],delete this.gameObject[ze.wasVisible]),this.target&&this.target[ze.wasVisible]!==void 0&&(this.target.visible=this.target[ze.wasVisible],delete this.target[ze.wasVisible]),delete this.gameObject[ze.toggleClone],delete this.gameObject[ze.reverseToggleClone]}};Be([u(O)],zc.prototype,"target"),Be([u()],zc.prototype,"toggleOnClick"),Be([u()],zc.prototype,"targetState"),Be([u()],zc.prototype,"hideSelf");let Zf=zc;class cn extends M{static _fadeBehaviour;static _fadeObjects=[];static add(e,t){const i=Array.isArray(e)?e:[e];for(const n of i)cn._fadeObjects.includes(n)||(console.log("adding hide on start",n),cn._fadeObjects.push(n));cn._fadeBehaviour===void 0&&(cn._fadeBehaviour=new Et("HideOnStart",jt.sceneStartTrigger(),me.fadeAction(cn._fadeObjects,0,!1)),t.addBehavior(cn._fadeBehaviour))}start(){x.setActive(this.gameObject,!1)}createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&(this.wasVisible||cn.add(t,e))}wasVisible=!1;beforeCreateDocument(){this.wasVisible=x.isActiveSelf(this.gameObject)}}class ol extends M{target;duration=.5;motionType="bounce";beforeCreateDocument(){}createBehaviours(e,t,i){if(this.target&&t.uuid===this.gameObject.uuid){const n=new Et("emphasize "+this.name,jt.tapTrigger(this.gameObject),me.emphasize(this.target,this.duration,this.motionType,void 0,"basic"));e.addBehavior(n)}}afterCreateDocument(e,t){}}Be([u()],ol.prototype,"target"),Be([u()],ol.prototype,"duration"),Be([u()],ol.prototype,"motionType");class Os extends M{target;clip="";toggleOnClick=!1;trigger="tap";start(){Uc(this.gameObject)}ensureAudioSource(){if(!this.target){const e=this.gameObject.addComponent(Mi);e&&(this.target=e,e.spatialBlend=1,e.volume=1,e.loop=!1,e.preload=!0)}}onPointerClick(e){e.use(),!(!this.target?.clip&&!this.clip)&&(this.ensureAudioSource(),this.target&&(this.target.isPlaying&&this.toggleOnClick?this.target.stop():(!this.toggleOnClick&&this.target.isPlaying&&this.target.stop(),this.clip?this.target.play(this.clip):this.target.play())))}createBehaviours(e,t,i){if(!(!this.target&&!this.clip)&&t.uuid===this.gameObject.uuid){const n=this.clip?this.clip:this.target?this.target.clip:void 0;if(!n||typeof n!="string")return;const s=this.target?this.target.gameObject:this.gameObject;aa.getName(n);const r=this.target?this.target.volume:1,a=this.target&&this.target.spatialBlend==0?"nonSpatial":"spatial";let l=!1;this.gameObject.traverse(p=>{p instanceof H&&p.visible&&(l=!0)}),l=!0;const c=e.addAudioClip(n);let h=me.playAudioAction(s,c,"play",r,a);this.target&&this.target.loop&&(h=me.sequence(h).makeLooping());const d=this.name?"_"+this.name:"";if(l&&this.trigger==="tap"){this.toggleOnClick&&(h.multiplePerformOperation="stop");const p=new Et("playAudio"+d,jt.tapTrigger(t),h);e.addBehavior(p)}if(this.target&&this.target.playOnAwake&&this.target.enabled)if(l&&this.trigger==="tap")console.warn("USDZExport: Audio sources that are played on tap can't also auto-play at scene start due to a QuickLook bug.");else{const p=new Et("playAudioOnStart"+d,jt.sceneStartTrigger(),h);e.addBehavior(p)}}}}Be([u(Mi)],Os.prototype,"target"),Be([u(URL)],Os.prototype,"clip"),Be([u()],Os.prototype,"toggleOnClick");const Jf=class lo extends M{animator;stateName;trigger="tap";animation;get target(){return this.animator?.gameObject||this.animation?.gameObject}start(){Uc(this.gameObject)}onPointerClick(e){e.use(),this.target&&this.stateName&&this.animator?.play(this.stateName,0,0,.1)}selfModel;stateAnimationModel;animationSequence=new Array;animationLoopAfterSequence=new Array;randomOffsetNormalized=0;createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&(this.selfModel=t)}static animationActions=[];static rootsWithExclusivePlayback=new Set;afterSerialize(){if(lo.rootsWithExclusivePlayback.size>1){const e='Multiple root objects targeted by more than one animation. To work around QuickLook bug FB13410767, animations will be set as "exclusive" and activating them will stop other animations being marked as exclusive.';E()&&ge(e),console.warn(e,...lo.rootsWithExclusivePlayback)}lo.animationActions=[],lo.rootsWithExclusivePlayback=new Set}afterCreateDocument(e,t){if(this.animationSequence===void 0&&this.animationLoopAfterSequence===void 0||!this.stateAnimationModel||!this.target)return;const i=t.document,n=t.extensions.find(a=>a instanceof Gu);if(!n)return;const s=n.getClipCount(this.target)>1;s&&(E()&&console.warn("Setting exclusive playback for "+this.target.name+"@"+this.stateName+" because it has "+n.getClipCount(this.target)+" animations. This works around QuickLook bug FB13410767."),lo.rootsWithExclusivePlayback.add(this.target));const r=this.name?this.name:"";i.traverse(a=>{if(a.uuid===this.target?.uuid){const l=lo.getActionForSequences(i,a,this.animationSequence,this.animationLoopAfterSequence,this.randomOffsetNormalized),c=new Et(this.trigger+"_"+r+"_toPlayAnimation_"+this.stateName+"_on_"+this.target?.name,this.trigger=="tap"?jt.tapTrigger(this.selfModel):jt.sceneStartTrigger(),l);s&&c.makeExclusive(!0),e.addBehavior(c)}})}static getActionForSequences(e,t,i,n,s){const r=(l,c)=>{let h=lo.animationActions.find(d=>d.affectedObjects==l&&d.start==c.start&&d.duration==c.duration&&d.animationSpeed==c.speed);return h||(h=me.startAnimationAction(l,c),lo.animationActions.push(h)),h},a=me.sequence();if(i&&i.length>0)for(const l of i)a.addAction(r(t,l));if(n&&n.length>0){const l=a.actions.length==0?a:me.sequence();for(const c of n)l.addAction(r(t,c));l.makeLooping(),a!==l&&a.addAction(l)}return s&&s>0&&a.actions.unshift(me.waitAction(s)),a}static getAndRegisterAnimationSequences(e,t,i){if(!t)return;const n=t.getComponent(ft),s=t.getComponent(Ht);if(!n&&!s)return;if(n&&!i)throw new Error("PlayAnimationOnClick: No stateName specified for animator "+n.name+" on "+t.name);let r=[],a=[];if(s){const f=e.registerAnimation(t,s.clip);f&&(s.loop?a.push(f):r.push(f));let g=0;if(s.minMaxOffsetNormalized){const y=s.minMaxOffsetNormalized.x,_=s.minMaxOffsetNormalized.y;g=(s.clip?.duration||1)*(y+Math.random()*(_-y))}return{animationSequence:r,animationLoopAfterSequence:a,randomTimeOffset:g}}const l=n?.runtimeAnimatorController;let c=l?.findState(i),h=[],d=[];if(l&&c){const f=new Array;f.push(c);let g=!1;for(;f.length<100;){if(!c||c===null||!c.transitions||c.transitions.length===0){c.motion?.isLooping&&(g=!0);break}const y=c.transitions.find(v=>v.conditions.length===0),_=y?l.getState(y.destinationState,0):null;if(_&&f.includes(_)){c=_,g=!0;break}else if(y){if(c=_,!c)break;f.push(c)}else{g=c.motion?.isLooping??!1;break}}if(g&&c){const y=f.indexOf(c);h=f.slice(0,y),d=f.slice(y),xx&&console.log("found loop from "+i,"states until loop",h,"states looping",d)}else h=f,d=[],xx&&console.log("found no loop from "+i,"states",h);if(!d.length){const y=h[h.length-1],_=y.motion?.clip;if(_){let v;if(e.holdClipMap.has(_))v=e.holdClipMap.get(_);else{const P=y.name+"_hold";v=_.clone(),v.duration=1,v.name=P;const R=_.duration;v.tracks=_.tracks.map(k=>{const A=k.clone();A.times=new Float32Array([0,R]);const L=k.values.length,N=k.getValueSize(),j=k.values.slice(L-N,L);return A.values=new Float32Array(2*N),A.values.set(j,0),A.values.set(j,N),A}),v.name=P,e.holdClipMap.set(_,v)}if(v){const P={name:v.name,motion:{clip:v,isLooping:!1,name:v.name},speed:1,transitions:[],behaviours:[],hash:y.hash+1};d.push(P)}}}}if(h.length===1&&(!h[0].motion?.clip||h[0].motion?.clip.tracks?.length===0)){r=new Array;const f=e.registerAnimation(t,null);f&&r.push(f);return}if(h=h.filter(f=>f.motion?.clip&&f.motion?.clip.tracks?.length>0),d=d.filter(f=>f.motion?.clip&&f.motion?.clip.tracks?.length>0),h.length===0&&d.length===0){console.warn("No clips found for state "+i+" on "+n?.name+", can't export animation data");return}const p=(f,g)=>{if(!t)return;const y=e.registerAnimation(t,f.motion.clip??null);y?(y.speed=f.speed,g.push(y)):console.warn("Couldn't register animation for state "+f.name+" on "+n?.name)};if(h.length>0){r=new Array;for(const f of h)p(f,r)}if(d.length>0){a=new Array;for(const f of d)p(f,a)}let m=0;if(n&&l&&n.minMaxOffsetNormalized){const f=n.minMaxOffsetNormalized.x,g=n.minMaxOffsetNormalized.y;m=((h.length?h[0]:d.length?d[0]:null)?.motion.clip?.duration||1)*(f+Math.random()*(g-f))}return{animationSequence:r,animationLoopAfterSequence:a,randomTimeOffset:m}}createAnimation(e,t,i){if(!this.target||!this.animator&&!this.animation)return;const n=lo.getAndRegisterAnimationSequences(e,this.target,this.stateName);n&&(this.animationSequence=n.animationSequence,this.animationLoopAfterSequence=n.animationLoopAfterSequence,this.randomOffsetNormalized=n.randomTimeOffset,this.stateAnimationModel=t)}};Be([u(ft)],Jf.prototype,"animator"),Be([u()],Jf.prototype,"stateName");let Nc=Jf;class sl extends M{getType(){}target;getDuration(){}}Be([u(O)],sl.prototype,"target");class Wc extends M{target}Be([u(sl)],Wc.prototype,"target");class Vc extends sl{type=1;duration=1;getType(){switch(this.type){case 1:return"hide";case 0:return"show"}}getDuration(){return this.duration}}Be([u()],Vc.prototype,"type"),Be([u()],Vc.prototype,"duration");class ey extends Wc{}class Qs{static _instance;static create(){return new Qs}static getOrCreate(){return this._instance||(this._instance=this.create()),this._instance}get isSecureConnection(){return window.location.protocol==="https:"}get quicklookButton(){return this._quicklookButton}_quicklookButton;get arButton(){return this._arButton}_arButton;get vrButton(){return this._vrButton}_vrButton;get sendToQuestButton(){return this._sendToQuestButton}_sendToQuestButton;get qrButton(){return An.getOrCreate().createQRCode()}createQuicklookButton(){if(this._quicklookButton)return this._quicklookButton;const e=document.createElement("button");this._quicklookButton=e,e.dataset.needle="quicklook-button";const t=G.supportsQuickLookAR();e.innerText="View in AR",e.prepend(Ct("view_in_ar"));let i=!1,n=null;return e.addEventListener("click",()=>{n=pc(to),n||(i=!0,n=new to),i&&(n.objectToExport=z.Current.scene),n?(e.classList.add("this-mode-is-requested"),n.exportAndOpen().then(()=>{e.classList.remove("this-mode-is-requested")}).catch(s=>{e.classList.remove("this-mode-is-requested"),console.error(s)})):console.warn("No USDZExporter component found in the scene")}),this.hideElementDuringXRSession(e),e}createARButton(e){if(this._arButton)return this._arButton;const t="immersive-ar",i=document.createElement("button");return this._arButton=i,i.classList.add("webxr-button"),i.dataset.needle="webxr-ar-button",i.innerText="Enter AR",i.prepend(Ct("view_in_ar")),i.title="Click to start an AR session",i.addEventListener("click",()=>K.start(t,e)),this.updateSessionSupported(i,t),this.listenToXRSessionState(i,t),this.hideElementDuringXRSession(i),this.isSecureConnection||(i.disabled=!0,i.title="WebXR requires a secure connection (HTTPS)"),G.isMozillaXR()||navigator.xr?.addEventListener("devicechange",()=>this.updateSessionSupported(i,t)),i}createVRButton(e){if(this._vrButton)return this._vrButton;const t="immersive-vr",i=document.createElement("button");return this._vrButton=i,i.classList.add("webxr-button"),i.dataset.needle="webxr-vr-button",i.innerText="Enter VR",i.prepend(Ct("panorama_photosphere")),i.title="Click to start a VR session",i.addEventListener("click",()=>K.start(t,e)),this.updateSessionSupported(i,t),this.listenToXRSessionState(i,t),this.hideElementDuringXRSession(i),this.isSecureConnection||(i.disabled=!0,i.title="WebXR requires a secure connection (HTTPS)"),G.isMozillaXR()||navigator.xr?.addEventListener("devicechange",()=>this.updateSessionSupported(i,t)),i}createSendToQuestButton(){if(this._sendToQuestButton)return this._sendToQuestButton;const e="https://oculus.com/open_url/?url=",t=document.createElement("button");return this._sendToQuestButton=t,t.dataset.needle="webxr-sendtoquest-button",t.innerText="Open on Quest",t.prepend(Ct("share_windows")),t.title="Click to send this page to the Oculus Browser on your Quest",t.addEventListener("click",()=>{const i=encodeURIComponent(window.location.href),n=e+i;window.open(n)==null&&Te("This page doesn't allow popups. Please paste "+n+" into your browser.")}),this.listenToXRSessionState(t),this.hideElementDuringXRSession(t),G.isMozillaXR()||navigator.xr?.addEventListener("devicechange",()=>{navigator.xr?.isSessionSupported("immersive-vr")?t.style.display="none":t.style.display=""}),t}createQRCode(){return An.getOrCreate().createQRCode()}updateSessionSupported(e,t){if(!("xr"in navigator)){e.style.display="none";return}K.isSessionSupported(t).then(i=>{e.style.display=i?"":"none",E()&&!i&&console.log('[WebXR] "'+t+'" is not supported on this device \u2013 make sure your server runs using HTTPS and you have a device connected that supports '+t)})}hideElementDuringXRSession(e){Md(t=>{e["previous-display"]=e.style.display,e.style.display="none"}),Xm(t=>{e["previous-display"]!=null&&(e.style.display=e["previous-display"])})}listenToXRSessionState(e,t){t&&(K.onSessionRequestStart(i=>{i.mode===t?e.classList.add("this-mode-is-requested"):(e["was-disabled"]=e.disabled,e.disabled=!0,e.classList.add("other-mode-is-requested"))}),K.onSessionRequestEnd(i=>{e.classList.remove("this-mode-is-requested"),e.classList.remove("other-mode-is-requested"),e.disabled=e["was-disabled"]}))}}var UT=Object.defineProperty,zT=Object.getOwnPropertyDescriptor,bt=(o,e,t,i)=>{for(var n=i>1?void 0:i?zT(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&UT(e,t,n),n};const $c=w("debugspriterenderer"),NT=w("wireframe");class ca{static cache={};static getOrCreateGeometry(e){if(e.__cached_geometry)return e.__cached_geometry;if(e.guid&&ca.cache[e.guid])return $c&&console.log("Take cached geometry for sprite",e.guid),ca.cache[e.guid];const t=new un;e.__cached_geometry=t;const i=new Float32Array(e.triangles.length*3),n=new Float32Array(e.triangles.length*2);for(let s=0;s<e.triangles.length;s+=1){const r=e.triangles[s];i[s*3]=-e.vertices[r].x,i[s*3+1]=e.vertices[r].y,i[s*3+2]=0;const a=e.uv[r];n[s*2]=a.x,n[s*2+1]=1-a.y}return t.setAttribute("position",new pt(i,3)),t.setAttribute("uv",new pt(n,2)),e.guid&&(this.cache[e.guid]=t),$c&&console.log("Built sprite geometry",e,t),t}}class WT{x;y}function Sx(o){o&&(o.colorSpace!=go&&(o.colorSpace=go,o.needsUpdate=!0),o.minFilter==dd&&o.magFilter==dd&&(o.anisotropy=1,o.needsUpdate=!0))}let jo=class{constructor(o){o&&(this.texture=o,this.triangles=[0,1,2,0,2,3],this.uv=[{x:0,y:0},{x:1,y:0},{x:1,y:1},{x:0,y:1}],this.vertices=[{x:-.5,y:-.5},{x:.5,y:-.5},{x:.5,y:.5},{x:-.5,y:.5}])}guid;texture;triangles;uv;vertices;__cached_geometry;get mesh(){return this._mesh||(this._mesh=new H(ca.getOrCreateGeometry(this),this.material)),this._mesh}_mesh;get material(){return this._material||(this.texture&&Sx(this.texture),this._material=new xe({map:this.texture,color:16777215,side:vi,transparent:!0})),this._material}_material;getGeometry(){return ca.getOrCreateGeometry(this)}};bt([u()],jo.prototype,"guid",2),bt([u(Re)],jo.prototype,"texture",2),bt([Qe()],jo.prototype,"triangles",2),bt([Qe()],jo.prototype,"uv",2),bt([Qe()],jo.prototype,"vertices",2);const ty=Symbol("spriteOwner");class rl{sprites;constructor(){this.sprites=[]}}bt([u(jo)],rl.prototype,"sprites",2);const iy=class k0{static create(){const e=new k0;return e.spriteSheet=new rl,e}constructor(){}clone(){const e=new k0;return e.index=this.index,e.spriteSheet=this.spriteSheet,e}set sprite(e){e&&(this.spriteSheet?((this.index===null||this.index===void 0)&&(this.index=0),this.spriteSheet.sprites[this.index]=e):(this.spriteSheet=new rl,this.spriteSheet.sprites=[e],this.index=0))}get sprite(){if(this.spriteSheet)return this.spriteSheet.sprites[this.index]}spriteSheet;index=0;update(e){if(!this.spriteSheet)return;const t=this.index;if(t<0||t>=this.spriteSheet.sprites.length)return;const i=this.spriteSheet.sprites[t],n=i?.texture;if(n&&(Sx(n),!i.__hasLoadedProgressive)){i.__hasLoadedProgressive=!0;const s=n;Ve.assignTextureLOD(n,0).then(r=>{r instanceof Re&&(i.texture=r,e?.map===s&&(e.map=r,e.needsUpdate=!0))})}}};bt([u(rl)],iy.prototype,"spriteSheet",2),bt([u()],iy.prototype,"index",2);let al=iy;class ci extends M{drawMode=0;size={x:1,y:1};color;sharedMaterial;transparent=!0;cutoutThreshold=0;castShadows=!1;renderOrder=0;toneMapped=!0;set texture(e){if(!this._spriteSheet)return;const t=this._spriteSheet.spriteSheet?.sprites[this.spriteIndex];t&&(t.texture=e,this.updateSprite())}addSprite(e,t=!1){if(this._spriteSheet||(this._spriteSheet=al.create()),!this._spriteSheet.spriteSheet)return-1;this._spriteSheet.spriteSheet?.sprites.push(e);const i=this._spriteSheet.spriteSheet?.sprites.length-1;return t&&(this.spriteIndex=i),i}get sprite(){return this._spriteSheet}set sprite(e){if(e!==this._spriteSheet)if(typeof e=="number"){const t=Math.round(e);$c&&console.log("[SpriteSheet] Set index to "+t+" (was "+this.spriteIndex+")",e),this.spriteIndex=t}else e instanceof jo?(this._spriteSheet||(this._spriteSheet=al.create()),this._spriteSheet.sprite!=e&&(this._spriteSheet.sprite=e),this.updateSprite()):e!=this._spriteSheet&&(this._spriteSheet=e,this.updateSprite())}set spriteIndex(e){this._spriteSheet&&(this._spriteSheet.index=e,this.updateSprite())}get spriteIndex(){return this._spriteSheet?.index??0}get spriteFrames(){return this._spriteSheet?.spriteSheet?.sprites.length??0}_spriteSheet;_currentSprite;awake(){this._currentSprite=void 0,this._spriteSheet?this._spriteSheet=this._spriteSheet.clone():this._spriteSheet=al.create(),$c&&console.log("Awake",this.name,this,this.sprite)}start(){this._currentSprite?this.gameObject&&this.gameObject.add(this._currentSprite):this.updateSprite()}updateSprite(e=!1){if(!this.__didAwake&&!e)return!1;const t=this._spriteSheet;if(!t?.spriteSheet?.sprites)return console.warn("SpriteRenderer has no data or spritesheet assigned..."),!1;const i=t.spriteSheet.sprites[this.spriteIndex];if(!i)return $c&&console.warn("Sprite not found",this.spriteIndex,t.spriteSheet.sprites),!1;if(this._currentSprite)this._currentSprite.geometry=ca.getOrCreateGeometry(i),this._currentSprite.material.map=i.texture;else{const n=new xe({color:16777215,side:vi});if(NT&&(n.wireframe=!0),this.color&&(n.color||(n.color=new ne),n.color.copy(this.color),n.opacity=this.color.alpha),n.transparent=!0,n.toneMapped=this.toneMapped,n.depthWrite=!1,i.texture&&!n.wireframe){let s=i.texture;s[ty]!==void 0&&s[ty]!==this&&this.spriteFrames>1&&(s=i.texture=s.clone()),s[ty]=this,n.map=s}this.sharedMaterial=n,this._currentSprite=new H(ca.getOrCreateGeometry(i),n),this._currentSprite.renderOrder=Math.round(this.renderOrder),Ve.assignTextureLOD(n,0)}return this._currentSprite.parent!==this.gameObject&&(this.drawMode===2&&this._currentSprite.scale.set(this.size.x,this.size.y,1),this.gameObject&&this.gameObject.add(this._currentSprite)),this._currentSprite&&this._currentSprite.layers.set(this.layer),this.sharedMaterial&&(this.sharedMaterial.alphaTest=this.cutoutThreshold,this.sharedMaterial.transparent=this.transparent),this._currentSprite.castShadow=this.castShadows,t?.update(this.sharedMaterial),!0}}bt([u()],ci.prototype,"drawMode",2),bt([u(WT)],ci.prototype,"size",2),bt([u(se)],ci.prototype,"color",2),bt([u(ve)],ci.prototype,"sharedMaterial",2),bt([u()],ci.prototype,"transparent",2),bt([u()],ci.prototype,"cutoutThreshold",2),bt([u()],ci.prototype,"castShadows",2),bt([u()],ci.prototype,"renderOrder",2),bt([u()],ci.prototype,"toneMapped",2),bt([u(al)],ci.prototype,"sprite",1);const Cx=w("debugwebxr"),VT=new ee().makeRotationY(Math.PI);class Ui extends M{static _eventListeners={};static onPlaced(e){const t="placed";return this._eventListeners[t]||(this._eventListeners[t]=[]),this._eventListeners[t].push(e),()=>{const i=this._eventListeners[t].indexOf(e);i>=0&&this._eventListeners[t].splice(i,1)}}static _hasPlaced=!1;static get hasPlaced(){return this._hasPlaced}get arScale(){return this._arScale}set arScale(e){this._arScale=Math.max(1e-6,e),this.onSetScale()}_arScale=1;invertForward=!1;customReticle;arTouchTransform=!0;autoPlace=!1;autoCenter=!1;useXRAnchor=!1;_isPlacing=!0;_startOffset=new ee;_createdPlacementObject=null;_reparentedComponents=[];_placementScene=new yi;_reticle=[];_hits=[];_placementStartTime=-1;_rigPlacementMatrix;_anchor=null;userInput;onEnable(){this.customReticle?.preload()}supportsXR(e){return e==="immersive-ar"}onEnterXR(e){Cx&&console.log("ENTER WEBXR: SessionRoot start..."),this._anchor=null,Ui._hasPlaced=!1,this.gameObject.updateMatrixWorld(),this._startOffset.copy(this.gameObject.matrixWorld);const t=new O;this._createdPlacementObject=t,t.name="AR Session Root",this._placementScene.name="AR Placement Scene",this._placementScene.children.length=0;for(let i=this.context.scene.children.length-1;i>=0;i--){const n=this.context.scene.children[i];this._placementScene.add(n)}if(this.context.scene.add(t),this.autoCenter){const i=Wt(this._placementScene.children),n=i.getCenter(new b),s=i.getSize(new b),r=new ee;r.makeTranslation(n.x,n.y-s.y*.5,n.z),this._startOffset.multiply(r)}this._reparentedComponents.length=0,this._reparentedComponents.push({comp:this,originalObject:this.gameObject}),x.addComponent(t,this);for(const i of this._reticle)Ci(i);this._reticle.length=0,this._isPlacing=!0,this.context.input.addEventListener("pointerup",this.onPlaceScene,{queue:ii.Early})}onLeaveXR(){this.context.input.removeEventListener("pointerup",this.onPlaceScene,{queue:ii.Early}),this.onRevertSceneChanges(),this._anchor=null,Ui._hasPlaced=!1,this._rigPlacementMatrix=void 0}onUpdateXR(e){if(e.xr.isTrackingImages){for(const t of this._reticle)t.visible=!1;return}if(this._isPlacing){const t=e.xr.rig?.gameObject;t&&t.parent!==this.context.scene&&this.context.scene.add(t);let i=!1;if(e.xr.isPassThrough&&e.xr.controllers.length>0&&!this.autoPlace)for(const n of e.xr.controllers){const s=n.getHitTest();s&&(i=!0,this.updateReticleAndHits(e.xr,n.index,s,e.xr.rigScale))}if(!i){const n=e.xr.getHitTest();n&&this.updateReticleAndHits(e.xr,0,n,e.xr.rigScale)}}else{if(this._anchor&&e.xr.referenceSpace){const t=e.xr.frame.getPose(this._anchor.anchorSpace,e.xr.referenceSpace);if(t&&this.context.time.frame%20===0){const i=e.xr.convertSpace(t.transform),n=this._reticle[0];n&&(n.position.copy(i.position),n.quaternion.copy(i.quaternion),this.onApplyPose(n))}}if(this.arTouchTransform?(this.userInput||(this.userInput=new Kp(this.context)),this.userInput?.enable()):this.userInput?.disable(),this.arTouchTransform&&this.userInput?.hasChanged){if(e.xr.rig){const t=e.xr.rig.gameObject;this.userInput.applyMatrixTo(t.matrix,!0),t.matrix.decompose(t.position,t.quaternion,t.scale),this.userInput.factor=t.scale.x}this.userInput.reset()}}}updateReticleAndHits(e,t,i,n){this._hits[t]=i.hit;let s=this._reticle[t];if(!s){if(this.customReticle)if(this.customReticle.asset)s=Da(this.customReticle.asset);else{this.customReticle.loadAssetAsync();return}else s=new H(new GS(.07,.09,32).rotateX(-Math.PI/2),new xe({side:vi,depthTest:!1,depthWrite:!1,transparent:!0,opacity:1,color:15658734})),s.name="AR Placement Reticle";if(Cx){const r=new _i(1);r.position.y+=.01,s.add(r)}this._reticle[t]=s,s.matrixAutoUpdate=!1,s.visible=!1}if(s.lastPos=s.lastPos||i.position.clone(),s.lastQuat=s.lastQuat||i.quaternion.clone(),s.position.copy(s.lastPos.lerp(i.position,this.context.time.deltaTime/.1)),s.lastPos.copy(s.position),s.quaternion.copy(s.lastQuat.slerp(i.quaternion,this.context.time.deltaTime/.05)),s.lastQuat.copy(s.quaternion),s.scale.set(n,n,n),this.customReticle&&this.applyViewBasedTransform(s),s.updateMatrix(),s.visible=!0,s.parent!==this.context.scene&&this.context.scene.add(s),this._placementStartTime<0&&(this._placementStartTime=this.context.time.realtimeSinceStartup),this.autoPlace)if(this.upVec.set(0,1,0).applyQuaternion(s.quaternion),this.upVec.dot($(0,1,0))>.9){let r=s["autoplace:timer"]||0;r>=1?(s.visible=!1,this.onPlaceScene(null)):(r+=this.context.time.deltaTime,s["autoplace:timer"]=r)}else s["autoplace:timer"]=0}onPlaceScene=e=>{if(this._isPlacing==!1||e?.used)return;let t=this._reticle[0];if(!t){console.warn("No reticle to place...");return}if(!t.visible&&!this.autoPlace){console.warn("Reticle is not visible (can not place)");return}if(K.active?.isTrackingImages){console.warn("Scene Placement is disabled while images are being tracked");return}let i=this._hits[0];if(e&&e.origin instanceof Qm){const n=this._reticle[e.origin.index];n&&(t=n,i=this._hits[e.origin.index])}if(e&&(e.stopImmediatePropagation(),e.stopPropagation(),e.use()),this._isPlacing=!1,this.context.input.removeEventListener("pointerup",this.onPlaceScene),this.onRevertSceneChanges(),t.position.copy(t.lastPos),t.quaternion.copy(t.lastQuat),this.onApplyPose(t),Ui._hasPlaced=!0,this.useXRAnchor&&this.onCreateAnchor(K.active,i),this.context.xr)for(const n of this.context.xr.controllers)n.cancelHitTestSource()};onSetScale(){if(!Ui._hasPlaced)return;const e=K.active?.rig?.gameObject;if(e){const t=K.active?.rigScale||1,i=1/this._arScale*t,n=new ee().makeScale(i,i,i).invert();e.matrix.premultiply(n),e.matrix.decompose(e.position,e.quaternion,e.scale)}}onRevertSceneChanges(){for(const e of this._reticle)e&&(e.visible=!1,e?.removeFromParent());this._reticle.length=0;for(let e=this._placementScene.children.length-1;e>=0;e--){const t=this._placementScene.children[e];this.context.scene.add(t)}this._createdPlacementObject?.removeFromParent();for(const e of this._reparentedComponents)x.addComponent(e.originalObject,e.comp)}async onCreateAnchor(e,t){if(t.createAnchor===void 0){console.warn("Hit does not support creating an anchor",t),E()&&ge("Hit does not support creating an anchor");return}else{const i=await t.createAnchor(e.viewerPose.transform);e.running&&i&&(this._anchor=i)}}upVec=new b(0,1,0);lookPoint=new b;worldUpVec=new b(0,1,0);applyViewBasedTransform(e){const t=this.context.mainCamera,i=e,n=t.worldPosition,s=i.worldPosition;this.upVec.set(0,1,0).applyQuaternion(e.quaternion);const r=t.worldPosition;r&&e.position.clone().sub(r).angleTo(this.upVec)<Math.PI/2&&this.upVec.negate();const a=this.upVec.angleTo(this.worldUpVec)*180/Math.PI,l=30;a>l&&a<180-l||a<-l&&a>-180+l?(this.lookPoint.copy(e.position).add(this.upVec),this.lookPoint.y=e.position.y,e.lookAt(this.lookPoint)):(n.y=s.y,e.lookAt(n))}onApplyPose(e){const t=K.active?.rig?.gameObject;if(!t){console.warn("No rig object to place");return}const i=t.parent||this.context.scene;this._rigPlacementMatrix?this._rigPlacementMatrix?.decompose(t.position,t.quaternion,t.scale):this._rigPlacementMatrix=t.matrix.clone(),this.applyViewBasedTransform(e),e.updateMatrix(),this.context.scene.add(e),e.attach(t),e.removeFromParent(),t.scale.set(this.arScale,this.arScale,this.arScale),t.position.multiplyScalar(this.arScale),t.updateMatrix(),this.invertForward&&t.matrix.premultiply(VT),t.matrix.premultiply(this._startOffset),t.matrix.decompose(t.position,t.quaternion,t.scale),i.add(t)}}class Kp{static up=new b(0,1,0);static zero=new b(0,0,0);static one=new b(1,1,1);oneFingerDrag=!0;twoFingerRotate=!0;twoFingerScale=!0;factor=1;context;offset;plane;_scale=1;_hasChanged=!1;get scale(){return this._scale}constructor(e){this.context=e,this.offset=new ee,this.plane=new tr,this.plane.setFromNormalAndCoplanarPoint(Kp.up,Kp.zero)}_enabled=!1;reset(){this._scale=1,this.offset.identity(),this._hasChanged=!0}get hasChanged(){return this._hasChanged}applyMatrixTo(e,t){this._hasChanged=!1,t?(this.offset.invert(),e.premultiply(this.offset)):e.multiply(this.offset)}currentlyUsedPointerIds=new Set;currentlyUnusedPointerIds=new Set;get isActive(){return this.currentlyUsedPointerIds.size<=0&&this.currentlyUnusedPointerIds.size>0}enable(){this._enabled||(this._enabled=!0,this.context.input.addEventListener("pointerdown",this.onPointerDownEarly,{queue:ii.Early}),this.context.input.addEventListener("pointerdown",this.onPointerDownLate,{queue:ii.Late}),this.context.input.addEventListener("pointerup",this.onPointerUpEarly,{queue:ii.Early}),window.addEventListener("touchstart",this.touchStart,{passive:!1}),window.addEventListener("touchmove",this.touchMove,{passive:!1}),window.addEventListener("touchend",this.touchEnd,{passive:!1}))}disable(){this._enabled&&(this._enabled=!1,this.context.input.removeEventListener("pointerdown",this.onPointerDownEarly,{queue:ii.Early}),this.context.input.removeEventListener("pointerdown",this.onPointerDownLate,{queue:ii.Late}),this.context.input.removeEventListener("pointerup",this.onPointerUpEarly,{queue:ii.Early}),window.removeEventListener("touchstart",this.touchStart),window.removeEventListener("touchmove",this.touchMove),window.removeEventListener("touchend",this.touchEnd))}onPointerDownEarly=e=>{this.isActive&&e.stopPropagation()};onPointerDownLate=e=>{e.used?this.currentlyUsedPointerIds.add(e.pointerId):this.currentlyUsedPointerIds.size<=0&&this.currentlyUnusedPointerIds.add(e.pointerId)};onPointerUpEarly=e=>{this.currentlyUsedPointerIds.delete(e.pointerId),this.currentlyUnusedPointerIds.delete(e.pointerId)};prev=new Map;_didMultitouch=!1;touchStart=e=>{if(!e.defaultPrevented)for(let t=0;t<e.changedTouches.length;t++){const i=e.changedTouches[t],n=G.isAndroidDevice()&&i.clientY<window.innerHeight*.1;this.prev.has(i.identifier)||this.prev.set(i.identifier,{ignore:n,x:0,z:0,screenx:0,screeny:0});const s=this.prev.get(i.identifier);if(s){const r=this.getPositionOnPlane(i.clientX,i.clientY);s.x=r.x,s.z=r.z,s.screenx=i.clientX,s.screeny=i.clientY}}};touchEnd=e=>{e.touches.length<=0&&(this._didMultitouch=!1);for(let t=0;t<e.changedTouches.length;t++){const i=e.changedTouches[t];this.prev.delete(i.identifier)}};touchMove=e=>{if(!e.defaultPrevented&&this.isActive){if(e.touches.length===1){if(this._didMultitouch)return;const t=e.touches[0],i=this.prev.get(t.identifier);if(!i||i.ignore)return;const n=this.getPositionOnPlane(t.clientX,t.clientY),s=n.x-i.x,r=n.z-i.z;if(s===0&&r===0)return;this.oneFingerDrag&&this.addMovement(s,r),i.x=n.x,i.z=n.z,i.screenx=t.clientX,i.screeny=t.clientY;return}else if(e.touches.length===2){this._didMultitouch=!0;const t=e.touches[0],i=e.touches[1],n=this.prev.get(t.identifier),s=this.prev.get(i.identifier);if(!n||!s)return;if(this.twoFingerRotate){const r=Math.atan2(t.clientY-i.clientY,t.clientX-i.clientX),a=Math.atan2(n.screeny-s.screeny,n.screenx-s.screenx),l=r-a;Math.abs(l)>.001&&this.addRotation(l)}if(this.twoFingerScale){const r=t.clientX-i.clientX,a=t.clientY-i.clientY,l=Math.sqrt(r*r+a*a),c=n.screenx-s.screenx,h=n.screeny-s.screeny,d=Math.sqrt(c*c+h*h),p=l-d;Math.abs(p)>2&&this.addScale(p)}n.screenx=t.clientX,n.screeny=t.clientY,s.screenx=i.clientX,s.screeny=i.clientY}}};_raycaster=new sd;_intersection=new b;_screenPos=new b;getPositionOnPlane(e,t){const i=this.context.mainCamera;return this._screenPos.x=e/window.innerWidth*2-1,this._screenPos.y=-(t/window.innerHeight)*2+1,this._screenPos.z=1,this._screenPos.unproject(i),this._raycaster.set(i.position,this._screenPos.sub(i.position)),this._raycaster.ray.intersectPlane(this.plane,this._intersection),this._intersection}addMovement(e,t){e/=this._scale,t/=this._scale,e*=this.factor,t*=this.factor,this.offset.elements[12]+=e,this.offset.elements[14]+=t,(e!==0||t!==0)&&(this._hasChanged=!0)}_tempMatrix=new ee;addScale(e){e/=window.innerWidth,e*=-1,this._scale*=1+e,this._tempMatrix.makeScale(1-e,1-e,1-e),this.offset.premultiply(this._tempMatrix),e!==0&&(this._hasChanged=!0)}addRotation(e){e*=-1,this._tempMatrix.makeRotationY(e),this.offset.premultiply(this._tempMatrix),e!==0&&(this._hasChanged=!0)}}const ks=w("debugautosync"),ny=Symbol("syncerId");class $T{_syncers={};getOrCreateSyncer(e){if(!e.guid)return null;if(this._syncers[e.guid])return this._syncers[e.guid];const t=new HT(e);return t[ny]=e.guid,this._syncers[t[ny]]=t,t}removeSyncer(e){delete this._syncers[e[ny]]}}const oy=new $T;class HT{comp;constructor(e){this.comp=e}hasChanges=!1;changedProperties={};get networkingKey(){return this.comp.guid}_isReceiving=!1;_isInit=!1;init(e){if(this._isInit)return;this._isInit=!0,this.comp=e,this.comp.context.post_render_callbacks.push(this.onHandleSending),this.comp.context.connection.beginListen(this.networkingKey,this.onHandleReceiving);const t=this.comp.context.connection.tryGetState(this.comp.guid);t&&this.onHandleReceiving(t)}destroy(){this._isInit&&(this.comp.context.post_render_callbacks.splice(this.comp.context.post_render_callbacks.indexOf(this.onHandleSending),1),this.comp.context.connection.stopListen(this.networkingKey,this.onHandleReceiving),this.comp=null,this._isInit=!1)}notifyChanged(e,t){this._isReceiving||(ks&&console.log("Property changed: "+e,t),this.hasChanges=!0,this.changedProperties[e]=t)}onHandleSending=()=>{if(!this.hasChanges)return;this.hasChanges=!1;const e=this.comp.context.connection;if(!e||!e.isConnected||!e.isInRoom){for(const t in this.changedProperties)delete this.changedProperties[t];return}for(const t in this.changedProperties){const i=this.changedProperties[t];ks&&console.log("SEND",this.comp.guid,this.networkingKey),e.send(this.networkingKey,{guid:this.comp.guid,property:t,data:i},fn.Queued),delete this.changedProperties[t]}};onHandleReceiving=e=>{if(ks&&console.log("SYNCFIELD RECEIVE",this.comp.name,this.comp.guid,e),!!this._isInit&&this.comp&&e.guid===this.comp.guid)try{this._isReceiving=!0,this.comp[e.property]=e.data}catch(t){console.error(t)}finally{this._isReceiving=!1}}}function GT(o,e){let t=e!==o;return!t&&o&&e&&(Array.isArray(o)&&Array.isArray(e)||typeof o=="object"&&typeof e=="object")&&(t=!0),t}const Hc=Symbol("AutoSyncHandler");function qT(o){if(o[Hc])return o[Hc];const e=oy.getOrCreateSyncer(o);return e?.init(o),o[Hc]=e,e}function XT(o){const e=o[Hc];e&&(oy.removeSyncer(e),e.destroy(),delete o[Hc])}const sy=function(o=null){return function(e,t){let i="";typeof t=="string"?i=t:i=t.name;let n=null,s;typeof o=="string"?s=e[o]:typeof o=="function"&&(s=o),s==null&&(E()||ks)&&o!=null&&console.warn('syncField: no callback function found for property "'+i+'"','"'+o+'"');const r=e,a=r.__internalAwake;if(typeof a!="function"){(ks||E())&&console.error('@syncField can currently only used on Needle Engine Components, custom object of type "'+e?.constructor?.name+'" is not supported',e);return}ks&&console.log(i);const l=Symbol(i);r.__internalAwake=function(){if(this[l]===void 0){if(this[l]=this[i],n=oy.getOrCreateSyncer(this),Object.getOwnPropertyDescriptor(this,i)?.set===void 0){let h=!1;Object.defineProperty(this,i,{set:function(d){const p=this[l];if(this[l]=d,h){(E()||ks)&&console.warn("Recursive call detected",i);return}h=!0;try{const m=GT(d,p);ks&&console.log("SyncField assignment",i,"changed?",m,d,s),m&&s?.call(this,d,p)!==!1&&qT(this)?.notifyChanged(i,d)}finally{h=!1}},get:function(){return this[l]},configurable:!0,enumerable:!0})}n?.init(this),a.call(this)}};const c=r.__internalDestroy;r.__internalDestroy=function(){XT(this),c.call(this)}}};var QT=Object.defineProperty,Xu=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&QT(e,t,n),n};const Yt=w("debugplayersync"),Qu=class $1 extends M{static async setupFrom(e,t){const i=ie.getOrCreateFromUrl(e);if(!i.asset){const r=await i.loadAssetAsync();r&&x.getOrAddComponent(r,xn)}const n=new $1;n._internalInit(t),n.asset=i;const s=new O;return s.guid=e,x.addComponent(s,n),n}autoSync=!0;asset;onPlayerSpawned;_localInstance;awake(){this.watchTabVisible(),this.onPlayerSpawned||(this.onPlayerSpawned=new ce)}onEnable(){this.context.connection.beginListen(te.RoomStateSent,this.onJoinedRoom),this.context.connection.beginListen(te.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(te.LeftRoom,this.destroyInstance),this.context.connection.isInRoom&&this.onJoinedRoom()}onDisable(){this.context.connection.stopListen(te.RoomStateSent,this.onJoinedRoom),this.context.connection.stopListen(te.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(te.LeftRoom,this.destroyInstance)}onJoinedRoom=()=>{Yt&&console.log("PlayerSync.joinedRoom. autoSync is set to "+this.autoSync),this.autoSync&&this.getInstance()};async getInstance(){if(this._localInstance)return this._localInstance;if(Yt&&console.log("PlayerSync.createInstance",this.asset?.url),!this.asset?.asset&&!this.asset?.url)return console.error('PlayerSync: can not create an instance because "asset" is not set and or has no URL!'),null;this.gameObject.guid||console.warn("PlayerSync: gameObject has no guid! This might cause issues with syncing the player state."),this._localInstance=this.asset?.instantiateSynced({parent:this.gameObject,deleteOnDisconnect:!0},!0);const e=await this._localInstance;if(e){const t=x.getComponentsInChildren(e,xn);if(Yt&&console.log(`PlayerSync.createInstance: found ${t?.length} PlayerState components. Owner: ${this.context.connection.connectionId}`),t?.length){for(const i of t)i.owner=this.context.connection.connectionId;this.onPlayerSpawned?.invoke(e)}else this._localInstance=void 0,console.error("<strong>Failed finding PlayerState on "+this.asset?.url+"</strong>: please make sure the asset has a PlayerState component!"),x.destroySynced(e)}else this._localInstance=void 0,console.warn("PlayerSync: failed instantiating asset!");return this._localInstance}destroyInstance=()=>{this._localInstance?.then(e=>{Yt&&console.log("PlayerSync.destroyInstance",e),ac(e,this.context.connection,!0,{saveInRoom:!1})}),this._localInstance=void 0};watchTabVisible(){window.addEventListener("visibilitychange",e=>{if(document.visibilityState==="visible")for(let t=xn.all.length-1;t>=0;t--){const i=xn.all[t];(!i.owner||!this.context.connection.userIsInRoom(i.owner))&&i.doDestroy()}})}};Xu([u()],Qu.prototype,"autoSync"),Xu([u(ie)],Qu.prototype,"asset"),Xu([u(ce)],Qu.prototype,"onPlayerSpawned");let ry=Qu;var Px=(o=>(o.OwnerChanged="ownerChanged",o))(Px||{});const ay=class Rt extends M{static _all=[];static get all(){return Rt._all}static _local=[];static get local(){return Rt._local}static getFor(e){if(e instanceof O)return x.getComponentInParent(e,Rt);if(e instanceof M)return x.getComponentInParent(e.gameObject,Rt)}static isLocalPlayer(e){return Rt.getFor(e)?.isLocalPlayer??!1}static _callbacks={};static addEventListener(e,t){return this._callbacks[e]||(this._callbacks[e]=[]),this._callbacks[e].push(t),t}static removeEventListener(e,t){if(!this._callbacks[e])return;const i=this._callbacks[e].indexOf(t);i>=0&&this._callbacks[e].splice(i,1)}static dispatchEvent(e,t){if(this._callbacks[e])for(const i of this._callbacks[e])i(t)}onOwnerChangeEvent=new ce;onFirstOwnerChangeEvent=new ce;hasOwner=!1;owner;dontDestroy=!1;get isLocalPlayer(){return this.owner===this.context.connection.connectionId}onOwnerChange(e,t){Yt&&console.log(`PlayerSync.onOwnerChange: ${t} \u2192 ${e} (me: ${this.context.connection.connectionId})`);const i=Rt._local.indexOf(this);i>=0&&Rt._local.splice(i,1);const n={playerState:this,oldValue:t,newValue:e};if(this.hasOwner||(this.hasOwner=!0,this.onFirstOwnerChangeEvent?.invoke(n)),this.onOwnerChangeEvent?.invoke(n),this.owner===this.context.connection.connectionId){Rt._local.push(this);const r=new CustomEvent("local-owner-changed",{detail:n});this.dispatchEvent(r)}const s=new CustomEvent("owner-changed",{detail:n});this.dispatchEvent(s),Rt.dispatchEvent("ownerChanged",s)}awake(){Rt.all.push(this),Yt&&console.log("Registered new PlayerState",this.guid,Rt.all.length-1,Rt.all),this.context.connection.beginListen(te.UserLeftRoom,this.onUserLeftRoom)}async start(){Yt&&console.log("PLAYERSTATE.START, owner: "+this.owner,this.context.connection.usersInRoom([])),this.owner?(this.context.connection.isInRoom||await Dn(300),this.context.connection.userIsInRoom(this.owner)==!1&&(Yt&&console.log(`PlayerSync.start \u2192 doDestroy "${this.name}" because user "${this.owner}" is not in room anymore...`,"Currently in room:",...this.context.connection.usersInRoom()),this.doDestroy())):this.owner||(Yt&&console.warn("PlayerState.start \u2192 owner is undefined!",this.name),setTimeout(()=>{!this.destroyed&&!this.owner?this.dontDestroy?Yt&&console.warn("PlayerState.start \u2192 owner is still undefined but dontDestroy is set to true",this.name):(Yt&&console.warn(`PlayerState.start \u2192 owner is still undefined: destroying "${this.name}" instance now`),this.doDestroy()):Yt&&console.log("PlayerState.start \u2192 owner is assigned",this.owner)},2e3))}doDestroy(){Yt&&console.log("PlayerSync.doDestroy \u2192 syncDestroy",this.name),ac(this.gameObject,this.context.connection,!0,{saveInRoom:!1})}onDestroy(){if(Yt&&console.warn("PlayerState.onDestroy",this.owner),this.context.connection.stopListen(te.UserLeftRoom,this.onUserLeftRoom),Rt.all.splice(Rt.all.indexOf(this),1),this.isLocalPlayer){const e=Rt._local.indexOf(this);e>=0&&Rt._local.splice(e,1)}}onUserLeftRoom=e=>{if(e.userId===this.owner){Yt&&console.log("PLAYERSYNC LEFT",this.owner),this.doDestroy();return}}};Xu([sy(ay.prototype.onOwnerChange)],ay.prototype,"owner");let xn=ay;var YT=Object.defineProperty,ll=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&YT(e,t,n),n};class Jn extends M{position="bottom";showNeedleLogo=!1;showSpatialMenu;createFullscreenButton;createMuteButton;createQRCodeButton;onEnable(){this.applyOptions()}applyOptions(){this.context.menu.setPosition(this.position),this.context.menu.showNeedleLogo(this.showNeedleLogo),this.createFullscreenButton===!0&&this.context.menu.showFullscreenOption(!0),this.createMuteButton===!0&&this.context.menu.showAudioPlaybackOption(!0),this.showSpatialMenu===!0&&this.context.menu.showSpatialMenu(this.showSpatialMenu),this.createQRCodeButton===!0&&(G.isMobileDevice()||this.context.menu.showQRCodeButton(!0))}}ll([u()],Jn.prototype,"position"),ll([u()],Jn.prototype,"showNeedleLogo"),ll([u()],Jn.prototype,"showSpatialMenu"),ll([u()],Jn.prototype,"createFullscreenButton"),ll([u()],Jn.prototype,"createMuteButton"),ll([u()],Jn.prototype,"createQRCodeButton");var KT=Object.defineProperty,ly=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&KT(e,t,n),n};const Gc=w("debugwebxr"),Ox=new U().setFromAxisAngle(new b(0,1,0),Math.PI);class Ms extends M{head;leftHand;rightHand;_leftHandMeshes;_rightHandMeshes;_syncTransforms;async onEnterXR(e){if(!this.activeAndEnabled)return;Gc&&console.warn("AVATAR ENTER XR",this.guid,this.sourceId,this,this.activeAndEnabled),this._syncTransforms&&(this._syncTransforms.length=0),await this.prepareAvatar();const t=xn.getFor(this);if(t?.owner){const i=this.gameObject.addComponent(Le);i.avatar=this.gameObject,i.connectionId=t.owner}else this.context.connection.isConnected?console.error("No player state found for avatar",this):t&&!this.context.connection.isConnected&&(t.dontDestroy=!0)}onLeaveXR(e){const t=this.gameObject.getComponent(Le);t&&t.destroy()}onUpdateXR(e){if(!this.activeAndEnabled)return;const t=xn.isLocalPlayer(this);if(!t)return;const i=e.xr;if(i.rig&&i.rig.gameObject!==this.gameObject.parent&&(this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),this.gameObject.scale.set(1,1,1),i.rig.gameObject.add(this.gameObject)),this._syncTransforms&&t)for(const l of this._syncTransforms)l.fastMode=!0,l.isOwned()||l.requestOwnership();if(this.head&&this.context.mainCamera){const l=this.head.asset;if(l.position.copy(this.context.mainCamera.position),l.position.x*=-1,l.position.z*=-1,l.quaternion.copy(this.context.mainCamera.quaternion),l.quaternion.x*=-1,this.context.time.frameCount%10===0&&this.head.asset){const c=x.getComponentsInChildren(this.head.asset,Ki);for(const h of c)h.enabled=!1,h.gameObject.visible=!1}}const n=e.xr.leftController,s=this.leftHand?.asset;n&&s?(s.position.copy(n.gripPosition),s.quaternion.copy(n.gripQuaternion),s.quaternion.multiply(Ox),s.visible=n.isTracking,this.updateHandVisibility(n,s,this._leftHandMeshes)):s&&s.visible&&(s.visible=!1);const r=e.xr.rightController,a=this.rightHand?.asset;r&&a?(a.position.copy(r.gripPosition),a.quaternion.copy(r.gripQuaternion),a.quaternion.multiply(Ox),a.visible=r.isTracking,this.updateHandVisibility(r,a,this._rightHandMeshes)):a&&a.visible&&(a.visible=!1)}onBeforeRender(){this.context.xr&&this.context.time.frame%10===0&&this.updateRemoteAvatarVisibility()}updateHandVisibility(e,t,i){if(i){const n=e.model&&e.model.visible&&e.model!==t;i.forEach(s=>{Co(s,!n)})}}updateRemoteAvatarVisibility(){if(this.context.connection.isConnected){const e=xn.getFor(this);if(e&&e.isLocalPlayer==!1){const t=K.getXRSync(this.context);if(t&&t.hasState(e.owner)){this.tryFindAvatarObjectsIfMissing();const i=this.leftHand?.asset;i&&(i.visible=t?.isTracking(e.owner,"left")??!1);const n=this.rightHand?.asset;n&&(n.visible=t?.isTracking(e.owner,"right")??!1)}if(this.head?.asset){const i=x.getComponentsInChildren(this.head.asset,Ki);for(const n of i)n.enabled=!1,n.gameObject.visible=!0}}}}tryFindAvatarObjectsIfMissing(){if(!this.head||!this.leftHand||!this.rightHand){const e={head:this.head,leftHand:this.leftHand,rightHand:this.rightHand};k_.tryFindAvatarObjects(this.gameObject,this.sourceId||"",e),e.head&&(this.head=e.head),e.leftHand&&(this.leftHand=e.leftHand),e.rightHand&&(this.rightHand=e.rightHand)}}async prepareAvatar(){if(this.tryFindAvatarObjectsIfMissing(),this.head)this.head instanceof O&&(this.head=new ie("",this.sourceId,this.head));else{const e=new O;e.name="Head";const t=pr.createPrimitive(ur.Cube);e.add(t),this.gameObject.add(e),this.head=new ie("",this.sourceId,e),Gc&&console.log("Create head",e)}if(this.rightHand)this.rightHand instanceof O&&(this.rightHand=new ie("",this.sourceId,this.rightHand));else{const e=new O;e.name="Right Hand",this.gameObject.add(e),this.rightHand=new ie("",this.sourceId,e),Gc&&console.log("Create right hand",e)}if(this.leftHand)this.leftHand instanceof O&&(this.leftHand=new ie("",this.sourceId,this.leftHand));else{const e=new O;e.name="Left Hand",this.gameObject.add(e),this.leftHand=new ie("",this.sourceId,e),Gc&&console.log("Create left hand",e)}await this.loadAvatarObjects(this.head,this.leftHand,this.rightHand),this._leftHandMeshes=[],this.leftHand.asset?.traverse(e=>{e?.isMesh&&this._leftHandMeshes.push(e)}),this._rightHandMeshes=[],this.rightHand.asset?.traverse(e=>{e?.isMesh&&this._rightHandMeshes.push(e)}),xn.isLocalPlayer(this.gameObject)&&(this._syncTransforms=x.getComponentsInChildren(this.gameObject,vn))}async loadAvatarObjects(e,t,i){const n=e.loadAssetAsync(),s=t.loadAssetAsync(),r=i.loadAssetAsync(),a=new Array;n&&a.push(n),s&&a.push(s),r&&a.push(r);const l=await Pm(a);Gc&&console.log("Avatar loaded results:",l)}}ly([u(ie)],Ms.prototype,"head"),ly([u(ie)],Ms.prototype,"leftHand"),ly([u(ie)],Ms.prototype,"rightHand");var ZT=Object.defineProperty,Yu=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&ZT(e,t,n),n};const Rs=w("debugwebxr"),Ts=new Array;class Do extends M{createControllerModel=!0;createHandModel=!0;customLeftHand;customRightHand;static factory=new PC;supportsXR(e){return e==="immersive-vr"||e==="immersive-ar"}_models=new Array;async onXRControllerAdded(e){if(!(e.xr.isVR||e.xr.isPassThrough))return;console.debug("XR Controller Added",e.controller.side,e.controller.index);const{controller:t}=e;if(this.createControllerModel||this.createHandModel){if(t.hand){if(this.createHandModel){const i=await this.loadHandModel(this,t);if(!i||!t.connected||!t.isHand){i?.handObject&&ja(i.handObject,!1),i?.handObject?.destroy();return}this._models.push({controller:t,model:i.handObject,handmesh:i.handmesh}),this._models.sort((n,s)=>n.controller.index-s.controller.index),this.scene.add(i.handObject),t.model=i.handObject}}else if(this.createControllerModel){const i=await t.getModelUrl();if(i){const n=await this.loadModel(t,i);if(!n||!t.connected||t.isHand)return;this._models.push({controller:t,model:n}),this._models.sort((s,r)=>s.controller.index-r.controller.index),this.scene.add(n),n.traverse(s=>{s.layers.set(2),s.matrixAutoUpdate=!1,s.updateMatrix()}),t.model=n}else t.targetRayMode!=="transient-pointer"&&console.warn("XRControllerModel: no model found for "+t.side)}}}onXRControllerRemoved(e){console.debug("XR Controller Removed",e.controller.side,e.controller.index);const t=this._models.findIndex(n=>n.controller===e.controller),i=this._models[t];i&&(this._models.splice(t,1),i.model&&(ja(i.model,!1),i.model.destroy(),i.model=void 0))}onBeforeXR(e,t){this.createHandModel&&(this.customLeftHand||this.customRightHand)&&(t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.includes("hand-tracking")||t.optionalFeatures.push("hand-tracking"))}onLeaveXR(e){for(const t of this._models)t&&(t.model&&(ja(t.model,!1),t.model.destroy(),t.model=void 0),t.controller.model===t.model&&(t.controller.model=null));this._models.length=0}onBeforeRender(){if(K.active&&(Rs&&(Ts[0]=Date.now()),this.updateRendering(K.active),Rs)){const e=Date.now()-Ts[0];Ts.push(e),Ts.length>=30&&(Ts[0]=0,Ts.reduce((t,i)=>t+i,0)/Ts.length,Ts.length=0)}}updateRendering(e){for(let t=0;t<this._models.length;t++){const i=this._models[t];if(!i)continue;const n=i.controller;if(!n.connected){Rs&&console.warn("XRControllerModel.onUpdateXR: controller is not connected anymore",n.side,n.hand);continue}if(i.model&&!i.handmesh)i.model.matrixAutoUpdate=!1,i.model.matrix.copy(n.gripMatrix),i.model.visible=n.isTracking,e.rig?.gameObject.add(i.model);else if(n.inputSource.hand&&i.handmesh){const s=e.referenceSpace,r=this.context.renderer.xr.getHand(n.index);if(s&&e.frame.getJointPose){for(const a of n.inputSource.hand.values()){const l=r.joints[a.jointName];if(l){const c=n.getHandJointPose(a);if(c){const h=c.transform.position,d=c.transform.orientation;l.position.copy(h),l.quaternion.copy(d),l.matrixAutoUpdate=!1}l.visible=c!=null}}i.model&&(i.model.visible=n.isTracking,i.model.visible&&i.model.parent!==e.rig?.gameObject&&e.rig?.gameObject.add(i.model)),i.model?.visible&&(i.handmesh?.updateMesh(),i.model.matrixAutoUpdate=!1,i.model.matrix.identity(),i.model.applyMatrix4(Pa))}}}}async loadModel(e,t){if(!e.connected)return console.warn("XRControllerModel.onXRControllerAdded: controller is not connected anymore",e.side),null;const i=await ie.getOrCreate("",t).instantiate();return ja(i),K.active?.isPassThrough&&i.traverseVisible(n=>{this.makeOccluder(n)}),i}async loadHandModel(e,t){const i=this.context,n=i.renderer.xr.getHand(t.index);n||(Rs?F.DrawLabel(t.rayWorldPosition,"No hand found for index "+t.index,.05,5):console.warn("No hand found for index "+t.index));const s=new fo;Yg(s,i),await ju(s,i,this.sourceId??"");const r=Af(s);let a="";const l=t.side==="left"?this.customLeftHand:this.customRightHand;l?(a=l.url.split(".").slice(0,-1).join("."),s.setPath("")):(a=t.inputSource.handedness==="left"?"left":"right",s.setPath("https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/"));const c=new O;ja(c);const h=new OC(c,n,s.path,a,s,d=>{const p=r?.gltf;p?.scene.children?.length===0&&(p.scene.children[0]=d),r?.gltf&&gn().createBuiltinComponents(e.context,e.sourceId||a,r.gltf,null,r),d.traverse(m=>{m.layers.set(2),K.active?.isPassThrough&&!l&&this.makeOccluder(m),m instanceof H&&Ve.assignMeshLOD(m,0)}),t.connected||(Rs&&F.DrawLabel(t.rayWorldPosition,"Hand is loaded but not connected anymore",.05,5),d.removeFromParent())});if(Rs&&c.add(new _i(.5)),t.inputSource.hand){Rs&&console.log(t.inputSource.hand);for(const d of t.inputSource.hand.values())if(n.joints[d.jointName]===void 0){const p=new os;p.matrixAutoUpdate=!1,p.visible=!0,n.joints[d.jointName]=p,n.add(p)}}else Rs&&F.DrawLabel(t.rayWorldPosition,"No inputSource.hand found for index "+t.index,.05,5);return{handObject:c,handmesh:h}}makeOccluder(e){if(e instanceof H){let t=e.material;t instanceof ve&&(t=e.material=t.clone(),t.depthWrite=!0,t.depthTest=!0,t.colorWrite=!1,e.receiveShadow=!1,e.renderOrder=-100)}}}Yu([u()],Do.prototype,"createControllerModel"),Yu([u()],Do.prototype,"createHandModel"),Yu([u(ie)],Do.prototype,"customLeftHand"),Yu([u(ie)],Do.prototype,"customRightHand");class Ku extends M{}var JT=Object.defineProperty,Es=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&JT(e,t,n),n};const cy=w("debugwebxr");class Ei extends M{movementSpeed=1.5;rotationStep=30;useTeleport=!0;usePinchToTeleport=!0;useTeleportTarget=!1;useTeleportFade=!1;showRays=!0;showHits=!0;isXRMovementHandler=!0;xrSessionMode="immersive-vr";_didApplyRotation=!1;_didTeleport=!1;onUpdateXR(e){const t=e.xr.rig;if(!t?.gameObject||e.xr.isPassThrough)return;const i=e.xr.leftController,n=e.xr.rightController;i&&this.onHandleMovement(i,t.gameObject),n&&(this.onHandleRotation(n,t.gameObject),this.useTeleport&&this.onHandleTeleport(n,t.gameObject))}onLeaveXR(e){for(const t of this._lines)t.removeFromParent();for(const t of this._hitDiscs)t?.removeFromParent()}onBeforeRender(){this.context.xr?.running&&(this.showRays&&this.renderRays(this.context.xr),this.showHits&&this.renderHits(this.context.xr))}onHandleMovement(e,t){const i=e.getStick("xr-standard-thumbstick");if(i.x!=0||i.y!=0){const n=$(i.x,0,i.y);n.multiplyScalar(this.context.time.deltaTimeUnscaled*this.movementSpeed);const s=$e(t);n.multiplyScalar(s.x),n.applyQuaternion(e.xr.poseOrientation),n.y=0,n.applyQuaternion(t.worldQuaternion),E()&&Number.isNaN(n.x)&&console.error("Stick movement resulted in NaN",{stick:i,vec:n}),t.position.add(n),t.updateWorldMatrix(!1,!1);for(const r of t.children)r.updateWorldMatrix(!1,!1)}}onHandleRotation(e,t){if(e._isMxInk)return;const i=e.getStick("xr-standard-thumbstick").x;if(this._didApplyRotation)Math.abs(i)<.3&&(this._didApplyRotation=!1);else if(Math.abs(i)>.5){this._didApplyRotation=!0;const n=i>0?1:-1,s=Z(this.context.mainCamera).clone();t.rotateY(n*D.toRadians(this.rotationStep));const r=Z(this.context.mainCamera).clone().sub(s);r.y=0,t.position.sub(r)}}_teleportBuffer=new Array;onHandleTeleport(e,t){let i=0;if(e.hand&&this.usePinchToTeleport&&e.isTeleportGesture){const n=e.getPointerId("primary");if(n!=null&&this.context.input.getIsPointerIdInUse(n))return;const s=e.getGesture("pinch");s&&(i=s.value)}else i=e.getStick("xr-standard-thumbstick")?.y;if(this._didTeleport)i>=0&&i<.4?this._didTeleport=!1:i<0&&i>-.4&&(this._didTeleport=!1);else if(i>.8){this._didTeleport=!0;const n=this.context.physics.raycastFromRay(e.ray)[0];if(n&&n.object instanceof ba){const r=n.normal?.dot($(0,1,0));if(r!==void 0&&r<.4)return}let s=n?.point;if(!s&&!this.useTeleportTarget){this._plane||(this._plane=new tr(new b(0,1,0),0));const r=t.worldPosition;this._plane.setFromNormalAndCoplanarPoint(new b(0,1,0),r);const a=e.ray;s=r.clone(),this._plane.intersectLine(new qS(a.origin,$(a.direction).multiplyScalar(1e4).add(a.origin)),s),s.distanceTo(r)>t.scale.x*10&&(s=null)}if(s){if(this.useTeleportTarget&&!x.getComponentInParent(n.object,Ku))return;const r=s.clone();if(cy&&F.DrawSphere(s,.025,16711680,5),this.context.mainCamera?.position){const a=this.context.xr?.getUserOffsetInRig();a&&(a.y=0,r.sub(a),cy&&F.DrawWireSphere(a.add(r),.025,65280,5))}this._teleportBuffer.push(t.matrix.clone()),this._teleportBuffer.length>10&&this._teleportBuffer.shift(),this.useTeleportFade?e.xr.fadeTransition()?.then(()=>{t.worldPosition=r}):t.worldPosition=r}}else if(i<-.8&&(this._didTeleport=!0,this._teleportBuffer.length>0)){const n=this._teleportBuffer.pop();n&&n.decompose(t.position,t.quaternion,t.scale)}}_plane=null;_lines=[];_hitDiscs=[];_hitDistances=[];_lastHitDistances=[];renderRays(e){for(let t=0;t<this._lines.length;t++){const i=this._lines[t];i&&(i.visible=!1)}for(let t=0;t<e.controllers.length;t++){const i=e.controllers[t];let n=this._lines[t];if(!i.connected||!i.isTracking||!i.ray||i.targetRayMode==="transient-pointer"||!i.hasSelectEvent){n&&(n.visible=!1);continue}n||(n=this.createRayLineObject(),n.scale.z=.5,this._lines[t]=n),i.updateRayWorldPosition(),i.updateRayWorldQuaternion();const s=i.rayWorldPosition,r=i.rayWorldQuaternion;n.position.copy(s),n.quaternion.copy(r);const a=e.rigScale,l=this.usePinchToTeleport&&i.isTeleportGesture,c=this._lastHitDistances[t],h=this._hitDistances[t]!=null,d=c??a;n.scale.set(a,a,d),n.visible=!0,n.layers.disableAll(),n.layers.enable(2);let p=n.material.opacity;l?p=1:this.showHits&&d<e.rigScale*.5?p=0:i.getButton("primary")?.pressed?p=.5:p=h?.2:.1,n.material.opacity=D.lerp(n.material.opacity,p,this.context.time.deltaTimeUnscaled/.1),n.parent!==this.context.scene&&this.context.scene.add(n)}}renderHits(e){for(const t of this._hitDiscs){if(!t)continue;const i=t.controller;if(!i||!i.connected||!i.isTracking){t.visible=!1;continue}}for(let t=0;t<e.controllers.length;t++){const i=e.controllers[t];if(!i.connected||!i.isTracking||!i.ray||!i.hasSelectEvent)continue;let n=this._hitDiscs[t],s=!0;const r=i.getPointerId("primary");r!=null&&this.context.input.getIsPointerIdInUse(r)&&(n&&(n.visible=!1),this._hitDistances[t]=null,this._lastHitDistances[t]=0,s=!1);const a=this.context.time.smoothedFps>=59?1:10;if((this.context.time.frame+i.index)%a!==0&&(s=!1),!s){const h=this._hitDiscs[t];h&&h.visible&&h.hit&&this.updateHitPointerPosition(i,h,h.hit.distance);continue}const l=this.context.physics.raycastFromRay(i.ray,{testObject:this.hitPointRaycastFilter,precise:!1});let c=l.find(h=>this.usePinchToTeleport&&i.isTeleportGesture?!0:this.isObjectWithInteractiveComponent(h.object));if(c||(c=l[0]),n&&(n.controller=i,n.hit=c),this._hitDistances[t]=c?.distance||null,c){this._lastHitDistances[t]=c.distance;const h=e.rigScale??1;cy&&(F.DrawWireSphere(c.point,.025*h,16711680),F.DrawLabel($(0,.2,0).add(c.point),c.object.name,.02,0)),n||(n=this.createHitPointObject(),this._hitDiscs[t]=n),n.hit=c,n.visible=c.distance>h*.05;let d=.01*(h+c.distance);const p=i.getButton("primary")?.pressed;p&&(d*=1.1),n.scale.set(d,d,d),n.layers.set(2);let m=n.material.opacity;if(p?m=1:m=c.distance<.15*h?.2:.6,n.material.opacity=D.lerp(n.material.opacity,m,this.context.time.deltaTimeUnscaled/.1),n.visible){if(c.normal){this.updateHitPointerPosition(i,n,c.distance);const f=c.normal.applyQuaternion(be(c.object));n.quaternion.setFromUnitVectors(eE,f)}else this.updateHitPointerPosition(i,n,c.distance);n.parent!==this.context.scene&&this.context.scene.add(n)}}else this._hitDiscs[t]&&(this._hitDiscs[t].visible=!1)}}isObjectWithInteractiveComponent(e,t=0){return fu(e)||e.isUI===!0?!0:e.isScene?!1:e.parent?this.isObjectWithInteractiveComponent(e.parent,t+1):!1}updateHitPointerPosition(e,t,i){const n=$(e.rayWorldPosition);n.add($(0,0,i-.01).applyQuaternion(e.rayWorldQuaternion)),t.position.lerp(n,this.context.time.deltaTimeUnscaled/.05)}hitPointRaycastFilter=e=>e.type==="SkinnedMesh"?"continue in children":!0;createHitPointObject(){const e=new H(new od(.3,6,6),new xe({color:15658734,opacity:.7,transparent:!0,depthTest:!1,depthWrite:!1,side:vi}));return e.layers.disableAll(),e.layers.enable(2),e}createRayLineObject(){const e=new kC;e.layers.disableAll(),e.layers.enable(2);const t=new MC;e.geometry=t;const i=new Float32Array(9);i.set([0,0,.02,0,0,.4,0,0,1]),t.setPositions(i);const n=new Float32Array(9);n.set([1,1,1,.1,.1,.1,0,0,0]),t.setColors(n);const s=new RC({color:16777215,vertexColors:!0,worldUnits:!0,linewidth:.004,transparent:!0,depthWrite:!1,blending:V0,dashed:!1});return e.material=s,e}}Es([u()],Ei.prototype,"movementSpeed"),Es([u()],Ei.prototype,"rotationStep"),Es([u()],Ei.prototype,"useTeleport"),Es([u()],Ei.prototype,"usePinchToTeleport"),Es([u()],Ei.prototype,"useTeleportTarget"),Es([u()],Ei.prototype,"useTeleportFade"),Es([u()],Ei.prototype,"showRays"),Es([u()],Ei.prototype,"showHits");const eE=new b(0,1,0);var tE=Object.defineProperty,_t=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&tE(e,t,n),n};const qc=w("debugwebxr"),iE=w("debugusdz"),rt=class Rl extends M{createVRButton=!0;createARButton=!0;createSendToQuestButton=!0;createQRCode=!0;useDefaultControls=!0;showControllerModels=!0;showHandModels=!0;usePlacementReticle=!0;customARPlacementReticle;usePlacementAdjustment=!0;arScale=1;useXRAnchor=!1;autoPlace=!1;autoCenter=!1;useQuicklookExport=!1;useDepthSensing=!1;useSpatialGrab=!0;defaultAvatar;_playerSync;_createdComponentsInSession=[];_usdzExporter;static activeWebXRComponent=null;awake(){K.getXRSync(this.context)}onEnable(){window.location.protocol!=="https:"&&ge('<a href="https://developer.mozilla.org/en-US/docs/Web/API/WebXR_Device_API" target="_blank">WebXR</a> only works on secure connections (https).'),this.useQuicklookExport&&(x.findObjectOfType(to)||(qc&&console.log("WebXR: Adding USDZExporter"),this._usdzExporter=x.addComponent(this.gameObject,to),this._usdzExporter.objectToExport=this.context.scene,this._usdzExporter.autoExportAnimations=!0,this._usdzExporter.autoExportAudioSources=!0)),this.handleCreatingHTML(),this.handleOfferSession(),this.defaultAvatar===!0&&(qc&&console.warn("WebXR: No default avatar set, using static default avatar"),this.defaultAvatar=new ie("https://cdn.needle.tools/static/avatars/DefaultAvatar.glb")),this.defaultAvatar&&(this._playerSync=this.gameObject.getOrAddComponent(ry),this._playerSync.autoSync=!1),this._playerSync&&typeof this.defaultAvatar!="boolean"&&(this._playerSync.asset=this.defaultAvatar,this._playerSync.onPlayerSpawned?.removeEventListener(this.onAvatarSpawned),this._playerSync.onPlayerSpawned?.addEventListener(this.onAvatarSpawned))}onDisable(){this._usdzExporter?.destroy(),this.removeButtons()}async handleOfferSession(){return this.createVRButton&&await K.isVRSupported()&&this.createVRButton?K.offerSession("immersive-vr","default",this.context):this.createARButton&&await K.isARSupported()&&this.createARButton?K.offerSession("immersive-ar","default",this.context):!1}get session(){return K.active??null}get sessionMode(){return K.activeMode??null}get arSessionRoot(){return this._activeWebARSessionRoot}async enterVR(e){return K.start("immersive-vr",e,this.context)}async enterAR(e){return K.start("immersive-ar",e,this.context)}exitXR(){K.stop()}_exitXRMenuButton;_previousXRState=0;_spatialGrabRaycaster;_activeWebARSessionRoot=null;get isActiveWebXR(){return!Rl.activeWebXRComponent||Rl.activeWebXRComponent===this}onBeforeXR(e,t){if(!this.isActiveWebXR){console.warn(`WebXR: another WebXR component is already active (${Rl.activeWebXRComponent?.name}). This is ignored: ${this.name}`);return}Rl.activeWebXRComponent=this,e=="immersive-ar"&&this.useDepthSensing&&(t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.push("depth-sensing"))}async onEnterXR(e){if(!this.isActiveWebXR)return;qc&&console.log("WebXR onEnterXR"),this._previousXRState=Jt.Global.Mask;const t=e.xr.isVR;if(Jt.Global.Set(t?Xn.VR:Xn.AR),e.xr.isAR){let i=x.findObjectOfType(Ui);if(!i)if(this.usePlacementReticle){const n=new O;for(const s of this.context.scene.children)n.add(s);this.context.scene.add(n),i=x.addComponent(n,Ui),this._createdComponentsInSession.push(i)}else(qc||E())&&console.warn("WebXR: No WebARSessionRoot found in scene and usePlacementReticle is disabled in WebXR component.");this._activeWebARSessionRoot=i,i&&(i.customReticle=this.customARPlacementReticle,i.arScale=this.arScale,i.arTouchTransform=this.usePlacementAdjustment,i.autoPlace=this.autoPlace,i.autoCenter=this.autoCenter,i.useXRAnchor=this.useXRAnchor)}this.useDefaultControls&&this.setDefaultMovementEnabled(!0),(this.showControllerModels||this.showHandModels)&&this.setDefaultControllerRenderingEnabled(!0),this.useSpatialGrab&&(this._spatialGrabRaycaster=x.findObjectOfType(ra)??void 0,this._spatialGrabRaycaster||(this._spatialGrabRaycaster=this.gameObject.addComponent(ra))),this.createLocalAvatar(e.xr),e.xr.isScreenBasedAR||(this._exitXRMenuButton=this.context.menu.appendChild({label:"Quit XR",onClick:()=>this.exitXR(),icon:"exit_to_app",priority:2e4}))}onUpdateXR(e){this.isActiveWebXR&&this._spatialGrabRaycaster&&(this._spatialGrabRaycaster.enabled=this.useSpatialGrab)}onLeaveXR(e){if(this._exitXRMenuButton?.remove(),!!this.isActiveWebXR){Jt.Global.Set(this._previousXRState),this._playerSync?.destroyInstance();for(const t of this._createdComponentsInSession)t.destroy();this._createdComponentsInSession.length=0,this._activeWebARSessionRoot=null,this.handleOfferSession(),Wl(1).then(()=>Rl.activeWebXRComponent=null)}}setDefaultMovementEnabled(e){let t=this.gameObject.getComponent(Ei);return!t&&e&&(t=this.gameObject.addComponent(Ei),this._createdComponentsInSession.push(t)),t&&(t.enabled=e),t}setDefaultControllerRenderingEnabled(e){let t=this.gameObject.getComponent(Do);return!t&&e&&(t=this.gameObject.addComponent(Do),this._createdComponentsInSession.push(t),t.createControllerModel=this.showControllerModels,t.createHandModel==this.showHandModels),t&&(t.enabled=e),t}async createLocalAvatar(e){this._playerSync&&e.running&&typeof this.defaultAvatar!="boolean"&&(this._playerSync.asset=this.defaultAvatar,await this._playerSync.getInstance())}onAvatarSpawned=e=>{qc&&console.log("WebXR.onAvatarSpawned",e);let t=x.getComponentInChildren(e,Ms);t??=x.addComponent(e,Ms)};getButtonsContainer(){return this.getButtonsFactory()}getButtonsFactory(){return this._buttonFactory||(this._buttonFactory=Qs.getOrCreate()),this._buttonFactory}_buttonFactory;handleCreatingHTML(){if(this.createARButton||this.createVRButton||this.useQuicklookExport){if((G.isiOS()&&G.isSafari()||iE)&&this.useQuicklookExport){const e=x.findObjectOfType(to);if(!e||e&&e.allowCreateQuicklookButton){const t=this.getButtonsFactory().createQuicklookButton();this.addButton(t,50)}}if(this.createARButton){const e=this.getButtonsFactory().createARButton();this.addButton(e,50)}if(this.createVRButton){const e=this.getButtonsFactory().createVRButton();this.addButton(e,50)}}if(this.createSendToQuestButton&&!G.isQuest()&&K.isVRSupported().then(e=>{if(!e){const t=this.getButtonsFactory().createSendToQuestButton();this.addButton(t,50)}}),this.createQRCode){const e=pc(Jn);if(e&&e.createQRCodeButton===!1)E()&&console.warn("WebXR: QRCode button is disabled in the Needle Menu component");else if(!G.isMobileDevice()){const t=An.getOrCreate().createQRCode();this.addButton(t,50)}}}_buttons=[];addButton(e,t){this._buttons.push(e),e.setAttribute("priority",t.toString()),this.context.menu.appendChild(e)}removeButtons(){for(const e of this._buttons)e.remove();this._buttons.length=0}};_t([u()],rt.prototype,"createVRButton"),_t([u()],rt.prototype,"createARButton"),_t([u()],rt.prototype,"createSendToQuestButton"),_t([u()],rt.prototype,"createQRCode"),_t([u()],rt.prototype,"useDefaultControls"),_t([u()],rt.prototype,"showControllerModels"),_t([u()],rt.prototype,"showHandModels"),_t([u()],rt.prototype,"usePlacementReticle"),_t([u(ie)],rt.prototype,"customARPlacementReticle"),_t([u()],rt.prototype,"usePlacementAdjustment"),_t([u()],rt.prototype,"arScale"),_t([u()],rt.prototype,"useXRAnchor"),_t([u()],rt.prototype,"autoPlace"),_t([u()],rt.prototype,"autoCenter"),_t([u()],rt.prototype,"useQuicklookExport"),_t([u()],rt.prototype,"useDepthSensing"),_t([u()],rt.prototype,"useSpatialGrab"),_t([u(ie)],rt.prototype,"defaultAvatar");let Zu=rt;const Ju=w("debugusdzbehaviours");class hy{get extensionName(){return"Behaviour"}behaviours=[];addBehavior(e){this.behaviours.push(e)}addAudioClip(e){if(!e||typeof e!="string")return"";const t="audio/"+aa.getName(e);return this.audioClips.push({clipUrl:e,filesKey:t}),t}behaviourComponents=[];behaviourComponentsCopy=[];audioClips=[];audioClipsCopy=[];targetUuids=new Set;getAllTargetUuids(){return this.targetUuids}onBeforeBuildDocument(e){if(!e.root)return Promise.resolve();const t=[];return e.root.traverse(i=>{x.foreachComponent(i,n=>{const s=n;if(typeof s.createBehaviours=="function"||typeof s.beforeCreateDocument=="function"||typeof s.afterCreateDocument=="function"||typeof s.afterSerialize=="function"){this.behaviourComponents.push(s);const r=s.beforeCreateDocument?.call(s,this,e);r instanceof Promise&&t.push(r)}},!1)}),Ju&&console.log("onBeforeBuildDocument: all components",this.behaviourComponents),Promise.all(t)}onExportObject(e,t,i){for(const n of this.behaviourComponents)n.createBehaviours?.call(n,this,t,i)}onAfterBuildDocument(e){for(const d of this.behaviourComponents)typeof d.afterCreateDocument=="function"&&d.afterCreateDocument(this,e);this.behaviourComponentsCopy=this.behaviourComponents.slice(),this.behaviourComponents.length=0,this.audioClipsCopy=this.audioClips.slice(),this.audioClips.length=0;const t=new Set,i=new Set,n=new Set,s=new Set,r=Ju;let a=`graph LR
1262
1262
  `,l="";function c(d){if(d instanceof Dr){r&&(a+=`subgraph Group_${d.id}
1263
1263
  `);for(const p of d.actions)r&&(a+=`${d.id}[${d.id}] -- ${d.type},loops:${d.loops} --> ${p.id}[${p.id}]
1264
1264
  `),c(p);r&&(a+=`end
1265
- `)}else if(d instanceof fi){d.tokenId==="StartAnimation"&&s.add(d);let p=d.tokenId;d.type!==void 0&&(p+=":"+d.type);const g=d.affectedObjects;if(g)if(Array.isArray(g))for(const m of g)i.add(m),r&&(l+=`${d.id}[${d.id}
1266
- ${p}] -- ${p} --> ${m.uuid}(("${m.displayName||m.name||m.uuid}"))
1267
- `);else typeof g=="object"?(i.add(g),r&&(l+=`${d.id}[${d.id}
1265
+ `)}else if(d instanceof fi){d.tokenId==="StartAnimation"&&s.add(d);let p=d.tokenId;d.type!==void 0&&(p+=":"+d.type);const m=d.affectedObjects;if(m)if(Array.isArray(m))for(const g of m)i.add(g),r&&(l+=`${d.id}[${d.id}
1268
1266
  ${p}] -- ${p} --> ${g.uuid}(("${g.displayName||g.name||g.uuid}"))
1269
- `)):typeof g=="string"&&i.add({uuid:g});const f=d.xFormTarget;f&&(typeof f=="object"?(i.add(f),r&&(l+=`${d.id}[${d.id}
1267
+ `);else typeof m=="object"?(i.add(m),r&&(l+=`${d.id}[${d.id}
1268
+ ${p}] -- ${p} --> ${m.uuid}(("${m.displayName||m.name||m.uuid}"))
1269
+ `)):typeof m=="string"&&i.add({uuid:m});const f=d.xFormTarget;f&&(typeof f=="object"?(i.add(f),r&&(l+=`${d.id}[${d.id}
1270
1270
  ${p}] -- ${p} --> ${f.uuid}(("${f.displayName||f.name||f.uuid}"))
1271
- `)):typeof f=="string"&&i.add({uuid:f}))}}function h(d,p){if(Array.isArray(d))for(const g of d)h(g,p);else if(d instanceof Xs){let g=d.tokenId;d.type!==void 0&&(g+=":"+d.type),typeof d.targetId=="object"&&(t.add(d.targetId),r&&(l+=`${d.targetId.uuid}(("${d.targetId.displayName}")) --> ${d.id}[${d.id}
1272
- ${g}]
1273
- `)),r&&(a+=`${d.id}((${d.id})) -- ${g} --> ${p.id}[${p.tokenId||p.id}]
1271
+ `)):typeof f=="string"&&i.add({uuid:f}))}}function h(d,p){if(Array.isArray(d))for(const m of d)h(m,p);else if(d instanceof Xs){let m=d.tokenId;d.type!==void 0&&(m+=":"+d.type),typeof d.targetId=="object"&&(t.add(d.targetId),r&&(l+=`${d.targetId.uuid}(("${d.targetId.displayName}")) --> ${d.id}[${d.id}
1272
+ ${m}]
1273
+ `)),r&&(a+=`${d.id}((${d.id})) -- ${m} --> ${p.id}[${p.tokenId||p.id}]
1274
1274
  `)}}for(const d of this.behaviours)r&&(a+=`subgraph ${d.id}
1275
1275
  `),c(d.action),h(d.trigger,d.action),r&&(a+=`end
1276
1276
  `);r&&(a+=`
@@ -1278,9 +1278,9 @@ ${g}]
1278
1278
  title Animations
1279
1279
  dateFormat X
1280
1280
  axisFormat %s
1281
- `;const p=Array.from(s),g=new Set;for(const _ of p)if(_.affectedObjects&&typeof _.affectedObjects!="string"){if(Array.isArray(_.affectedObjects))for(const v of _.affectedObjects)g.add(v);else g.add(_.affectedObjects);r&&(d+=`section ${_.animationName} (${_.id})
1281
+ `;const p=Array.from(s),m=new Set;for(const _ of p)if(_.affectedObjects&&typeof _.affectedObjects!="string"){if(Array.isArray(_.affectedObjects))for(const v of _.affectedObjects)m.add(v);else m.add(_.affectedObjects);r&&(d+=`section ${_.animationName} (${_.id})
1282
1282
  `,d+=`${_.id} : ${_.start}, ${_.duration}s
1283
- `)}r&&s.size&&console.log(d);const f=new Set;for(const _ of g){_.getPath||console.error("USDZExporter: Animation target object has no getPath method. This is likely a bug",_);let v=_.getPath();v.startsWith("<")&&(v=v.substring(1)),v.endsWith(">")&&(v=v.substring(0,v.length-1)),f.add({path:v,obj:_})}const m=Array.from(f).sort((_,v)=>_.path.length-v.path.length),y=new Array;for(let _=0;_<m.length;_++)for(let v=_+1;v<m.length;v++)if(m[v].path.startsWith(m[_].path)){const P=m[v],R=m[_];y.push({child:P.obj.displayName+" ("+P.path+")",parent:R.obj.displayName+" ("+R.path+")"})}y.length&&console.warn("USDZExporter: There are overlapping PlayAnimation actions. This can lead to undefined runtime behaviour when playing multiple animations. Please restructure the hierarchy so that animations don't overlap.",{overlappingTargets:y,playAnimationActions:s})}for(const d of new Set([...t,...i]))if(Array.isArray(d))for(const p of d)n.add(p.uuid);else n.add(d.uuid);Ju&&console.log("All Behavior trigger sources and action targets",t,i,n),this.targetUuids=new Set(n)}onAfterHierarchy(e,t){if(this.behaviours?.length){t.beginBlock('def Scope "Behaviors"');for(const i of this.behaviours)i.writeTo(this,e.document,t);t.closeBlock()}}async onAfterSerialize(e){Ju&&console.log("onAfterSerialize behaviours",this.behaviourComponentsCopy);for(const t of this.behaviourComponentsCopy)typeof t.afterSerialize=="function"&&(t.afterSerialize.constructor.name==="AsyncFunction"?await t.afterSerialize(this,e):t.afterSerialize(this,e));for(const{clipUrl:t,filesKey:i}of this.audioClipsCopy){if(e.files[i])return;const n=await(await(await fetch(t)).blob()).arrayBuffer(),s=new Uint8Array(n);e.files[i]=s}this.behaviourComponentsCopy.length=0,this.audioClipsCopy.length=0}}class dy{get extensionName(){return"Physics"}onExportObject(e,t,i){const n=x.getComponents(e,Ye).filter(l=>l.enabled),s=x.getComponents(e,ai).filter(l=>l.enabled&&!l.isTrigger);let r=n.length>0?n[0]:null;const a=s.length>0?s[0]:null;a&&!r&&(r=new Ye,r.isKinematic=!0),r&&t.addEventListener("serialize",(l,c)=>{if(r){if(l.appendLine(),l.beginBlock('def RealityKitComponent "RigidBody"',"{",!0),r.useGravity||l.appendLine("bool gravityEnabled = 0"),l.appendLine('uniform token info:id = "RealityKit.RigidBody"'),r.isKinematic&&l.appendLine('token motionType = "Kinematic"'),l.beginBlock('def RealityKitStruct "massFrame"',"{",!0),l.appendLine(`float m_mass = ${r.mass}`),l.beginBlock('def RealityKitStruct "m_pose"',"{",!0),l.appendLine(`float3 position = (${r.centerOfMass.x}, ${r.centerOfMass.y}, ${r.centerOfMass.z})`),l.closeBlock("}"),l.closeBlock("}"),s.length>0){const h=s[0];l.beginBlock('def RealityKitStruct "material"',"{",!0);const d=h.sharedMaterial;d&&d.dynamicFriction!==void 0&&l.appendLine(`double dynamicFriction = ${h.sharedMaterial?.dynamicFriction}`),d&&d.bounciness!==void 0&&l.appendLine(`double restitution = ${h.sharedMaterial?.bounciness}`),d&&d.staticFriction!==void 0&&l.appendLine(`double staticFriction = ${h.sharedMaterial?.staticFriction}`),l.closeBlock("}")}l.closeBlock("}")}}),a&&(t.addEventListener("serialize",(l,c)=>{l.beginBlock('def RealityKitComponent "Collider"',"{",!0),l.appendLine("uint group = 1"),l.appendLine('uniform token info:id = "RealityKit.Collider"'),l.appendLine("uint mask = 4294967295");const h=a.isTrigger?"Trigger":"Default";if(l.appendLine(`token type = "${h}"`),l.beginBlock('def RealityKitStruct "Shape"',"{",!0),a instanceof Ga){const d=a;l.appendLine('token shapeType = "Sphere"'),l.appendLine(`float radius = ${d.radius}`)}else if(a instanceof Ou){const d=a;l.appendLine('token shapeType = "Box"'),l.appendLine(`float3 extent = (${d.size.x}, ${d.size.y}, ${d.size.z})`)}else if(a instanceof Mo){const d=a;l.appendLine('token shapeType = "Capsule"'),l.appendLine(`float radius = ${d.radius}`),l.appendLine(`float height = ${d.height}`)}else if(a instanceof xs&&a.sharedMesh?.geometry){const d=a.sharedMesh.geometry;d.boundingBox||d.computeBoundingBox();const p=a.sharedMesh.geometry.boundingBox;p&&(l.appendLine('token shapeType = "Box"'),l.appendLine(`float3 extent = (${p.max.x-p.min.x}, ${p.max.y-p.min.y}, ${p.max.z-p.min.z})`),console.log("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. MeshCollider will be exported as Box",a))}else console.warn("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. Ignoring collider:",a);l.beginBlock('def RealityKitStruct "pose"',"{",!0),l.closeBlock("}"),l.closeBlock("}"),l.closeBlock("}")}),s.length>1&&console.log("WARNING: Multiple colliders detected. visionOS / iOS can only support objects with a single collider, only exporting the first collider: ",a))}}const nE=w("debugshadowcomponents");rb.prototype.interactable={get(){return this.interactive},set(o){this.interactable=o}};class rn extends M{isRoot(){return this.Root?.gameObject===this.gameObject}get canvas(){const e=this.Root;return e?.isCanvas?e:null}get Canvas(){return this.canvas}markDirty(){ei.markUIDirty(this.context)}get shadowComponent(){return this._shadowComponent}set shadowComponent(e){this._shadowComponent=e}_shadowComponent=null;_controlsChildLayout=!0;get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(e){this._controlsChildLayout=e,this.shadowComponent&&(this.shadowComponent.autoLayout=e)}_root=void 0;get Root(){return this._root===void 0&&(this._root=x.getComponentInParent(this.gameObject,Xc)),this._root}_parentComponent=void 0;__internalNewInstanceCreated(e){return super.__internalNewInstanceCreated(e),this.shadowComponent=null,this._root=void 0,this._parentComponent=void 0,this}onEnable(){super.onEnable()}addShadowComponent(e,t){if(!e)return;this.removeShadowComponent();const i=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=x.getComponentInParent(i,rn),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have an UI element outside a Canvas? UI components must be a child of a Canvas component`,this);return}e.name=this.name+" ("+(this.constructor.name??"UI")+")",e.autoLayout=this._parentComponent.controlsChildLayout,e[Si]=this,this.setShadowComponentOwner(e);let n=!1;if(this.Root?.gameObject===this.gameObject)this.gameObject.add(e);else{const s=this._parentComponent.shadowComponent;s&&(s?.add(e),n=!0)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),lc&&e.add(new _i(.5)),this.onAfterAddedToScene(),n&&GC(),nE&&console.warn("Added shadow component",this.shadowComponent)}setShadowComponentOwner(e){if(e&&(e[Si]===void 0||e[Si]===this)&&(e[Si]=this,e.children))for(const t of e.children)this.setShadowComponentOwner(t)}traverseOwnedShadowComponents(e,t,i){if(e&&e[Si]===t){i(e);for(const n of e.children)this.traverseOwnedShadowComponents(n,t,i)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(e){this.shadowComponent&&(this.shadowComponent.interactable=e)}}class Xc extends rn{awake(){super.awake()}}var oE=Object.defineProperty,sE=Object.getOwnPropertyDescriptor,Qc=(o,e,t,i)=>{for(var n=i>1?void 0:i?sE(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&oE(e,t,n),n};const uy=w("debugui"),py=w("debuguilayout");class kx{width;height}class Mx{x;y;width;height}const Sn=new b,Yc=new ee,ep=new U,cl=class H1 extends rn{get parent(){return this._parentRectTransform}get translation(){return this.gameObject.position}get rotation(){return this.gameObject.quaternion}get scale(){return this.gameObject.scale}_anchoredPosition;get anchoredPosition(){return this._anchoredPosition||(this._anchoredPosition=new J),this._anchoredPosition}set anchoredPosition(e){this._anchoredPosition=e}sizeDelta=new J(100,100);pivot=new J(.5,.5);anchorMin=new J(0,0);anchorMax=new J(1,1);minWidth;minHeight;get width(){let e=this.sizeDelta.x;if(this.anchorMin.x!==this.anchorMax.x&&this._parentRectTransform){const t=this._parentRectTransform.width,i=this.anchorMax.x-this.anchorMin.x;e=t*i,e+=this.sizeDelta.x}return this.minWidth!==void 0&&e<this.minWidth?this.minWidth:e}get height(){let e=this.sizeDelta.y;if(this.anchorMin.y!==this.anchorMax.y&&this._parentRectTransform){const t=this._parentRectTransform.height,i=this.anchorMax.y-this.anchorMin.y;e=t*i,e+=this.sizeDelta.y}return this.minHeight!==void 0&&e<this.minHeight?this.minHeight:e}lastMatrix;rectBlock;_transformNeedsUpdate=!1;_initialPosition;_parentRectTransform;_lastUpdateFrame=-1;awake(){super.awake(),this._lastUpdateFrame=-1,this._parentRectTransform=void 0,this.rectBlock=new O,this.rectBlock.name=this.name,this.lastMatrix=new ee,this._lastAnchoring=null,this._initialPosition=this.gameObject.position.clone(),this._initialPosition.z=0,this._anchoredPosition||(this._anchoredPosition=new J),Va(this,"_anchoredPosition",()=>{this.markDirty()}),Va(this,"sizeDelta",()=>{this.markDirty()}),Va(this,"pivot",()=>{this.markDirty()}),Va(this,"anchorMin",()=>{this.markDirty()}),Va(this,"anchorMax",()=>{this.markDirty()})}onEnable(){super.onEnable(),this.rectBlock||(this.rectBlock=new O),this.lastMatrix||(this.lastMatrix=new ee),this._lastAnchoring||(this._lastAnchoring=new J),this._initialPosition||(this._initialPosition=new b),this._anchoredPosition||(this._anchoredPosition=new J),this.addShadowComponent(this.rectBlock),this._transformNeedsUpdate=!0,this.canvas?.registerTransform(this)}onDisable(){super.onDisable(),this.removeShadowComponent(),this.canvas?.unregisterTransform(this)}onParentRectTransformChanged(e){this._transformNeedsUpdate||this.onApplyTransform(py?`${e.name} changed`:void 0)}get isDirty(){return this._transformNeedsUpdate||(this._transformNeedsUpdate=!this.lastMatrix.equals(this.gameObject.matrix)),this._transformNeedsUpdate}markDirty(){this._transformNeedsUpdate||(py&&console.warn("RectTransform markDirty()",this.name),this._transformNeedsUpdate=!0,this._lastUpdateFrame=-1)}updateTransform(){(this._transformNeedsUpdate||!this.lastMatrix.equals(this.gameObject.matrix))&&this.canUpdate()&&this.onApplyTransform(this._transformNeedsUpdate?"Marked dirty":"Matrix changed")}canUpdate(){return this._transformNeedsUpdate&&this.activeAndEnabled&&this._lastUpdateFrame!==this.context.time.frame}onApplyTransform(e){if(this.context.time.frameCount===this._lastUpdateFrame)return;this._lastUpdateFrame=this.context.time.frameCount;const t=this.shadowComponent;if(!t)return;this.gameObject.parent?this._parentRectTransform=x.getComponentInParent(this.gameObject.parent,H1):this._parentRectTransform=void 0,this._transformNeedsUpdate=!1,py&&console.warn("RectTransform \u2192 ApplyTransform",this.name+" because "+e),this.isRoot()?this.Root.screenspace||(t.rotation.y=Math.PI):(t.matrix.identity(),t.matrixAutoUpdate=!1,Sn.set(0,0,0),this.applyPivot(Sn),t.matrix.setPosition(Sn.x,Sn.y,0),(this.gameObject.quaternion.x||this.gameObject.quaternion.y||this.gameObject.quaternion.z)&&(ep.copy(this.gameObject.quaternion),ep.x*=-1,ep.z*=-1,Yc.makeRotationFromQuaternion(ep),t.matrix.premultiply(Yc)),Sn.set(0,0,0),this.applyAnchoring(Sn),this.canvas?.screenspace?Sn.z+=.1:Sn.z+=.01,Yc.identity(),Yc.setPosition(Sn.x,Sn.y,Sn.z),t.matrix.premultiply(Yc),t.matrix.scale(this.gameObject.scale)),this.lastMatrix.copy(this.gameObject.matrix);const i=!0;for(const n of eu(this.gameObject,rn,i,1)){if(n===this||!n.activeAndEnabled)continue;const s=n;s.onParentRectTransformChanged&&s.onParentRectTransformChanged(this)}}_lastAnchoring;applyAnchoring(e){this._lastAnchoring||(this._lastAnchoring=new J);const t=this._lastAnchoring.sub(this._anchoredPosition);this.gameObject.position.x+=t.x,this.gameObject.position.y+=t.y,this._lastAnchoring.copy(this._anchoredPosition),e.x+=this._initialPosition.x-this.gameObject.position.x,e.y+=this._initialPosition.y-this.gameObject.position.y,e.z+=this._initialPosition.z-this.gameObject.position.z;const i=this._parentRectTransform;if(i){let n=0;const s=1-this.anchorMax.y-this.anchorMin.y;n-=i.height*.5*s,e.y+=n;let r=0;const a=1-this.anchorMax.x-this.anchorMin.x;r-=i.width*.5*a,e.x+=r}}applyPivot(e){if(this.pivot&&!this.isRoot()){const t=this.pivot.x-.5;e.x-=t*this.sizeDelta.x*this.gameObject.scale.x;const i=this.pivot.y-.5;e.y-=i*this.sizeDelta.y*this.gameObject.scale.y}}getBasicOptions(){const e={width:this.sizeDelta.x,height:this.sizeDelta.y,offset:0,backgroundOpacity:0,borderWidth:0,borderRadius:0,borderOpacity:0,letterSpacing:-.03};return this.ensureValidSize(e),e}ensureValidSize(e,t=1e-4){return e.width<=0&&(e.width=t),e.height<=0&&(e.height=1e-4),e}_createdBlocks=[];_createdTextBlocks=[];createNewBlock(e){e={...this.getBasicOptions(),...e},uy&&console.log(this.name,e);const t=new rb(e);return this._createdBlocks.push(t),t}createNewText(e){uy&&console.log(e),e={...this.getBasicOptions(),...e},uy&&console.log(this.name,e);const t=new sb(e);return this._createdTextBlocks.push(t),t}};Qc([u(J)],cl.prototype,"anchoredPosition",1),Qc([u(J)],cl.prototype,"sizeDelta",2),Qc([u(J)],cl.prototype,"pivot",2),Qc([u(J)],cl.prototype,"anchorMin",2),Qc([u(J)],cl.prototype,"anchorMax",2);let Cn=cl;var rE=Object.defineProperty,Rx=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&rE(e,t,n),n};class hl extends M{effectColor;effectDistance}Rx([u(se)],hl.prototype,"effectColor"),Rx([u(J)],hl.prototype,"effectDistance");var aE=Object.defineProperty,lE=Object.getOwnPropertyDescriptor,Tx=(o,e,t,i)=>{for(var n=i>1?void 0:i?lE(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&aE(e,t,n),n};const tp={backgroundColor:new ne(1,1,1),backgroundOpacity:1,borderColor:new ne(1,1,1),borderOpacity:1},my=class Xh extends rn{get isGraphic(){return!0}get color(){return this._color||(this._color=new se(1,1,1,1)),this._color}set color(e){(!this._color||this._color.r!==e.r||this._color.g!==e.g||this._color.b!==e.b||this._color.alpha!==e.alpha)&&(this._color||(this._color=new se(1,1,1,1)),this._color.copy(e),this.onColorChanged())}_alphaFactor=1;setAlphaFactor(e){this._alphaFactor=e,this.onColorChanged()}get alphaFactor(){return this._alphaFactor}sRGBColor=new ne(1,0,1);onColorChanged(){this.uiObject&&(this.sRGBColor.copy(this._color),this.sRGBColor.convertLinearToSRGB(),tp.backgroundColor=this.sRGBColor,tp.backgroundOpacity=this._color.alpha*this._alphaFactor,this.applyEffects(tp,this._alphaFactor),this.uiObject.set(tp),this.markDirty())}get m_Color(){return this._color}raycastTarget=!0;uiObject=null;_color=null;_rect=null;_stateManager=null;get rectTransform(){if(this._rect||(this._rect=x.getComponent(this.gameObject,Cn)),!this._rect)throw new Error("Not Supported: Make sure to add a RectTransform component before adding a UI Graphic component.");return this._rect}onParentRectTransformChanged(){this.uiObject?.set({width:this.rectTransform.width,height:this.rectTransform.height}),this.markDirty()}__internalNewInstanceCreated(e){return super.__internalNewInstanceCreated(e),this._rect=null,this.uiObject=null,this._stateManager=null,this._color&&(this._color=this._color.clone()),this}setState(e){this.makePanel(),this.uiObject&&(this.uiObject.setState(e),this?.markDirty())}setupState(e){this.makePanel(),this.uiObject&&(this._stateManager||(this._stateManager=new qC(this.uiObject)),this.uiObject.setupState(e.state,e.attributes))}setOptions(e){this.makePanel(),this.uiObject&&this.uiObject.set(e)}awake(){super.awake(),this.makePanel(),Va(this,"_color",()=>nR(this,this.onColorChanged))}onEnable(){super.onEnable(),this.uiObject&&(this.rectTransform.shadowComponent?.add(this.uiObject),this.addShadowComponent(this.uiObject,this.rectTransform))}onDisable(){super.onDisable(),this.uiObject&&this.removeShadowComponent()}_currentlyCreatingPanel=!1;makePanel(){if(this.uiObject||this._currentlyCreatingPanel)return;this._currentlyCreatingPanel=!0;const e={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:.015};this.onBeforeCreate(e),this.applyEffects(e),this.onCreate(e),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated(),this.onColorChanged()}onBeforeCreate(e){}onCreate(e){this.uiObject=this.rectTransform.createNewBlock(e),this.uiObject.name=this.name}onAfterCreated(){}applyEffects(e,t=1){const i=this.gameObject?.getComponent(hl);i&&(i.effectDistance&&(e.borderWidth=Math.max(Math.abs(i.effectDistance.x),Math.abs(i.effectDistance.y))),i.effectColor&&(e.borderColor=i.effectColor,e.borderOpacity=i.effectColor.alpha*t))}static textureCache=new Map;async setTexture(e){if(this.setOptions({backgroundOpacity:0}),e){if(Xh.textureCache.has(e))e=Xh.textureCache.get(e);else if(!e.isRenderTargetTexture){const t=e.clone();t.colorSpace=po,Xh.textureCache.set(e,t),e=t}this.setOptions({backgroundImage:e,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"}),Ve.assignTextureLOD(e,0).then(t=>{t instanceof Re&&(e&&Xh.textureCache.set(e,t),this.setOptions({backgroundImage:t}),this.markDirty())})}else this.setOptions({backgroundImage:void 0,borderRadius:0,backgroundOpacity:this.color.alpha});this.markDirty()}onAfterAddedToScene(){super.onAfterAddedToScene(),this.shadowComponent&&(this.shadowComponent.offset=this.shadowComponent.position.z)}};Tx([u(se)],my.prototype,"color",1),Tx([u()],my.prototype,"raycastTarget",2);let Kc=my;class Zc extends Kc{_flippedObject=!1;onAfterCreated(){this.uiObject&&!this._flippedObject&&(this._flippedObject=!0,this.uiObject.scale.y*=-1)}}var cE=Object.defineProperty,hE=Object.getOwnPropertyDescriptor,Bo=(o,e,t,i)=>{for(var n=i>1?void 0:i?hE(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&cE(e,t,n),n};const Fr=w("debugtext");var at=(o=>(o[o.UpperLeft=0]="UpperLeft",o[o.UpperCenter=1]="UpperCenter",o[o.UpperRight=2]="UpperRight",o[o.MiddleLeft=3]="MiddleLeft",o[o.MiddleCenter=4]="MiddleCenter",o[o.MiddleRight=5]="MiddleRight",o[o.LowerLeft=6]="LowerLeft",o[o.LowerCenter=7]="LowerCenter",o[o.LowerRight=8]="LowerRight",o))(at||{}),Ex=(o=>(o[o.Normal=0]="Normal",o[o.Bold=1]="Bold",o[o.Italic=2]="Italic",o[o.BoldAndItalic=3]="BoldAndItalic",o))(Ex||{});class Dt extends Kc{alignment=0;verticalOverflow=0;horizontalOverflow=0;lineSpacing=1;supportRichText=!1;font;fontStyle=0;setAlphaFactor(e){super.setAlphaFactor(e),this.uiObject?.set({fontOpacity:this.color.alpha*this.alphaFactor}),this.markDirty()}get text(){return this._text}set text(e){e!==this._text&&(this._text=e,this.feedText(this.text,this.supportRichText),this.markDirty())}set_text(e){this.text=e}get fontSize(){return this._fontSize}set fontSize(e){this._fontSize=e,this.uiObject?.set({fontSize:e})}sRGBTextColor=new ne(1,0,1);onColorChanged(){this.sRGBTextColor.copy(this.color),this.sRGBTextColor.convertLinearToSRGB(),this.uiObject?.set({color:this.sRGBTextColor,fontOpacity:this.color.alpha})}onParentRectTransformChanged(){super.onParentRectTransformChanged(),this.uiObject&&this.updateOverflow()}onBeforeCanvasRender(e){this.updateOverflow()}updateOverflow(){const e=this.uiObject?._overflow;e&&(e._needsUpdate=!0)}onCreate(e){Fr&&console.log(this),this.horizontalOverflow==1&&(e.whiteSpace="pre"),this.verticalOverflow==0&&(this.context.renderer.localClippingEnabled=!0,e.overflow="hidden"),this.horizontalOverflow==1&&this.verticalOverflow==0,e.lineHeight=this.lineSpacing,delete e.backgroundOpacity,delete e.backgroundColor,Fr&&(e.backgroundColor=16750848,e.backgroundOpacity=.5);const t=this.rectTransform;e={...e,...this.getTextOpts()},this.getAlignment(e),Fr&&(e.backgroundColor=Math.random()*16777215,e.backgroundOpacity=.1),this.uiObject=t.createNewText(e),this.feedText(this.text,this.supportRichText)}onAfterAddedToScene(){super.onAfterAddedToScene(),this.handleTextRenderOnTop()}_text="";_fontSize=12;_textMeshUi=null;getTextOpts(){const e=this.fontSize,t={color:this.color,fontOpacity:this.color.alpha,fontSize:e,fontKerning:"normal"};return this.setFont(t,this.fontStyle),t}onEnable(){super.onEnable(),this._didHandleTextRenderOnTop=!1,this.uiObject&&this.uiObject.addAfterUpdate(()=>{this.setShadowComponentOwner(this.uiObject),this.markDirty()}),setTimeout(()=>this.markDirty(),10),this.canvas?.registerEventReceiver(this)}onDisable(){super.onDisable(),this.canvas?.unregisterEventReceiver(this)}getAlignment(e){switch(e.flexDirection="column",this.alignment){case 0:case 3:case 6:e.textAlign="left";break;case 1:case 4:case 7:e.textAlign="center";break;case 2:case 5:case 8:e.textAlign="right";break}switch(this.alignment){default:case 0:case 1:case 2:e.alignItems="start";break;case 3:case 4:case 5:e.alignItems="center";break;case 6:case 7:case 8:e.alignItems="end";break}return e}feedText(e,t){if(Fr&&console.log("feedText",this.uiObject,e,t),!!this.uiObject)if(this._textMeshUi||(this._textMeshUi=[]),this.uiObject.children.length=0,!t||e.length===0)this.uiObject.textContent=e;else{let i=this.getNextTag(e);if(i){if(i.startIndex>0){for(let r=this.uiObject.children.length-1;r>=0;r--){const a=this.uiObject.children[r];a.isUI&&(this.uiObject.remove(a),a.clear())}const s=new bm({textContent:e.substring(0,i.startIndex),color:"inherit"});this.uiObject.add(s)}}else{this.uiObject.textContent="",this.setOptions({textContent:e});return}const n=[];for(;i;){const s=this.getNextTag(e,i.endIndex),r={fontFamily:this.uiObject?.get("fontFamily"),color:"inherit",textContent:""};if(s){r.textContent=this.getText(e,i,s),this.handleTag(i,r,n);const a=new bm(r);this.uiObject?.add(a)}else{r.textContent=e.substring(i.endIndex),this.handleTag(i,r,n);const a=new bm(r);this.uiObject?.add(a)}i=s}}}_didHandleTextRenderOnTop=!1;handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;const e=[],t=this.canvas,i={renderOnTop:t.renderOnTop,depthWrite:t.depthWrite,doubleSided:t.doubleSided};for(;;){let n=!1;if(this._textMeshUi)for(let s=0;s<this._textMeshUi.length;s++){if(e[s]===!0)continue;n=!0;const r=this._textMeshUi[s];r.textContent&&(wu(r,i),e[s]=!0)}if(!n)break;yield}}handleTag(e,t,i){if(!e.isEndTag){if(e.type.includes("color")){const n=new gy(e,{color:t.color});if(i.push(n),e.type.length>6){const s=parseInt("0x"+e.type.substring(7));t.color=s}else t.color=new ne(1,1,1)}else if(e.type=="b"){this.setFont(t,1);const n=new gy(e,{fontWeight:700});i.push(n)}else if(e.type=="i"){this.setFont(t,2);const n=new gy(e,{fontStyle:"italic"});i.push(n)}}}getText(e,t,i){return e.substring(t.endIndex,i.startIndex)}getNextTag(e,t=0){const i=e.indexOf("<",t),n=e.indexOf(">",i);if(i>=0&&n>=0){const s=e.substring(i+1,n);return{type:s,startIndex:i,endIndex:n+1,isEndTag:s.startsWith("/")}}return null}setFont(e,t){if(!this.font)return;const i=this.font,n=this.getFamilyNameWithCorrectSuffix(i,t);Fr&&console.log("Selected font family:"+n);let s=ab.getFontFamily(n);switch(s||(s=ab.addFontFamily(n)),e.fontFamily=s,t){default:case 0:e.fontWeight=400,e.fontStyle="normal";break;case 1:e.fontWeight=700,e.fontStyle="normal";break;case 2:e.fontWeight=400,e.fontStyle="italic";break;case 3:e.fontStyle="italic",e.fontWeight=400}let r=s.getVariant(e.fontWeight,e.fontStyle);if(!r){let a=n;a?.endsWith("-msdf.json")||(a+="-msdf.json");let l=n;l?.endsWith(".png")||(l+=".png"),r=s.addVariant(e.fontWeight,e.fontStyle,a,l),r?.addEventListener("ready",()=>{this.markDirty()})}}getFamilyNameWithCorrectSuffix(e,t){const i=e.lastIndexOf("-");if(i<0)return e;const n=e.substring(i+1)?.toLowerCase();if(dE.includes(n))return Fr&&console.warn("Unsupported font style: "+n),e;const s=e.lastIndexOf("/");let r=e;s>=0&&(r=r.substring(s+1));const a=r[0]===r[0].toUpperCase(),l=e.substring(0,i);switch(Fr&&console.log("Select font: ",e,Ex[t],r,a,l),t){case 0:return a?l+"-Regular":l+"-regular";case 1:return a?l+"-Bold":l+"-bold";case 2:return a?l+"-Italic":l+"-italic";case 3:return a?l+"-BoldItalic":l+"-bolditalic";default:return e}}}Bo([u()],Dt.prototype,"alignment",2),Bo([u()],Dt.prototype,"verticalOverflow",2),Bo([u()],Dt.prototype,"horizontalOverflow",2),Bo([u()],Dt.prototype,"lineSpacing",2),Bo([u()],Dt.prototype,"supportRichText",2),Bo([u(URL)],Dt.prototype,"font",2),Bo([u()],Dt.prototype,"fontStyle",2),Bo([u()],Dt.prototype,"text",1),Bo([u()],Dt.prototype,"fontSize",1);class gy{tag;previousValues;constructor(e,t){this.tag=e,this.previousValues=t}}const dE=["medium","mediumitalic","black","blackitalic","thin","thinitalic","extrabold","light","lightitalic","semibold"];class dl{static global_id=0;static getId(){return this.global_id++}id;content="";font=[];pointSize=144;width;height;depth;wrapMode;horizontalAlignment;verticalAlignment;material;setDepth(e){return this.depth=e,this}setPointSize(e){return this.pointSize=e,this}setHorizontalAlignment(e){return this.horizontalAlignment=e,this}setVerticalAlignment(e){return this.verticalAlignment=e,this}constructor(e){this.id=e}writeTo(e,t){t.beginBlock(`def Preliminary_Text "${this.id}"`,"(",!1),t.appendLine('prepend apiSchemas = ["MaterialBindingAPI"]'),t.closeBlock(")"),t.beginBlock(),this.content&&t.appendLine(`string content = "${this.content}"`),(!this.font||this.font.length<=0)&&(this.font||=[],this.font?.push("sans-serif"));const i=this.font.map(n=>`"${n}"`).join(", ");t.appendLine(`string[] font = [ ${i} ]`),t.appendLine(`double pointSize = ${this.pointSize}`),typeof this.width=="number"&&t.appendLine(`double width = ${this.width}`),typeof this.height=="number"&&t.appendLine(`double height = ${this.height}`),typeof this.depth=="number"&&t.appendLine(`double depth = ${this.depth}`),this.wrapMode&&t.appendLine(`token wrapMode = "${this.wrapMode}"`),this.horizontalAlignment&&t.appendLine(`token horizontalAlignment = "${this.horizontalAlignment}"`),this.verticalAlignment&&t.appendLine(`token verticalAlignment = "${this.verticalAlignment}"`),this.material!==void 0&&t.appendLine(`rel material:binding = </StageRoot/Materials/${Vu(this.material)}>`),t.closeBlock()}}class fy{static singleLine(e,t,i){const n=new dl("text_"+dl.getId());return n.content=e,t&&(n.pointSize=t),i&&(n.depth=i),n}static multiLine(e,t,i,n,s,r){const a=new dl("text_"+dl.getId());return a.content=e,a.width=t,a.height=i,a.horizontalAlignment=n,a.verticalAlignment=s,r!==void 0&&(a.wrapMode=r),a}}const uE=new ee().makeRotationY(Math.PI),pE=new ee().makeScale(-1,1,-1);class ip{get extensionName(){return"text"}exportText(e,t,i){const n=x.getComponent(e,Dt);if(!n)return;const s=x.getComponent(e,Cn);let r=100,a=100;s&&(r=s.width,a=s.height);const l=uE.clone();s&&l.premultiply(pE),t.setMatrix(l);const c=n.color.clone();t.material=new ut({color:c,emissive:c}),t.addEventListener("serialize",(h,d)=>{let p=n.text;p=p.replace(/\r/g,""),p=p.replace(/\n/g,"\\n");const g=fy.multiLine(p,r,a,"center","bottom","flowing");this.setTextAlignment(g,n.alignment),this.setOverflow(g,n),t.material&&(g.material=t.material),g.pointSize=this.convertToTextSize(n.fontSize),g.depth=.001,g.writeTo(void 0,h)})}convertToTextSize(e){return 1/.0502*144*e}setOverflow(e,t){t.horizontalOverflow?e.wrapMode="singleLine":e.wrapMode="flowing"}setTextAlignment(e,t){switch(t){case at.LowerLeft:case at.MiddleLeft:case at.UpperLeft:e.horizontalAlignment="left";break;case at.LowerCenter:case at.MiddleCenter:case at.UpperCenter:e.horizontalAlignment="center";break;case at.LowerRight:case at.MiddleRight:case at.UpperRight:e.horizontalAlignment="right";break}switch(t){case at.LowerLeft:case at.LowerCenter:case at.LowerRight:e.verticalAlignment="bottom";break;case at.MiddleLeft:case at.MiddleCenter:case at.MiddleRight:e.verticalAlignment="middle";break;case at.UpperLeft:case at.UpperCenter:case at.UpperRight:e.verticalAlignment="top";break}}}var mE=Object.defineProperty,Ke=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&mE(e,t,n),n};const Ax=w("debuguilayout");class Ur{left=0;right=0;top=0;bottom=0;get vertical(){return this.top+this.bottom}get horizontal(){return this.left+this.right}}Ke([u()],Ur.prototype,"left"),Ke([u()],Ur.prototype,"right"),Ke([u()],Ur.prototype,"top"),Ke([u()],Ur.prototype,"bottom");class Ai extends M{_rectTransform=null;get rectTransform(){return this._rectTransform}onParentRectTransformChanged(e){this._needsUpdate=!0}_needsUpdate=!1;get isDirty(){return this._needsUpdate}get isLayoutGroup(){return!0}updateLayout(){this._rectTransform&&(Ax&&console.warn("Layout Update",this.context.time.frame,this.name),this._needsUpdate=!1,this.onCalculateLayout(this._rectTransform))}childAlignment=0;reverseArrangement=!1;spacing=0;padding;minWidth=0;minHeight=0;flexibleHeight=0;flexibleWidth=0;preferredHeight=0;preferredWidth=0;start(){this._needsUpdate=!0}onEnable(){Ax&&console.log(this.name,this),this._rectTransform=this.gameObject.getComponent(Cn);const e=this.gameObject.getComponentInParent(ul);e&&e.registerLayoutGroup(this),this._needsUpdate=!0}onDisable(){const e=this.gameObject.getComponentInParent(ul);e&&e.unregisterLayoutGroup(this)}set m_Spacing(e){e!==this.spacing&&(this._needsUpdate=!0,this.spacing=e)}get m_Spacing(){return this.spacing}}Ke([u()],Ai.prototype,"childAlignment"),Ke([u()],Ai.prototype,"reverseArrangement"),Ke([u()],Ai.prototype,"spacing"),Ke([u(Ur)],Ai.prototype,"padding"),Ke([u()],Ai.prototype,"minWidth"),Ke([u()],Ai.prototype,"minHeight"),Ke([u()],Ai.prototype,"flexibleHeight"),Ke([u()],Ai.prototype,"flexibleWidth"),Ke([u()],Ai.prototype,"preferredHeight"),Ke([u()],Ai.prototype,"preferredWidth");class As extends Ai{childControlHeight=!0;childControlWidth=!0;childForceExpandHeight=!1;childForceExpandWidth=!1;childScaleHeight=!1;childScaleWidth=!1;onCalculateLayout(e){const t=this.primaryAxis,i=e.width;let n=i;const s=e.height;let r=s;n-=this.padding.horizontal,r-=this.padding.vertical,t==="x"?this.padding.horizontal:this.padding.vertical;const a=t==="x",l=a?"y":"x",c=a?this.childControlWidth:this.childControlHeight,h=a?this.childControlHeight:this.childControlWidth,d=a?this.childForceExpandWidth:this.childForceExpandHeight,p=a?this.childForceExpandHeight:this.childForceExpandWidth,g=a?r:n,f=a?i:s,m=.5*(a?this.childAlignment%3:Math.floor(this.childAlignment/3));let y=0;a?y+=this.padding.left:y+=this.padding.top;let _=0,v=0;for(let L=0;L<this.gameObject.children.length;L++){const N=this.gameObject.children[L],j=x.getComponent(N,Cn);j?.activeAndEnabled&&(v+=1,a?_+=j.width:_+=j.height)}let P=0;const R=this.spacing*(v-1);if(d||c){let L=0;a?L=n-=R:L=r-=R,v>0&&(P=L/v)}let k=0;k+=this.padding.left,k-=this.padding.right,m!==0&&(y=f-_,y*=m,y-=R*m,a?(y-=this.padding.right*m,y+=this.padding.left*(1-m),y<this.padding.left&&(y=this.padding.left)):(y-=this.padding.bottom*m,y+=this.padding.top*(1-m),y<this.padding.top&&(y=this.padding.top)));let A=1;for(let L=0;L<this.gameObject.children.length;L++){const N=this.gameObject.children[L],j=x.getComponent(N,Cn);if(j?.activeAndEnabled){j.pivot?.set(.5,.5),j.anchorMin.set(0,1),j.anchorMax.set(0,1);const q=i*.5+k*.5;j.anchoredPosition.x!==q&&(j.anchoredPosition.x=q);const Y=s*-.5;j.anchoredPosition.y!==Y&&(j.anchoredPosition.y=Y),p&&h&&j.sizeDelta[l]!==g&&(j.sizeDelta[l]=g),d&&c&&j.sizeDelta[t]!==P&&(j.sizeDelta[t]=P);const I=a?j.width:j.height,V=I*.5;if(y+=V,d){const oe=P*A-P*.5;oe>y&&(y=oe-P*.5+I+this.padding.left,y-=V)}let W=y;t==="y"&&(W=-W),j.anchoredPosition[t]!==W&&(j.anchoredPosition[t]=W),y+=V,y+=this.spacing,A+=1}}}}Ke([u()],As.prototype,"childControlHeight"),Ke([u()],As.prototype,"childControlWidth"),Ke([u()],As.prototype,"childForceExpandHeight"),Ke([u()],As.prototype,"childForceExpandWidth"),Ke([u()],As.prototype,"childScaleHeight"),Ke([u()],As.prototype,"childScaleWidth");class yy extends As{get primaryAxis(){return"y"}}class by extends As{get primaryAxis(){return"x"}}class _y extends Ai{onCalculateLayout(){}}var gE=Object.defineProperty,fE=Object.getOwnPropertyDescriptor,eo=(o,e,t,i)=>{for(var n=i>1?void 0:i?fE(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&gE(e,t,n),n},Ix=(o=>(o[o.ScreenSpaceOverlay=0]="ScreenSpaceOverlay",o[o.ScreenSpaceCamera=1]="ScreenSpaceCamera",o[o.WorldSpace=2]="WorldSpace",o[o.Undefined=-1]="Undefined",o))(Ix||{});const vy=w("debuguilayout"),en=class G1 extends Xc{get isCanvas(){return!0}get screenspace(){return this.renderMode!==2}set renderOnTop(e){e!==this._renderOnTop&&(this._renderOnTop=e,this.onRenderSettingsChanged())}get renderOnTop(){return this._renderOnTop!==void 0?this._renderOnTop:!!(this.screenspace&&this._renderMode===0)}_renderOnTop;set depthWrite(e){this._depthWrite!==e&&(this._depthWrite=e,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}_depthWrite=!1;set doubleSided(e){this._doubleSided!==e&&(this._doubleSided=e,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}_doubleSided=!0;set castShadows(e){this._castShadows!==e&&(this._castShadows=e,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}_castShadows=!1;set receiveShadows(e){this._receiveShadows!==e&&(this._receiveShadows=e,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}_receiveShadows=!1;get renderMode(){return this._renderMode}set renderMode(e){this._renderMode!==e&&(this._renderMode=e,this.onRenderSettingsChanged())}_renderMode=-1;_rootCanvas;set rootCanvas(e){this._rootCanvas instanceof G1||(this._rootCanvas=e)}get rootCanvas(){return this._rootCanvas}_scaleFactor=1;get scaleFactor(){return this._scaleFactor}set scaleFactor(e){this._scaleFactor=e}worldCamera;planeDistance=-1;awake(){this.shadowComponent=this.gameObject,this.previousParent=this.gameObject.parent,vy&&console.log("Canvas.Awake()",this.previousParent?.name+"/"+this.gameObject.name),super.awake()}start(){this.applyRenderSettings()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this._lastMatrixWorld=new ee,this.applyRenderSettings(),document.addEventListener("resize",this._boundRenderSettingsChanged),this.context.pre_render_callbacks.push(this.onBeforeRenderRoutine),this.context.post_render_callbacks.push(this.onAfterRenderRoutine)}onDisable(){super.onDisable(),document.removeEventListener("resize",this._boundRenderSettingsChanged);const e=this.context.pre_render_callbacks.indexOf(this.onBeforeRenderRoutine);e!==-1&&this.context.pre_render_callbacks.splice(e,1);const t=this.context.post_render_callbacks.indexOf(this.onAfterRenderRoutine);t!==-1&&this.context.post_render_callbacks.splice(t,1)}_boundRenderSettingsChanged=this.onRenderSettingsChanged.bind(this);previousParent=null;_lastMatrixWorld=null;_rectTransforms=[];registerTransform(e){this._rectTransforms.push(e)}unregisterTransform(e){const t=this._rectTransforms.indexOf(e);t!==-1&&this._rectTransforms.splice(t,1)}_layoutGroups=new Map;registerLayoutGroup(e){const t=e.gameObject;this._layoutGroups.set(t,e)}unregisterLayoutGroup(e){const t=e.gameObject;this._layoutGroups.delete(t)}_receivers=[];registerEventReceiver(e){this._receivers.push(e)}unregisterEventReceiver(e){const t=this._receivers.indexOf(e);t!==-1&&this._receivers.splice(t,1)}async onEnterXR(e){this.screenspace?(e.xr.isVR||e.xr.isPassThrough)&&(this.gameObject.visible=!1):(this.gameObject.visible=!1,await Wl(1).then(()=>{this.gameObject.visible=!0}))}onLeaveXR(e){this.screenspace&&(e.xr.isVR||e.xr.isPassThrough)&&(this.gameObject.visible=!0)}onBeforeRenderRoutine=()=>{if(this.previousParent=this.gameObject.parent,(this.context.xr?.isVR||this.context.xr?.isPassThrough)&&this.screenspace){this.gameObject.visible=!1,this.gameObject.removeFromParent();return}this.renderOnTop||this.screenspace?this.gameObject.removeFromParent():(this.onUpdateRenderMode(),this.handleLayoutUpdates(),this.shadowComponent?.updateMatrixWorld(!0),this.shadowComponent?.updateWorldMatrix(!0,!0),this.invokeBeforeRenderEvents(),ei.ensureUpdateMeshUI(lb,this.context))};onAfterRenderRoutine=()=>{if((this.context.xr?.isVR||this.context.xr?.isPassThrough)&&this.screenspace){this.previousParent?.add(this.gameObject);return}if((this.screenspace||this.renderOnTop)&&this.previousParent&&this.context.mainCamera){this.screenspace?this.context.mainCamera?.add(this.gameObject):this.previousParent.add(this.gameObject);const e=this.context.renderer.autoClear,t=this.context.renderer.autoClearColor;this.context.renderer.autoClear=!1,this.context.renderer.autoClearColor=!1,this.context.renderer.clearDepth(),this.onUpdateRenderMode(!0),this.handleLayoutUpdates(),this.shadowComponent?.updateMatrixWorld(!0),this.invokeBeforeRenderEvents(),ei.ensureUpdateMeshUI(lb,this.context,!0),this.context.renderer.render(this.gameObject,this.context.mainCamera),this.context.renderer.autoClear=e,this.context.renderer.autoClearColor=t,this.previousParent.add(this.gameObject)}this._lastMatrixWorld?.copy(this.gameObject.matrixWorld)};invokeBeforeRenderEvents(){for(const e of this._receivers)e.onBeforeCanvasRender?.(this)}handleLayoutUpdates(){this._lastMatrixWorld===null&&(this._lastMatrixWorld=new ee);const e=!this._lastMatrixWorld.equals(this.gameObject.matrixWorld);vy&&e&&console.log("Canvas Layout changed",this.context.time.frameCount,this.name);for(const t of this._rectTransforms){e&&t.markDirty();let i=this._layoutGroups.get(t.gameObject);t.isDirty&&!i&&(i=t.gameObject.getComponentInParent(Ai)),(t.isDirty||i?.isDirty)&&(vy&&console.log("CANVAS UPDATE ### "+t.name+" ##################################### "+this.context.time.frame),i?.updateLayout(),t.updateTransform())}}applyRenderSettings(){this.onRenderSettingsChanged()}_updateRenderSettingsRoutine;onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),we.OnBeforeRender))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.onUpdateRenderMode(),wu(this.shadowComponent,this);for(const e of x.getComponentsInChildren(this.gameObject,rn))wu(e.shadowComponent,this)}}_activeRenderMode=-1;_lastWidth=-1;_lastHeight=-1;onUpdateRenderMode(e=!1){if(!e&&this._renderMode===this._activeRenderMode&&this._lastWidth===this.context.domWidth&&this._lastHeight===this.context.domHeight)return;this._activeRenderMode=this._renderMode;let t=this.context.mainCameraComponent,i=10;switch(t&&t.nearClipPlane>0&&t.farClipPlane>0&&(i=D.lerp(t.nearClipPlane,t.farClipPlane,.01)),this._renderMode===1&&(this.worldCamera&&(t=this.worldCamera),this.planeDistance>0&&(i=this.planeDistance)),this._renderMode){case 0:case 1:if(this._lastWidth=this.context.domWidth,this._lastHeight=this.context.domHeight,!t)return;const n=i+.01;this.gameObject.position.x=0,this.gameObject.position.y=0,this.gameObject.position.z=-n,this.gameObject.quaternion.identity();const s=this.gameObject.getComponent(Cn);let r=!1;s.sizeDelta.x!==this.context.domWidth&&(r=!0),s.sizeDelta.y!==this.context.domHeight&&(r=!0);const a=t.fieldOfView*Math.PI/180,l=2*Math.tan(a/2)*Math.abs(n);this.gameObject.scale.x=l/this.context.domHeight,this.gameObject.scale.y=l/this.context.domHeight,this.gameObject.scale.z=.01,r&&(s.sizeDelta.x=this.context.domWidth,s.sizeDelta.y=this.context.domHeight,s?.markDirty());break;case 2:this._lastWidth=-1,this._lastHeight=-1;break}}};eo([u()],en.prototype,"renderOnTop",1),eo([u()],en.prototype,"depthWrite",1),eo([u()],en.prototype,"doubleSided",1),eo([u()],en.prototype,"castShadows",1),eo([u()],en.prototype,"receiveShadows",1),eo([u()],en.prototype,"renderMode",1),eo([u(en)],en.prototype,"rootCanvas",1),eo([u()],en.prototype,"scaleFactor",1),eo([u(si)],en.prototype,"worldCamera",2),eo([u()],en.prototype,"planeDistance",2);let ul=en;var yE=Object.defineProperty,bE=Object.getOwnPropertyDescriptor,wy=(o,e,t,i)=>{for(var n=i>1?void 0:i?bE(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&yE(e,t,n),n};class Is extends M{get alpha(){return this._alpha}set alpha(e){e!==this._alpha&&(this._alpha=e,this.markDirty())}get isCanvasGroup(){return!0}_alpha=1;interactable=!0;blocksRaycasts=!0;_isDirty=!1;markDirty(){this._isDirty||(this._isDirty=!0,this.startCoroutine(this.applyChangesDelayed(),we.OnBeforeRender))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}_buffer=[];applyChangesNow(){this._buffer.length=0;for(const e of x.getComponentsInChildren(this.gameObject,rn,this._buffer)){const t=e;t.setAlphaFactor&&t.setAlphaFactor(this._alpha)}}}wy([u()],Is.prototype,"alpha",1),wy([u()],Is.prototype,"interactable",2),wy([u()],Is.prototype,"blocksRaycasts",2);class xy{get extensionName(){return"tmui"}onExportObject(e,t,i){const n=x.getComponent(e,ul);if(n&&n.enabled&&n.renderMode===Ix.WorldSpace){const s=new ip,r=x.getComponent(e,Cn),a=x.getComponent(e,Is),l=new Array;if(r){if(!x.isActiveSelf(e)){const d=x.isActiveSelf(e);x.setActive(e,!0),r.onEnable(),r.updateTransform(),l.push(()=>{r.onDisable(),x.setActive(e,d)})}e.traverse(d=>{if(!x.isActiveInHierarchy(d)){const p=x.isActiveSelf(d);x.setActive(d,!0);const g=x.getComponent(d,rn);g&&(g.onEnable(),l.push(()=>{g.onDisable()}));const f=x.getComponent(d,Cn);f&&(f.onEnable(),f.updateTransform(),f.onApplyTransform(),l.push(()=>{f.onDisable()}));const m=x.getComponent(d,Dt);m&&(m.onEnable(),l.push(()=>{m.onDisable()})),l.push(()=>{x.setActive(d,p)})}}),r.width,r.height;const c=it.createEmpty(),h=r.shadowComponent;if(t.add(c),h){const d=h.matrix;c.setMatrix(d);const p=new Map,g=new Map;p.set(h,c),g.set(h,a?a.alpha:1),h.traverse(f=>{if(f===h)return;const m=it.createEmpty();m.setMatrix(f.matrix);const y=f.parent,_=!!y&&typeof y.textContent=="string"&&y.textContent.length>0;let v=g.get(y)||1;const P=x.getComponent(f,Is);if(P&&(v*=P.alpha),f instanceof H&&_){const k=f[Si];k?s.exportText(k.gameObject,m,i):console.error("Error when exporting UI: shadow component owner not found. This is likely a bug.",f)}if(f instanceof H&&!_){const k=f.geometry.clone();k.scale(1,1,-1),this.flipWindingOrder(k),m.geometry=k;const A=new ne,L=f.material.opacity;A.copy(f.material.color),m.material=new xe({color:A,opacity:L*v,map:f.material.map,transparent:!0})}p.set(f,m),g.set(f,v);const R=p.get(y);if(!R){console.error("Error when exporting UI: shadow component parent not found!",f,f.parent);return}R.add(m)})}}for(const c of l)c()}}flipWindingOrder(e){const t=e.index.array;for(let i=0,n=t.length/3;i<n;i++){const s=t[i*3];t[i*3]=t[i*3+2],t[i*3+2]=s}e.index.needsUpdate=!0}}const Jc=w("debugusdz");function _E(o,e){const t=[],i=x.getComponentsInChildren(o,ft),n=x.getComponentsInChildren(o,Ht),s=new Array,r=new Array;if(e.injectImplicitBehaviours)for(const a of i){if(!a||!a.runtimeAnimatorController||!a.enabled)continue;const l=a.runtimeAnimatorController.activeState;if(!l||!l.motion||!l.motion.clip||l.motion.clip.tracks?.length<1||s.includes(a))continue;const c=new Nc;c.animator=a,c.stateName=l.name,c.trigger="start",c.name="PlayAnimationOnClick_implicitAtStart_"+c.stateName;const h=new O;x.addComponent(h,c),r.push(h),s.push(a),o.add(h)}else for(const a of i){if(!a||!a.runtimeAnimatorController||!a.enabled)continue;Jc&&console.log(a);const l=[];for(const c of a.runtimeAnimatorController.enumerateActions()){Jc&&console.log(c);const h=c.getClip();l.includes(h)||l.push(h)}t.push({root:a.gameObject,clips:l})}if(e.injectImplicitBehaviours)for(const a of n){if(!a||!a.clip||!a.enabled||!a.playAutomatically||s.includes(a))continue;const l=new Nc;l.animation=a,l.stateName=a.clip.name,l.trigger="start",l.name="PlayAnimationOnClick_implicitAtStart_"+l.stateName;const c=new O;x.addComponent(c,l),r.push(c),s.push(a),o.add(c)}else for(const a of n){Jc&&console.log(a);const l=[];for(const c of a.animations)l.includes(c)||l.push(c);t.push({root:a.gameObject,clips:l})}Jc&&t?.length>0&&console.log("USDZ Animation Clips without behaviours",t);for(const a of t)for(const l of a.clips)e.registerAnimation(a.root,l);return r}function vE(o,e){const t=x.getComponentsInChildren(o,Mi),i=x.getComponentsInChildren(o,Os),n=new Array,s=new Array;Jc&&console.log({audioSources:t,playAudioOnClicks:i});for(const r of i){if(!r.target)continue;const a=t.indexOf(r.target);a>-1&&t.splice(a,1)}for(const r of t){if(!r||!r.clip||r.volume<=0||n.includes(r))continue;const a=new Os;a.target=r,a.name="PlayAudioOnClick_implicitAtStart_",a.trigger="start";const l=new O;x.addComponent(l,a),console.log("implicit PlayAudioOnStart",l,a),s.push(l),n.push(r),o.add(l)}return s}function wE(o){return new Et("DisableAtStart",jt.sceneStartTrigger(),me.fadeAction(o,0,!1))}function Lx(o,e){const t=o.domElement.shadowRoot.querySelector("link[rel='ar']");if(t)return t;const i=document.createElement("div");i.classList.add("menu"),i.classList.add("quicklook-menu"),i.style.display="none",i.style.visibility="hidden";const n=document.createElement("button");n.id="open-in-ar",e?(n.innerText="View in AR",n.title="View this scene in AR. The scene will be exported to USDZ and opened with Apple's QuickLook."):(n.innerText="View in AR",n.title="Download this scene for AR. Open the downloaded USDZ file to view it in AR using Apple's QuickLook."),i.appendChild(n);const s=document.createElement("a");s.id="needle-usdz-link",s.style.display="none",s.rel="ar",s.href="",s.target="_blank",i.appendChild(s);const r=document.createElement("img");return r.id="button",s.appendChild(r),o.domElement.shadowRoot.appendChild(i),s}var xE=Object.defineProperty,kt=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&xE(e,t,n),n};const Ii=w("debugusdz"),SE=w("debugusdzpruning");class zr{callToAction;checkoutTitle;checkoutSubtitle;callToActionURL}kt([u()],zr.prototype,"callToAction"),kt([u()],zr.prototype,"checkoutTitle"),kt([u()],zr.prototype,"checkoutSubtitle"),kt([u()],zr.prototype,"callToActionURL");const hi=class Qh extends M{static beforeExport=new ce;static afterExport=new ce;objectToExport=void 0;autoExportAnimations=!0;autoExportAudioSources=!0;exportFileName=void 0;customUsdzFile=void 0;customBranding;anchoringType="plane";maxTextureSize=2048;planeAnchoringAlignment="horizontal";interactive=!0;physics=!0;allowCreateQuicklookButton=!0;quickLookCompatible=!0;extensions=[];link;button;start(){Ii&&(console.log("USDZExporter",this),console.log("Debug USDZ Mode. Press 'T' to export"),window.addEventListener("keydown",e=>{switch(e.key){case"t":this.exportAndOpen();break}})),this.objectToExport||(this.objectToExport=this.gameObject),!this.objectToExport?.children?.length&&!this.objectToExport?.isMesh&&(this.objectToExport=this.context.scene)}onEnable(){const e=G.supportsQuickLookAR(),t=G.isiOS()||G.isiPad();!this.button&&(Ii||e||t)&&(this.allowCreateQuicklookButton&&(this.button=this.createQuicklookButton()),this.lastCallback=this.quicklookCallback.bind(this),this.link=Lx(this.context,e),this.link.addEventListener("message",this.lastCallback)),Ii&&Te("USDZ Exporter enabled: "+this.name),document.getElementById("open-in-ar")?.addEventListener("click",this.onClickedOpenInARElement),ec.registerExporter(this)}onDisable(){this.button?.remove(),this.link?.removeEventListener("message",this.lastCallback),Ii&&Te("USDZ Exporter disabled: "+this.name),document.getElementById("open-in-ar")?.removeEventListener("click",this.onClickedOpenInARElement),ec.unregisterExporter(this)}onClickedOpenInARElement=e=>{e.preventDefault(),this.exportAndOpen()};async exportAsync(){return this.exportAndOpen()}async exportAndOpen(){let e=this.exportFileName??this.objectToExport?.name??this.name;if(e+="-"+tx(),Wn()||(e!==""&&(e+="-"),e+="MadeWithNeedle"),this.link||(this.link=Lx(this.context,G.supportsQuickLookAR())),this.customUsdzFile)return Ii&&console.log("Exporting custom usdz",this.customUsdzFile),this.openInQuickLook(this.customUsdzFile,e),null;if(!this.objectToExport)return console.warn("No object to export",this),null;Qh.beforeExport.invoke({exporter:this});const t=await this.export(this.objectToExport).finally(()=>{Qh.afterExport.invoke({exporter:this})});return t?(Ii&&console.log("USDZ generation done. Downloading as "+e),this.openInQuickLook(t,e),t):(console.error("USDZ generation failed. Please report a bug",this),null)}async export(e){if(!e)return console.warn("No object to export"),null;const t=this._currentExportTasks.get(e);if(t)return t;const i=this.internalExport(e);return i instanceof Promise?(this._currentExportTasks.set(e,i),i.then(n=>(this._currentExportTasks.delete(e),n)).catch(n=>(this._currentExportTasks.delete(e),console.error("Error during USDZ export \u2013 please report a bug!",n),null))):i}_currentExportTasks=new Map;_previousTimeScale=1;async internalExport(e){re.start("export-usdz",{onProgress:R=>{this.dispatchEvent(new CustomEvent("export-progress",{detail:{progress:R}}))}}),re.report("export-usdz",{message:"Starting export",totalSteps:40,currentStep:0}),re.report("export-usdz",{message:"Load progressive textures",autoStep:5}),re.start("export-usdz-textures","export-usdz");const t=x.getComponentsInChildren(e,ci);for(const R of t)R&&R.enabled&&R.updateSprite(!0);const i=x.getComponentsInChildren(e,Ti),n=new Array;let s=0;for(const R of i){for(const k of R.sharedMeshes)if(k){const A=Ve.assignMeshLOD(k,0);A instanceof Promise&&n.push(new Promise((L,N)=>{A.then(()=>{s++,re.report("export-usdz-textures",{message:"Loaded progressive mesh",currentStep:s,totalSteps:n.length}),L()}).catch(j=>N(j))}))}for(const k of R.sharedMaterials)if(k){const A=Ve.assignTextureLOD(k,0);A instanceof Promise&&n.push(new Promise((L,N)=>{A.then(()=>{s++,re.report("export-usdz-textures",{message:"Loaded progressive texture",currentStep:s,totalSteps:n.length}),L()}).catch(j=>N(j))}))}}Ii&&Te("Progressive Loading: "+n.length),await Promise.all(n),Ii&&Te("Progressive Loading: done"),re.end("export-usdz-textures");const r=Jt.Global.Mask;Jt.Global.Set(Xn.AR);const a=new rx,l=new Gu(this.quickLookCompatible);let c;const h=[];this.interactive&&(h.push(new hy),h.push(new aa),globalThis.NEEDLE_USE_RAPIER&&x.getComponentsInChildren(e,Ye).length>0&&(this.physics?(c=new dy,h.push(c)):E()&&console.warn("USDZExporter: Physics export is disabled, but there are active Rigidbody components in the scene. They will not be exported.")),h.push(new ip),h.push(new xy));const d=[l,...h,...this.extensions],p={self:this,exporter:a,extensions:d,object:e};re.report("export-usdz","Invoking before-export"),this.dispatchEvent(new CustomEvent("before-export",{detail:p})),this.applyWebARSessionRoot(),this._previousTimeScale=this.context.time.timeScale,this.context.time.timeScale=0,re.report("export-usdz","auto export animations and audio sources");const g=new Array;this.autoExportAnimations&&g.push(..._E(e,l)),d.find(R=>R.extensionName==="Audio")&&this.autoExportAudioSources&&g.push(...vE(e)),a.debug=Ii,a.pruneUnusedNodes=!SE;const f=la.instance.objs.map(R=>R.batchedMesh);a.keepObject=R=>{let k=!0;const A=x.getComponent(R,Ti);return A&&!A.enabled&&(k=!1),k&&f.includes(R)&&(k=!1),k&&x.getComponentInParent(R,Ac)&&(k=!1),k&&x.getComponentInParent(R,$n)&&(k=!1),Ii&&!k&&console.log("USDZExporter: Discarding object",R),k},a.beforeWritingDocument=()=>{if(E()&&l&&c){const R=l.animatedRoots;for(const k of R){const A=x.getComponentsInChildren(k,Ye).filter(N=>N.enabled),L=x.getComponents(k,ai).filter(N=>N.enabled&&!N.isTrigger);(A.length>0||L.length>0)&&console.error("An animated object has physics components in its child hierarchy. This can lead to undefined behaviour due to a bug in Apple's QuickLook (FB15925487). Remove the physics components from child objects or verify that you get the expected results.",k)}}};const m=new Array;this.objectToExport&&this.quickLookCompatible&&this.interactive&&this.objectToExport.traverse(R=>{R.visible||m.push(R)});const y=d.find(R=>R.extensionName==="Behaviour");this.interactive&&y&&m.length>0&&y.addBehavior(wE(m));let _=!0;this.quickLookCompatible&&!this.interactive&&(_=!1),this.anchoringType!=="plane"&&this.anchoringType!=="none"&&this.anchoringType!=="image"&&this.anchoringType!=="face"&&(this.anchoringType="plane"),this.planeAnchoringAlignment!=="horizontal"&&this.planeAnchoringAlignment!=="vertical"&&this.planeAnchoringAlignment!=="any"&&(this.planeAnchoringAlignment="horizontal"),re.report("export-usdz","Invoking exporter.parse");const v=await a.parse(this.objectToExport,{ar:{anchoring:{type:this.anchoringType},planeAnchoring:{alignment:this.planeAnchoringAlignment}},extensions:d,quickLookCompatible:this.quickLookCompatible,maxTextureSize:this.maxTextureSize,exportInvisible:_}),P=new Blob([v],{type:"model/vnd.usdz+zip"});this.revertWebARSessionRoot(),this.context.time.timeScale=this._previousTimeScale,re.report("export-usdz","Invoking after-export"),this.dispatchEvent(new CustomEvent("after-export",{detail:p}));for(const R of g)x.destroy(R);return Jt.Global.Set(r),re.end("export-usdz"),P}openInQuickLook(e,t){const i=e instanceof Blob?URL.createObjectURL(e):e,n=this.buildQuicklookOverlay();Ii&&console.log("QuickLook Overlay",n);const s=n.callToAction?encodeURIComponent(n.callToAction):"",r=n.checkoutTitle?encodeURIComponent(n.checkoutTitle):"",a=n.checkoutSubtitle?encodeURIComponent(n.checkoutSubtitle):"";this.link.href=i+`#callToAction=${s}&checkoutTitle=${r}&checkoutSubtitle=${a}&callToActionURL=${n.callToActionURL}`,this.lastCallback||(this.lastCallback=this.quicklookCallback.bind(this),this.link.addEventListener("message",this.lastCallback)),this.link.download=t+".usdz",this.link.click()}download(e,t){Qh.save(e,t)}static save(e,t){const i=document.createElement("a");i.style.display="none",document.body.appendChild(i),typeof e=="string"?i.href=e:i.href=URL.createObjectURL(e),i.download=t,i.click(),i.remove()}lastCallback;quicklookCallback(e){if(e?.data=="_apple_ar_quicklook_button_tapped"){Ii&&ge("Quicklook closed via call to action button");var t=new CustomEvent("quicklook-button-tapped",{detail:this});if(this.dispatchEvent(t),!t.defaultPrevented){const i=new URLSearchParams(this.link.href);if(i){const n=i.get("callToActionURL");Ii&&Te("Quicklook url: "+n),n&&(Wn()?globalThis.open(n,"_blank"):console.warn("Quicklook closed: custom redirects require a Needle Engine Pro license: https://needle.tools/pricing",n))}}}}buildQuicklookOverlay(){const e={};return this.customBranding&&Object.assign(e,this.customBranding),Wn()||(console.log("Custom Quicklook banner text requires pro license: https://needle.tools/pricing"),e.callToAction="Close",e.checkoutTitle="\u{1F335} Made with Needle",e.checkoutSubtitle="_"),(e.callToAction?.length||e.checkoutTitle?.length||e.checkoutSubtitle?.length)&&(e.callToAction?.length||(e.callToAction="\0"),e.checkoutTitle?.length||(e.checkoutTitle="\0"),e.checkoutSubtitle?.length||(e.checkoutSubtitle="\0")),this.dispatchEvent(new CustomEvent("quicklook-overlay",{detail:e})),e}static invertForwardMatrix=new ee().makeRotationY(Math.PI);static invertForwardQuaternion=new U().setFromEuler(new nt(0,Math.PI,0));_rootSessionRootWasAppliedTo=null;_rootPositionBeforeExport=new b;_rootRotationBeforeExport=new U;_rootScaleBeforeExport=new b;getARScaleAndTarget(){if(!this.objectToExport)return{scale:1,_invertForward:!1,target:this.gameObject,sessionRoot:null};const e=x.findObjectOfType(Zu);let t=x.getComponentInParent(this.objectToExport,Ui);t||(t=x.getComponentInChildren(this.objectToExport,Ui));let i=1,n=!1;const s=this.objectToExport;return e?i=e.arScale:t&&(i=t.arScale,n=t.invertForward),{scale:1/i,_invertForward:n,target:s,sessionRoot:t?.gameObject??null}}applyWebARSessionRoot(){if(!this.objectToExport)return;const{scale:e,_invertForward:t,target:i,sessionRoot:n}=this.getARScaleAndTarget(),s=n?.matrixWorld.clone().invert();this._rootSessionRootWasAppliedTo=i,this._rootPositionBeforeExport.copy(i.position),this._rootRotationBeforeExport.copy(i.quaternion),this._rootScaleBeforeExport.copy(i.scale),i.scale.multiplyScalar(e),t&&i.quaternion.multiply(Qh.invertForwardQuaternion),i.updateMatrix(),i.updateMatrixWorld(!0),n&&s&&i.matrix.premultiply(s)}revertWebARSessionRoot(){if(!this.objectToExport||!this._rootSessionRootWasAppliedTo)return;const e=this._rootSessionRootWasAppliedTo;e.position.copy(this._rootPositionBeforeExport),e.quaternion.copy(this._rootRotationBeforeExport),e.scale.copy(this._rootScaleBeforeExport),e.updateMatrix(),e.updateMatrixWorld(!0),this._rootSessionRootWasAppliedTo=null}createQuicklookButton(){const e=Qs.getOrCreate().createQuicklookButton();return e.parentNode||this.context.menu.appendChild(e),e}};kt([u(O)],hi.prototype,"objectToExport"),kt([u()],hi.prototype,"autoExportAnimations"),kt([u()],hi.prototype,"autoExportAudioSources"),kt([u()],hi.prototype,"exportFileName"),kt([u(URL)],hi.prototype,"customUsdzFile"),kt([u(zr)],hi.prototype,"customBranding"),kt([u()],hi.prototype,"anchoringType"),kt([u()],hi.prototype,"maxTextureSize"),kt([u()],hi.prototype,"planeAnchoringAlignment"),kt([u()],hi.prototype,"interactive"),kt([u()],hi.prototype,"physics"),kt([u()],hi.prototype,"allowCreateQuicklookButton"),kt([u()],hi.prototype,"quickLookCompatible");let to=hi;var CE=Object.defineProperty,PE=Object.getOwnPropertyDescriptor,Sy=(o,e,t,i)=>{for(var n=PE(e,t),s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&CE(e,t,n),n};class pl extends M{get fog(){return this._fog||(this._fog=new j0(0,0,50)),this._fog}get mode(){return 1}set near(e){this.fog.near=e}get near(){return this.fog.near}set far(e){this.fog.far=e}get far(){return this.fog.far}set color(e){this.fog.color.copy(e)}get color(){return this.fog.color}_fog;onEnable(){this.scene.fog=this.fog}onDisable(){this.scene.fog===this._fog&&(this.scene.fog=null)}}Sy([u()],pl.prototype,"near"),Sy([u()],pl.prototype,"far"),Sy([u(ne)],pl.prototype,"color");var OE=Object.defineProperty,Cy=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&OE(e,t,n),n};class Nr extends M{objectBounds=!1;color;isGizmo=!0;_gizmoObject=null;_boxHelper=null;onEnable(){this.isGizmo&&!lc||(this._gizmoObject||(this.objectBounds?this._gizmoObject=new XS(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=cg(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),we.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){for(;this._boxHelper;)this._boxHelper?.update(),yield}}Cy([u()],Nr.prototype,"objectBounds"),Cy([u(ne)],Nr.prototype,"color"),Cy([u()],Nr.prototype,"isGizmo");var kE=Object.defineProperty,Py=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&kE(e,t,n),n};class ml extends M{isGizmo=!1;color0;color1;gridHelper;size;divisions;offset;onEnable(){if(this.isGizmo&&!lc)return;const e=this.size,t=this.divisions;this.gridHelper||(this.gridHelper=new Jp(e,t,this.color0??new ne(.4,.4,.4),this.color1??new ne(.6,.6,.6)),this.offset!==void 0&&(this.gridHelper.position.y+=this.offset)),this.gridHelper&&this.gameObject.add(this.gridHelper)}onDisable(){this.gridHelper&&(this.gameObject.remove(this.gridHelper),this.gridHelper=null)}}Py([u()],ml.prototype,"isGizmo"),Py([u(ne)],ml.prototype,"color0"),Py([u(ne)],ml.prototype,"color1");var ME=Object.defineProperty,Oy=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&ME(e,t,n),n};class ky extends M{connectedBody;get rigidBody(){return this._rigidBody}_rigidBody=null;onEnable(){this._rigidBody||(this._rigidBody=this.gameObject.getComponent(Ye)),this.rigidBody&&this.connectedBody&&this.startCoroutine(this.create())}*create(){yield,this.rigidBody&&this.connectedBody&&this.activeAndEnabled&&this.createJoint(this.rigidBody,this.connectedBody)}}Oy([u(Ye)],ky.prototype,"connectedBody");class My extends ky{createJoint(e,t){this.context.physics.engine?.addFixedJoint(e,t)}}class eh extends ky{anchor;axis;createJoint(e,t){this.axis&&this.anchor&&this.context.physics.engine?.addHingeJoint(e,t,this.anchor,this.axis)}}Oy([u(b)],eh.prototype,"anchor"),Oy([u(b)],eh.prototype,"axis");var RE=Object.defineProperty,TE=Object.getOwnPropertyDescriptor,io=(o,e,t,i)=>{for(var n=i>1?void 0:i?TE(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&RE(e,t,n),n};function Ry(o){return o*Math.PI/180}const jx=300,Ls=w("debuglights");class di extends M{type=0;range=1;spotAngle=1;innerSpotAngle=1;set color(e){this._color=e,this.light!==void 0&&(this.light.color=e)}get color(){return this.light?this.light.color:this._color}_color=new ne(16777215);set shadowNearPlane(e){if(e!==this._shadowNearPlane&&(this._shadowNearPlane=e,this.light?.shadow?.camera!==void 0)){const t=this.light.shadow.camera;t.near=e}}get shadowNearPlane(){return this._shadowNearPlane}_shadowNearPlane=.1;set shadowBias(e){e!==this._shadowBias&&(this._shadowBias=e,this.light?.shadow?.bias!==void 0&&(this.light.shadow.bias=e,this.light.shadow.needsUpdate=!0))}get shadowBias(){return this._shadowBias}_shadowBias=0;set shadowNormalBias(e){e!==this._shadowNormalBias&&(this._shadowNormalBias=e,this.light?.shadow?.normalBias!==void 0&&(this.light.shadow.normalBias=e,this.light.shadow.needsUpdate=!0))}get shadowNormalBias(){return this._shadowNormalBias}_shadowNormalBias=0;_overrideShadowBiasSettings=!1;set shadows(e){this._shadows=e,this.light&&(this.light.castShadow=e!==0,this.updateShadowSoftHard())}get shadows(){return this._shadows}_shadows=1;lightmapBakeType=4;set intensity(e){if(this._intensity=e,this.light){let t=1;if(this.context.isInXR&&this._webARRoot){const i=this._webARRoot?.arScale;typeof i=="number"&&i>0&&(t/=i)}this.light.intensity=e*t}Ls&&console.log("Set light intensity to "+this._intensity,e,this)}get intensity(){return this._intensity}_intensity=-1;get shadowDistance(){const e=this.light;return e?.shadow?e.shadow.camera.far:-1}set shadowDistance(e){this._shadowDistance=e;const t=this.light;if(t?.shadow){const i=t.shadow.camera;i.far=e,i.updateProjectionMatrix()}}_shadowDistance;shadowWidth;shadowHeight;get shadowResolution(){const e=this.light;return e?.shadow?e.shadow.mapSize.x:-1}set shadowResolution(e){if(e===this._shadowResolution)return;this._shadowResolution=e;const t=this.light;t?.shadow&&(t.shadow.mapSize.set(e,e),t.shadow.needsUpdate=!0)}_shadowResolution=void 0;get isBaked(){return this.lightmapBakeType===2}get selfIsLight(){if(this.gameObject.isLight===!0)return!0;switch(this.gameObject.type){case"SpotLight":case"PointLight":case"DirectionalLight":return!0}return!1}light=void 0;getWorldPosition(e){return this.light?this.type===1?this.light.getWorldPosition(e).multiplyScalar(1):this.light.getWorldPosition(e):e}awake(){this.color=new ne(this.color??16777215),Ls&&console.log(this.name,this)}onEnable(){Ls&&console.log("ENABLE LIGHT",this.name),this.createLight(),!this.isBaked&&(this.light&&(this.light.visible=!0,this.light.intensity=this._intensity,Ls&&console.log("Set light intensity to "+this.light.intensity,this.name),this.selfIsLight||this.light.parent!==this.gameObject&&this.gameObject.add(this.light)),this.type===1&&this.startCoroutine(this.updateMainLightRoutine(),we.LateUpdate))}onDisable(){Ls&&console.log("DISABLE LIGHT",this.name),this.light&&(this.selfIsLight?this.light.intensity=0:this.light.visible=!1)}_webXRStartedListener;_webXREndedListener;_webARRoot;onEnterXR(e){this._webARRoot=x.getComponentInParent(this.gameObject,Ui)??void 0}onLeaveXR(e){}createLight(){const e=this.selfIsLight;if(e&&!this.light)switch(this.light=this.gameObject,this.light.name=this.name,this._intensity=this.light.intensity,this.type){case 1:this.setDirectionalLight(this.light);break}else if(!this.light)switch(this.type){case 1:const t=new em(this.color,this.intensity*Math.PI);if(t.position.set(0,0,-jx*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(t.target),sr(t.target,0,0,0),this.light=t,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),Ls){const r=new YS(this.light,.2,this.color);this.context.scene.add(r)}break;case 0:const i=new QS(this.color,this.intensity*Math.PI,this.range,Ry(this.spotAngle/2),1-Ry(this.innerSpotAngle/2)/Ry(this.spotAngle/2),2);i.position.set(0,0,0),i.rotation.set(0,0,0),this.light=i;const n=i.target;i.add(n),n.position.set(0,0,this.range),n.rotation.set(0,0,0);break;case 2:const s=new tm(this.color,this.intensity*Math.PI,this.range);this.light=s;break}if(this.light){if(this._intensity>=0?this.light.intensity=this._intensity:this._intensity=this.light.intensity,this.shadows!==0?this.light.castShadow=!0:this.light.castShadow=!1,this.light.shadow){this._shadowResolution!==void 0&&this._shadowResolution>4?(this.light.shadow.mapSize.width=this._shadowResolution,this.light.shadow.mapSize.height=this._shadowResolution):(this.light.shadow.mapSize.width=2048,this.light.shadow.mapSize.height=2048),Ls&&console.log("Override shadow bias?",this._overrideShadowBiasSettings,this.shadowBias,this.shadowNormalBias),this.light.shadow.bias=this.shadowBias,this.light.shadow.normalBias=this.shadowNormalBias,this.updateShadowSoftHard();const t=this.light.shadow.camera;if(t.near=this.shadowNearPlane,this._shadowDistance!==void 0&&typeof this._shadowDistance=="number"?t.far=this._shadowDistance:t.far=jx*Math.abs(this.gameObject.scale.z),this.gameObject.scale.set(1,1,1),this.shadowWidth!==void 0)t.left=-this.shadowWidth/2,t.right=this.shadowWidth/2;else{const i=this.gameObject.scale.x;t.left*=i,t.right*=i}if(this.shadowHeight!==void 0)t.top=this.shadowHeight/2,t.bottom=-this.shadowHeight/2;else{const i=this.gameObject.scale.y;t.top*=i,t.bottom*=i}this.light.shadow.needsUpdate=!0,Ls&&this.context.scene.add(new KS(t))}this.isBaked?this.light.removeFromParent():e||this.gameObject.add(this.light)}}*updateMainLightRoutine(){for(;;){this.type===1&&((!this.context.mainLight||this.intensity>this.context.mainLight.intensity)&&(this.context.mainLight=this),yield);break}}static allowChangingRendererShadowMapType=!0;updateShadowSoftHard(){this.light&&this.light.shadow&&(this.shadows===2||(this.light.shadow.radius=1,this.light.shadow.blurSamples=1))}setDirectionalLight(e){e.add(e.target),e.target.position.set(0,0,-1)}}io([u()],di.prototype,"type",2),io([u(ne)],di.prototype,"color",1),io([u()],di.prototype,"shadowNearPlane",1),io([u()],di.prototype,"shadowBias",1),io([u()],di.prototype,"shadowNormalBias",1),io([u()],di.prototype,"shadows",1),io([u()],di.prototype,"lightmapBakeType",2),io([u()],di.prototype,"intensity",1),io([u()],di.prototype,"shadowDistance",1),io([u()],di.prototype,"shadowResolution",1),new b(0,0,0);var EE=Object.defineProperty,th=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&EE(e,t,n),n};const Ty=w("debuglods"),AE=w("nolods");class gl{screenRelativeTransitionHeight;distance;renderers}th([u()],gl.prototype,"screenRelativeTransitionHeight"),th([u()],gl.prototype,"distance"),th([u(Ti)],gl.prototype,"renderers");class IE{model;get renderers(){return this.model.renderers}constructor(e){this.model=e}}class ih extends M{fadeMode=0;localReferencePoint=void 0;lodCount=0;size=0;animateCrossFading=!1;lodModels;_lods=[];_settings=[];_lodsHandler;start(){if(Ty&&console.log("LODGROUP",this.name,this.lodModels,this),!AE&&!this._lodsHandler&&this.gameObject&&this.lodModels&&Array.isArray(this.lodModels)){const e=[];for(const i of this.lodModels){const n=new IE(i);this._lods.push(n);for(const s of n.renderers)e.includes(s)||e.push(s)}this._lodsHandler=new Array;for(let i=0;i<e.length;i++){const n=new ZS;this._lodsHandler.push(n),this.gameObject.add(n)}const t=new O;t.name="Cull "+this.name;for(let i=0;i<e.length;i++){const n=e[i],s=this._lodsHandler[i],r=n.gameObject;Ty&&console.log(i,r.name);for(const a of this._lods){const l=a.model.distance;let c=null;if(a.renderers.includes(n)?c=r:c=t,c.type==="Group"){console.warn(`LODGroup ${this.name}: Group or MultiMaterial object's are not supported as LOD object: ${c.name}`);continue}Ty&&console.log("LEVEL",c.name,l),s.autoUpdate=!1,this.onAddLodLevel(s,c,a.model.distance)}}}}onAfterRender(){if(!this.gameObject||!this._lodsHandler)return;const e=this.context.mainCamera;if(e)for(const t of this._lodsHandler){t.update(e);const i=t.getCurrentLevel(),n=t.levels[i];t.layers.mask=n.object.layers.mask}}onAddLodLevel(e,t,i){if(t===this.gameObject){console.warn("LODGroup component must be on parent object and not mesh directly at the moment",t.name,t);return}e.addLevel(t,i*this._distanceFactor,.01);const n={lod:e,levelIndex:e.levels.length-1,distance:i};this._settings.push(n)}_distanceFactor=1;distanceFactor(e){if(e!==this._distanceFactor){this._distanceFactor=e;for(const t of this._settings){const i=t.lod.levels[t.levelIndex];i.distance=t.distance*e}}}}th([u(b)],ih.prototype,"localReferencePoint"),th([u(gl)],ih.prototype,"lodModels");var LE=Object.defineProperty,Dx=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&LE(e,t,n),n};const np=w("debugnestedgltf");class nh extends M{filePath;loaded=new ce;loadAssetInParent=!0;_isLoadingOrDoneLoading=!1;listenToProgress(e){this.filePath?.beginListenDownload(e)}preload(){return this.filePath?.preload()||null}async start(){if(this._isLoadingOrDoneLoading)return;np&&console.log(this,this.guid);const e=this.gameObject.parent;if(e&&this.filePath){this._isLoadingOrDoneLoading=!0;const t=new En;t.idProvider=new At(this.hash(this.guid)),t.parent=this.loadAssetInParent!==!1?e:this.gameObject,this.gameObject.updateMatrix();const i=this.gameObject.matrix;np&&console.log("Load nested:",this.filePath?.url??this.filePath,this.gameObject.position);const n=await this.filePath?.instantiate?.call(this.filePath,t);np&&console.log("Nested loaded:",this.filePath?.url??this.filePath,n),n&&this.loadAssetInParent!==!1&&(n.matrixAutoUpdate=!1,n.matrix.identity(),n.applyMatrix4(i),n.matrixAutoUpdate=!0,n.layers.disableAll(),n.layers.set(this.layer),this.loaded.invoke({component:this,instance:n,asset:this.filePath})),np&&console.log("Nested loading done:",this.filePath?.url??this.filePath,n)}}onDestroy(){this.filePath?.unload()}hash(e){let t=0;for(let i=0;i<e.length;i++)t=e.charCodeAt(i)+((t<<5)-t);return t}}Dx([u(ie)],nh.prototype,"filePath"),Dx([u(ce)],nh.prototype,"loaded");var jE=Object.defineProperty,Ey=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&jE(e,t,n),n};const DE=w("debugnet"),op=class M0 extends M{url=null;urlParameterName=null;localhost=null;awake(){DE&&console.log(this),this.context.connection.registerProvider(this)}getWebsocketUrl(){let e=this.url?M0.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){const i=w(this.urlParameterName);i&&typeof i=="string"&&(e=i)}if(!e)return null;const t=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(e);return t?.groups?t?.groups.socket_prefix?e:"wss://"+t?.groups.url:null}static GetUrl(e,t){let i=e;const n=M0.IsLocalNetwork()&&t;if(n&&(i=t),e?.startsWith("/")){const s=n?i:window.location.origin;s?.endsWith("/")&&e.startsWith("/")&&(e=e.substring(1)),i=s+e}return i}static IsLocalNetwork(e=window.location.hostname){return Wi(e)}};Ey([u()],op.prototype,"url"),Ey([u()],op.prototype,"urlParameterName"),Ey([u()],op.prototype,"localhost");let Ay=op;var BE=Object.defineProperty,sp=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&BE(e,t,n),n};class Wr extends M{referenceSpace;from;affectPosition=!1;affectRotation=!1;alignLookDirection=!1;levelLookDirection=!1;levelPosition=!1;positionOffset=new b(0,0,0);rotationOffset=new b(0,0,0);offset=new b(0,0,0);update(){if(!this.from)return;var e=Z(this.from),t=be(this.from);this.offset.copy(this.positionOffset);const i=this.offset.length();if(this.referenceSpace&&this.offset.transformDirection(this.referenceSpace.matrixWorld).multiplyScalar(i),e.add(this.offset),this.levelPosition&&this.referenceSpace){const a=new tr(this.gameObject.up,0),l=Z(this.referenceSpace);a.setFromNormalAndCoplanarPoint(this.gameObject.up,l);const c=new b(0,0,0);a.projectPoint(e,c),e.copy(c)}this.affectPosition&&mt(this.gameObject,e);const n=new nt(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),s=new U().setFromEuler(n);this.affectRotation&&pn(this.gameObject,t.multiply(s));const r=new b;this.from.getWorldDirection(r).multiplyScalar(50),this.levelLookDirection&&(r.y=0),this.alignLookDirection&&this.gameObject.lookAt(r)}}sp([u(x)],Wr.prototype,"referenceSpace"),sp([u(x)],Wr.prototype,"from"),sp([u(b)],Wr.prototype,"positionOffset"),sp([u(b)],Wr.prototype,"rotationOffset");var FE=Object.defineProperty,js=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&FE(e,t,n),n};class ui{time=0;value=0;inTangent=1/0;inWeight;outTangent=1/0;outWeight;weightedMode;constructor(e=0,t=0){this.time=e,this.value=t}}js([u()],ui.prototype,"time"),js([u()],ui.prototype,"value"),js([u()],ui.prototype,"inTangent"),js([u()],ui.prototype,"inWeight"),js([u()],ui.prototype,"outTangent"),js([u()],ui.prototype,"outWeight"),js([u()],ui.prototype,"weightedMode");const Bx=class Yh{static linearFromTo(e,t,i){const n=new Yh,s=new ui;s.time=0,s.value=e;const r=new ui;return r.time=i,r.value=t,n.keys.push(s,r),n}static constant(e){const t=new Yh,i=new ui;return i.time=0,i.value=e,t.keys.push(i),t}keys=[];clone(){const e=new Yh;return e.keys=this.keys?.map(t=>{const i=new ui;return i.time=t.time,i.value=t.value,i.inTangent=t.inTangent,i.inWeight=t.inWeight,i.outTangent=t.outTangent,i.outWeight=t.outWeight,i.weightedMode=t.weightedMode,i})||[],e}get duration(){return!this.keys||this.keys.length==0?0:this.keys[this.keys.length-1].time}evaluate(e){if(!this.keys||this.keys.length==0)return 0;if(this.keys.length===1)return this.keys[0].value;if(this.keys[0].time>=e)return this.keys[0].value;for(let t=0;t<this.keys.length;t++){const i=this.keys[t];if(i.time<=e)if(t+1<this.keys.length){const n=this.keys[t+1];if(n.time<e)continue;return!isFinite(i.outTangent)||!isFinite(n.inTangent)?i.value:Yh.interpolateValue(e,i,n)}else return i.value}return this.keys[this.keys.length-1].value}static interpolateValue(e,t,i){const n=t.time,s=t.value,r=t.outTangent,a=i.time,l=i.value,c=i.inTangent,h=a-n,d=h*h,p=d*h,g=((r+c)*h-2*(l-s))/p,f=(3*(l-s)-(c+2*r)*h)/d,m=r,y=s,_=e-n,v=_*_,P=v*_;return g*P+f*v+m*_+y}};js([u(ui)],Bx.prototype,"keys");let oh=Bx;var UE=Object.defineProperty,S=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&UE(e,t,n),n};const rp=w("debugparticles");var Fo=(o=>(o[o.Billboard=0]="Billboard",o[o.Stretch=1]="Stretch",o[o.HorizontalBillboard=2]="HorizontalBillboard",o[o.VerticalBillboard=3]="VerticalBillboard",o[o.Mesh=4]="Mesh",o))(Fo||{});class Vr{alphaKeys=[];colorKeys=[];get duration(){return 1}evaluate(e,t){let i,n=0,s=null,r=0;for(let a=0;a<this.alphaKeys.length;a++){const l=this.alphaKeys[a];(l.time<e||!i)&&(i=l,n=a)}for(let a=0;a<this.colorKeys.length;a++){const l=this.colorKeys[a];(l.time<e||!s)&&(s=l,r=a)}if(s)if(r+1<this.colorKeys.length){const a=this.colorKeys[r+1],l=D.remap(e,s.time,a.time,0,1);t.r=D.lerp(s.color.r,a.color.r,l),t.g=D.lerp(s.color.g,a.color.g,l),t.b=D.lerp(s.color.b,a.color.b,l)}else t.r=s.color.r,t.g=s.color.g,t.b=s.color.b;if(i)if(n+1<this.alphaKeys.length){const a=this.alphaKeys[n+1],l=D.remap(e,i.time,a.time,0,1);t.alpha=D.lerp(i.alpha,a.alpha,l)}else t.alpha=i.alpha;return t}}S([u()],Vr.prototype,"alphaKeys"),S([u()],Vr.prototype,"colorKeys");var sh=(o=>(o[o.Local=0]="Local",o[o.World=1]="World",o[o.Custom=2]="Custom",o))(sh||{}),ap=(o=>(o[o.Sphere=0]="Sphere",o[o.SphereShell=1]="SphereShell",o[o.Hemisphere=2]="Hemisphere",o[o.HemisphereShell=3]="HemisphereShell",o[o.Cone=4]="Cone",o[o.Box=5]="Box",o[o.Mesh=6]="Mesh",o[o.ConeShell=7]="ConeShell",o[o.ConeVolume=8]="ConeVolume",o[o.ConeVolumeShell=9]="ConeVolumeShell",o[o.Circle=10]="Circle",o[o.CircleEdge=11]="CircleEdge",o[o.SingleSidedEdge=12]="SingleSidedEdge",o[o.MeshRenderer=13]="MeshRenderer",o[o.SkinnedMeshRenderer=14]="SkinnedMeshRenderer",o[o.BoxShell=15]="BoxShell",o[o.BoxEdge=16]="BoxEdge",o[o.Donut=17]="Donut",o[o.Rectangle=18]="Rectangle",o[o.Sprite=19]="Sprite",o[o.SpriteRenderer=20]="SpriteRenderer",o))(ap||{});const Uo=class Kh{static constant(e){const t=new Kh;return t.setConstant(e),t}static betweenTwoConstants(e,t){const i=new Kh;return i.setMinMaxConstant(e,t),i}static curve(e,t=1){const i=new Kh;return i.setCurve(e,t),i}setConstant(e){this.mode=0,this.constant=e}setMinMaxConstant(e,t){this.mode=3,this.constantMin=e,this.constantMax=t}setCurve(e,t=1){this.mode=1,this.curve=e,this.curveMultiplier=t}mode="Constant";constant;constantMin;constantMax;curve;curveMin;curveMax;curveMultiplier;clone(){const e=new Kh;return e.mode=this.mode,e.constant=this.constant,e.constantMin=this.constantMin,e.constantMax=this.constantMax,e.curve=this.curve?.clone(),e.curveMin=this.curveMin?.clone(),e.curveMax=this.curveMax?.clone(),e.curveMultiplier=this.curveMultiplier,e}evaluate(e,t){const i=t===void 0?Math.random():t;switch(this.mode){case 0:case"Constant":return this.constant;case 1:case"Curve":return e=D.clamp01(e),this.curve.evaluate(e)*this.curveMultiplier;case 2:case"TwoCurves":const n=e*this.curveMin.duration,s=e*this.curveMax.duration;return D.lerp(this.curveMin.evaluate(n),this.curveMax.evaluate(s),i%1)*this.curveMultiplier;case 3:case"TwoConstants":return D.lerp(this.constantMin,this.constantMax,i%1);default:this.curveMax.evaluate(e)*this.curveMultiplier;break}return 0}getMax(){switch(this.mode){case 0:case"Constant":return this.constant;case 1:case"Curve":return this.getMaxFromCurve(this.curve)*this.curveMultiplier;case 2:case"TwoCurves":return Math.max(this.getMaxFromCurve(this.curveMin),this.getMaxFromCurve(this.curveMax))*this.curveMultiplier;case 3:case"TwoConstants":return Math.max(this.constantMin,this.constantMax);default:return 0}}getMaxFromCurve(e){if(!e)return 0;let t=Number.MIN_VALUE;for(let i=0;i<e.keys.length;i++){const n=e.keys[i];n.value>t&&(t=n.value)}return t}};S([u()],Uo.prototype,"mode"),S([u()],Uo.prototype,"constant"),S([u()],Uo.prototype,"constantMin"),S([u()],Uo.prototype,"constantMax"),S([u(oh)],Uo.prototype,"curve"),S([u(oh)],Uo.prototype,"curveMin"),S([u(oh)],Uo.prototype,"curveMax"),S([u()],Uo.prototype,"curveMultiplier");let Q=Uo;const Ds=class Tt{static constant(e){const t=new Tt;return t.constant(e),t}static betweenTwoColors(e,t){const i=new Tt;return i.betweenTwoColors(e,t),i}constant(e){return this.mode=0,this.color=e,this}betweenTwoColors(e,t){return this.mode=2,this.colorMin=e,this.colorMax=t,this}mode=0;color;colorMin;colorMax;gradient;gradientMin;gradientMax;static _temp=new se(0,0,0,1);static _temp2=new se(0,0,0,1);evaluate(e,t){const i=t===void 0?Math.random():t;switch(this.mode){case 0:case"Color":return this.color;case 1:case"Gradient":return this.gradient.evaluate(e,Tt._temp),Tt._temp;case 2:case"TwoColors":return Tt._temp.lerpColors(this.colorMin,this.colorMax,i);case 3:case"TwoGradients":return this.gradientMin.evaluate(e,Tt._temp),this.gradientMax.evaluate(e,Tt._temp2),Tt._temp.lerp(Tt._temp2,i);case 4:case"RandomColor":const n=Math.random();return this.gradientMin.evaluate(e,Tt._temp),this.gradientMax.evaluate(e,Tt._temp2),Tt._temp.lerp(Tt._temp2,n)}return Tt._temp.set(16777215),Tt._temp.alpha=1,Tt._temp}};S([u()],Ds.prototype,"mode"),S([u(se)],Ds.prototype,"color"),S([u(se)],Ds.prototype,"colorMin"),S([u(se)],Ds.prototype,"colorMax"),S([u(Vr)],Ds.prototype,"gradient"),S([u(Vr)],Ds.prototype,"gradientMin"),S([u(Vr)],Ds.prototype,"gradientMax");let $r=Ds;var Iy=(o=>(o[o.Hierarchy=0]="Hierarchy",o[o.Local=1]="Local",o[o.Shape=2]="Shape",o))(Iy||{});class Bt{cullingMode;duration;emitterVelocityMode;flipRotation;gravityModifier;gravityModifierMultiplier;loop;maxParticles;playOnAwake;prewarm;ringBufferLoopRange;ringBufferMode;scalingMode;simulationSpace;simulationSpeed;startColor;startDelay;startDelayMultiplier;startLifetime;startLifetimeMultiplier;startRotation;startRotationMultiplier;startRotation3D;startRotationX;startRotationXMultiplier;startRotationY;startRotationYMultiplier;startRotationZ;startRotationZMultiplier;startSize;startSize3D;startSizeMultiplier;startSizeX;startSizeXMultiplier;startSizeY;startSizeYMultiplier;startSizeZ;startSizeZMultiplier;startSpeed;startSpeedMultiplier;stopAction;useUnscaledTime}S([u(Q)],Bt.prototype,"gravityModifier"),S([u($r)],Bt.prototype,"startColor"),S([u(Q)],Bt.prototype,"startDelay"),S([u(Q)],Bt.prototype,"startLifetime"),S([u(Q)],Bt.prototype,"startRotation"),S([u(Q)],Bt.prototype,"startRotationX"),S([u(Q)],Bt.prototype,"startRotationY"),S([u(Q)],Bt.prototype,"startRotationZ"),S([u(Q)],Bt.prototype,"startSize"),S([u(Q)],Bt.prototype,"startSizeX"),S([u(Q)],Bt.prototype,"startSizeY"),S([u(Q)],Bt.prototype,"startSizeZ"),S([u(Q)],Bt.prototype,"startSpeed");class lp{cycleCount;maxCount;minCount;probability;repeatInterval;time;count;_performed=0;reset(){this._performed=0}run(e){if(e<=this.time)return 0;let t=0;if(this.cycleCount===0||this._performed<this.cycleCount){const i=this.time+this.repeatInterval*this._performed;if(e>=i&&(this._performed+=1,Math.random()<this.probability))switch(this.count.mode){case 0:t=this.count.constant;break;case 3:t=D.lerp(this.count.constantMin,this.count.constantMax,Math.random());break;case 1:t=this.count.curve.evaluate(Math.random());break;case 2:const n=Math.random();t=D.lerp(this.count.curveMin.evaluate(n),this.count.curveMax.evaluate(n),Math.random());break}}return t}}class zo{enabled;get burstCount(){return this.bursts?.length??0}bursts;rateOverTime;rateOverTimeMultiplier;rateOverDistance;rateOverDistanceMultiplier;system;reset(){this.bursts?.forEach(e=>e.reset())}getBurst(){let e=0;if(this.burstCount>0)for(let t=0;t<this.burstCount;t++){const i=this.bursts[t];this.system.main.loop&&i.time>=this.system.time&&i.reset(),e+=Math.round(i.run(this.system.time))}return e}}S([u()],zo.prototype,"enabled"),S([u()],zo.prototype,"bursts"),S([u(Q)],zo.prototype,"rateOverTime"),S([u()],zo.prototype,"rateOverTimeMultiplier"),S([u(Q)],zo.prototype,"rateOverDistance"),S([u()],zo.prototype,"rateOverDistanceMultiplier");class cp{enabled;color}S([u($r)],cp.prototype,"color");class Hr{enabled;separateAxes;size;sizeMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;_time=0;_temp=new b;evaluate(e,t,i){if(t||(t=this._temp),!this.enabled)return t.x=t.y=t.z=1,t;if(this.separateAxes)t.x=this.x.evaluate(e,i)*this.xMultiplier,t.y=this.y.evaluate(e,i)*this.yMultiplier,t.z=this.z.evaluate(e,i)*this.zMultiplier;else{const n=this.size.evaluate(e,i)*this.sizeMultiplier;t.x=n}return t}}S([u(Q)],Hr.prototype,"size"),S([u(Q)],Hr.prototype,"x"),S([u(Q)],Hr.prototype,"y"),S([u(Q)],Hr.prototype,"z");const Ze=class Zh{get type(){return ap[this.shapeType]}initialize(e){this.onInitialize(e),e.position.x=this._vector.x,e.position.y=this._vector.y,e.position.z=this._vector.z}toJSON(){return this}clone(){return new Zh}shapeType=5;enabled=!0;alignToDirection=!1;angle=0;arc=360;arcSpread;arcSpeedMultiplier;arcMode;boxThickness;position;rotation;_rotation=new nt;scale;radius;radiusThickness;sphericalDirectionAmount;randomDirectionAmount;randomPositionAmount;meshShapeType;meshRenderer;_meshObj;_meshGeometry;setMesh(e){this.meshRenderer=e,e?(this._meshObj=e.sharedMeshes[Math.floor(Math.random()*e.sharedMeshes.length)],this._meshGeometry=this._meshObj.geometry):(this._meshObj=void 0,this._meshGeometry=void 0)}system;_space;_worldSpaceMatrix=new ee;_worldSpaceMatrixInverse=new ee;constructor(){rp&&console.log(this)}update(e,t){}onUpdate(e,t,i,n){this.system=e,this._space=i,i===1&&(this._worldSpaceMatrix.copy(n.matrixWorld),this._worldSpaceMatrix.elements[0]=1,this._worldSpaceMatrix.elements[5]=1,this._worldSpaceMatrix.elements[10]=1,this._worldSpaceMatrixInverse.copy(this._worldSpaceMatrix).invert())}applyRotation(e){const t=this.rotation.x!==0||this.rotation.y!==0||this.rotation.z!==0;return t&&(this._rotation.x=D.toRadians(this.rotation.x),this._rotation.y=D.toRadians(this.rotation.y),this._rotation.z=D.toRadians(this.rotation.z),this._rotation.order="ZYX",e.applyEuler(this._rotation)),t}_vector=new b(0,0,0);_temp=new b(0,0,0);_triangle=new JS;onInitialize(e){this._vector.set(0,0,0),e.mesh=void 0,e.mesh_geometry=void 0;const t=this._temp.copy(this.position),i=this._space===1;i&&t.applyQuaternion(this.system.worldQuaternion);let n=this.radius;if(i&&(n*=this.system.worldScale.x),this.enabled){switch(this.shapeType){case 5:rp&&F.DrawWireBox(this.position,this.scale,14540253,1),this._vector.x=Math.random()*this.scale.x-this.scale.x/2,this._vector.y=Math.random()*this.scale.y-this.scale.y/2,this._vector.z=Math.random()*this.scale.z-this.scale.z/2,this._vector.add(t);break;case 4:this.randomConePoint(this.position,this.angle,n,this.radiusThickness,this.arc,this.arcMode,this._vector);break;case 0:this.randomSpherePoint(this.position,n,this.radiusThickness,this.arc,this._vector);break;case 10:this.randomCirclePoint(this.position,n,this.radiusThickness,this.arc,this._vector);break;case 13:const s=this.meshRenderer;s?.destroyed==!1&&this.setMesh(s);const r=e.mesh=this._meshObj,a=e.mesh_geometry=this._meshGeometry;if(r&&a)switch(this.meshShapeType){case 0:{const l=a.getAttribute("position"),c=Math.floor(Math.random()*l.count);this._vector.fromBufferAttribute(l,c),this._vector.applyMatrix4(r.matrixWorld),e.mesh_normal=c}break;case 1:break;case 2:{const l=a.index;if(l){let c=Math.random(),h=Math.random();c+h>1&&(c=1-c,h=1-h);const d=Math.floor(Math.random()*(l.count/3));let p=d*3,g=d*3+1,f=d*3+2;p=l.getX(p),g=l.getX(g),f=l.getX(f);const m=a.getAttribute("position");this._triangle.a.fromBufferAttribute(m,p),this._triangle.b.fromBufferAttribute(m,g),this._triangle.c.fromBufferAttribute(m,f),this._vector.set(0,0,0).addScaledVector(this._triangle.a,c).addScaledVector(this._triangle.b,h).addScaledVector(this._triangle.c,1-(c+h)),this._vector.applyMatrix4(r.matrixWorld),e.mesh_normal=d}}break}break;default:this._vector.set(0,0,0),E()&&!globalThis.__particlesystem_shapetype_unsupported&&(console.warn("ParticleSystem ShapeType is not supported:",ap[this.shapeType]),globalThis.__particlesystem_shapetype_unsupported=!0);break}this.randomizePosition(this._vector,this.randomPositionAmount)}this.applyRotation(this._vector),i&&(this._vector.applyQuaternion(this.system.worldQuaternion),this._vector.add(this.system.worldPos)),rp&&F.DrawSphere(this._vector,.03,16711680,.5,!0)}_dir=new b;getDirection(e,t){if(!this.enabled)return this._dir.set(0,0,1),this._dir;switch(this.shapeType){case 5:this._dir.set(0,0,1);break;case 4:this._dir.set(0,0,1);break;case 10:case 0:const i=t.x,n=t.y,s=t.z;this._dir.set(i,n,s),this.system?.worldspace?this._dir.sub(this.system.worldPos):this._dir.sub(this.position);break;case 13:const r=e.mesh,a=e.mesh_geometry;if(r&&a)switch(this.meshShapeType){case 0:{const l=a.getAttribute("normal"),c=e.mesh_normal;this._dir.fromBufferAttribute(l,c)}break;case 1:break;case 2:{const l=a.index;if(l){const c=e.mesh_normal,h=l.getX(c*3),d=l.getX(c*3+1),p=l.getX(c*3+2),g=a.getAttribute("position"),f=$(),m=$(),y=$();f.fromBufferAttribute(g,h),m.fromBufferAttribute(g,d),y.fromBufferAttribute(g,p),f.sub(m),y.sub(m),f.cross(y),this._dir.copy(f).multiplyScalar(-1);const _=be(r);this._dir.applyQuaternion(_)}}break}break;default:this._dir.set(0,0,1);break}return this._space===1&&this._dir.applyQuaternion(this.system.worldQuaternion),this.applyRotation(this._dir),this._dir.normalize(),this.spherizeDirection(this._dir,this.sphericalDirectionAmount),this.randomizeDirection(this._dir,this.randomDirectionAmount),rp&&(F.DrawSphere(t,.01,8925952,.5,!0),F.DrawDirection(t,this._dir,8925952,.5,!0)),this._dir}static _randomQuat=new U;static _tempVec=new b;randomizePosition(e,t){if(t<=0)return;const i=Zh._tempVec;i.set(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1),i.x*=t*this.scale.x,i.y*=t*this.scale.y,i.z*=t*this.scale.z,e.add(i)}randomizeDirection(e,t){if(t===0)return;const i=Zh._randomQuat,n=Zh._tempVec;n.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).normalize(),i.setFromAxisAngle(n,t*Math.random()*Math.PI),e.applyQuaternion(i)}spherizeDirection(e,t){if(t===0)return;const i=Math.random()*Math.PI*2,n=Math.acos(1-Math.random()*2),s=Math.sin(n)*Math.cos(i),r=Math.sin(n)*Math.sin(i),a=Math.cos(n),l=new b(s,r,a);e.lerp(l,t)}randomSpherePoint(e,t,i,n,s){const r=Math.random(),a=Math.random(),l=2*Math.PI*r*(n/360),c=Math.acos(2*a-1),h=D.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,d=e.x+this.scale.x*(-h*Math.sin(c)*Math.cos(l)),p=e.y+this.scale.y*(h*Math.sin(c)*Math.sin(l)),g=e.z+this.scale.z*(h*Math.cos(c));s.x=d,s.y=p,s.z=g}randomCirclePoint(e,t,i,n,s){const r=Math.random(),a=2*Math.PI*r*(n/360),l=D.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,c=e.x+this.scale.x*l*Math.cos(a),h=e.y+this.scale.y*l*Math.sin(a),d=e.z;s.x=c,s.y=h,s.z=d}_loopTime=0;_loopDirection=1;randomConePoint(e,t,i,n,s,r,a){let l=0,c=0;switch(r){case 0:l=Math.random(),c=Math.random();break;case 2:this._loopTime>1&&(this._loopDirection=-1),this._loopTime<0&&(this._loopDirection=1);case 1:l=.5,c=Math.random(),this._loopTime+=this.system.deltaTime*this._loopDirection;break}let h=2*Math.PI*l*(s/360);switch(r){case 2:case 1:h+=Math.PI+.5,h+=this._loopTime*Math.PI*2,h%=D.toRadians(s);break}const d=Math.acos(2*c-1),p=D.lerp(1,1-Math.pow(1-Math.random(),Math.PI),n)*i,g=e.x+-p*Math.sin(d)*Math.cos(h),f=e.y+p*Math.sin(d)*Math.sin(h),m=e.z;a.x=g*this.scale.x,a.y=f*this.scale.y,a.z=m*this.scale.z}};S([u()],Ze.prototype,"shapeType"),S([u()],Ze.prototype,"enabled"),S([u()],Ze.prototype,"alignToDirection"),S([u()],Ze.prototype,"angle"),S([u()],Ze.prototype,"arc"),S([u()],Ze.prototype,"arcSpread"),S([u()],Ze.prototype,"arcSpeedMultiplier"),S([u()],Ze.prototype,"arcMode"),S([u(b)],Ze.prototype,"boxThickness"),S([u(b)],Ze.prototype,"position"),S([u(b)],Ze.prototype,"rotation"),S([u(b)],Ze.prototype,"scale"),S([u()],Ze.prototype,"radius"),S([u()],Ze.prototype,"radiusThickness"),S([u()],Ze.prototype,"sphericalDirectionAmount"),S([u()],Ze.prototype,"randomDirectionAmount"),S([u()],Ze.prototype,"randomPositionAmount"),S([u()],Ze.prototype,"meshShapeType"),S([u(Bc)],Ze.prototype,"meshRenderer");let Ly=Ze;class _e{damping;enabled;frequency;octaveCount;octaveMultiplier;octaveScale;positionAmount;quality;remap;remapEnabled;remapMultiplier;remapX;remapXMultiplier;remapY;remapYMultiplier;remapZ;remapZMultiplier;scrollSpeedMultiplier;separateAxes;strengthMultiplier;strengthX;strengthXMultiplier;strengthY;strengthYMultiplier;strengthZ;strengthZMultiplier;_noise;_time=0;update(e){this._time+=e.time.deltaTime*this.scrollSpeedMultiplier}_temp=new b;apply(e,t,i,n,s,r){if(!this.enabled)return;this._noise||(this._noise=FC(()=>0));const a=this._temp.set(t.x,t.y,t.z).multiplyScalar(this.frequency),l=this._noise(a.x,a.y,a.z,this._time),c=this._noise(a.x,a.y,a.z,this._time+1e3*this.frequency),h=this._noise(a.x,a.y,a.z,this._time+2e3*this.frequency);this._temp.set(l,c,h).normalize();const d=s/r;let p=this.positionAmount.evaluate(d);this.separateAxes?(this._temp.x*=p*this.strengthXMultiplier,this._temp.y*=p*this.strengthYMultiplier,this._temp.z*=p*this.strengthZMultiplier):(this.strengthX&&(p*=this.strengthX.evaluate(d)*1.5),this._temp.multiplyScalar(p)),i.x+=this._temp.x,i.y+=this._temp.y,i.z+=this._temp.z}}S([u()],_e.prototype,"damping"),S([u()],_e.prototype,"enabled"),S([u()],_e.prototype,"frequency"),S([u()],_e.prototype,"octaveCount"),S([u()],_e.prototype,"octaveMultiplier"),S([u()],_e.prototype,"octaveScale"),S([u(Q)],_e.prototype,"positionAmount"),S([u()],_e.prototype,"quality"),S([u(Q)],_e.prototype,"remap"),S([u()],_e.prototype,"remapEnabled"),S([u()],_e.prototype,"remapMultiplier"),S([u(Q)],_e.prototype,"remapX"),S([u()],_e.prototype,"remapXMultiplier"),S([u(Q)],_e.prototype,"remapY"),S([u()],_e.prototype,"remapYMultiplier"),S([u(Q)],_e.prototype,"remapZ"),S([u()],_e.prototype,"remapZMultiplier"),S([u()],_e.prototype,"scrollSpeedMultiplier"),S([u()],_e.prototype,"separateAxes"),S([u()],_e.prototype,"strengthMultiplier"),S([u(Q)],_e.prototype,"strengthX"),S([u()],_e.prototype,"strengthXMultiplier"),S([u(Q)],_e.prototype,"strengthY"),S([u()],_e.prototype,"strengthYMultiplier"),S([u(Q)],_e.prototype,"strengthZ"),S([u()],_e.prototype,"strengthZMultiplier");class Fe{enabled;attachRibbonToTransform=!1;colorOverLifetime;colorOverTrail;dieWithParticles=!0;inheritParticleColor=!0;lifetime;lifetimeMultiplier;minVertexDistance=.2;mode=0;ratio=1;ribbonCount=1;shadowBias=0;sizeAffectsLifetime=!1;sizeAffectsWidth=!1;splitSubEmitterRibbons=!1;textureMode=0;widthOverTrail;widthOverTrailMultiplier;worldSpace=!1;getWidth(e,t,i,n){const s=this.widthOverTrail.evaluate(i,n);return e*=s,e}getColor(e,t,i){const n=this.colorOverTrail.evaluate(i),s=this.colorOverLifetime.evaluate(t);e.x*=n.r*s.r,e.y*=n.g*s.g,e.z*=n.b*s.b,"alpha"in n&&"alpha"in s&&(e.w*=n.alpha*s.alpha)}}S([u()],Fe.prototype,"enabled"),S([u()],Fe.prototype,"attachRibbonToTransform"),S([u($r)],Fe.prototype,"colorOverLifetime"),S([u($r)],Fe.prototype,"colorOverTrail"),S([u()],Fe.prototype,"dieWithParticles"),S([u()],Fe.prototype,"inheritParticleColor"),S([u(Q)],Fe.prototype,"lifetime"),S([u()],Fe.prototype,"lifetimeMultiplier"),S([u()],Fe.prototype,"minVertexDistance"),S([u()],Fe.prototype,"mode"),S([u()],Fe.prototype,"ratio"),S([u()],Fe.prototype,"ribbonCount"),S([u()],Fe.prototype,"shadowBias"),S([u()],Fe.prototype,"sizeAffectsLifetime"),S([u()],Fe.prototype,"sizeAffectsWidth"),S([u()],Fe.prototype,"splitSubEmitterRibbons"),S([u()],Fe.prototype,"textureMode"),S([u(Q)],Fe.prototype,"widthOverTrail"),S([u()],Fe.prototype,"widthOverTrailMultiplier"),S([u()],Fe.prototype,"worldSpace");class We{enabled;space=0;orbitalX;orbitalY;orbitalZ;orbitalXMultiplier;orbitalYMultiplier;orbitalZMultiplier;orbitalOffsetX;orbitalOffsetY;orbitalOffsetZ;speedModifier;speedModifierMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;_system;update(e){this._system=e}_temp=new b;_temp2=new b;_temp3=new b;_hasOrbital=!1;_index=0;_orbitalMatrix=new ee;init(e){this._index==0&&(e.debug=!0),this._index+=1,e.orbitx=this.orbitalX.evaluate(Math.random()),e.orbity=this.orbitalY.evaluate(Math.random()),e.orbitz=this.orbitalZ.evaluate(Math.random()),this._hasOrbital=e.orbitx!=0||e.orbity!=0||e.orbitz!=0}apply(e,t,i,n,s,r,a){if(!this.enabled)return;const l=r/a,c=this.speedModifier.evaluate(l)*this.speedModifierMultiplier,h=this.x.evaluate(l),d=this.y.evaluate(l),p=this.z.evaluate(l);if(this._temp.set(-h,d,p),this._system&&this._system.main.simulationSpace===1&&this._temp.applyQuaternion(this._system.worldQuaternion),this._hasOrbital&&this._system?.worldPos){const g=this._temp2.set(i.x,i.y,i.z),f=this.orbitalXMultiplier,m=this.orbitalYMultiplier,y=this.orbitalZMultiplier,_=c*Math.PI*2*10,v=Math.cos(_*f),P=Math.sin(_*f),R=Math.cos(_*m),k=Math.sin(_*m),A=Math.cos(_*y),L=Math.sin(_*y),N=g.x*(R*A)+g.y*(R*L)+g.z*-k,j=g.x*(P*k*A-v*L)+g.y*(P*k*L+v*A)+g.z*(P*R),q=g.x*(v*k*A+P*L)+g.y*(v*k*L-P*A)+g.z*(v*R),Y=this._temp3.set(g.x-N,g.y-j,g.z-q);Y.normalize(),Y.multiplyScalar(.2/s*Math.max(this.orbitalXMultiplier,this.orbitalYMultiplier,this.orbitalZMultiplier)),n.x+=Y.x,n.y+=Y.y,n.z+=Y.z}n.x+=this._temp.x,n.y+=this._temp.y,n.z+=this._temp.z,n.x*=c,n.y*=c,n.z*=c}}S([u()],We.prototype,"enabled"),S([u()],We.prototype,"space"),S([u(Q)],We.prototype,"orbitalX"),S([u(Q)],We.prototype,"orbitalY"),S([u(Q)],We.prototype,"orbitalZ"),S([u()],We.prototype,"orbitalXMultiplier"),S([u()],We.prototype,"orbitalYMultiplier"),S([u()],We.prototype,"orbitalZMultiplier"),S([u()],We.prototype,"orbitalOffsetX"),S([u()],We.prototype,"orbitalOffsetY"),S([u()],We.prototype,"orbitalOffsetZ"),S([u(Q)],We.prototype,"speedModifier"),S([u()],We.prototype,"speedModifierMultiplier"),S([u(Q)],We.prototype,"x"),S([u()],We.prototype,"xMultiplier"),S([u(Q)],We.prototype,"y"),S([u()],We.prototype,"yMultiplier"),S([u(Q)],We.prototype,"z"),S([u()],We.prototype,"zMultiplier");class Ft{animation;enabled;cycleCount;frameOverTime;frameOverTimeMultiplier;numTilesX;numTilesY;startFrame;startFrameMultiplier;rowMode;rowIndex;spriteCount;timeMode;sampleOnceAtStart(){if(this.timeMode===0)switch(this.frameOverTime.mode){case 0:case 3:case 2:case 1:return!0}return!1}getStartIndex(){return this.sampleOnceAtStart()?Math.random()*(this.numTilesX*this.numTilesY):0}evaluate(e){if(!this.sampleOnceAtStart())return this.getIndex(e)}getIndex(e){const t=this.numTilesX*this.numTilesY;e=e*this.cycleCount;let i=this.frameOverTime.evaluate(e%1);return i*=this.frameOverTimeMultiplier,i*=t,i=i%t,i=Math.floor(i),i}}S([u()],Ft.prototype,"animation"),S([u()],Ft.prototype,"enabled"),S([u()],Ft.prototype,"cycleCount"),S([u(Q)],Ft.prototype,"frameOverTime"),S([u()],Ft.prototype,"frameOverTimeMultiplier"),S([u()],Ft.prototype,"numTilesX"),S([u()],Ft.prototype,"numTilesY"),S([u(Q)],Ft.prototype,"startFrame"),S([u()],Ft.prototype,"startFrameMultiplier"),S([u()],Ft.prototype,"rowMode"),S([u()],Ft.prototype,"rowIndex"),S([u()],Ft.prototype,"spriteCount"),S([u()],Ft.prototype,"timeMode");class Pn{enabled;separateAxes;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t){return this.enabled?this.separateAxes?0:this.z.evaluate(e,t)*-1:0}}S([u()],Pn.prototype,"enabled"),S([u()],Pn.prototype,"separateAxes"),S([u(Q)],Pn.prototype,"x"),S([u()],Pn.prototype,"xMultiplier"),S([u(Q)],Pn.prototype,"y"),S([u()],Pn.prototype,"yMultiplier"),S([u(Q)],Pn.prototype,"z"),S([u()],Pn.prototype,"zMultiplier");class tn{enabled;range;separateAxes;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t){if(!this.enabled)return 0;if(!this.separateAxes){const i=D.lerp(this.range.x,this.range.y,t);return this.z.evaluate(i)*-1}return 0}}S([u()],tn.prototype,"enabled"),S([u()],tn.prototype,"range"),S([u()],tn.prototype,"separateAxes"),S([u(Q)],tn.prototype,"x"),S([u()],tn.prototype,"xMultiplier"),S([u(Q)],tn.prototype,"y"),S([u()],tn.prototype,"yMultiplier"),S([u(Q)],tn.prototype,"z"),S([u()],tn.prototype,"zMultiplier");class lt{enabled;dampen;drag;dragMultiplier;limit;limitMultiplier;separateAxes;limitX;limitXMultiplier;limitY;limitYMultiplier;limitZ;limitZMultiplier;multiplyDragByParticleSize=!1;multiplyDragByParticleVelocity=!1;space;_temp=new b;_temp2=new b;apply(e,t,i,n,s,r,a){if(this.enabled){const l=this.limit.evaluate(s)*this.limitMultiplier;if(t.length()>l){this._temp.copy(t).normalize().multiplyScalar(l);const c=this.dampen*.5;t.x=D.lerp(t.x,this._temp.x,c),t.y=D.lerp(t.y,this._temp.y,c),t.z=D.lerp(t.z,this._temp.z,c),i.x=D.lerp(i.x,this._temp.x,c),i.y=D.lerp(i.y,this._temp.y,c),i.z=D.lerp(i.z,this._temp.z,c)}}}}S([u()],lt.prototype,"enabled"),S([u()],lt.prototype,"dampen"),S([u(Q)],lt.prototype,"drag"),S([u()],lt.prototype,"dragMultiplier"),S([u(Q)],lt.prototype,"limit"),S([u()],lt.prototype,"limitMultiplier"),S([u()],lt.prototype,"separateAxes"),S([u(Q)],lt.prototype,"limitX"),S([u()],lt.prototype,"limitXMultiplier"),S([u(Q)],lt.prototype,"limitY"),S([u()],lt.prototype,"limitYMultiplier"),S([u(Q)],lt.prototype,"limitZ"),S([u()],lt.prototype,"limitZMultiplier"),S([u()],lt.prototype,"multiplyDragByParticleSize"),S([u()],lt.prototype,"multiplyDragByParticleVelocity"),S([u()],lt.prototype,"space");const rh=class q1{enabled;curve;curveMultiplier;mode;clone(){const e=new q1;return e.enabled=this.enabled,e.curve=this.curve?.clone(),e.curveMultiplier=this.curveMultiplier,e.mode=this.mode,e}system;get _lastWorldPosition(){return this.system._iv_lastWorldPosition||(this.system._iv_lastWorldPosition=new b),this.system._iv_lastWorldPosition}get _velocity(){return this.system._iv_velocity||(this.system._iv_velocity=new b),this.system._iv_velocity}_temp=new b;_firstUpdate=!0;awake(e){this.system=e,this.reset()}reset(){this._firstUpdate=!0}update(e){this.enabled&&this.system.worldspace!==!1&&(this._firstUpdate?(this._firstUpdate=!1,this._velocity.set(0,0,0),this._lastWorldPosition.copy(this.system.worldPos)):this._lastWorldPosition&&(this._velocity.copy(this.system.worldPos).sub(this._lastWorldPosition).multiplyScalar(1/this.system.deltaTime),this._lastWorldPosition.copy(this.system.worldPos)))}applyInitial(e){if(this.enabled&&this.system.worldspace!==!1&&this.mode===0){const t=this.curve.evaluate(Math.random(),Math.random());this._temp.copy(this._velocity).multiplyScalar(t),e.x+=this._temp.x,e.y+=this._temp.y,e.z+=this._temp.z}}_frames=0;applyCurrent(e,t,i){if(this.enabled&&this.system&&this.system.worldspace!==!1&&this.mode===1){const n=this.curve.evaluate(t,i);this._temp.copy(this._velocity).multiplyScalar(n),e.x+=this._temp.x,e.y+=this._temp.y,e.z+=this._temp.z}}};S([u()],rh.prototype,"enabled"),S([u(Q)],rh.prototype,"curve"),S([u()],rh.prototype,"curveMultiplier"),S([u()],rh.prototype,"mode");let jy=rh;class pi{enabled;range;separateAxes;size;sizeMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t,i,n){const s=e.length(),r=D.remap(s,this.range.x,this.range.y,0,1),a=this.size.evaluate(r,i);return n.x*=a,n.y*=a,n.z*=a,n}}S([u()],pi.prototype,"enabled"),S([u(J)],pi.prototype,"range"),S([u()],pi.prototype,"separateAxes"),S([u(Q)],pi.prototype,"size"),S([u()],pi.prototype,"sizeMultiplier"),S([u(Q)],pi.prototype,"x"),S([u()],pi.prototype,"xMultiplier"),S([u(Q)],pi.prototype,"y"),S([u()],pi.prototype,"yMultiplier"),S([u(Q)],pi.prototype,"z"),S([u()],pi.prototype,"zMultiplier");class fl{enabled;range;color;evaluate(e,t,i){const n=e.length(),s=D.remap(n,this.range.x,this.range.y,0,1),r=this.color.evaluate(s,t);i.x*=r.r,i.y*=r.g,i.z*=r.b,"alpha"in r&&(i.w*=r.alpha)}}S([u()],fl.prototype,"enabled"),S([u(J)],fl.prototype,"range"),S([u($r)],fl.prototype,"color"),new b(1,1,1),new b(0,0,1);class Dy{constructor(e,t,i,n){this.system=e,this.particleSystem=t,this.subSystem=i,this.subParticleSystem=n,this.subParticleSystem&&this.subParticleSystem&&(this.subParticleSystem.onlyUsedByOther=!0);const s=1e3;this._circularBuffer=new wi(()=>new ym,s)}type="NeedleParticleSubEmitter";emitterType;emitterProbability;q_=new U;v_=new b;v2_=new b;_emitterMatrix=new ym;_circularBuffer;clone(){throw new Error("Method not implemented.")}initialize(e){e.emissionState={burstIndex:0,burstWaveIndex:0,time:0,waitEmiting:0},this._emitterMatrix.copy(this.subSystem.matrixWorld).invert().premultiply(this.system.matrixWorld),this._emitterMatrix.setPosition(0,0,0),this.emitterType===By.Birth&&this.run(e)}update(e,t){this.run(e)}frameUpdate(e){}toJSON(){}reset(){}run(e){if(this.subSystem.currentParticles>=this.subSystem.main.maxParticles||!this.subParticleSystem||!e.emissionState||this.emitterProbability&&Math.random()>this.emitterProbability)return;const t=this.system.deltaTime;if(this.emitterType===By.Death){let n=e.life;if(e[yl]!==void 0&&(n=e[yl]),!(e.age+t*1.2>=n))return;const s=this.subSystem.main.maxParticles-this.subSystem.currentParticles;e.emissionState.waitEmiting=s}const i=new ym;i.set(1,0,0,e.position.x,0,1,0,e.position.y,0,0,1,e.position.z,0,0,0,1),this.particleSystem.worldSpace||i.multiplyMatrices(this._emitterMatrix,i),this.subParticleSystem.emit(t,e.emissionState,i)}}var zE=Object.defineProperty,Ue=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&zE(e,t,n),n};const Bs=w("debugparticles"),NE=w("noprogressive"),WE=w("debugprogressive");var By=(o=>(o[o.Birth=0]="Birth",o[o.Collision=1]="Collision",o[o.Death=2]="Death",o[o.Trigger=3]="Trigger",o[o.Manual=4]="Manual",o))(By||{});class nn extends M{renderMode;particleMaterial;trailMaterial;particleMesh;maxParticleSize;minParticleSize;velocityScale;cameraVelocityScale;lengthScale;start(){if(this.maxParticleSize!==.5&&this.minParticleSize!==0&&E()){const e=`ParticleSystem "${this.name}" has non-default min/max particle size. This may not render correctly. Please set min size to 0 and the max size to 0.5 and use the "StartSize" setting instead`;console.warn(e)}}get transparent(){return this.particleMaterial?.transparent??!1}getMaterial(e=!1){let t=e===!0&&this.trailMaterial?this.trailMaterial:this.particleMaterial;if(t){if(t.type==="MeshStandardMaterial"){Bs&&console.debug("ParticleSystemRenderer.getMaterial: MeshStandardMaterial detected, converting to MeshBasicMaterial. See https://github.com/Alchemist0823/three.quarks/issues/101"),"map"in t&&t.map&&(t.map.colorSpace=po,t.map.premultiplyAlpha=!1);const i=new xe;i.copy(t),e?this.trailMaterial=i:this.particleMaterial=i}t.map&&(t.map.colorSpace=po,t.map.premultiplyAlpha=!1),e&&t.side===as&&(t=t.clone(),t.side=ud,e?this.trailMaterial=t:this.particleMaterial=t)}return t&&!NE&&t._didRequestTextureLOD===void 0&&(t._didRequestTextureLOD=0,WE&&console.log("Load material LOD",t.name),Ve.assignTextureLOD(t,0)),t}getMesh(e){let t=null;if(!t&&(this.particleMesh instanceof H&&(t=this.particleMesh.geometry),t===null)){t=new In(1,1);const i=t.attributes.uv;for(let n=0;n<i.count;n++)i.setX(n,1-i.getX(n))}return new H(t,this.getMaterial())}}Ue([u()],nn.prototype,"renderMode"),Ue([u(ve)],nn.prototype,"particleMaterial"),Ue([u(ve)],nn.prototype,"trailMaterial"),Ue([u()],nn.prototype,"maxParticleSize"),Ue([u()],nn.prototype,"minParticleSize"),Ue([u()],nn.prototype,"velocityScale"),Ue([u()],nn.prototype,"cameraVelocityScale"),Ue([u()],nn.prototype,"lengthScale");class hp{_curve;_factor;constructor(e,t=1){this._curve=e,this._factor=t}type="function";startGen(e){}genValue(e,t){return this._curve.evaluate(t,Math.random())*this._factor}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}}class Fy{type="value";toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}startGen(e){}system;constructor(e){this.system=e}}class VE extends Fy{genValue(){return this.system.textureSheetAnimation.getStartIndex()}}class $E extends Fy{_lastPosition=new b;_lastDistance=0;update(){const e=Z(this.system.gameObject);this._lastDistance=this._lastPosition.distanceTo(e),this._lastPosition.copy(e)}genValue(){if(!this.system.isPlaying||!this.system.emission.enabled||this.system.currentParticles>=this.system.maxParticles)return 0;let e=this.system.emission.rateOverTime.evaluate(this.system.time/this.system.duration,Math.random());if(this.system.deltaTime>0){const n=this.system.emission.rateOverDistance.evaluate(this.system.time/this.system.duration,Math.random());let s=this._lastDistance/this.system.deltaTime*n;Number.isFinite(s)||(s=0),e+=s}const t=this.system.emission.getBurst();t>0&&(e+=t/this.system.deltaTime);const i=this.system.maxParticles-this.system.currentParticles;return D.clamp(e,0,i/this.system.deltaTime)}}class HE extends Fy{genValue(){return this.system.isPlaying,0}}class Fs{system;get context(){return this.system.context}constructor(e){this.type=Object.getPrototypeOf(this).constructor.name||"ParticleSystemBaseBehaviour",e&&(this.system=e)}type;initialize(e){}update(e,t){}frameUpdate(e){}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}reset(){}}class GE extends Fs{type="NeedleTextureSheet";update(e,t){const i=this.system.textureSheetAnimation;if(i.enabled){const n=e.age/e.life,s=i.evaluate(n);s!==void 0&&(e.uvTile=s)}}}const Fx=Symbol("particleRotation");class qE extends Fs{type="NeedleRotation";initialize(e){e[Fx]=Math.random()}update(e,t){if(e.rotation===void 0)return;const i=e.age/e.life;if(typeof e.rotation=="number"&&(this.system.rotationOverLifetime.enabled?e.rotation+=this.system.rotationOverLifetime.evaluate(i,e[Fx])*t:this.system.renderer.renderMode===Fo.Billboard&&(e.rotation=Math.PI),this.system.rotationBySpeed.enabled)){const n=e.velocity.length();e.rotation+=this.system.rotationBySpeed.evaluate(i,n)*t}}}const Ux=Symbol("sizeLerpFactor"),XE=new b;class QE extends Fs{type="NeedleSize";_minSize=0;_maxSize=1;initialize(e){e[Ux]=Math.random(),this._minSize=this.system.renderer.minParticleSize,this._maxSize=this.system.renderer.maxParticleSize}update(e,t){const i=e.age/e.life;let n=1;this.system.sizeOverLifetime.enabled&&(n*=this.system.sizeOverLifetime.evaluate(i,void 0,e[Ux]).x);let s=1;this.system.renderer.renderMode!==Fo.Mesh&&(s=this.system.worldScale.x/this.system.cameraScale);const r=$(e.startSize).multiplyScalar(n*s);if(e.size.set(r.x,r.y,r.z),this.system.localspace){const a=$x(this.system,XE);e.size.x*=a.x,e.size.y*=a.y,e.size.z*=a.z}}}const yl=Symbol("particleLife"),Uy=Symbol("trailLifetime"),zx=Symbol("trailStartLength"),zy=Symbol("trailWidthRandom");class YE extends Fs{type="NeedleTrail";initialize(e){e instanceof ob&&(e[yl]=e.life,this.system.trails.enabled&&this.system.trails.dieWithParticles===!1&&(e[Uy]=this.system.trails.lifetime.evaluate(Math.random(),Math.random()),e.life+=e[Uy]),e[zx]=e.length,e[zy]=Math.random())}update(e){if(this.system.trails?.enabled&&e instanceof ob){const t=e,i=e.age/e[yl],n=e.previous.values(),s=e.previous.length;for(let r=0;r<s;r++){const a=n.next().value,l=1-r/(s-1),c=e.size;if(c.x<=0&&!this.system.trails.sizeAffectsWidth){const h=20*this.system.trails.widthOverTrail.evaluate(.5,t[zy]);c.x=h,c.y=h,c.z=h}a.size=this.system.trails.getWidth(c.x,i,l,t[zy]),a.color.copy(e.color),this.system.trails.getColor(a.color,i,l)}if(e.age>e[yl]){e.velocity.set(0,0,0);const r=(e.age-e[yl])/e[Uy];t.length=D.lerp(e[zx],0,r)}}}}const dp=Symbol("startVelocity"),Nx=Symbol("gravityModifier"),Ny=Symbol("gravitySpeed"),up=Symbol("velocity lerp factor"),Wy=new b;class KE extends Fs{type="NeedleVelocity";_gravityDirection=new b;initialize(e){const t=this.system.main.simulationSpeed;e.startSpeed=this.system.main.startSpeed.evaluate(Math.random(),Math.random());const i=this.system.shape.getDirection(e,e.position);e.velocity.x=i.x*e.startSpeed,e.velocity.y=i.y*e.startSpeed,e.velocity.z=i.z*e.startSpeed,this.system.inheritVelocity?.enabled&&this.system.inheritVelocity.applyInitial(e.velocity),e[dp]?e[dp].copy(e.velocity):e[dp]=e.velocity.clone();const n=this.system.main.gravityModifier.evaluate(Math.random(),Math.random());e[Nx]=n*t,e[Ny]=n*t*.5,e[up]=Math.random(),this.system.velocityOverLifetime?.init(e),this._gravityDirection.set(0,-1,0),this.system.main.simulationSpace===sh.Local&&this._gravityDirection.applyQuaternion(this.system.worldQuaternionInverted).normalize()}update(e,t){const i=e[dp],n=e[Nx];if(n!==0){const d=n*e[Ny];Wy.copy(this._gravityDirection).multiplyScalar(d),e[Ny]+=t*.05,i.add(Wy)}e.velocity.copy(i);const s=e.age/e.life;this.system.inheritVelocity?.enabled&&this.system.inheritVelocity.applyCurrent(e.velocity,s,e[up]);const r=this.system.noise;r.enabled&&r.apply(0,e.position,e.velocity,t,e.age,e.life);const a=this.system.sizeBySpeed;a?.enabled&&(e.size=a.evaluate(e.velocity,s,e[up],e.size));const l=this.system.colorBySpeed;l?.enabled&&l.evaluate(e.velocity,e[up],e.color);const c=this.system.velocityOverLifetime;c.enabled&&c.apply(e,0,e.position,e.velocity,t,e.age,e.life);const h=this.system.limitVelocityOverLifetime;if(h.enabled&&h.apply(e.position,i,e.velocity,e.size,s,t,1),this.system.worldspace){const d=this.system.worldScale;e.velocity.x*=d.x,e.velocity.y*=d.y,e.velocity.z*=d.z}}}const Wx=Symbol("colorLerpFactor"),Vx=new se(1,1,1,1),Gr=new se(1,1,1,1);class ZE extends Fs{type="NeedleColor";initialize(e){}_init(e){const t=this.system.renderer.particleMaterial;Gr.copy(this.system.main.startColor.evaluate(Math.random())),t?.color&&(Vx.copy(t.color),Gr.multiply(Vx)),Gr.convertLinearToSRGB(),e.startColor.set(Gr.r,Gr.g,Gr.b,Gr.alpha),e.color.copy(e.startColor),e[Wx]=Math.random()}update(e,t){if(e.age===0&&this._init(e),this.system.colorOverLifetime.enabled){const i=e.age/e.life,n=this.system.colorOverLifetime.color.evaluate(i,e[Wx]);e.color.set(n.r,n.g,n.b,"alpha"in n?n.alpha:1).multiply(e.startColor)}else e.color.copy(e.startColor)}}class JE{system;emission;get anim(){return this.system.textureSheetAnimation}constructor(e){this.system=e,this.emission=new $E(this.system)}get prewarm(){return!1}get material(){return this.system.renderer.getMaterial(this.system.trails.enabled)}get layers(){return this.system.gameObject.layers}update(){this.emission.update()}autoDestroy;get looping(){return this.system.main.loop}get duration(){return this.system.duration}get shape(){return this.system.shape}get startLife(){return new hp(this.system.main.startLifetime)}get startSpeed(){return new hp(this.system.main.startSpeed)}get startRotation(){return new hp(this.system.main.startRotation)}get startSize(){return new hp(this.system.main.startSize)}startLength;get startColor(){return new NC(new WC(1,1,1,1))}get emissionOverTime(){return this.emission}get emissionOverDistance(){return new HE(this.system)}emissionBursts;onlyUsedByOther;behaviors=[];get instancingGeometry(){return this.system.renderer.getMesh(this.system.renderer.renderMode).geometry}get renderMode(){if(this.system.trails.enabled===!0)return yo.Trail;switch(this.system.renderer.renderMode){case Fo.Billboard:return yo.BillBoard;case Fo.Stretch:return yo.StretchedBillBoard;case Fo.HorizontalBillboard:return yo.HorizontalBillBoard;case Fo.VerticalBillboard:return yo.VerticalBillBoard;case Fo.Mesh:return yo.Mesh}return yo.BillBoard}rendererEmitterSettings={startLength:new VC(220),followLocalOrigin:!1};get speedFactor(){let e=this.system.main.simulationSpeed;return this.system.renderer?.renderMode===Fo.Stretch&&(e*=this.system.renderer.velocityScale??1),e}flatWhiteTexture;clonedTexture={original:void 0,clone:void 0};get texture(){const e=this.material;if(e&&e.map){const t=e.map;if(this.clonedTexture.original!==t||!this.clonedTexture.clone){const i=t.clone();i.premultiplyAlpha=!1,i.colorSpace=po,this.clonedTexture.original=t,this.clonedTexture.clone=i}return this.clonedTexture.clone}return this.flatWhiteTexture||(this.flatWhiteTexture=Fg(new se(1,1,1,1),1)),this.flatWhiteTexture}get startTileIndex(){return new VE(this.system)}get uTileCount(){return this.anim.enabled?this.anim?.numTilesX:void 0}get vTileCount(){return this.anim.enabled?this.anim?.numTilesY:void 0}get renderOrder(){return 1}get blending(){return this.system.renderer.particleMaterial?.blending??eC}get transparent(){return this.system.renderer.transparent}get worldSpace(){return this.system.main.simulationSpace===sh.World}}class eA{burstParticleIndex=0;burstParticleCount=0;isBursting=!1;travelDistance=0;previousWorldPos;burstIndex=0;burstWaveIndex=0;time=0;waitEmiting=0}const Ut=class qp extends M{play(e=!1){e&&x.foreachComponent(this.gameObject,t=>{t instanceof qp&&t!==this&&t.play(!1)},!0),this._isPlaying=!0,this._particleSystem&&(this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1),this.emission?.reset()}pause(e=!0){e&&x.foreachComponent(this.gameObject,t=>{t instanceof qp&&t!==this&&t.pause(!1)},!0),this._isPlaying=!1}stop(e=!0,t=!1){e&&x.foreachComponent(this.gameObject,i=>{i instanceof qp&&i!==this&&i.stop(!1,t)},!0),this._isPlaying=!1,this._time=0,t&&this.reset()}reset(){this._time=0,this._particleSystem&&(this._particleSystem.particleNum=0,this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1,this.emission?.reset())}_state;emit(e){if(this._particleSystem){this.onUpdate(),e=Math.min(e,this.maxParticles-this.currentParticles),this._state||(this._state=new eA),this._state.waitEmiting=e,this._state.time=0;const t=this._particleSystem.emitEnded;this._particleSystem.emitEnded=!1,this._particleSystem.emit(this.deltaTime,this._state,this._particleSystem.emitter.matrixWorld),this._particleSystem.emitEnded=t}}get playOnAwake(){return this.main.playOnAwake}set playOnAwake(e){this.main.playOnAwake=e}colorOverLifetime;main;emission;sizeOverLifetime;shape;noise;trails;velocityOverLifetime;limitVelocityOverLifetime;inheritVelocity;colorBySpeed;textureSheetAnimation;rotationOverLifetime;rotationBySpeed;sizeBySpeed;get renderer(){return this._renderer}get isPlaying(){return this._isPlaying}get currentParticles(){return this._particleSystem?.particleNum??0}get maxParticles(){return this.main.maxParticles}get time(){return this._time}get duration(){return this.main.duration}get deltaTime(){return this.context.time.deltaTime*this.main.simulationSpeed}get scale(){return this.gameObject.scale.x}get cameraScale(){return this._cameraScale}_cameraScale=1;get container(){return this._container}get worldspace(){return this.main.simulationSpace===sh.World}get localspace(){return this.main.simulationSpace===sh.Local}__worldQuaternion=new U;get worldQuaternion(){return this.__worldQuaternion}_worldQuaternionInverted=new U;get worldQuaternionInverted(){return this._worldQuaternionInverted}_worldScale=new b;get worldScale(){return this._worldScale}_worldPositionFrame=-1;_worldPos=new b;get worldPos(){return this._worldPositionFrame!==this.context.time.frame&&(this._worldPositionFrame=this.context.time.frame,Z(this.gameObject,this._worldPos)),this._worldPos}get matrixWorld(){return this._container.matrixWorld}get isSubsystem(){return this._isUsedAsSubsystem}addBehaviour(e){return this._particleSystem?(e instanceof Fs&&(e.system=this),Bs&&console.debug("Add custom ParticleSystem Behaviour",e),this._particleSystem.addBehavior(e),!0):!1}removeBehaviour(e){if(!this._particleSystem)return!1;const t=this._particleSystem.behaviors,i=t.indexOf(e);return i!==-1&&((E()||Bs)&&console.debug("Remove custom ParticleSystem Behaviour",i,e),t.splice(i,1)),!0}removeAllBehaviours(){return this._particleSystem?(this._particleSystem.behaviors.length=0,!0):!1}get behaviours(){return this._particleSystem?this._particleSystem.behaviors:null}get particleSystem(){return this._particleSystem??null}_renderer;_batchSystem;_particleSystem;_interface;_container;_time=0;_isPlaying=!0;_isUsedAsSubsystem=!1;_didPreWarm=!1;set bursts(e){for(let t=0;t<e.length;t++){const i=e[t];if(!(i instanceof lp)){const n=new lp;Aa(n,i),e[t]=n}}this._bursts=e}_bursts;set subEmitterSystems(e){for(let t=0;t<e.length;t++){const i=e[t];if(!(i instanceof pp)){const n=new pp;Aa(n,i),e[t]=n}}Bs&&e.length>0&&console.log("SubEmitters: ",e,this),this._subEmitterSystems=e}_subEmitterSystems;onAfterDeserialize(e){if(this._subEmitterSystems&&Array.isArray(this._subEmitterSystems))for(const t of this._subEmitterSystems)t._deserialize(this.context,this.gameObject)}awake(){if(this._worldPositionFrame=-1,this._renderer=this.gameObject.getComponent(nn),!this.main)throw new Error("Not Supported: ParticleSystem needs a serialized MainModule. Creating new particle systems at runtime is currently not supported.");this._container=new O,this._container.matrixAutoUpdate=!1,this.context.scene.add(this._container),this._batchSystem=new UC,this._batchSystem.name=this.gameObject.name,this._container.add(this._batchSystem),this._interface=new JE(this),this._particleSystem=new zC(this._interface),this._particleSystem.addBehavior(new QE(this)),this._particleSystem.addBehavior(new ZE(this)),this._particleSystem.addBehavior(new GE(this)),this._particleSystem.addBehavior(new qE(this)),this._particleSystem.addBehavior(new KE(this)),this._particleSystem.addBehavior(new YE(this)),this._batchSystem.addSystem(this._particleSystem);const e=this._particleSystem.emitter;this.context.scene.add(e),this.inheritVelocity.system&&this.inheritVelocity.system!==this&&(this.inheritVelocity=this.inheritVelocity.clone()),this.inheritVelocity.awake(this),Bs&&(console.log(this),this.gameObject.add(new _i(1)))}start(){this.addSubParticleSystems(),this.updateLayers(),this.renderer.particleMesh instanceof H&&this._interface.renderMode==yo.Mesh&&Ve.assignMeshLOD(this.renderer.particleMesh,0).then(e=>{e&&this.particleSystem&&this._interface.renderMode==yo.Mesh&&(this.particleSystem.instancingGeometry=e)})}onDestroy(){this._container?.removeFromParent(),this._batchSystem?.removeFromParent(),this._particleSystem?.emitter.removeFromParent(),this._particleSystem?.dispose()}onEnable(){this.main&&(this.inheritVelocity&&(this.inheritVelocity.system=this),this._batchSystem&&(this._batchSystem.visible=!0),this.playOnAwake&&this.play(),this._isPlaying=this.playOnAwake)}onDisable(){this._batchSystem&&(this._batchSystem.visible=!1)}onBeforeRender(){this.main&&(this._didPreWarm===!1&&this.main?.prewarm===!0&&(this._didPreWarm=!0,this.preWarm()),this.onUpdate(),this.onSimulate(this.deltaTime))}preWarm(){if(!this.emission?.enabled||this.emission.rateOverTime.getMax()<=0)return;const e=1/60,t=this.main.duration,i=this.main.startLifetime.getMax(),n=Math.min(Math.max(t,i)/Math.max(.01,this.main.simulationSpeed),1e3),s=Math.ceil(n/e),r=Date.now();Bs&&console.log(`Particles ${this.name} - Prewarm for ${s} frames (${n} sec). Duration: ${t}, Lifetime: ${i}`);for(let a=0;a<s&&!(this.currentParticles>=this.maxParticles);a++){const l=Date.now()-r;if(l>2e3){console.warn(`Particles ${this.name} - Prewarm took too long. Aborting: ${l}`);break}this.onUpdate(),this.onSimulate(e)}}_lastBatchesCount=-1;onSimulate(e){if(this._batchSystem){let t=this.context.time.frameCount%60===0;this._lastBatchesCount!==this._batchSystem.batches.length&&(this._lastBatchesCount=this._batchSystem.batches.length,t=!0),t&&this.updateLayers(),this._batchSystem.update(e)}this._time+=e,this._time>this.duration&&(this._time=0)}updateLayers(){if(this._batchSystem)for(let e=0;e<this._batchSystem.batches.length;e++){const t=this._batchSystem.batches[e];t.layers.disableAll();const i=this.layer;t.layers.mask=1<<i}}onUpdate(){if(this._bursts&&(this.emission.bursts=this._bursts,delete this._bursts),!this._isPlaying)return;const e=this.context.mainCamera;if(e){const n=$e(e);this._cameraScale=n.x}const t=!this.worldspace,i=this.gameObject;if(be(i,this.__worldQuaternion),this._worldQuaternionInverted.copy(this.__worldQuaternion).invert(),$e(this.gameObject,this._worldScale),t&&this._container&&this.gameObject?.parent){const n=$x(this,Wy);this._container.matrix.makeScale(n.x,n.y,n.z),this._container.matrix.makeRotationFromQuaternion(this.__worldQuaternion),this._container.matrix.setPosition(this.worldPos),this._container.matrix.scale(this.gameObject.scale)}this.emission.system=this,this._interface.update(),this.shape.onUpdate(this,this.context,this.main.simulationSpace,this.gameObject),this.noise.update(this.context),this.inheritVelocity?.update(this.context),this.velocityOverLifetime.update(this)}addSubParticleSystems(){if(this._subEmitterSystems&&this._particleSystem)for(const e of this._subEmitterSystems){e.particleSystem&&(e.particleSystem.__internalAwake?e.particleSystem.__internalAwake():E()&&console.warn("SubParticleSystem serialization issue(?)",e.particleSystem,e));const t=e.particleSystem?._particleSystem;if(t){e.particleSystem._isUsedAsSubsystem=!0;const i=new Dy(this,this._particleSystem,e.particleSystem,t);i.emitterType=e.type,i.emitterProbability=e.emitProbability,this._particleSystem.addBehavior(i)}else Bs&&console.warn("Could not add SubParticleSystem",e,this)}}};Ue([u(cp)],Ut.prototype,"colorOverLifetime"),Ue([u(Bt)],Ut.prototype,"main"),Ue([u(zo)],Ut.prototype,"emission"),Ue([u(Hr)],Ut.prototype,"sizeOverLifetime"),Ue([u(Ly)],Ut.prototype,"shape"),Ue([u(_e)],Ut.prototype,"noise"),Ue([u(Fe)],Ut.prototype,"trails"),Ue([u(We)],Ut.prototype,"velocityOverLifetime"),Ue([u(lt)],Ut.prototype,"limitVelocityOverLifetime"),Ue([u(jy)],Ut.prototype,"inheritVelocity"),Ue([u(fl)],Ut.prototype,"colorBySpeed"),Ue([u(Ft)],Ut.prototype,"textureSheetAnimation"),Ue([u(Pn)],Ut.prototype,"rotationOverLifetime"),Ue([u(tn)],Ut.prototype,"rotationBySpeed"),Ue([u(pi)],Ut.prototype,"sizeBySpeed");let ah=Ut;class pp{particleSystem;emitProbability=1;properties;type;_deserialize(e,t){const i=this.particleSystem;if(i instanceof ah)return;let n="";i&&typeof i.guid=="string"&&(n=i.guid,this.particleSystem=x.findByGuid(n,t)),Bs&&!(this.particleSystem instanceof ah)&&console.warn("Could not find particle system for sub emitter",n,t,this)}}function $x(o,e){if(e.set(1,1,1),o.gameObject.parent&&o.localspace)switch(o.main.scalingMode){case Iy.Local:e=$e(o.gameObject.parent,e),e.x=1/e.x,e.y=1/e.y,e.z=1/e.z;break;default:if(!o.unsupported_scaling_mode){o.unsupported_scaling_mode=!0;const t="ParticleSystem scale mode "+Iy[o.main.scalingMode]+" is not supported";E()&&ge(t),console.warn(t,o.name,o)}e=$e(o.gameObject,e);break}return e}var tA=Object.defineProperty,Vy=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&tA(e,t,n),n};class bl extends M{strength=1;radius=2;targets=[];update(){const e=this.gameObject.worldPosition,t=-this.strength*this.context.time.deltaTime;this.targets?.forEach(i=>{if(!i)return;const n=i.gameObject.worldPosition.sub(e),s=n.length();if(s>this.radius)return;let r=t;s>1?r/=s*s:r/=Math.max(.05,s),i.applyImpulse(n.multiplyScalar(r))})}}Vy([u()],bl.prototype,"strength"),Vy([u()],bl.prototype,"radius"),Vy([u(Ye)],bl.prototype,"targets");class Il extends M{_didAssignPlayerColor=!1;onEnable(){this.context.connection.beginListen(te.JoinedRoom,this.tryAssignColor),this._didAssignPlayerColor||this.startCoroutine(this.waitForConnection())}onDisable(){this.context.connection.stopListen(te.JoinedRoom,this.tryAssignColor)}*waitForConnection(){for(;!this.destroyed&&this.activeAndEnabled&&(yield Dg(.2),!this.tryAssignColor()););}tryAssignColor=()=>{const e=x.getComponentInParent(this.gameObject,xn);if(e&&e.owner)return this._didAssignPlayerColor=!0,this.assignUserColor(e.owner),!0;const t=x.getComponentInParent(this.gameObject,Le);return t?.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(t.connectionId),!0):!1};assignUserColor(e){const t=Il.hashCode(e),i=Il.colorFromHashCode(t);if(this.gameObject.type==="Mesh"){const n=this.gameObject;this.assignColor(i,e,n)}else if(this.gameObject.children)for(const n of this.gameObject.children){const s=n;s.material&&s.material.color&&this.assignColor(i,e,s)}}assignColor(e,t,i){let n=i.material;n&&(n._playerMaterial!==t&&(n=n.clone(),n._playerMaterial=t,i.material=n),n.color=e)}static hashCode(e){var t=0,i,n;if(e.length===0)return t;for(i=0;i<e.length;i++)n=e.charCodeAt(i),t=(t<<5)-t+n,t|=0;return t}static colorFromHashCode(e){const t=(e&16711680)>>16,i=(e&65280)>>8,n=e&255;return new ne(t/255,i/255,n/255)}}const lh=w("debugpost");let $y=null;function iA(o){$y=o}function Hx(o){let e=o.gameObject;for(;e;){for(const t of eu(e))if(t.isPostProcessingManager===!0)return t;e=e.parent}return null}function nA(o){let e=Hx(o);if(!e)if($y){lh&&console.warn("Adding postprocessing manager to the scene.");const t=o.scene;e=bn(t,$y)}else E()&&console.warn("No post processing manager found");return e}const ct={AT_START:-1e4,NormalPass:0,DepthDownsamplingPass:10,SSAO:20,SMAA:30,TiltShift:40,DepthOfField:50,ChromaticAberration:60,Bloom:70,Vignette:80,Pixelation:90,ToneMapping:100,HueSaturation:110,BrightnessContrast:120,Sharpening:130,AT_END:1e4};let Je=null;function oA(o){lh==="verbose"&&console.debug("Before ordering effects",[...o]),Je||(Je=new Map,Je.set(T.POSTPROCESSING.MODULE.NormalPass,ct.NormalPass),Je.set(T.POSTPROCESSING.MODULE.DepthDownsamplingPass,ct.DepthDownsamplingPass),Je.set(T.POSTPROCESSING.MODULE.SMAAEffect,ct.SMAA),Je.set(T.POSTPROCESSING.MODULE.SSAOEffect,ct.SSAO),Je.set(T.POSTPROCESSING_AO.MODULE.N8AOPostPass,ct.SSAO),Je.set(T.POSTPROCESSING_AO.MODULE.N8AOPass,ct.SSAO),Je.set(T.POSTPROCESSING.MODULE.TiltShiftEffect,ct.TiltShift),Je.set(T.POSTPROCESSING.MODULE.DepthOfFieldEffect,ct.DepthOfField),Je.set(T.POSTPROCESSING.MODULE.ChromaticAberrationEffect,ct.ChromaticAberration),Je.set(T.POSTPROCESSING.MODULE.BloomEffect,ct.Bloom),Je.set(T.POSTPROCESSING.MODULE.SelectiveBloomEffect,ct.Bloom),Je.set(T.POSTPROCESSING.MODULE.VignetteEffect,ct.Vignette),Je.set(T.POSTPROCESSING.MODULE.PixelationEffect,ct.Pixelation),Je.set(T.POSTPROCESSING.MODULE.ToneMappingEffect,ct.ToneMapping),Je.set(T.POSTPROCESSING.MODULE.HueSaturationEffect,ct.HueSaturation),Je.set(T.POSTPROCESSING.MODULE.BrightnessContrastEffect,ct.BrightnessContrast)),o.sort((e,t)=>{const i=typeof e.priority=="number"?e.priority:Je.get(e.effect.constructor)??Number.NEGATIVE_INFINITY,n=typeof t.priority=="number"?t.priority:Je.get(t.effect.constructor)??Number.NEGATIVE_INFINITY;return i===Number.NEGATIVE_INFINITY?(lh&&console.warn("Unknown effect found: ",e.constructor.name,e),1):n===Number.NEGATIVE_INFINITY?(lh&&console.warn("Unknown effect found: ",t.constructor.name,t),-1):i-n}),lh==="verbose"&&console.debug("After ordering effects",[...o])}var sA=Object.defineProperty,rA=Object.getOwnPropertyDescriptor,Gx=(o,e,t,i)=>{for(var n=rA(e,t),s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&sA(e,t,n),n};const aA=w("debugpost");class B{isVolumeParameter=!0;constructor(e){e!==void 0&&this.initialize(e)}_isInitialized=!1;get isInitialized(){return this._isInitialized}initialize(e){e!==void 0&&(this._value=e,this._defaultValue=e,this._valueRaw=e,this._isInitialized=!0)}get overrideState(){return this._active}set overrideState(e){if(this._active===e)return;this._active=e;const t=e?this._valueRaw:this._defaultValue;this.processValue(t,!0)}_active=!0;get value(){return this._valueRaw}set value(e){this.isInitialized||this.initialize(e),this.processValue(e,!1)}_value;_valueRaw;set defaultValue(e){this._defaultValue=e}_defaultValue=void 0;__init(){this.processValue(this._valueRaw,!0)}valueProcessor;onValueChanged;processValue(e,t){if(e==null||!t&&this.testIfValueChanged(e)===!1)return;const i=this._value;aA&&typeof i=="number"&&typeof e=="number"&&(i?.toFixed(4),e?.toFixed(4)),!this._active&&this._defaultValue!==void 0?(this._value=this._defaultValue,e=this._defaultValue,this._valueRaw=e):(this._valueRaw=e,this._active&&this.valueProcessor&&(e=this.valueProcessor(e)),this._value=e),this.onValueChanged&&this.onValueChanged(e,i,this)}testIfValueChanged(e){return this._valueRaw!==e}}Gx([u()],B.prototype,"overrideState"),Gx([u()],B.prototype,"value");class lA extends Xi{constructor(){super([B])}onSerialize(e,t){}onDeserialize(e,t){const i=t.target,n=t.path;let s;if(i&&n&&(s=i[n]),(typeof s!="object"||typeof s=="object"&&s.isVolumeParameter!==!0)&&(s=new B),typeof e=="object"&&"value"in e){const r=e.value;s.initialize(r),s.overrideState=e.overrideState}else s.value=e;return s}}new lA;var cA=Object.defineProperty,hA=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&cA(e,t,n),n};const Hy=w("debugpost");class et extends M{get isPostProcessingEffect(){return!0}order=void 0;constructor(e=void 0){if(super(),e)for(const t of Object.keys(e)){const i=e[t],n=this[t];n instanceof B?n.initialize(i):n!==void 0&&(this[t]=i)}}active=!0;_manager=null;onEnable(){super.onEnable(),Hy&&console.warn("Enable",this.constructor.name+(this.__internalDidAwakeAndStart?"":" (awake)")),this.__internalDidAwakeAndStart&&(this.active=!0),this.onEffectEnabled()}onDisable(){super.onDisable(),Hy&&console.warn("Disable",this.constructor.name),this._manager?.removeEffect(this),this.active=!1}onEffectEnabled(e){e&&e.isPostProcessingManager===!0?this._manager=e:this._manager||(this._manager=nA(this)),this._manager.addEffect(this),this._manager.dirty=!0}init(){}_result;_postprocessingContext=null;get postprocessingContext(){return this._postprocessingContext}apply(e){return this._postprocessingContext=e,this._result||(this.initParameters(),this._result=this.onCreateEffect?.call(this)),this._result&&this.initParameters(),this._result}unapply(){}dispose(){Hy&&console.warn("DISPOSE",this),this._result&&(Array.isArray(this._result)?this._result.forEach(e=>e.dispose()):this._result.dispose()),this._result=void 0}initParameters(){const e=Object.keys(this);for(const t of e){const i=this[t];i instanceof B&&i.__init()}}onEditorModification(e){const t=e.propertyName;if(this[t]instanceof B){const i=e.value;return this[t].value=i,!0}}}hA([u()],et.prototype,"active");var dA=Object.defineProperty,uA=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&dA(e,t,n),n};const pA=w("debugpost"),Gy={};function on(o,e){Gy[o]=e}function mA(o){return o.__type in Gy?Gy[o.__type]:(pA&&o.__type&&console.warn("Unknown postprocessing type",o.__type,o),et)}class mp{components=[];__init(e){this.components?.forEach(t=>{t.gameObject===void 0&&e.gameObject.addComponent(t),t.init()})}addEffect(e){this.components.push(e)}removeEffect(e){const t=this.components.indexOf(e);t>=0&&this.components.splice(t,1)}}uA([Qe([o=>mA(o),et])],mp.prototype,"components");var gA=Object.defineProperty,fA=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&gA(e,t,n),n};const yA=w("debugpost");class ch extends et{get typeName(){return"Antialiasing"}preset=new B(2);onCreateEffect(){const e=new T.POSTPROCESSING.MODULE.SMAAEffect({preset:this.preset?.value??T.POSTPROCESSING.MODULE.SMAAPreset.HIGH,edgeDetectionMode:T.POSTPROCESSING.MODULE.EdgeDetectionMode.LUMA});return this.preset.onValueChanged=t=>{yA&&console.log("Antialiasing preset changed to",t),e.applyPreset(t)},e}}fA([u(B)],ch.prototype,"preset"),on("Antialiasing",ch);var bA=Object.defineProperty,qy=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&bA(e,t,n),n};const gp=class X1 extends et{static useSelectiveBloom=!1;get typeName(){return"Bloom"}threshold=new B(.9);intensity=new B(1);scatter=new B(.7);selectiveBloom;init(){this.threshold.valueProcessor=e=>e,this.intensity.valueProcessor=e=>e,this.scatter.valueProcessor=e=>e}onCreateEffect(){let e;if(this.selectiveBloom==null&&(this.selectiveBloom=X1.useSelectiveBloom),this.selectiveBloom){const t=e=new T.POSTPROCESSING.MODULE.SelectiveBloomEffect(this.context.scene,this.context.mainCamera,{blendFunction:T.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});t.inverted=!0}else e=new T.POSTPROCESSING.MODULE.BloomEffect({blendFunction:T.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});return this.intensity.onValueChanged=t=>{e.intensity=t},this.threshold.onValueChanged=t=>{e.luminanceMaterial.threshold=Math.pow(t,2.2)},this.scatter.onValueChanged=t=>{e.luminancePass.enabled=!0,e.luminanceMaterial.smoothing=t,e.mipmapBlurPass&&(e.mipmapBlurPass.radius=uo.lerp(.1,.9,t))},e}};qy([u(B)],gp.prototype,"threshold"),qy([u(B)],gp.prototype,"intensity"),qy([u(B)],gp.prototype,"scatter");let fp=gp;on("Bloom",fp);var _A=Object.defineProperty,vA=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&_A(e,t,n),n};class hh extends et{get typeName(){return"ChromaticAberration"}intensity=new B(0);onCreateEffect(){const e=new T.POSTPROCESSING.MODULE.ChromaticAberrationEffect;return e.offset=new J(0,0),e.radialModulation=!0,e.modulationOffset=.15,this.intensity.valueProcessor=t=>t*.02,this.intensity.onValueChanged=t=>{e.offset.x=-t,e.offset.y=t},e}}vA([u(B)],hh.prototype,"intensity"),on("ChromaticAberration",hh);var dh=(o=>(o[o.None=0]="None",o[o.Neutral=1]="Neutral",o[o.ACES=2]="ACES",o[o.AgX=3]="AgX",o[o.KhronosNeutral=4]="KhronosNeutral",o))(dh||{});const qx=new Map;function Xy(o){switch(o){case 0:return dm;case 1:return hm;case 2:return cd;case 3:return ld;case 4:return ya;default:return qx.has(o)||(qx.set(o,!0),console.warn("[Postprocessing] Unknown tone mapping mode",o)),ya}}function wA(o){switch(o){case dm:return 0;case cd:return 2;case ld:return 3;case ya:return 1;case hm:return 1;default:return 0}}function yp(o){switch(o){case dm:return T.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR;case cd:return T.POSTPROCESSING.MODULE.ToneMappingMode.ACES_FILMIC;case ld:return T.POSTPROCESSING.MODULE.ToneMappingMode.AGX;case ya:return T.POSTPROCESSING.MODULE.ToneMappingMode.NEUTRAL;case hm:return T.POSTPROCESSING.MODULE.ToneMappingMode.REINHARD;default:return T.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR}}var xA=Object.defineProperty,Xx=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&xA(e,t,n),n};const Qy=w("debugpost");class Us extends et{get typeName(){return"ToneMapping"}mode=new B(void 0);exposure=new B(1);setMode(e){const t=dh[e];return t===void 0?(console.error("[PostProcessing] Invalid ToneMapping mode",e),this):(this.mode.value=t,this)}get isToneMapping(){return!0}onEffectEnabled(){const e=Hx(this);e&&super.onEffectEnabled(e)}_tonemappingEffect=null;onCreateEffect(){if(this.mode.isInitialized==!1){const i=wA(this.context.renderer.toneMapping);Qy&&console.log("[PostProcessing] Initializing ToneMapping mode to renderer.toneMapping",this.context.renderer.toneMapping+" \u2192 "+i),this.mode.initialize(i)}this._tonemappingEffect?.dispose();const e=Xy(this.mode.value),t=this._tonemappingEffect=new T.POSTPROCESSING.MODULE.ToneMappingEffect({mode:yp(e)});return this.mode.onValueChanged=i=>{if(typeof i=="string")i=Wv(i),t.mode=yp(i);else{const n=Xy(i);t.mode=yp(n)}t.name="ToneMapping ("+dh[i]+")",Qy&&console.log("[PostProcessing] ToneMapping mode changed to",dh[i],e,t.mode)},Qy&&console.log("[PostProcessing] Use ToneMapping",dh[this.mode.value],e,t.mode,"renderer.tonemapping: "+this.context.renderer.toneMapping),t}onBeforeRender(){if(this._tonemappingEffect&&this.postprocessingContext?.handler.getEffectIsActive(this._tonemappingEffect)&&(this.mode.overrideState&&(this.context.renderer.toneMapping=Xy(this.mode.value)),this.exposure.overrideState&&this.exposure.value!==void 0)){const e=Math.max(0,this.exposure.value);this.context.renderer.toneMappingExposure=e}}}Xx([u(B)],Us.prototype,"mode"),Xx([u(B)],Us.prototype,"exposure"),on("Tonemapping",Us);var SA=Object.defineProperty,bp=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&SA(e,t,n),n};class zs extends et{get typeName(){return"ColorAdjustments"}remap=!0;postExposure=new B(1);contrast=new B(0);hueShift=new B(0);saturation=new B(0);init(){this.postExposure.valueProcessor=e=>(this.remap&&(e=Math.pow(2,e)),e),this.contrast.valueProcessor=e=>{if(!this.remap)return e;let t=1;return e>0?t=200:e<0&&(t=100),e/t},this.contrast.defaultValue=0,this.hueShift.valueProcessor=e=>this.remap?Math.PI*e/180:e,this.hueShift.defaultValue=0,this.saturation.valueProcessor=e=>this.remap?e<0?e/100:e/(100*Math.PI):e,this.saturation.defaultValue=0}onCreateEffect(){const e=[];let t=this.postprocessingContext?.components.find(s=>s instanceof Us);t||(t=new Us,this.postprocessingContext?.components.push(t)),this.postExposure.onValueChanged=s=>{this.postExposure.overrideState&&t?t.exposure.value=s:console.warn("[PostProcessing] PostExposure is set to override but no ToneMappingEffect found in the postprocessing stack. Please add a ToneMappingEffect to your postprocessing stack to use PostExposure.")};const i=new T.POSTPROCESSING.MODULE.BrightnessContrastEffect;this.contrast.onValueChanged=s=>i.contrast=s;const n=new T.POSTPROCESSING.MODULE.HueSaturationEffect;return this.hueShift.onValueChanged=s=>n.hue=s,this.saturation.onValueChanged=s=>n.saturation=s,e.push(i),e.push(n),e}}bp([u(B)],zs.prototype,"postExposure"),bp([u(B)],zs.prototype,"contrast"),bp([u(B)],zs.prototype,"hueShift"),bp([u(B)],zs.prototype,"saturation"),on("ColorAdjustments",zs);var CA=Object.defineProperty,qr=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&CA(e,t,n),n};const PA=w("debugpost");class On extends et{get typeName(){return"DepthOfField"}mode;focusDistance=new B(1);focalLength=new B(.2);aperture=new B(20);gaussianMaxRadius=new B;resolutionScale=new B(1/window.devicePixelRatio);bokehScale=new B;init(){this.focalLength.valueProcessor=t=>{const i=t/300;return D.lerp(2,.01,i)};const e=20;this.aperture.valueProcessor=t=>{const i=1-t/32;return D.lerp(1,e,i)}}onCreateEffect(){if(this.mode===0){PA&&console.warn("DepthOfField: Mode is set to Off");return}const e=new T.POSTPROCESSING.MODULE.DepthOfFieldEffect(this.context.mainCamera,{worldFocusRange:.2,focalLength:1,bokehScale:20,resolutionScale:this.resolutionScale.value});return this.focusDistance.onValueChanged=t=>{e.cocMaterial.worldFocusDistance=t},this.focalLength.onValueChanged=t=>e.cocMaterial.worldFocusRange=t,this.aperture.onValueChanged=t=>e.bokehScale=t,this.resolutionScale&&(this.resolutionScale.onValueChanged=t=>e.resolution.scale=t),[e]}unapply(){}}qr([u()],On.prototype,"mode"),qr([u(B)],On.prototype,"focusDistance"),qr([u(B)],On.prototype,"focalLength"),qr([u(B)],On.prototype,"aperture"),qr([u(B)],On.prototype,"gaussianMaxRadius"),qr([u(B)],On.prototype,"resolutionScale"),qr([u(B)],On.prototype,"bokehScale"),on("DepthOfField",On);class uh extends et{effect;constructor(e){super(),this.effect=e}get typeName(){return this.effect.constructor.name}onCreateEffect(){return this.effect}}var OA=Object.defineProperty,kA=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&OA(e,t,n),n};class ph extends et{get typeName(){return"PixelationEffect"}granularity=new B(10);onCreateEffect(){const e=new T.POSTPROCESSING.MODULE.PixelationEffect;return this.granularity.onValueChanged=t=>{e.granularity=t},e}}kA([u(B)],ph.prototype,"granularity"),on("PixelationEffect",ph);var MA=Object.defineProperty,mh=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&MA(e,t,n),n};class No extends et{get typeName(){return"ScreenSpaceAmbientOcclusion"}intensity=new B(2);falloff=new B(1);samples=new B(9);color=new B(new ne(0,0,0));luminanceInfluence=new B(.7);onBeforeRender(){if(this._ssao&&this.context.mainCamera instanceof de){const e=this.context.mainCamera.far-this.context.mainCamera.near;this._ssao.ssaoMaterial.worldDistanceFalloff=e*.01,this._ssao.ssaoMaterial.worldDistanceThreshold=this.context.mainCamera.far}}_ssao;onCreateEffect(){const e=this.context.mainCamera,t=new T.POSTPROCESSING.MODULE.NormalPass(this.context.scene,e),i=new T.POSTPROCESSING.MODULE.DepthDownsamplingPass({normalBuffer:t.texture,resolutionScale:.5}),n=this._ssao=new T.POSTPROCESSING.MODULE.SSAOEffect(e,t.texture,{normalDepthBuffer:i.texture,worldDistanceThreshold:1,worldDistanceFalloff:1,worldProximityThreshold:.1,worldProximityFalloff:2,intensity:1,blendFunction:T.POSTPROCESSING.MODULE.BlendFunction.MULTIPLY,luminanceInfluence:.5});this.intensity.onValueChanged=r=>{n.intensity=r},this.falloff.onValueChanged=r=>{n.ssaoMaterial.radius=r*.1},this.samples.onValueChanged=r=>{n.ssaoMaterial.samples=r},this.color.onValueChanged=r=>{n.color||(n.color=new ne),n.color.copy(r)},this.luminanceInfluence.onValueChanged=r=>{n.luminanceInfluence=r};const s=new Array;return s.push(t),s.push(i),s.push(n),s}}mh([u(B)],No.prototype,"intensity"),mh([u(B)],No.prototype,"falloff"),mh([u(B)],No.prototype,"samples"),mh([u(B)],No.prototype,"color"),mh([u(B)],No.prototype,"luminanceInfluence"),on("ScreenSpaceAmbientOcclusion",No);var RA=Object.defineProperty,Xr=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&RA(e,t,n),n};const TA=w("debugN8AO");var Yy=(o=>(o[o.Performance=0]="Performance",o[o.Low=1]="Low",o[o.Medium=2]="Medium",o[o.High=3]="High",o[o.Ultra=4]="Ultra",o))(Yy||{});class kn extends et{get typeName(){return"ScreenSpaceAmbientOcclusionN8"}get pass(){return this._ssao}gammaCorrection=!0;aoRadius=new B(1);falloff=new B(1);intensity=new B(1);color=new B(new ne(0,0,0));screenspaceRadius=!1;quality=2;_ssao;onValidate(){this._ssao&&(this._ssao.setQualityMode(Yy[this.quality]),this._ssao.configuration.gammaCorrection=this.gammaCorrection,this._ssao.configuration.screenSpaceRadius=this.screenspaceRadius)}onCreateEffect(){const e=this.context.mainCamera,t=this.context.domWidth,i=this.context.domHeight,n=this._ssao=new T.POSTPROCESSING_AO.MODULE.N8AOPostPass(this.context.scene,e,t,i);n.name="SSAO_N8";const s=Yy[this.quality];n.setQualityMode(s),n.configuration.transparencyAware=!1;const r=new jn(t,i);return n.configuration.beautyRenderTarget=r,n.configuration.autoRenderBeauty=!1,n.configuration.gammaCorrection=this.gammaCorrection,n.configuration.screenSpaceRadius=this.screenspaceRadius,TA&&(n.enableDebugMode(),console.log(n),setInterval(()=>{console.log("SSAO",n.lastTime)},1e3),setInterval(()=>{console.log("SSAO",n.enabled,{ssao:n,autoRenderBeauty:n.configuration.autoRenderBeauty})},4e3)),this.intensity.onValueChanged=a=>{n.configuration.intensity=a},this.falloff.onValueChanged=a=>{n.configuration.distanceFalloff=a},this.aoRadius.onValueChanged=a=>{n.configuration.aoRadius=a},this.color.onValueChanged=a=>{n.color||(n.color=new ne),n.configuration.color.copy(a)},n}}Xr([Pt(),u()],kn.prototype,"gammaCorrection"),Xr([u(B)],kn.prototype,"aoRadius"),Xr([u(B)],kn.prototype,"falloff"),Xr([u(B)],kn.prototype,"intensity"),Xr([u(B)],kn.prototype,"color"),Xr([Pt(),u()],kn.prototype,"screenspaceRadius"),Xr([Pt(),u()],kn.prototype,"quality"),on("ScreenSpaceAmbientOcclusionN8",kn);var EA=Object.defineProperty,AA=Object.getOwnPropertyDescriptor,Qx=(o,e,t,i)=>{for(var n=AA(e,t),s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&EA(e,t,n),n};class gh extends et{get typeName(){return"Sharpening"}order=ct.Sharpening;_effect;onCreateEffect(){return this._effect??=new(IA()),this.effect}get effect(){return this._effect}set amount(e){this._amount=e,this._effect&&(this._effect.uniforms.get("amount").value=e)}get amount(){return this._effect?this._effect.uniforms.get("amount").value:this._amount}_amount=1;set radius(e){this._radius=e,this._effect&&(this._effect.uniforms.get("radius").value=e)}get radius(){return this._effect?this._effect.uniforms.get("radius").value:this._radius}_radius=1}Qx([u()],gh.prototype,"amount"),Qx([u()],gh.prototype,"radius");function IA(){const o=`
1283
+ `)}r&&s.size&&console.log(d);const f=new Set;for(const _ of m){_.getPath||console.error("USDZExporter: Animation target object has no getPath method. This is likely a bug",_);let v=_.getPath();v.startsWith("<")&&(v=v.substring(1)),v.endsWith(">")&&(v=v.substring(0,v.length-1)),f.add({path:v,obj:_})}const g=Array.from(f).sort((_,v)=>_.path.length-v.path.length),y=new Array;for(let _=0;_<g.length;_++)for(let v=_+1;v<g.length;v++)if(g[v].path.startsWith(g[_].path)){const P=g[v],R=g[_];y.push({child:P.obj.displayName+" ("+P.path+")",parent:R.obj.displayName+" ("+R.path+")"})}y.length&&console.warn("USDZExporter: There are overlapping PlayAnimation actions. This can lead to undefined runtime behaviour when playing multiple animations. Please restructure the hierarchy so that animations don't overlap.",{overlappingTargets:y,playAnimationActions:s})}for(const d of new Set([...t,...i]))if(Array.isArray(d))for(const p of d)n.add(p.uuid);else n.add(d.uuid);Ju&&console.log("All Behavior trigger sources and action targets",t,i,n),this.targetUuids=new Set(n)}onAfterHierarchy(e,t){if(this.behaviours?.length){t.beginBlock('def Scope "Behaviors"');for(const i of this.behaviours)i.writeTo(this,e.document,t);t.closeBlock()}}async onAfterSerialize(e){Ju&&console.log("onAfterSerialize behaviours",this.behaviourComponentsCopy);for(const t of this.behaviourComponentsCopy)typeof t.afterSerialize=="function"&&(t.afterSerialize.constructor.name==="AsyncFunction"?await t.afterSerialize(this,e):t.afterSerialize(this,e));for(const{clipUrl:t,filesKey:i}of this.audioClipsCopy){if(e.files[i])return;const n=await(await(await fetch(t)).blob()).arrayBuffer(),s=new Uint8Array(n);e.files[i]=s}this.behaviourComponentsCopy.length=0,this.audioClipsCopy.length=0}}class dy{get extensionName(){return"Physics"}onExportObject(e,t,i){const n=x.getComponents(e,Ye).filter(l=>l.enabled),s=x.getComponents(e,ai).filter(l=>l.enabled&&!l.isTrigger);let r=n.length>0?n[0]:null;const a=s.length>0?s[0]:null;a&&!r&&(r=new Ye,r.isKinematic=!0),r&&t.addEventListener("serialize",(l,c)=>{if(r){if(l.appendLine(),l.beginBlock('def RealityKitComponent "RigidBody"',"{",!0),r.useGravity||l.appendLine("bool gravityEnabled = 0"),l.appendLine('uniform token info:id = "RealityKit.RigidBody"'),r.isKinematic&&l.appendLine('token motionType = "Kinematic"'),l.beginBlock('def RealityKitStruct "massFrame"',"{",!0),l.appendLine(`float m_mass = ${r.mass}`),l.beginBlock('def RealityKitStruct "m_pose"',"{",!0),l.appendLine(`float3 position = (${r.centerOfMass.x}, ${r.centerOfMass.y}, ${r.centerOfMass.z})`),l.closeBlock("}"),l.closeBlock("}"),s.length>0){const h=s[0];l.beginBlock('def RealityKitStruct "material"',"{",!0);const d=h.sharedMaterial;d&&d.dynamicFriction!==void 0&&l.appendLine(`double dynamicFriction = ${h.sharedMaterial?.dynamicFriction}`),d&&d.bounciness!==void 0&&l.appendLine(`double restitution = ${h.sharedMaterial?.bounciness}`),d&&d.staticFriction!==void 0&&l.appendLine(`double staticFriction = ${h.sharedMaterial?.staticFriction}`),l.closeBlock("}")}l.closeBlock("}")}}),a&&(t.addEventListener("serialize",(l,c)=>{l.beginBlock('def RealityKitComponent "Collider"',"{",!0),l.appendLine("uint group = 1"),l.appendLine('uniform token info:id = "RealityKit.Collider"'),l.appendLine("uint mask = 4294967295");const h=a.isTrigger?"Trigger":"Default";if(l.appendLine(`token type = "${h}"`),l.beginBlock('def RealityKitStruct "Shape"',"{",!0),a instanceof Ga){const d=a;l.appendLine('token shapeType = "Sphere"'),l.appendLine(`float radius = ${d.radius}`)}else if(a instanceof Ou){const d=a;l.appendLine('token shapeType = "Box"'),l.appendLine(`float3 extent = (${d.size.x}, ${d.size.y}, ${d.size.z})`)}else if(a instanceof Mo){const d=a;l.appendLine('token shapeType = "Capsule"'),l.appendLine(`float radius = ${d.radius}`),l.appendLine(`float height = ${d.height}`)}else if(a instanceof xs&&a.sharedMesh?.geometry){const d=a.sharedMesh.geometry;d.boundingBox||d.computeBoundingBox();const p=a.sharedMesh.geometry.boundingBox;p&&(l.appendLine('token shapeType = "Box"'),l.appendLine(`float3 extent = (${p.max.x-p.min.x}, ${p.max.y-p.min.y}, ${p.max.z-p.min.z})`),console.log("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. MeshCollider will be exported as Box",a))}else console.warn("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. Ignoring collider:",a);l.beginBlock('def RealityKitStruct "pose"',"{",!0),l.closeBlock("}"),l.closeBlock("}"),l.closeBlock("}")}),s.length>1&&console.log("WARNING: Multiple colliders detected. visionOS / iOS can only support objects with a single collider, only exporting the first collider: ",a))}}const nE=w("debugshadowcomponents");rb.prototype.interactable={get(){return this.interactive},set(o){this.interactable=o}};class rn extends M{isRoot(){return this.Root?.gameObject===this.gameObject}get canvas(){const e=this.Root;return e?.isCanvas?e:null}get Canvas(){return this.canvas}markDirty(){ei.markUIDirty(this.context)}get shadowComponent(){return this._shadowComponent}set shadowComponent(e){this._shadowComponent=e}_shadowComponent=null;_controlsChildLayout=!0;get controlsChildLayout(){return this._controlsChildLayout}set controlsChildLayout(e){this._controlsChildLayout=e,this.shadowComponent&&(this.shadowComponent.autoLayout=e)}_root=void 0;get Root(){return this._root===void 0&&(this._root=x.getComponentInParent(this.gameObject,Xc)),this._root}_parentComponent=void 0;__internalNewInstanceCreated(e){return super.__internalNewInstanceCreated(e),this.shadowComponent=null,this._root=void 0,this._parentComponent=void 0,this}onEnable(){super.onEnable()}addShadowComponent(e,t){if(!e)return;this.removeShadowComponent();const i=this.isRoot()?this.gameObject:this.gameObject.parent;if(this._parentComponent=x.getComponentInParent(i,rn),!this._parentComponent){console.warn(`Component "${this.name}" doesn't have a UI parent anywhere. Do you have an UI element outside a Canvas? UI components must be a child of a Canvas component`,this);return}e.name=this.name+" ("+(this.constructor.name??"UI")+")",e.autoLayout=this._parentComponent.controlsChildLayout,e[Si]=this,this.setShadowComponentOwner(e);let n=!1;if(this.Root?.gameObject===this.gameObject)this.gameObject.add(e);else{const s=this._parentComponent.shadowComponent;s&&(s?.add(e),n=!0)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),lc&&e.add(new _i(.5)),this.onAfterAddedToScene(),n&&GC(),nE&&console.warn("Added shadow component",this.shadowComponent)}setShadowComponentOwner(e){if(e&&(e[Si]===void 0||e[Si]===this)&&(e[Si]=this,e.children))for(const t of e.children)this.setShadowComponentOwner(t)}traverseOwnedShadowComponents(e,t,i){if(e&&e[Si]===t){i(e);for(const n of e.children)this.traverseOwnedShadowComponents(n,t,i)}}removeShadowComponent(){this.shadowComponent&&this.shadowComponent.removeFromParent()}onAfterAddedToScene(){}setInteractable(e){this.shadowComponent&&(this.shadowComponent.interactable=e)}}class Xc extends rn{awake(){super.awake()}}var oE=Object.defineProperty,sE=Object.getOwnPropertyDescriptor,Qc=(o,e,t,i)=>{for(var n=i>1?void 0:i?sE(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&oE(e,t,n),n};const uy=w("debugui"),py=w("debuguilayout");class kx{width;height}class Mx{x;y;width;height}const Sn=new b,Yc=new ee,ep=new U,cl=class H1 extends rn{get parent(){return this._parentRectTransform}get translation(){return this.gameObject.position}get rotation(){return this.gameObject.quaternion}get scale(){return this.gameObject.scale}_anchoredPosition;get anchoredPosition(){return this._anchoredPosition||(this._anchoredPosition=new J),this._anchoredPosition}set anchoredPosition(e){this._anchoredPosition=e}sizeDelta=new J(100,100);pivot=new J(.5,.5);anchorMin=new J(0,0);anchorMax=new J(1,1);minWidth;minHeight;get width(){let e=this.sizeDelta.x;if(this.anchorMin.x!==this.anchorMax.x&&this._parentRectTransform){const t=this._parentRectTransform.width,i=this.anchorMax.x-this.anchorMin.x;e=t*i,e+=this.sizeDelta.x}return this.minWidth!==void 0&&e<this.minWidth?this.minWidth:e}get height(){let e=this.sizeDelta.y;if(this.anchorMin.y!==this.anchorMax.y&&this._parentRectTransform){const t=this._parentRectTransform.height,i=this.anchorMax.y-this.anchorMin.y;e=t*i,e+=this.sizeDelta.y}return this.minHeight!==void 0&&e<this.minHeight?this.minHeight:e}lastMatrix;rectBlock;_transformNeedsUpdate=!1;_initialPosition;_parentRectTransform;_lastUpdateFrame=-1;awake(){super.awake(),this._lastUpdateFrame=-1,this._parentRectTransform=void 0,this.rectBlock=new O,this.rectBlock.name=this.name,this.lastMatrix=new ee,this._lastAnchoring=null,this._initialPosition=this.gameObject.position.clone(),this._initialPosition.z=0,this._anchoredPosition||(this._anchoredPosition=new J),Va(this,"_anchoredPosition",()=>{this.markDirty()}),Va(this,"sizeDelta",()=>{this.markDirty()}),Va(this,"pivot",()=>{this.markDirty()}),Va(this,"anchorMin",()=>{this.markDirty()}),Va(this,"anchorMax",()=>{this.markDirty()})}onEnable(){super.onEnable(),this.rectBlock||(this.rectBlock=new O),this.lastMatrix||(this.lastMatrix=new ee),this._lastAnchoring||(this._lastAnchoring=new J),this._initialPosition||(this._initialPosition=new b),this._anchoredPosition||(this._anchoredPosition=new J),this.addShadowComponent(this.rectBlock),this._transformNeedsUpdate=!0,this.canvas?.registerTransform(this)}onDisable(){super.onDisable(),this.removeShadowComponent(),this.canvas?.unregisterTransform(this)}onParentRectTransformChanged(e){this._transformNeedsUpdate||this.onApplyTransform(py?`${e.name} changed`:void 0)}get isDirty(){return this._transformNeedsUpdate||(this._transformNeedsUpdate=!this.lastMatrix.equals(this.gameObject.matrix)),this._transformNeedsUpdate}markDirty(){this._transformNeedsUpdate||(py&&console.warn("RectTransform markDirty()",this.name),this._transformNeedsUpdate=!0,this._lastUpdateFrame=-1)}updateTransform(){(this._transformNeedsUpdate||!this.lastMatrix.equals(this.gameObject.matrix))&&this.canUpdate()&&this.onApplyTransform(this._transformNeedsUpdate?"Marked dirty":"Matrix changed")}canUpdate(){return this._transformNeedsUpdate&&this.activeAndEnabled&&this._lastUpdateFrame!==this.context.time.frame}onApplyTransform(e){if(this.context.time.frameCount===this._lastUpdateFrame)return;this._lastUpdateFrame=this.context.time.frameCount;const t=this.shadowComponent;if(!t)return;this.gameObject.parent?this._parentRectTransform=x.getComponentInParent(this.gameObject.parent,H1):this._parentRectTransform=void 0,this._transformNeedsUpdate=!1,py&&console.warn("RectTransform \u2192 ApplyTransform",this.name+" because "+e),this.isRoot()?this.Root.screenspace||(t.rotation.y=Math.PI):(t.matrix.identity(),t.matrixAutoUpdate=!1,Sn.set(0,0,0),this.applyPivot(Sn),t.matrix.setPosition(Sn.x,Sn.y,0),(this.gameObject.quaternion.x||this.gameObject.quaternion.y||this.gameObject.quaternion.z)&&(ep.copy(this.gameObject.quaternion),ep.x*=-1,ep.z*=-1,Yc.makeRotationFromQuaternion(ep),t.matrix.premultiply(Yc)),Sn.set(0,0,0),this.applyAnchoring(Sn),this.canvas?.screenspace?Sn.z+=.1:Sn.z+=.01,Yc.identity(),Yc.setPosition(Sn.x,Sn.y,Sn.z),t.matrix.premultiply(Yc),t.matrix.scale(this.gameObject.scale)),this.lastMatrix.copy(this.gameObject.matrix);const i=!0;for(const n of eu(this.gameObject,rn,i,1)){if(n===this||!n.activeAndEnabled)continue;const s=n;s.onParentRectTransformChanged&&s.onParentRectTransformChanged(this)}}_lastAnchoring;applyAnchoring(e){this._lastAnchoring||(this._lastAnchoring=new J);const t=this._lastAnchoring.sub(this._anchoredPosition);this.gameObject.position.x+=t.x,this.gameObject.position.y+=t.y,this._lastAnchoring.copy(this._anchoredPosition),e.x+=this._initialPosition.x-this.gameObject.position.x,e.y+=this._initialPosition.y-this.gameObject.position.y,e.z+=this._initialPosition.z-this.gameObject.position.z;const i=this._parentRectTransform;if(i){let n=0;const s=1-this.anchorMax.y-this.anchorMin.y;n-=i.height*.5*s,e.y+=n;let r=0;const a=1-this.anchorMax.x-this.anchorMin.x;r-=i.width*.5*a,e.x+=r}}applyPivot(e){if(this.pivot&&!this.isRoot()){const t=this.pivot.x-.5;e.x-=t*this.sizeDelta.x*this.gameObject.scale.x;const i=this.pivot.y-.5;e.y-=i*this.sizeDelta.y*this.gameObject.scale.y}}getBasicOptions(){const e={width:this.sizeDelta.x,height:this.sizeDelta.y,offset:0,backgroundOpacity:0,borderWidth:0,borderRadius:0,borderOpacity:0,letterSpacing:-.03};return this.ensureValidSize(e),e}ensureValidSize(e,t=1e-4){return e.width<=0&&(e.width=t),e.height<=0&&(e.height=1e-4),e}_createdBlocks=[];_createdTextBlocks=[];createNewBlock(e){e={...this.getBasicOptions(),...e},uy&&console.log(this.name,e);const t=new rb(e);return this._createdBlocks.push(t),t}createNewText(e){uy&&console.log(e),e={...this.getBasicOptions(),...e},uy&&console.log(this.name,e);const t=new sb(e);return this._createdTextBlocks.push(t),t}};Qc([u(J)],cl.prototype,"anchoredPosition",1),Qc([u(J)],cl.prototype,"sizeDelta",2),Qc([u(J)],cl.prototype,"pivot",2),Qc([u(J)],cl.prototype,"anchorMin",2),Qc([u(J)],cl.prototype,"anchorMax",2);let Cn=cl;var rE=Object.defineProperty,Rx=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&rE(e,t,n),n};class hl extends M{effectColor;effectDistance}Rx([u(se)],hl.prototype,"effectColor"),Rx([u(J)],hl.prototype,"effectDistance");var aE=Object.defineProperty,lE=Object.getOwnPropertyDescriptor,Tx=(o,e,t,i)=>{for(var n=i>1?void 0:i?lE(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&aE(e,t,n),n};const tp={backgroundColor:new ne(1,1,1),backgroundOpacity:1,borderColor:new ne(1,1,1),borderOpacity:1},my=class Xh extends rn{get isGraphic(){return!0}get color(){return this._color||(this._color=new se(1,1,1,1)),this._color}set color(e){(!this._color||this._color.r!==e.r||this._color.g!==e.g||this._color.b!==e.b||this._color.alpha!==e.alpha)&&(this._color||(this._color=new se(1,1,1,1)),this._color.copy(e),this.onColorChanged())}_alphaFactor=1;setAlphaFactor(e){this._alphaFactor=e,this.onColorChanged()}get alphaFactor(){return this._alphaFactor}sRGBColor=new ne(1,0,1);onColorChanged(){this.uiObject&&(this.sRGBColor.copy(this._color),this.sRGBColor.convertLinearToSRGB(),tp.backgroundColor=this.sRGBColor,tp.backgroundOpacity=this._color.alpha*this._alphaFactor,this.applyEffects(tp,this._alphaFactor),this.uiObject.set(tp),this.markDirty())}get m_Color(){return this._color}raycastTarget=!0;uiObject=null;_color=null;_rect=null;_stateManager=null;get rectTransform(){if(this._rect||(this._rect=x.getComponent(this.gameObject,Cn)),!this._rect)throw new Error("Not Supported: Make sure to add a RectTransform component before adding a UI Graphic component.");return this._rect}onParentRectTransformChanged(){this.uiObject?.set({width:this.rectTransform.width,height:this.rectTransform.height}),this.markDirty()}__internalNewInstanceCreated(e){return super.__internalNewInstanceCreated(e),this._rect=null,this.uiObject=null,this._stateManager=null,this._color&&(this._color=this._color.clone()),this}setState(e){this.makePanel(),this.uiObject&&(this.uiObject.setState(e),this?.markDirty())}setupState(e){this.makePanel(),this.uiObject&&(this._stateManager||(this._stateManager=new qC(this.uiObject)),this.uiObject.setupState(e.state,e.attributes))}setOptions(e){this.makePanel(),this.uiObject&&this.uiObject.set(e)}awake(){super.awake(),this.makePanel(),Va(this,"_color",()=>nR(this,this.onColorChanged))}onEnable(){super.onEnable(),this.uiObject&&(this.rectTransform.shadowComponent?.add(this.uiObject),this.addShadowComponent(this.uiObject,this.rectTransform))}onDisable(){super.onDisable(),this.uiObject&&this.removeShadowComponent()}_currentlyCreatingPanel=!1;makePanel(){if(this.uiObject||this._currentlyCreatingPanel)return;this._currentlyCreatingPanel=!0;const e={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:.015};this.onBeforeCreate(e),this.applyEffects(e),this.onCreate(e),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated(),this.onColorChanged()}onBeforeCreate(e){}onCreate(e){this.uiObject=this.rectTransform.createNewBlock(e),this.uiObject.name=this.name}onAfterCreated(){}applyEffects(e,t=1){const i=this.gameObject?.getComponent(hl);i&&(i.effectDistance&&(e.borderWidth=Math.max(Math.abs(i.effectDistance.x),Math.abs(i.effectDistance.y))),i.effectColor&&(e.borderColor=i.effectColor,e.borderOpacity=i.effectColor.alpha*t))}static textureCache=new Map;async setTexture(e){if(this.setOptions({backgroundOpacity:0}),e){if(Xh.textureCache.has(e))e=Xh.textureCache.get(e);else if(!e.isRenderTargetTexture){const t=e.clone();t.colorSpace=po,Xh.textureCache.set(e,t),e=t}this.setOptions({backgroundImage:e,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"}),Ve.assignTextureLOD(e,0).then(t=>{t instanceof Re&&(e&&Xh.textureCache.set(e,t),this.setOptions({backgroundImage:t}),this.markDirty())})}else this.setOptions({backgroundImage:void 0,borderRadius:0,backgroundOpacity:this.color.alpha});this.markDirty()}onAfterAddedToScene(){super.onAfterAddedToScene(),this.shadowComponent&&(this.shadowComponent.offset=this.shadowComponent.position.z)}};Tx([u(se)],my.prototype,"color",1),Tx([u()],my.prototype,"raycastTarget",2);let Kc=my;class Zc extends Kc{_flippedObject=!1;onAfterCreated(){this.uiObject&&!this._flippedObject&&(this._flippedObject=!0,this.uiObject.scale.y*=-1)}}var cE=Object.defineProperty,hE=Object.getOwnPropertyDescriptor,Bo=(o,e,t,i)=>{for(var n=i>1?void 0:i?hE(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&cE(e,t,n),n};const Fr=w("debugtext");var at=(o=>(o[o.UpperLeft=0]="UpperLeft",o[o.UpperCenter=1]="UpperCenter",o[o.UpperRight=2]="UpperRight",o[o.MiddleLeft=3]="MiddleLeft",o[o.MiddleCenter=4]="MiddleCenter",o[o.MiddleRight=5]="MiddleRight",o[o.LowerLeft=6]="LowerLeft",o[o.LowerCenter=7]="LowerCenter",o[o.LowerRight=8]="LowerRight",o))(at||{}),Ex=(o=>(o[o.Normal=0]="Normal",o[o.Bold=1]="Bold",o[o.Italic=2]="Italic",o[o.BoldAndItalic=3]="BoldAndItalic",o))(Ex||{});class Dt extends Kc{alignment=0;verticalOverflow=0;horizontalOverflow=0;lineSpacing=1;supportRichText=!1;font;fontStyle=0;setAlphaFactor(e){super.setAlphaFactor(e),this.uiObject?.set({fontOpacity:this.color.alpha*this.alphaFactor}),this.markDirty()}get text(){return this._text}set text(e){e!==this._text&&(this._text=e,this.feedText(this.text,this.supportRichText),this.markDirty())}set_text(e){this.text=e}get fontSize(){return this._fontSize}set fontSize(e){this._fontSize=e,this.uiObject?.set({fontSize:e})}sRGBTextColor=new ne(1,0,1);onColorChanged(){this.sRGBTextColor.copy(this.color),this.sRGBTextColor.convertLinearToSRGB(),this.uiObject?.set({color:this.sRGBTextColor,fontOpacity:this.color.alpha})}onParentRectTransformChanged(){super.onParentRectTransformChanged(),this.uiObject&&this.updateOverflow()}onBeforeCanvasRender(e){this.updateOverflow()}updateOverflow(){const e=this.uiObject?._overflow;e&&(e._needsUpdate=!0)}onCreate(e){Fr&&console.log(this),this.horizontalOverflow==1&&(e.whiteSpace="pre"),this.verticalOverflow==0&&(this.context.renderer.localClippingEnabled=!0,e.overflow="hidden"),this.horizontalOverflow==1&&this.verticalOverflow==0,e.lineHeight=this.lineSpacing,delete e.backgroundOpacity,delete e.backgroundColor,Fr&&(e.backgroundColor=16750848,e.backgroundOpacity=.5);const t=this.rectTransform;e={...e,...this.getTextOpts()},this.getAlignment(e),Fr&&(e.backgroundColor=Math.random()*16777215,e.backgroundOpacity=.1),this.uiObject=t.createNewText(e),this.feedText(this.text,this.supportRichText)}onAfterAddedToScene(){super.onAfterAddedToScene(),this.handleTextRenderOnTop()}_text="";_fontSize=12;_textMeshUi=null;getTextOpts(){const e=this.fontSize,t={color:this.color,fontOpacity:this.color.alpha,fontSize:e,fontKerning:"normal"};return this.setFont(t,this.fontStyle),t}onEnable(){super.onEnable(),this._didHandleTextRenderOnTop=!1,this.uiObject&&this.uiObject.addAfterUpdate(()=>{this.setShadowComponentOwner(this.uiObject),this.markDirty()}),setTimeout(()=>this.markDirty(),10),this.canvas?.registerEventReceiver(this)}onDisable(){super.onDisable(),this.canvas?.unregisterEventReceiver(this)}getAlignment(e){switch(e.flexDirection="column",this.alignment){case 0:case 3:case 6:e.textAlign="left";break;case 1:case 4:case 7:e.textAlign="center";break;case 2:case 5:case 8:e.textAlign="right";break}switch(this.alignment){default:case 0:case 1:case 2:e.alignItems="start";break;case 3:case 4:case 5:e.alignItems="center";break;case 6:case 7:case 8:e.alignItems="end";break}return e}feedText(e,t){if(Fr&&console.log("feedText",this.uiObject,e,t),!!this.uiObject)if(this._textMeshUi||(this._textMeshUi=[]),this.uiObject.children.length=0,!t||e.length===0)this.uiObject.textContent=e;else{let i=this.getNextTag(e);if(i){if(i.startIndex>0){for(let r=this.uiObject.children.length-1;r>=0;r--){const a=this.uiObject.children[r];a.isUI&&(this.uiObject.remove(a),a.clear())}const s=new bm({textContent:e.substring(0,i.startIndex),color:"inherit"});this.uiObject.add(s)}}else{this.uiObject.textContent="",this.setOptions({textContent:e});return}const n=[];for(;i;){const s=this.getNextTag(e,i.endIndex),r={fontFamily:this.uiObject?.get("fontFamily"),color:"inherit",textContent:""};if(s){r.textContent=this.getText(e,i,s),this.handleTag(i,r,n);const a=new bm(r);this.uiObject?.add(a)}else{r.textContent=e.substring(i.endIndex),this.handleTag(i,r,n);const a=new bm(r);this.uiObject?.add(a)}i=s}}}_didHandleTextRenderOnTop=!1;handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;const e=[],t=this.canvas,i={renderOnTop:t.renderOnTop,depthWrite:t.depthWrite,doubleSided:t.doubleSided};for(;;){let n=!1;if(this._textMeshUi)for(let s=0;s<this._textMeshUi.length;s++){if(e[s]===!0)continue;n=!0;const r=this._textMeshUi[s];r.textContent&&(wu(r,i),e[s]=!0)}if(!n)break;yield}}handleTag(e,t,i){if(!e.isEndTag){if(e.type.includes("color")){const n=new gy(e,{color:t.color});if(i.push(n),e.type.length>6){const s=parseInt("0x"+e.type.substring(7));t.color=s}else t.color=new ne(1,1,1)}else if(e.type=="b"){this.setFont(t,1);const n=new gy(e,{fontWeight:700});i.push(n)}else if(e.type=="i"){this.setFont(t,2);const n=new gy(e,{fontStyle:"italic"});i.push(n)}}}getText(e,t,i){return e.substring(t.endIndex,i.startIndex)}getNextTag(e,t=0){const i=e.indexOf("<",t),n=e.indexOf(">",i);if(i>=0&&n>=0){const s=e.substring(i+1,n);return{type:s,startIndex:i,endIndex:n+1,isEndTag:s.startsWith("/")}}return null}setFont(e,t){if(!this.font)return;const i=this.font,n=this.getFamilyNameWithCorrectSuffix(i,t);Fr&&console.log("Selected font family:"+n);let s=ab.getFontFamily(n);switch(s||(s=ab.addFontFamily(n)),e.fontFamily=s,t){default:case 0:e.fontWeight=400,e.fontStyle="normal";break;case 1:e.fontWeight=700,e.fontStyle="normal";break;case 2:e.fontWeight=400,e.fontStyle="italic";break;case 3:e.fontStyle="italic",e.fontWeight=400}let r=s.getVariant(e.fontWeight,e.fontStyle);if(!r){let a=n;a?.endsWith("-msdf.json")||(a+="-msdf.json");let l=n;l?.endsWith(".png")||(l+=".png"),r=s.addVariant(e.fontWeight,e.fontStyle,a,l),r?.addEventListener("ready",()=>{this.markDirty()})}}getFamilyNameWithCorrectSuffix(e,t){const i=e.lastIndexOf("-");if(i<0)return e;const n=e.substring(i+1)?.toLowerCase();if(dE.includes(n))return Fr&&console.warn("Unsupported font style: "+n),e;const s=e.lastIndexOf("/");let r=e;s>=0&&(r=r.substring(s+1));const a=r[0]===r[0].toUpperCase(),l=e.substring(0,i);switch(Fr&&console.log("Select font: ",e,Ex[t],r,a,l),t){case 0:return a?l+"-Regular":l+"-regular";case 1:return a?l+"-Bold":l+"-bold";case 2:return a?l+"-Italic":l+"-italic";case 3:return a?l+"-BoldItalic":l+"-bolditalic";default:return e}}}Bo([u()],Dt.prototype,"alignment",2),Bo([u()],Dt.prototype,"verticalOverflow",2),Bo([u()],Dt.prototype,"horizontalOverflow",2),Bo([u()],Dt.prototype,"lineSpacing",2),Bo([u()],Dt.prototype,"supportRichText",2),Bo([u(URL)],Dt.prototype,"font",2),Bo([u()],Dt.prototype,"fontStyle",2),Bo([u()],Dt.prototype,"text",1),Bo([u()],Dt.prototype,"fontSize",1);class gy{tag;previousValues;constructor(e,t){this.tag=e,this.previousValues=t}}const dE=["medium","mediumitalic","black","blackitalic","thin","thinitalic","extrabold","light","lightitalic","semibold"];class dl{static global_id=0;static getId(){return this.global_id++}id;content="";font=[];pointSize=144;width;height;depth;wrapMode;horizontalAlignment;verticalAlignment;material;setDepth(e){return this.depth=e,this}setPointSize(e){return this.pointSize=e,this}setHorizontalAlignment(e){return this.horizontalAlignment=e,this}setVerticalAlignment(e){return this.verticalAlignment=e,this}constructor(e){this.id=e}writeTo(e,t){t.beginBlock(`def Preliminary_Text "${this.id}"`,"(",!1),t.appendLine('prepend apiSchemas = ["MaterialBindingAPI"]'),t.closeBlock(")"),t.beginBlock(),this.content&&t.appendLine(`string content = "${this.content}"`),(!this.font||this.font.length<=0)&&(this.font||=[],this.font?.push("sans-serif"));const i=this.font.map(n=>`"${n}"`).join(", ");t.appendLine(`string[] font = [ ${i} ]`),t.appendLine(`double pointSize = ${this.pointSize}`),typeof this.width=="number"&&t.appendLine(`double width = ${this.width}`),typeof this.height=="number"&&t.appendLine(`double height = ${this.height}`),typeof this.depth=="number"&&t.appendLine(`double depth = ${this.depth}`),this.wrapMode&&t.appendLine(`token wrapMode = "${this.wrapMode}"`),this.horizontalAlignment&&t.appendLine(`token horizontalAlignment = "${this.horizontalAlignment}"`),this.verticalAlignment&&t.appendLine(`token verticalAlignment = "${this.verticalAlignment}"`),this.material!==void 0&&t.appendLine(`rel material:binding = </StageRoot/Materials/${Vu(this.material)}>`),t.closeBlock()}}class fy{static singleLine(e,t,i){const n=new dl("text_"+dl.getId());return n.content=e,t&&(n.pointSize=t),i&&(n.depth=i),n}static multiLine(e,t,i,n,s,r){const a=new dl("text_"+dl.getId());return a.content=e,a.width=t,a.height=i,a.horizontalAlignment=n,a.verticalAlignment=s,r!==void 0&&(a.wrapMode=r),a}}const uE=new ee().makeRotationY(Math.PI),pE=new ee().makeScale(-1,1,-1);class ip{get extensionName(){return"text"}exportText(e,t,i){const n=x.getComponent(e,Dt);if(!n)return;const s=x.getComponent(e,Cn);let r=100,a=100;s&&(r=s.width,a=s.height);const l=uE.clone();s&&l.premultiply(pE),t.setMatrix(l);const c=n.color.clone();t.material=new ut({color:c,emissive:c}),t.addEventListener("serialize",(h,d)=>{let p=n.text;p=p.replace(/\r/g,""),p=p.replace(/\n/g,"\\n");const m=fy.multiLine(p,r,a,"center","bottom","flowing");this.setTextAlignment(m,n.alignment),this.setOverflow(m,n),t.material&&(m.material=t.material),m.pointSize=this.convertToTextSize(n.fontSize),m.depth=.001,m.writeTo(void 0,h)})}convertToTextSize(e){return 1/.0502*144*e}setOverflow(e,t){t.horizontalOverflow?e.wrapMode="singleLine":e.wrapMode="flowing"}setTextAlignment(e,t){switch(t){case at.LowerLeft:case at.MiddleLeft:case at.UpperLeft:e.horizontalAlignment="left";break;case at.LowerCenter:case at.MiddleCenter:case at.UpperCenter:e.horizontalAlignment="center";break;case at.LowerRight:case at.MiddleRight:case at.UpperRight:e.horizontalAlignment="right";break}switch(t){case at.LowerLeft:case at.LowerCenter:case at.LowerRight:e.verticalAlignment="bottom";break;case at.MiddleLeft:case at.MiddleCenter:case at.MiddleRight:e.verticalAlignment="middle";break;case at.UpperLeft:case at.UpperCenter:case at.UpperRight:e.verticalAlignment="top";break}}}var mE=Object.defineProperty,Ke=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&mE(e,t,n),n};const Ax=w("debuguilayout");class Ur{left=0;right=0;top=0;bottom=0;get vertical(){return this.top+this.bottom}get horizontal(){return this.left+this.right}}Ke([u()],Ur.prototype,"left"),Ke([u()],Ur.prototype,"right"),Ke([u()],Ur.prototype,"top"),Ke([u()],Ur.prototype,"bottom");class Ai extends M{_rectTransform=null;get rectTransform(){return this._rectTransform}onParentRectTransformChanged(e){this._needsUpdate=!0}_needsUpdate=!1;get isDirty(){return this._needsUpdate}get isLayoutGroup(){return!0}updateLayout(){this._rectTransform&&(Ax&&console.warn("Layout Update",this.context.time.frame,this.name),this._needsUpdate=!1,this.onCalculateLayout(this._rectTransform))}childAlignment=0;reverseArrangement=!1;spacing=0;padding;minWidth=0;minHeight=0;flexibleHeight=0;flexibleWidth=0;preferredHeight=0;preferredWidth=0;start(){this._needsUpdate=!0}onEnable(){Ax&&console.log(this.name,this),this._rectTransform=this.gameObject.getComponent(Cn);const e=this.gameObject.getComponentInParent(ul);e&&e.registerLayoutGroup(this),this._needsUpdate=!0}onDisable(){const e=this.gameObject.getComponentInParent(ul);e&&e.unregisterLayoutGroup(this)}set m_Spacing(e){e!==this.spacing&&(this._needsUpdate=!0,this.spacing=e)}get m_Spacing(){return this.spacing}}Ke([u()],Ai.prototype,"childAlignment"),Ke([u()],Ai.prototype,"reverseArrangement"),Ke([u()],Ai.prototype,"spacing"),Ke([u(Ur)],Ai.prototype,"padding"),Ke([u()],Ai.prototype,"minWidth"),Ke([u()],Ai.prototype,"minHeight"),Ke([u()],Ai.prototype,"flexibleHeight"),Ke([u()],Ai.prototype,"flexibleWidth"),Ke([u()],Ai.prototype,"preferredHeight"),Ke([u()],Ai.prototype,"preferredWidth");class As extends Ai{childControlHeight=!0;childControlWidth=!0;childForceExpandHeight=!1;childForceExpandWidth=!1;childScaleHeight=!1;childScaleWidth=!1;onCalculateLayout(e){const t=this.primaryAxis,i=e.width;let n=i;const s=e.height;let r=s;n-=this.padding.horizontal,r-=this.padding.vertical,t==="x"?this.padding.horizontal:this.padding.vertical;const a=t==="x",l=a?"y":"x",c=a?this.childControlWidth:this.childControlHeight,h=a?this.childControlHeight:this.childControlWidth,d=a?this.childForceExpandWidth:this.childForceExpandHeight,p=a?this.childForceExpandHeight:this.childForceExpandWidth,m=a?r:n,f=a?i:s,g=.5*(a?this.childAlignment%3:Math.floor(this.childAlignment/3));let y=0;a?y+=this.padding.left:y+=this.padding.top;let _=0,v=0;for(let L=0;L<this.gameObject.children.length;L++){const N=this.gameObject.children[L],j=x.getComponent(N,Cn);j?.activeAndEnabled&&(v+=1,a?_+=j.width:_+=j.height)}let P=0;const R=this.spacing*(v-1);if(d||c){let L=0;a?L=n-=R:L=r-=R,v>0&&(P=L/v)}let k=0;k+=this.padding.left,k-=this.padding.right,g!==0&&(y=f-_,y*=g,y-=R*g,a?(y-=this.padding.right*g,y+=this.padding.left*(1-g),y<this.padding.left&&(y=this.padding.left)):(y-=this.padding.bottom*g,y+=this.padding.top*(1-g),y<this.padding.top&&(y=this.padding.top)));let A=1;for(let L=0;L<this.gameObject.children.length;L++){const N=this.gameObject.children[L],j=x.getComponent(N,Cn);if(j?.activeAndEnabled){j.pivot?.set(.5,.5),j.anchorMin.set(0,1),j.anchorMax.set(0,1);const q=i*.5+k*.5;j.anchoredPosition.x!==q&&(j.anchoredPosition.x=q);const Y=s*-.5;j.anchoredPosition.y!==Y&&(j.anchoredPosition.y=Y),p&&h&&j.sizeDelta[l]!==m&&(j.sizeDelta[l]=m),d&&c&&j.sizeDelta[t]!==P&&(j.sizeDelta[t]=P);const I=a?j.width:j.height,V=I*.5;if(y+=V,d){const oe=P*A-P*.5;oe>y&&(y=oe-P*.5+I+this.padding.left,y-=V)}let W=y;t==="y"&&(W=-W),j.anchoredPosition[t]!==W&&(j.anchoredPosition[t]=W),y+=V,y+=this.spacing,A+=1}}}}Ke([u()],As.prototype,"childControlHeight"),Ke([u()],As.prototype,"childControlWidth"),Ke([u()],As.prototype,"childForceExpandHeight"),Ke([u()],As.prototype,"childForceExpandWidth"),Ke([u()],As.prototype,"childScaleHeight"),Ke([u()],As.prototype,"childScaleWidth");class yy extends As{get primaryAxis(){return"y"}}class by extends As{get primaryAxis(){return"x"}}class _y extends Ai{onCalculateLayout(){}}var gE=Object.defineProperty,fE=Object.getOwnPropertyDescriptor,eo=(o,e,t,i)=>{for(var n=i>1?void 0:i?fE(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&gE(e,t,n),n},Ix=(o=>(o[o.ScreenSpaceOverlay=0]="ScreenSpaceOverlay",o[o.ScreenSpaceCamera=1]="ScreenSpaceCamera",o[o.WorldSpace=2]="WorldSpace",o[o.Undefined=-1]="Undefined",o))(Ix||{});const vy=w("debuguilayout"),en=class G1 extends Xc{get isCanvas(){return!0}get screenspace(){return this.renderMode!==2}set renderOnTop(e){e!==this._renderOnTop&&(this._renderOnTop=e,this.onRenderSettingsChanged())}get renderOnTop(){return this._renderOnTop!==void 0?this._renderOnTop:!!(this.screenspace&&this._renderMode===0)}_renderOnTop;set depthWrite(e){this._depthWrite!==e&&(this._depthWrite=e,this.onRenderSettingsChanged())}get depthWrite(){return this._depthWrite}_depthWrite=!1;set doubleSided(e){this._doubleSided!==e&&(this._doubleSided=e,this.onRenderSettingsChanged())}get doubleSided(){return this._doubleSided}_doubleSided=!0;set castShadows(e){this._castShadows!==e&&(this._castShadows=e,this.onRenderSettingsChanged())}get castShadows(){return this._castShadows}_castShadows=!1;set receiveShadows(e){this._receiveShadows!==e&&(this._receiveShadows=e,this.onRenderSettingsChanged())}get receiveShadows(){return this._receiveShadows}_receiveShadows=!1;get renderMode(){return this._renderMode}set renderMode(e){this._renderMode!==e&&(this._renderMode=e,this.onRenderSettingsChanged())}_renderMode=-1;_rootCanvas;set rootCanvas(e){this._rootCanvas instanceof G1||(this._rootCanvas=e)}get rootCanvas(){return this._rootCanvas}_scaleFactor=1;get scaleFactor(){return this._scaleFactor}set scaleFactor(e){this._scaleFactor=e}worldCamera;planeDistance=-1;awake(){this.shadowComponent=this.gameObject,this.previousParent=this.gameObject.parent,vy&&console.log("Canvas.Awake()",this.previousParent?.name+"/"+this.gameObject.name),super.awake()}start(){this.applyRenderSettings()}onEnable(){super.onEnable(),this._updateRenderSettingsRoutine=void 0,this._lastMatrixWorld=new ee,this.applyRenderSettings(),document.addEventListener("resize",this._boundRenderSettingsChanged),this.context.pre_render_callbacks.push(this.onBeforeRenderRoutine),this.context.post_render_callbacks.push(this.onAfterRenderRoutine)}onDisable(){super.onDisable(),document.removeEventListener("resize",this._boundRenderSettingsChanged);const e=this.context.pre_render_callbacks.indexOf(this.onBeforeRenderRoutine);e!==-1&&this.context.pre_render_callbacks.splice(e,1);const t=this.context.post_render_callbacks.indexOf(this.onAfterRenderRoutine);t!==-1&&this.context.post_render_callbacks.splice(t,1)}_boundRenderSettingsChanged=this.onRenderSettingsChanged.bind(this);previousParent=null;_lastMatrixWorld=null;_rectTransforms=[];registerTransform(e){this._rectTransforms.push(e)}unregisterTransform(e){const t=this._rectTransforms.indexOf(e);t!==-1&&this._rectTransforms.splice(t,1)}_layoutGroups=new Map;registerLayoutGroup(e){const t=e.gameObject;this._layoutGroups.set(t,e)}unregisterLayoutGroup(e){const t=e.gameObject;this._layoutGroups.delete(t)}_receivers=[];registerEventReceiver(e){this._receivers.push(e)}unregisterEventReceiver(e){const t=this._receivers.indexOf(e);t!==-1&&this._receivers.splice(t,1)}async onEnterXR(e){this.screenspace?(e.xr.isVR||e.xr.isPassThrough)&&(this.gameObject.visible=!1):(this.gameObject.visible=!1,await Wl(1).then(()=>{this.gameObject.visible=!0}))}onLeaveXR(e){this.screenspace&&(e.xr.isVR||e.xr.isPassThrough)&&(this.gameObject.visible=!0)}onBeforeRenderRoutine=()=>{if(this.previousParent=this.gameObject.parent,(this.context.xr?.isVR||this.context.xr?.isPassThrough)&&this.screenspace){this.gameObject.visible=!1,this.gameObject.removeFromParent();return}this.renderOnTop||this.screenspace?this.gameObject.removeFromParent():(this.onUpdateRenderMode(),this.handleLayoutUpdates(),this.shadowComponent?.updateMatrixWorld(!0),this.shadowComponent?.updateWorldMatrix(!0,!0),this.invokeBeforeRenderEvents(),ei.ensureUpdateMeshUI(lb,this.context))};onAfterRenderRoutine=()=>{if((this.context.xr?.isVR||this.context.xr?.isPassThrough)&&this.screenspace){this.previousParent?.add(this.gameObject);return}if((this.screenspace||this.renderOnTop)&&this.previousParent&&this.context.mainCamera){this.screenspace?this.context.mainCamera?.add(this.gameObject):this.previousParent.add(this.gameObject);const e=this.context.renderer.autoClear,t=this.context.renderer.autoClearColor;this.context.renderer.autoClear=!1,this.context.renderer.autoClearColor=!1,this.context.renderer.clearDepth(),this.onUpdateRenderMode(!0),this.handleLayoutUpdates(),this.shadowComponent?.updateMatrixWorld(!0),this.invokeBeforeRenderEvents(),ei.ensureUpdateMeshUI(lb,this.context,!0),this.context.renderer.render(this.gameObject,this.context.mainCamera),this.context.renderer.autoClear=e,this.context.renderer.autoClearColor=t,this.previousParent.add(this.gameObject)}this._lastMatrixWorld?.copy(this.gameObject.matrixWorld)};invokeBeforeRenderEvents(){for(const e of this._receivers)e.onBeforeCanvasRender?.(this)}handleLayoutUpdates(){this._lastMatrixWorld===null&&(this._lastMatrixWorld=new ee);const e=!this._lastMatrixWorld.equals(this.gameObject.matrixWorld);vy&&e&&console.log("Canvas Layout changed",this.context.time.frameCount,this.name);for(const t of this._rectTransforms){e&&t.markDirty();let i=this._layoutGroups.get(t.gameObject);t.isDirty&&!i&&(i=t.gameObject.getComponentInParent(Ai)),(t.isDirty||i?.isDirty)&&(vy&&console.log("CANVAS UPDATE ### "+t.name+" ##################################### "+this.context.time.frame),i?.updateLayout(),t.updateTransform())}}applyRenderSettings(){this.onRenderSettingsChanged()}_updateRenderSettingsRoutine;onRenderSettingsChanged(){this._updateRenderSettingsRoutine||(this._updateRenderSettingsRoutine=this.startCoroutine(this._updateRenderSettingsDelayed(),we.OnBeforeRender))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.onUpdateRenderMode(),wu(this.shadowComponent,this);for(const e of x.getComponentsInChildren(this.gameObject,rn))wu(e.shadowComponent,this)}}_activeRenderMode=-1;_lastWidth=-1;_lastHeight=-1;onUpdateRenderMode(e=!1){if(!e&&this._renderMode===this._activeRenderMode&&this._lastWidth===this.context.domWidth&&this._lastHeight===this.context.domHeight)return;this._activeRenderMode=this._renderMode;let t=this.context.mainCameraComponent,i=10;switch(t&&t.nearClipPlane>0&&t.farClipPlane>0&&(i=D.lerp(t.nearClipPlane,t.farClipPlane,.01)),this._renderMode===1&&(this.worldCamera&&(t=this.worldCamera),this.planeDistance>0&&(i=this.planeDistance)),this._renderMode){case 0:case 1:if(this._lastWidth=this.context.domWidth,this._lastHeight=this.context.domHeight,!t)return;const n=i+.01;this.gameObject.position.x=0,this.gameObject.position.y=0,this.gameObject.position.z=-n,this.gameObject.quaternion.identity();const s=this.gameObject.getComponent(Cn);let r=!1;s.sizeDelta.x!==this.context.domWidth&&(r=!0),s.sizeDelta.y!==this.context.domHeight&&(r=!0);const a=t.fieldOfView*Math.PI/180,l=2*Math.tan(a/2)*Math.abs(n);this.gameObject.scale.x=l/this.context.domHeight,this.gameObject.scale.y=l/this.context.domHeight,this.gameObject.scale.z=.01,r&&(s.sizeDelta.x=this.context.domWidth,s.sizeDelta.y=this.context.domHeight,s?.markDirty());break;case 2:this._lastWidth=-1,this._lastHeight=-1;break}}};eo([u()],en.prototype,"renderOnTop",1),eo([u()],en.prototype,"depthWrite",1),eo([u()],en.prototype,"doubleSided",1),eo([u()],en.prototype,"castShadows",1),eo([u()],en.prototype,"receiveShadows",1),eo([u()],en.prototype,"renderMode",1),eo([u(en)],en.prototype,"rootCanvas",1),eo([u()],en.prototype,"scaleFactor",1),eo([u(si)],en.prototype,"worldCamera",2),eo([u()],en.prototype,"planeDistance",2);let ul=en;var yE=Object.defineProperty,bE=Object.getOwnPropertyDescriptor,wy=(o,e,t,i)=>{for(var n=i>1?void 0:i?bE(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&yE(e,t,n),n};class Is extends M{get alpha(){return this._alpha}set alpha(e){e!==this._alpha&&(this._alpha=e,this.markDirty())}get isCanvasGroup(){return!0}_alpha=1;interactable=!0;blocksRaycasts=!0;_isDirty=!1;markDirty(){this._isDirty||(this._isDirty=!0,this.startCoroutine(this.applyChangesDelayed(),we.OnBeforeRender))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}_buffer=[];applyChangesNow(){this._buffer.length=0;for(const e of x.getComponentsInChildren(this.gameObject,rn,this._buffer)){const t=e;t.setAlphaFactor&&t.setAlphaFactor(this._alpha)}}}wy([u()],Is.prototype,"alpha",1),wy([u()],Is.prototype,"interactable",2),wy([u()],Is.prototype,"blocksRaycasts",2);class xy{get extensionName(){return"tmui"}onExportObject(e,t,i){const n=x.getComponent(e,ul);if(n&&n.enabled&&n.renderMode===Ix.WorldSpace){const s=new ip,r=x.getComponent(e,Cn),a=x.getComponent(e,Is),l=new Array;if(r){if(!x.isActiveSelf(e)){const d=x.isActiveSelf(e);x.setActive(e,!0),r.onEnable(),r.updateTransform(),l.push(()=>{r.onDisable(),x.setActive(e,d)})}e.traverse(d=>{if(!x.isActiveInHierarchy(d)){const p=x.isActiveSelf(d);x.setActive(d,!0);const m=x.getComponent(d,rn);m&&(m.onEnable(),l.push(()=>{m.onDisable()}));const f=x.getComponent(d,Cn);f&&(f.onEnable(),f.updateTransform(),f.onApplyTransform(),l.push(()=>{f.onDisable()}));const g=x.getComponent(d,Dt);g&&(g.onEnable(),l.push(()=>{g.onDisable()})),l.push(()=>{x.setActive(d,p)})}}),r.width,r.height;const c=it.createEmpty(),h=r.shadowComponent;if(t.add(c),h){const d=h.matrix;c.setMatrix(d);const p=new Map,m=new Map;p.set(h,c),m.set(h,a?a.alpha:1),h.traverse(f=>{if(f===h)return;const g=it.createEmpty();g.setMatrix(f.matrix);const y=f.parent,_=!!y&&typeof y.textContent=="string"&&y.textContent.length>0;let v=m.get(y)||1;const P=x.getComponent(f,Is);if(P&&(v*=P.alpha),f instanceof H&&_){const k=f[Si];k?s.exportText(k.gameObject,g,i):console.error("Error when exporting UI: shadow component owner not found. This is likely a bug.",f)}if(f instanceof H&&!_){const k=f.geometry.clone();k.scale(1,1,-1),this.flipWindingOrder(k),g.geometry=k;const A=new ne,L=f.material.opacity;A.copy(f.material.color),g.material=new xe({color:A,opacity:L*v,map:f.material.map,transparent:!0})}p.set(f,g),m.set(f,v);const R=p.get(y);if(!R){console.error("Error when exporting UI: shadow component parent not found!",f,f.parent);return}R.add(g)})}}for(const c of l)c()}}flipWindingOrder(e){const t=e.index.array;for(let i=0,n=t.length/3;i<n;i++){const s=t[i*3];t[i*3]=t[i*3+2],t[i*3+2]=s}e.index.needsUpdate=!0}}const Jc=w("debugusdz");function _E(o,e){const t=[],i=x.getComponentsInChildren(o,ft),n=x.getComponentsInChildren(o,Ht),s=new Array,r=new Array;if(e.injectImplicitBehaviours)for(const a of i){if(!a||!a.runtimeAnimatorController||!a.enabled)continue;const l=a.runtimeAnimatorController.activeState;if(!l||!l.motion||!l.motion.clip||l.motion.clip.tracks?.length<1||s.includes(a))continue;const c=new Nc;c.animator=a,c.stateName=l.name,c.trigger="start",c.name="PlayAnimationOnClick_implicitAtStart_"+c.stateName;const h=new O;x.addComponent(h,c),r.push(h),s.push(a),o.add(h)}else for(const a of i){if(!a||!a.runtimeAnimatorController||!a.enabled)continue;Jc&&console.log(a);const l=[];for(const c of a.runtimeAnimatorController.enumerateActions()){Jc&&console.log(c);const h=c.getClip();l.includes(h)||l.push(h)}t.push({root:a.gameObject,clips:l})}if(e.injectImplicitBehaviours)for(const a of n){if(!a||!a.clip||!a.enabled||!a.playAutomatically||s.includes(a))continue;const l=new Nc;l.animation=a,l.stateName=a.clip.name,l.trigger="start",l.name="PlayAnimationOnClick_implicitAtStart_"+l.stateName;const c=new O;x.addComponent(c,l),r.push(c),s.push(a),o.add(c)}else for(const a of n){Jc&&console.log(a);const l=[];for(const c of a.animations)l.includes(c)||l.push(c);t.push({root:a.gameObject,clips:l})}Jc&&t?.length>0&&console.log("USDZ Animation Clips without behaviours",t);for(const a of t)for(const l of a.clips)e.registerAnimation(a.root,l);return r}function vE(o,e){const t=x.getComponentsInChildren(o,Mi),i=x.getComponentsInChildren(o,Os),n=new Array,s=new Array;Jc&&console.log({audioSources:t,playAudioOnClicks:i});for(const r of i){if(!r.target)continue;const a=t.indexOf(r.target);a>-1&&t.splice(a,1)}for(const r of t){if(!r||!r.clip||r.volume<=0||n.includes(r))continue;const a=new Os;a.target=r,a.name="PlayAudioOnClick_implicitAtStart_",a.trigger="start";const l=new O;x.addComponent(l,a),console.log("implicit PlayAudioOnStart",l,a),s.push(l),n.push(r),o.add(l)}return s}function wE(o){return new Et("DisableAtStart",jt.sceneStartTrigger(),me.fadeAction(o,0,!1))}function Lx(o,e){const t=o.domElement.shadowRoot.querySelector("link[rel='ar']");if(t)return t;const i=document.createElement("div");i.classList.add("menu"),i.classList.add("quicklook-menu"),i.style.display="none",i.style.visibility="hidden";const n=document.createElement("button");n.id="open-in-ar",e?(n.innerText="View in AR",n.title="View this scene in AR. The scene will be exported to USDZ and opened with Apple's QuickLook."):(n.innerText="View in AR",n.title="Download this scene for AR. Open the downloaded USDZ file to view it in AR using Apple's QuickLook."),i.appendChild(n);const s=document.createElement("a");s.id="needle-usdz-link",s.style.display="none",s.rel="ar",s.href="",s.target="_blank",i.appendChild(s);const r=document.createElement("img");return r.id="button",s.appendChild(r),o.domElement.shadowRoot.appendChild(i),s}var xE=Object.defineProperty,kt=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&xE(e,t,n),n};const Ii=w("debugusdz"),SE=w("debugusdzpruning");class zr{callToAction;checkoutTitle;checkoutSubtitle;callToActionURL}kt([u()],zr.prototype,"callToAction"),kt([u()],zr.prototype,"checkoutTitle"),kt([u()],zr.prototype,"checkoutSubtitle"),kt([u()],zr.prototype,"callToActionURL");const hi=class Qh extends M{static beforeExport=new ce;static afterExport=new ce;objectToExport=void 0;autoExportAnimations=!0;autoExportAudioSources=!0;exportFileName=void 0;customUsdzFile=void 0;customBranding;anchoringType="plane";maxTextureSize=2048;planeAnchoringAlignment="horizontal";interactive=!0;physics=!0;allowCreateQuicklookButton=!0;quickLookCompatible=!0;extensions=[];link;button;start(){Ii&&(console.log("USDZExporter",this),console.log("Debug USDZ Mode. Press 'T' to export"),window.addEventListener("keydown",e=>{switch(e.key){case"t":this.exportAndOpen();break}})),this.objectToExport||(this.objectToExport=this.gameObject),!this.objectToExport?.children?.length&&!this.objectToExport?.isMesh&&(this.objectToExport=this.context.scene)}onEnable(){const e=G.supportsQuickLookAR(),t=G.isiOS()||G.isiPad();!this.button&&(Ii||e||t)&&(this.allowCreateQuicklookButton&&(this.button=this.createQuicklookButton()),this.lastCallback=this.quicklookCallback.bind(this),this.link=Lx(this.context,e),this.link.addEventListener("message",this.lastCallback)),Ii&&Te("USDZ Exporter enabled: "+this.name),document.getElementById("open-in-ar")?.addEventListener("click",this.onClickedOpenInARElement),ec.registerExporter(this)}onDisable(){this.button?.remove(),this.link?.removeEventListener("message",this.lastCallback),Ii&&Te("USDZ Exporter disabled: "+this.name),document.getElementById("open-in-ar")?.removeEventListener("click",this.onClickedOpenInARElement),ec.unregisterExporter(this)}onClickedOpenInARElement=e=>{e.preventDefault(),this.exportAndOpen()};async exportAsync(){return this.exportAndOpen()}async exportAndOpen(){let e=this.exportFileName??this.objectToExport?.name??this.name;if(e+="-"+tx(),Wn()||(e!==""&&(e+="-"),e+="MadeWithNeedle"),this.link||(this.link=Lx(this.context,G.supportsQuickLookAR())),this.customUsdzFile)return Ii&&console.log("Exporting custom usdz",this.customUsdzFile),this.openInQuickLook(this.customUsdzFile,e),null;if(!this.objectToExport)return console.warn("No object to export",this),null;Qh.beforeExport.invoke({exporter:this});const t=await this.export(this.objectToExport).finally(()=>{Qh.afterExport.invoke({exporter:this})});return t?(Ii&&console.log("USDZ generation done. Downloading as "+e),this.openInQuickLook(t,e),t):(console.error("USDZ generation failed. Please report a bug",this),null)}async export(e){if(!e)return console.warn("No object to export"),null;const t=this._currentExportTasks.get(e);if(t)return t;const i=this.internalExport(e);return i instanceof Promise?(this._currentExportTasks.set(e,i),i.then(n=>(this._currentExportTasks.delete(e),n)).catch(n=>(this._currentExportTasks.delete(e),console.error("Error during USDZ export \u2013 please report a bug!",n),null))):i}_currentExportTasks=new Map;_previousTimeScale=1;async internalExport(e){re.start("export-usdz",{onProgress:R=>{this.dispatchEvent(new CustomEvent("export-progress",{detail:{progress:R}}))}}),re.report("export-usdz",{message:"Starting export",totalSteps:40,currentStep:0}),re.report("export-usdz",{message:"Load progressive textures",autoStep:5}),re.start("export-usdz-textures","export-usdz");const t=x.getComponentsInChildren(e,ci);for(const R of t)R&&R.enabled&&R.updateSprite(!0);const i=x.getComponentsInChildren(e,Ti),n=new Array;let s=0;for(const R of i){for(const k of R.sharedMeshes)if(k){const A=Ve.assignMeshLOD(k,0);A instanceof Promise&&n.push(new Promise((L,N)=>{A.then(()=>{s++,re.report("export-usdz-textures",{message:"Loaded progressive mesh",currentStep:s,totalSteps:n.length}),L()}).catch(j=>N(j))}))}for(const k of R.sharedMaterials)if(k){const A=Ve.assignTextureLOD(k,0);A instanceof Promise&&n.push(new Promise((L,N)=>{A.then(()=>{s++,re.report("export-usdz-textures",{message:"Loaded progressive texture",currentStep:s,totalSteps:n.length}),L()}).catch(j=>N(j))}))}}Ii&&Te("Progressive Loading: "+n.length),await Promise.all(n),Ii&&Te("Progressive Loading: done"),re.end("export-usdz-textures");const r=Jt.Global.Mask;Jt.Global.Set(Xn.AR);const a=new rx,l=new Gu(this.quickLookCompatible);let c;const h=[];this.interactive&&(h.push(new hy),h.push(new aa),globalThis.NEEDLE_USE_RAPIER&&x.getComponentsInChildren(e,Ye).length>0&&(this.physics?(c=new dy,h.push(c)):E()&&console.warn("USDZExporter: Physics export is disabled, but there are active Rigidbody components in the scene. They will not be exported.")),h.push(new ip),h.push(new xy));const d=[l,...h,...this.extensions],p={self:this,exporter:a,extensions:d,object:e};re.report("export-usdz","Invoking before-export"),this.dispatchEvent(new CustomEvent("before-export",{detail:p})),this.applyWebARSessionRoot(),this._previousTimeScale=this.context.time.timeScale,this.context.time.timeScale=0,re.report("export-usdz","auto export animations and audio sources");const m=new Array;this.autoExportAnimations&&m.push(..._E(e,l)),d.find(R=>R.extensionName==="Audio")&&this.autoExportAudioSources&&m.push(...vE(e)),a.debug=Ii,a.pruneUnusedNodes=!SE;const f=la.instance.objs.map(R=>R.batchedMesh);a.keepObject=R=>{let k=!0;const A=x.getComponent(R,Ti);return A&&!A.enabled&&(k=!1),k&&f.includes(R)&&(k=!1),k&&x.getComponentInParent(R,Ac)&&(k=!1),k&&x.getComponentInParent(R,$n)&&(k=!1),Ii&&!k&&console.log("USDZExporter: Discarding object",R),k},a.beforeWritingDocument=()=>{if(E()&&l&&c){const R=l.animatedRoots;for(const k of R){const A=x.getComponentsInChildren(k,Ye).filter(N=>N.enabled),L=x.getComponents(k,ai).filter(N=>N.enabled&&!N.isTrigger);(A.length>0||L.length>0)&&console.error("An animated object has physics components in its child hierarchy. This can lead to undefined behaviour due to a bug in Apple's QuickLook (FB15925487). Remove the physics components from child objects or verify that you get the expected results.",k)}}};const g=new Array;this.objectToExport&&this.quickLookCompatible&&this.interactive&&this.objectToExport.traverse(R=>{R.visible||g.push(R)});const y=d.find(R=>R.extensionName==="Behaviour");this.interactive&&y&&g.length>0&&y.addBehavior(wE(g));let _=!0;this.quickLookCompatible&&!this.interactive&&(_=!1),this.anchoringType!=="plane"&&this.anchoringType!=="none"&&this.anchoringType!=="image"&&this.anchoringType!=="face"&&(this.anchoringType="plane"),this.planeAnchoringAlignment!=="horizontal"&&this.planeAnchoringAlignment!=="vertical"&&this.planeAnchoringAlignment!=="any"&&(this.planeAnchoringAlignment="horizontal"),re.report("export-usdz","Invoking exporter.parse");const v=await a.parse(this.objectToExport,{ar:{anchoring:{type:this.anchoringType},planeAnchoring:{alignment:this.planeAnchoringAlignment}},extensions:d,quickLookCompatible:this.quickLookCompatible,maxTextureSize:this.maxTextureSize,exportInvisible:_}),P=new Blob([v],{type:"model/vnd.usdz+zip"});this.revertWebARSessionRoot(),this.context.time.timeScale=this._previousTimeScale,re.report("export-usdz","Invoking after-export"),this.dispatchEvent(new CustomEvent("after-export",{detail:p}));for(const R of m)x.destroy(R);return Jt.Global.Set(r),re.end("export-usdz"),P}openInQuickLook(e,t){const i=e instanceof Blob?URL.createObjectURL(e):e,n=this.buildQuicklookOverlay();Ii&&console.log("QuickLook Overlay",n);const s=n.callToAction?encodeURIComponent(n.callToAction):"",r=n.checkoutTitle?encodeURIComponent(n.checkoutTitle):"",a=n.checkoutSubtitle?encodeURIComponent(n.checkoutSubtitle):"";this.link.href=i+`#callToAction=${s}&checkoutTitle=${r}&checkoutSubtitle=${a}&callToActionURL=${n.callToActionURL}`,this.lastCallback||(this.lastCallback=this.quicklookCallback.bind(this),this.link.addEventListener("message",this.lastCallback)),this.link.download=t+".usdz",this.link.click()}download(e,t){Qh.save(e,t)}static save(e,t){const i=document.createElement("a");i.style.display="none",document.body.appendChild(i),typeof e=="string"?i.href=e:i.href=URL.createObjectURL(e),i.download=t,i.click(),i.remove()}lastCallback;quicklookCallback(e){if(e?.data=="_apple_ar_quicklook_button_tapped"){Ii&&ge("Quicklook closed via call to action button");var t=new CustomEvent("quicklook-button-tapped",{detail:this});if(this.dispatchEvent(t),!t.defaultPrevented){const i=new URLSearchParams(this.link.href);if(i){const n=i.get("callToActionURL");Ii&&Te("Quicklook url: "+n),n&&(Wn()?globalThis.open(n,"_blank"):console.warn("Quicklook closed: custom redirects require a Needle Engine Pro license: https://needle.tools/pricing",n))}}}}buildQuicklookOverlay(){const e={};return this.customBranding&&Object.assign(e,this.customBranding),Wn()||(console.log("Custom Quicklook banner text requires pro license: https://needle.tools/pricing"),e.callToAction="Close",e.checkoutTitle="\u{1F335} Made with Needle",e.checkoutSubtitle="_"),(e.callToAction?.length||e.checkoutTitle?.length||e.checkoutSubtitle?.length)&&(e.callToAction?.length||(e.callToAction="\0"),e.checkoutTitle?.length||(e.checkoutTitle="\0"),e.checkoutSubtitle?.length||(e.checkoutSubtitle="\0")),this.dispatchEvent(new CustomEvent("quicklook-overlay",{detail:e})),e}static invertForwardMatrix=new ee().makeRotationY(Math.PI);static invertForwardQuaternion=new U().setFromEuler(new nt(0,Math.PI,0));_rootSessionRootWasAppliedTo=null;_rootPositionBeforeExport=new b;_rootRotationBeforeExport=new U;_rootScaleBeforeExport=new b;getARScaleAndTarget(){if(!this.objectToExport)return{scale:1,_invertForward:!1,target:this.gameObject,sessionRoot:null};const e=x.findObjectOfType(Zu);let t=x.getComponentInParent(this.objectToExport,Ui);t||(t=x.getComponentInChildren(this.objectToExport,Ui));let i=1,n=!1;const s=this.objectToExport;return e?i=e.arScale:t&&(i=t.arScale,n=t.invertForward),{scale:1/i,_invertForward:n,target:s,sessionRoot:t?.gameObject??null}}applyWebARSessionRoot(){if(!this.objectToExport)return;const{scale:e,_invertForward:t,target:i,sessionRoot:n}=this.getARScaleAndTarget(),s=n?.matrixWorld.clone().invert();this._rootSessionRootWasAppliedTo=i,this._rootPositionBeforeExport.copy(i.position),this._rootRotationBeforeExport.copy(i.quaternion),this._rootScaleBeforeExport.copy(i.scale),i.scale.multiplyScalar(e),t&&i.quaternion.multiply(Qh.invertForwardQuaternion),i.updateMatrix(),i.updateMatrixWorld(!0),n&&s&&i.matrix.premultiply(s)}revertWebARSessionRoot(){if(!this.objectToExport||!this._rootSessionRootWasAppliedTo)return;const e=this._rootSessionRootWasAppliedTo;e.position.copy(this._rootPositionBeforeExport),e.quaternion.copy(this._rootRotationBeforeExport),e.scale.copy(this._rootScaleBeforeExport),e.updateMatrix(),e.updateMatrixWorld(!0),this._rootSessionRootWasAppliedTo=null}createQuicklookButton(){const e=Qs.getOrCreate().createQuicklookButton();return e.parentNode||this.context.menu.appendChild(e),e}};kt([u(O)],hi.prototype,"objectToExport"),kt([u()],hi.prototype,"autoExportAnimations"),kt([u()],hi.prototype,"autoExportAudioSources"),kt([u()],hi.prototype,"exportFileName"),kt([u(URL)],hi.prototype,"customUsdzFile"),kt([u(zr)],hi.prototype,"customBranding"),kt([u()],hi.prototype,"anchoringType"),kt([u()],hi.prototype,"maxTextureSize"),kt([u()],hi.prototype,"planeAnchoringAlignment"),kt([u()],hi.prototype,"interactive"),kt([u()],hi.prototype,"physics"),kt([u()],hi.prototype,"allowCreateQuicklookButton"),kt([u()],hi.prototype,"quickLookCompatible");let to=hi;var CE=Object.defineProperty,PE=Object.getOwnPropertyDescriptor,Sy=(o,e,t,i)=>{for(var n=PE(e,t),s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&CE(e,t,n),n};class pl extends M{get fog(){return this._fog||(this._fog=new j0(0,0,50)),this._fog}get mode(){return 1}set near(e){this.fog.near=e}get near(){return this.fog.near}set far(e){this.fog.far=e}get far(){return this.fog.far}set color(e){this.fog.color.copy(e)}get color(){return this.fog.color}_fog;onEnable(){this.scene.fog=this.fog}onDisable(){this.scene.fog===this._fog&&(this.scene.fog=null)}}Sy([u()],pl.prototype,"near"),Sy([u()],pl.prototype,"far"),Sy([u(ne)],pl.prototype,"color");var OE=Object.defineProperty,Cy=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&OE(e,t,n),n};class Nr extends M{objectBounds=!1;color;isGizmo=!0;_gizmoObject=null;_boxHelper=null;onEnable(){this.isGizmo&&!lc||(this._gizmoObject||(this.objectBounds?this._gizmoObject=new XS(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=cg(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),we.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){for(;this._boxHelper;)this._boxHelper?.update(),yield}}Cy([u()],Nr.prototype,"objectBounds"),Cy([u(ne)],Nr.prototype,"color"),Cy([u()],Nr.prototype,"isGizmo");var kE=Object.defineProperty,Py=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&kE(e,t,n),n};class ml extends M{isGizmo=!1;color0;color1;gridHelper;size;divisions;offset;onEnable(){if(this.isGizmo&&!lc)return;const e=this.size,t=this.divisions;this.gridHelper||(this.gridHelper=new Jp(e,t,this.color0??new ne(.4,.4,.4),this.color1??new ne(.6,.6,.6)),this.offset!==void 0&&(this.gridHelper.position.y+=this.offset)),this.gridHelper&&this.gameObject.add(this.gridHelper)}onDisable(){this.gridHelper&&(this.gameObject.remove(this.gridHelper),this.gridHelper=null)}}Py([u()],ml.prototype,"isGizmo"),Py([u(ne)],ml.prototype,"color0"),Py([u(ne)],ml.prototype,"color1");var ME=Object.defineProperty,Oy=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&ME(e,t,n),n};class ky extends M{connectedBody;get rigidBody(){return this._rigidBody}_rigidBody=null;onEnable(){this._rigidBody||(this._rigidBody=this.gameObject.getComponent(Ye)),this.rigidBody&&this.connectedBody&&this.startCoroutine(this.create())}*create(){yield,this.rigidBody&&this.connectedBody&&this.activeAndEnabled&&this.createJoint(this.rigidBody,this.connectedBody)}}Oy([u(Ye)],ky.prototype,"connectedBody");class My extends ky{createJoint(e,t){this.context.physics.engine?.addFixedJoint(e,t)}}class eh extends ky{anchor;axis;createJoint(e,t){this.axis&&this.anchor&&this.context.physics.engine?.addHingeJoint(e,t,this.anchor,this.axis)}}Oy([u(b)],eh.prototype,"anchor"),Oy([u(b)],eh.prototype,"axis");var RE=Object.defineProperty,TE=Object.getOwnPropertyDescriptor,io=(o,e,t,i)=>{for(var n=i>1?void 0:i?TE(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&RE(e,t,n),n};function Ry(o){return o*Math.PI/180}const jx=300,Ls=w("debuglights");class di extends M{type=0;range=1;spotAngle=1;innerSpotAngle=1;set color(e){this._color=e,this.light!==void 0&&(this.light.color=e)}get color(){return this.light?this.light.color:this._color}_color=new ne(16777215);set shadowNearPlane(e){if(e!==this._shadowNearPlane&&(this._shadowNearPlane=e,this.light?.shadow?.camera!==void 0)){const t=this.light.shadow.camera;t.near=e}}get shadowNearPlane(){return this._shadowNearPlane}_shadowNearPlane=.1;set shadowBias(e){e!==this._shadowBias&&(this._shadowBias=e,this.light?.shadow?.bias!==void 0&&(this.light.shadow.bias=e,this.light.shadow.needsUpdate=!0))}get shadowBias(){return this._shadowBias}_shadowBias=0;set shadowNormalBias(e){e!==this._shadowNormalBias&&(this._shadowNormalBias=e,this.light?.shadow?.normalBias!==void 0&&(this.light.shadow.normalBias=e,this.light.shadow.needsUpdate=!0))}get shadowNormalBias(){return this._shadowNormalBias}_shadowNormalBias=0;_overrideShadowBiasSettings=!1;set shadows(e){this._shadows=e,this.light&&(this.light.castShadow=e!==0,this.updateShadowSoftHard())}get shadows(){return this._shadows}_shadows=1;lightmapBakeType=4;set intensity(e){if(this._intensity=e,this.light){let t=1;if(this.context.isInXR&&this._webARRoot){const i=this._webARRoot?.arScale;typeof i=="number"&&i>0&&(t/=i)}this.light.intensity=e*t}Ls&&console.log("Set light intensity to "+this._intensity,e,this)}get intensity(){return this._intensity}_intensity=-1;get shadowDistance(){const e=this.light;return e?.shadow?e.shadow.camera.far:-1}set shadowDistance(e){this._shadowDistance=e;const t=this.light;if(t?.shadow){const i=t.shadow.camera;i.far=e,i.updateProjectionMatrix()}}_shadowDistance;shadowWidth;shadowHeight;get shadowResolution(){const e=this.light;return e?.shadow?e.shadow.mapSize.x:-1}set shadowResolution(e){if(e===this._shadowResolution)return;this._shadowResolution=e;const t=this.light;t?.shadow&&(t.shadow.mapSize.set(e,e),t.shadow.needsUpdate=!0)}_shadowResolution=void 0;get isBaked(){return this.lightmapBakeType===2}get selfIsLight(){if(this.gameObject.isLight===!0)return!0;switch(this.gameObject.type){case"SpotLight":case"PointLight":case"DirectionalLight":return!0}return!1}light=void 0;getWorldPosition(e){return this.light?this.type===1?this.light.getWorldPosition(e).multiplyScalar(1):this.light.getWorldPosition(e):e}awake(){this.color=new ne(this.color??16777215),Ls&&console.log(this.name,this)}onEnable(){Ls&&console.log("ENABLE LIGHT",this.name),this.createLight(),!this.isBaked&&(this.light&&(this.light.visible=!0,this.light.intensity=this._intensity,Ls&&console.log("Set light intensity to "+this.light.intensity,this.name),this.selfIsLight||this.light.parent!==this.gameObject&&this.gameObject.add(this.light)),this.type===1&&this.startCoroutine(this.updateMainLightRoutine(),we.LateUpdate))}onDisable(){Ls&&console.log("DISABLE LIGHT",this.name),this.light&&(this.selfIsLight?this.light.intensity=0:this.light.visible=!1)}_webXRStartedListener;_webXREndedListener;_webARRoot;onEnterXR(e){this._webARRoot=x.getComponentInParent(this.gameObject,Ui)??void 0}onLeaveXR(e){}createLight(){const e=this.selfIsLight;if(e&&!this.light)switch(this.light=this.gameObject,this.light.name=this.name,this._intensity=this.light.intensity,this.type){case 1:this.setDirectionalLight(this.light);break}else if(!this.light)switch(this.type){case 1:const t=new em(this.color,this.intensity*Math.PI);if(t.position.set(0,0,-jx*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(t.target),sr(t.target,0,0,0),this.light=t,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),Ls){const r=new YS(this.light,.2,this.color);this.context.scene.add(r)}break;case 0:const i=new QS(this.color,this.intensity*Math.PI,this.range,Ry(this.spotAngle/2),1-Ry(this.innerSpotAngle/2)/Ry(this.spotAngle/2),2);i.position.set(0,0,0),i.rotation.set(0,0,0),this.light=i;const n=i.target;i.add(n),n.position.set(0,0,this.range),n.rotation.set(0,0,0);break;case 2:const s=new tm(this.color,this.intensity*Math.PI,this.range);this.light=s;break}if(this.light){if(this._intensity>=0?this.light.intensity=this._intensity:this._intensity=this.light.intensity,this.shadows!==0?this.light.castShadow=!0:this.light.castShadow=!1,this.light.shadow){this._shadowResolution!==void 0&&this._shadowResolution>4?(this.light.shadow.mapSize.width=this._shadowResolution,this.light.shadow.mapSize.height=this._shadowResolution):(this.light.shadow.mapSize.width=2048,this.light.shadow.mapSize.height=2048),Ls&&console.log("Override shadow bias?",this._overrideShadowBiasSettings,this.shadowBias,this.shadowNormalBias),this.light.shadow.bias=this.shadowBias,this.light.shadow.normalBias=this.shadowNormalBias,this.updateShadowSoftHard();const t=this.light.shadow.camera;if(t.near=this.shadowNearPlane,this._shadowDistance!==void 0&&typeof this._shadowDistance=="number"?t.far=this._shadowDistance:t.far=jx*Math.abs(this.gameObject.scale.z),this.gameObject.scale.set(1,1,1),this.shadowWidth!==void 0)t.left=-this.shadowWidth/2,t.right=this.shadowWidth/2;else{const i=this.gameObject.scale.x;t.left*=i,t.right*=i}if(this.shadowHeight!==void 0)t.top=this.shadowHeight/2,t.bottom=-this.shadowHeight/2;else{const i=this.gameObject.scale.y;t.top*=i,t.bottom*=i}this.light.shadow.needsUpdate=!0,Ls&&this.context.scene.add(new KS(t))}this.isBaked?this.light.removeFromParent():e||this.gameObject.add(this.light)}}*updateMainLightRoutine(){for(;;){this.type===1&&((!this.context.mainLight||this.intensity>this.context.mainLight.intensity)&&(this.context.mainLight=this),yield);break}}static allowChangingRendererShadowMapType=!0;updateShadowSoftHard(){this.light&&this.light.shadow&&(this.shadows===2||(this.light.shadow.radius=1,this.light.shadow.blurSamples=1))}setDirectionalLight(e){e.add(e.target),e.target.position.set(0,0,-1)}}io([u()],di.prototype,"type",2),io([u(ne)],di.prototype,"color",1),io([u()],di.prototype,"shadowNearPlane",1),io([u()],di.prototype,"shadowBias",1),io([u()],di.prototype,"shadowNormalBias",1),io([u()],di.prototype,"shadows",1),io([u()],di.prototype,"lightmapBakeType",2),io([u()],di.prototype,"intensity",1),io([u()],di.prototype,"shadowDistance",1),io([u()],di.prototype,"shadowResolution",1),new b(0,0,0);var EE=Object.defineProperty,th=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&EE(e,t,n),n};const Ty=w("debuglods"),AE=w("nolods");class gl{screenRelativeTransitionHeight;distance;renderers}th([u()],gl.prototype,"screenRelativeTransitionHeight"),th([u()],gl.prototype,"distance"),th([u(Ti)],gl.prototype,"renderers");class IE{model;get renderers(){return this.model.renderers}constructor(e){this.model=e}}class ih extends M{fadeMode=0;localReferencePoint=void 0;lodCount=0;size=0;animateCrossFading=!1;lodModels;_lods=[];_settings=[];_lodsHandler;start(){if(Ty&&console.log("LODGROUP",this.name,this.lodModels,this),!AE&&!this._lodsHandler&&this.gameObject&&this.lodModels&&Array.isArray(this.lodModels)){const e=[];for(const i of this.lodModels){const n=new IE(i);this._lods.push(n);for(const s of n.renderers)e.includes(s)||e.push(s)}this._lodsHandler=new Array;for(let i=0;i<e.length;i++){const n=new ZS;this._lodsHandler.push(n),this.gameObject.add(n)}const t=new O;t.name="Cull "+this.name;for(let i=0;i<e.length;i++){const n=e[i],s=this._lodsHandler[i],r=n.gameObject;Ty&&console.log(i,r.name);for(const a of this._lods){const l=a.model.distance;let c=null;if(a.renderers.includes(n)?c=r:c=t,c.type==="Group"){console.warn(`LODGroup ${this.name}: Group or MultiMaterial object's are not supported as LOD object: ${c.name}`);continue}Ty&&console.log("LEVEL",c.name,l),s.autoUpdate=!1,this.onAddLodLevel(s,c,a.model.distance)}}}}onAfterRender(){if(!this.gameObject||!this._lodsHandler)return;const e=this.context.mainCamera;if(e)for(const t of this._lodsHandler){t.update(e);const i=t.getCurrentLevel(),n=t.levels[i];t.layers.mask=n.object.layers.mask}}onAddLodLevel(e,t,i){if(t===this.gameObject){console.warn("LODGroup component must be on parent object and not mesh directly at the moment",t.name,t);return}e.addLevel(t,i*this._distanceFactor,.01);const n={lod:e,levelIndex:e.levels.length-1,distance:i};this._settings.push(n)}_distanceFactor=1;distanceFactor(e){if(e!==this._distanceFactor){this._distanceFactor=e;for(const t of this._settings){const i=t.lod.levels[t.levelIndex];i.distance=t.distance*e}}}}th([u(b)],ih.prototype,"localReferencePoint"),th([u(gl)],ih.prototype,"lodModels");var LE=Object.defineProperty,Dx=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&LE(e,t,n),n};const np=w("debugnestedgltf");class nh extends M{filePath;loaded=new ce;loadAssetInParent=!0;_isLoadingOrDoneLoading=!1;listenToProgress(e){this.filePath?.beginListenDownload(e)}preload(){return this.filePath?.preload()||null}async start(){if(this._isLoadingOrDoneLoading)return;np&&console.log(this,this.guid);const e=this.gameObject.parent;if(e&&this.filePath){this._isLoadingOrDoneLoading=!0;const t=new En;t.idProvider=new At(this.hash(this.guid)),t.parent=this.loadAssetInParent!==!1?e:this.gameObject,this.gameObject.updateMatrix();const i=this.gameObject.matrix;np&&console.log("Load nested:",this.filePath?.url??this.filePath,this.gameObject.position);const n=await this.filePath?.instantiate?.call(this.filePath,t);np&&console.log("Nested loaded:",this.filePath?.url??this.filePath,n),n&&this.loadAssetInParent!==!1&&(n.matrixAutoUpdate=!1,n.matrix.identity(),n.applyMatrix4(i),n.matrixAutoUpdate=!0,n.layers.disableAll(),n.layers.set(this.layer),this.loaded.invoke({component:this,instance:n,asset:this.filePath})),np&&console.log("Nested loading done:",this.filePath?.url??this.filePath,n)}}onDestroy(){this.filePath?.unload()}hash(e){let t=0;for(let i=0;i<e.length;i++)t=e.charCodeAt(i)+((t<<5)-t);return t}}Dx([u(ie)],nh.prototype,"filePath"),Dx([u(ce)],nh.prototype,"loaded");var jE=Object.defineProperty,Ey=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&jE(e,t,n),n};const DE=w("debugnet"),op=class M0 extends M{url=null;urlParameterName=null;localhost=null;awake(){DE&&console.log(this),this.context.connection.registerProvider(this)}getWebsocketUrl(){let e=this.url?M0.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){const i=w(this.urlParameterName);i&&typeof i=="string"&&(e=i)}if(!e)return null;const t=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(e);return t?.groups?t?.groups.socket_prefix?e:"wss://"+t?.groups.url:null}static GetUrl(e,t){let i=e;const n=M0.IsLocalNetwork()&&t;if(n&&(i=t),e?.startsWith("/")){const s=n?i:window.location.origin;s?.endsWith("/")&&e.startsWith("/")&&(e=e.substring(1)),i=s+e}return i}static IsLocalNetwork(e=window.location.hostname){return Wi(e)}};Ey([u()],op.prototype,"url"),Ey([u()],op.prototype,"urlParameterName"),Ey([u()],op.prototype,"localhost");let Ay=op;var BE=Object.defineProperty,sp=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&BE(e,t,n),n};class Wr extends M{referenceSpace;from;affectPosition=!1;affectRotation=!1;alignLookDirection=!1;levelLookDirection=!1;levelPosition=!1;positionOffset=new b(0,0,0);rotationOffset=new b(0,0,0);offset=new b(0,0,0);update(){if(!this.from)return;var e=Z(this.from),t=be(this.from);this.offset.copy(this.positionOffset);const i=this.offset.length();if(this.referenceSpace&&this.offset.transformDirection(this.referenceSpace.matrixWorld).multiplyScalar(i),e.add(this.offset),this.levelPosition&&this.referenceSpace){const a=new tr(this.gameObject.up,0),l=Z(this.referenceSpace);a.setFromNormalAndCoplanarPoint(this.gameObject.up,l);const c=new b(0,0,0);a.projectPoint(e,c),e.copy(c)}this.affectPosition&&mt(this.gameObject,e);const n=new nt(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),s=new U().setFromEuler(n);this.affectRotation&&pn(this.gameObject,t.multiply(s));const r=new b;this.from.getWorldDirection(r).multiplyScalar(50),this.levelLookDirection&&(r.y=0),this.alignLookDirection&&this.gameObject.lookAt(r)}}sp([u(x)],Wr.prototype,"referenceSpace"),sp([u(x)],Wr.prototype,"from"),sp([u(b)],Wr.prototype,"positionOffset"),sp([u(b)],Wr.prototype,"rotationOffset");var FE=Object.defineProperty,js=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&FE(e,t,n),n};class ui{time=0;value=0;inTangent=1/0;inWeight;outTangent=1/0;outWeight;weightedMode;constructor(e=0,t=0){this.time=e,this.value=t}}js([u()],ui.prototype,"time"),js([u()],ui.prototype,"value"),js([u()],ui.prototype,"inTangent"),js([u()],ui.prototype,"inWeight"),js([u()],ui.prototype,"outTangent"),js([u()],ui.prototype,"outWeight"),js([u()],ui.prototype,"weightedMode");const Bx=class Yh{static linearFromTo(e,t,i){const n=new Yh,s=new ui;s.time=0,s.value=e;const r=new ui;return r.time=i,r.value=t,n.keys.push(s,r),n}static constant(e){const t=new Yh,i=new ui;return i.time=0,i.value=e,t.keys.push(i),t}keys=[];clone(){const e=new Yh;return e.keys=this.keys?.map(t=>{const i=new ui;return i.time=t.time,i.value=t.value,i.inTangent=t.inTangent,i.inWeight=t.inWeight,i.outTangent=t.outTangent,i.outWeight=t.outWeight,i.weightedMode=t.weightedMode,i})||[],e}get duration(){return!this.keys||this.keys.length==0?0:this.keys[this.keys.length-1].time}evaluate(e){if(!this.keys||this.keys.length==0)return 0;if(this.keys.length===1)return this.keys[0].value;if(this.keys[0].time>=e)return this.keys[0].value;for(let t=0;t<this.keys.length;t++){const i=this.keys[t];if(i.time<=e)if(t+1<this.keys.length){const n=this.keys[t+1];if(n.time<e)continue;return!isFinite(i.outTangent)||!isFinite(n.inTangent)?i.value:Yh.interpolateValue(e,i,n)}else return i.value}return this.keys[this.keys.length-1].value}static interpolateValue(e,t,i){const n=t.time,s=t.value,r=t.outTangent,a=i.time,l=i.value,c=i.inTangent,h=a-n,d=h*h,p=d*h,m=((r+c)*h-2*(l-s))/p,f=(3*(l-s)-(c+2*r)*h)/d,g=r,y=s,_=e-n,v=_*_,P=v*_;return m*P+f*v+g*_+y}};js([u(ui)],Bx.prototype,"keys");let oh=Bx;var UE=Object.defineProperty,S=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&UE(e,t,n),n};const rp=w("debugparticles");var Fo=(o=>(o[o.Billboard=0]="Billboard",o[o.Stretch=1]="Stretch",o[o.HorizontalBillboard=2]="HorizontalBillboard",o[o.VerticalBillboard=3]="VerticalBillboard",o[o.Mesh=4]="Mesh",o))(Fo||{});class Vr{alphaKeys=[];colorKeys=[];get duration(){return 1}evaluate(e,t){let i,n=0,s=null,r=0;for(let a=0;a<this.alphaKeys.length;a++){const l=this.alphaKeys[a];(l.time<e||!i)&&(i=l,n=a)}for(let a=0;a<this.colorKeys.length;a++){const l=this.colorKeys[a];(l.time<e||!s)&&(s=l,r=a)}if(s)if(r+1<this.colorKeys.length){const a=this.colorKeys[r+1],l=D.remap(e,s.time,a.time,0,1);t.r=D.lerp(s.color.r,a.color.r,l),t.g=D.lerp(s.color.g,a.color.g,l),t.b=D.lerp(s.color.b,a.color.b,l)}else t.r=s.color.r,t.g=s.color.g,t.b=s.color.b;if(i)if(n+1<this.alphaKeys.length){const a=this.alphaKeys[n+1],l=D.remap(e,i.time,a.time,0,1);t.alpha=D.lerp(i.alpha,a.alpha,l)}else t.alpha=i.alpha;return t}}S([u()],Vr.prototype,"alphaKeys"),S([u()],Vr.prototype,"colorKeys");var sh=(o=>(o[o.Local=0]="Local",o[o.World=1]="World",o[o.Custom=2]="Custom",o))(sh||{}),ap=(o=>(o[o.Sphere=0]="Sphere",o[o.SphereShell=1]="SphereShell",o[o.Hemisphere=2]="Hemisphere",o[o.HemisphereShell=3]="HemisphereShell",o[o.Cone=4]="Cone",o[o.Box=5]="Box",o[o.Mesh=6]="Mesh",o[o.ConeShell=7]="ConeShell",o[o.ConeVolume=8]="ConeVolume",o[o.ConeVolumeShell=9]="ConeVolumeShell",o[o.Circle=10]="Circle",o[o.CircleEdge=11]="CircleEdge",o[o.SingleSidedEdge=12]="SingleSidedEdge",o[o.MeshRenderer=13]="MeshRenderer",o[o.SkinnedMeshRenderer=14]="SkinnedMeshRenderer",o[o.BoxShell=15]="BoxShell",o[o.BoxEdge=16]="BoxEdge",o[o.Donut=17]="Donut",o[o.Rectangle=18]="Rectangle",o[o.Sprite=19]="Sprite",o[o.SpriteRenderer=20]="SpriteRenderer",o))(ap||{});const Uo=class Kh{static constant(e){const t=new Kh;return t.setConstant(e),t}static betweenTwoConstants(e,t){const i=new Kh;return i.setMinMaxConstant(e,t),i}static curve(e,t=1){const i=new Kh;return i.setCurve(e,t),i}setConstant(e){this.mode=0,this.constant=e}setMinMaxConstant(e,t){this.mode=3,this.constantMin=e,this.constantMax=t}setCurve(e,t=1){this.mode=1,this.curve=e,this.curveMultiplier=t}mode="Constant";constant;constantMin;constantMax;curve;curveMin;curveMax;curveMultiplier;clone(){const e=new Kh;return e.mode=this.mode,e.constant=this.constant,e.constantMin=this.constantMin,e.constantMax=this.constantMax,e.curve=this.curve?.clone(),e.curveMin=this.curveMin?.clone(),e.curveMax=this.curveMax?.clone(),e.curveMultiplier=this.curveMultiplier,e}evaluate(e,t){const i=t===void 0?Math.random():t;switch(this.mode){case 0:case"Constant":return this.constant;case 1:case"Curve":return e=D.clamp01(e),this.curve.evaluate(e)*this.curveMultiplier;case 2:case"TwoCurves":const n=e*this.curveMin.duration,s=e*this.curveMax.duration;return D.lerp(this.curveMin.evaluate(n),this.curveMax.evaluate(s),i%1)*this.curveMultiplier;case 3:case"TwoConstants":return D.lerp(this.constantMin,this.constantMax,i%1);default:this.curveMax.evaluate(e)*this.curveMultiplier;break}return 0}getMax(){switch(this.mode){case 0:case"Constant":return this.constant;case 1:case"Curve":return this.getMaxFromCurve(this.curve)*this.curveMultiplier;case 2:case"TwoCurves":return Math.max(this.getMaxFromCurve(this.curveMin),this.getMaxFromCurve(this.curveMax))*this.curveMultiplier;case 3:case"TwoConstants":return Math.max(this.constantMin,this.constantMax);default:return 0}}getMaxFromCurve(e){if(!e)return 0;let t=Number.MIN_VALUE;for(let i=0;i<e.keys.length;i++){const n=e.keys[i];n.value>t&&(t=n.value)}return t}};S([u()],Uo.prototype,"mode"),S([u()],Uo.prototype,"constant"),S([u()],Uo.prototype,"constantMin"),S([u()],Uo.prototype,"constantMax"),S([u(oh)],Uo.prototype,"curve"),S([u(oh)],Uo.prototype,"curveMin"),S([u(oh)],Uo.prototype,"curveMax"),S([u()],Uo.prototype,"curveMultiplier");let Q=Uo;const Ds=class Tt{static constant(e){const t=new Tt;return t.constant(e),t}static betweenTwoColors(e,t){const i=new Tt;return i.betweenTwoColors(e,t),i}constant(e){return this.mode=0,this.color=e,this}betweenTwoColors(e,t){return this.mode=2,this.colorMin=e,this.colorMax=t,this}mode=0;color;colorMin;colorMax;gradient;gradientMin;gradientMax;static _temp=new se(0,0,0,1);static _temp2=new se(0,0,0,1);evaluate(e,t){const i=t===void 0?Math.random():t;switch(this.mode){case 0:case"Color":return this.color;case 1:case"Gradient":return this.gradient.evaluate(e,Tt._temp),Tt._temp;case 2:case"TwoColors":return Tt._temp.lerpColors(this.colorMin,this.colorMax,i);case 3:case"TwoGradients":return this.gradientMin.evaluate(e,Tt._temp),this.gradientMax.evaluate(e,Tt._temp2),Tt._temp.lerp(Tt._temp2,i);case 4:case"RandomColor":const n=Math.random();return this.gradientMin.evaluate(e,Tt._temp),this.gradientMax.evaluate(e,Tt._temp2),Tt._temp.lerp(Tt._temp2,n)}return Tt._temp.set(16777215),Tt._temp.alpha=1,Tt._temp}};S([u()],Ds.prototype,"mode"),S([u(se)],Ds.prototype,"color"),S([u(se)],Ds.prototype,"colorMin"),S([u(se)],Ds.prototype,"colorMax"),S([u(Vr)],Ds.prototype,"gradient"),S([u(Vr)],Ds.prototype,"gradientMin"),S([u(Vr)],Ds.prototype,"gradientMax");let $r=Ds;var Iy=(o=>(o[o.Hierarchy=0]="Hierarchy",o[o.Local=1]="Local",o[o.Shape=2]="Shape",o))(Iy||{});class Bt{cullingMode;duration;emitterVelocityMode;flipRotation;gravityModifier;gravityModifierMultiplier;loop;maxParticles;playOnAwake;prewarm;ringBufferLoopRange;ringBufferMode;scalingMode;simulationSpace;simulationSpeed;startColor;startDelay;startDelayMultiplier;startLifetime;startLifetimeMultiplier;startRotation;startRotationMultiplier;startRotation3D;startRotationX;startRotationXMultiplier;startRotationY;startRotationYMultiplier;startRotationZ;startRotationZMultiplier;startSize;startSize3D;startSizeMultiplier;startSizeX;startSizeXMultiplier;startSizeY;startSizeYMultiplier;startSizeZ;startSizeZMultiplier;startSpeed;startSpeedMultiplier;stopAction;useUnscaledTime}S([u(Q)],Bt.prototype,"gravityModifier"),S([u($r)],Bt.prototype,"startColor"),S([u(Q)],Bt.prototype,"startDelay"),S([u(Q)],Bt.prototype,"startLifetime"),S([u(Q)],Bt.prototype,"startRotation"),S([u(Q)],Bt.prototype,"startRotationX"),S([u(Q)],Bt.prototype,"startRotationY"),S([u(Q)],Bt.prototype,"startRotationZ"),S([u(Q)],Bt.prototype,"startSize"),S([u(Q)],Bt.prototype,"startSizeX"),S([u(Q)],Bt.prototype,"startSizeY"),S([u(Q)],Bt.prototype,"startSizeZ"),S([u(Q)],Bt.prototype,"startSpeed");class lp{cycleCount;maxCount;minCount;probability;repeatInterval;time;count;_performed=0;reset(){this._performed=0}run(e){if(e<=this.time)return 0;let t=0;if(this.cycleCount===0||this._performed<this.cycleCount){const i=this.time+this.repeatInterval*this._performed;if(e>=i&&(this._performed+=1,Math.random()<this.probability))switch(this.count.mode){case 0:t=this.count.constant;break;case 3:t=D.lerp(this.count.constantMin,this.count.constantMax,Math.random());break;case 1:t=this.count.curve.evaluate(Math.random());break;case 2:const n=Math.random();t=D.lerp(this.count.curveMin.evaluate(n),this.count.curveMax.evaluate(n),Math.random());break}}return t}}class zo{enabled;get burstCount(){return this.bursts?.length??0}bursts;rateOverTime;rateOverTimeMultiplier;rateOverDistance;rateOverDistanceMultiplier;system;reset(){this.bursts?.forEach(e=>e.reset())}getBurst(){let e=0;if(this.burstCount>0)for(let t=0;t<this.burstCount;t++){const i=this.bursts[t];this.system.main.loop&&i.time>=this.system.time&&i.reset(),e+=Math.round(i.run(this.system.time))}return e}}S([u()],zo.prototype,"enabled"),S([u()],zo.prototype,"bursts"),S([u(Q)],zo.prototype,"rateOverTime"),S([u()],zo.prototype,"rateOverTimeMultiplier"),S([u(Q)],zo.prototype,"rateOverDistance"),S([u()],zo.prototype,"rateOverDistanceMultiplier");class cp{enabled;color}S([u($r)],cp.prototype,"color");class Hr{enabled;separateAxes;size;sizeMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;_time=0;_temp=new b;evaluate(e,t,i){if(t||(t=this._temp),!this.enabled)return t.x=t.y=t.z=1,t;if(this.separateAxes)t.x=this.x.evaluate(e,i)*this.xMultiplier,t.y=this.y.evaluate(e,i)*this.yMultiplier,t.z=this.z.evaluate(e,i)*this.zMultiplier;else{const n=this.size.evaluate(e,i)*this.sizeMultiplier;t.x=n}return t}}S([u(Q)],Hr.prototype,"size"),S([u(Q)],Hr.prototype,"x"),S([u(Q)],Hr.prototype,"y"),S([u(Q)],Hr.prototype,"z");const Ze=class Zh{get type(){return ap[this.shapeType]}initialize(e){this.onInitialize(e),e.position.x=this._vector.x,e.position.y=this._vector.y,e.position.z=this._vector.z}toJSON(){return this}clone(){return new Zh}shapeType=5;enabled=!0;alignToDirection=!1;angle=0;arc=360;arcSpread;arcSpeedMultiplier;arcMode;boxThickness;position;rotation;_rotation=new nt;scale;radius;radiusThickness;sphericalDirectionAmount;randomDirectionAmount;randomPositionAmount;meshShapeType;meshRenderer;_meshObj;_meshGeometry;setMesh(e){this.meshRenderer=e,e?(this._meshObj=e.sharedMeshes[Math.floor(Math.random()*e.sharedMeshes.length)],this._meshGeometry=this._meshObj.geometry):(this._meshObj=void 0,this._meshGeometry=void 0)}system;_space;_worldSpaceMatrix=new ee;_worldSpaceMatrixInverse=new ee;constructor(){rp&&console.log(this)}update(e,t){}onUpdate(e,t,i,n){this.system=e,this._space=i,i===1&&(this._worldSpaceMatrix.copy(n.matrixWorld),this._worldSpaceMatrix.elements[0]=1,this._worldSpaceMatrix.elements[5]=1,this._worldSpaceMatrix.elements[10]=1,this._worldSpaceMatrixInverse.copy(this._worldSpaceMatrix).invert())}applyRotation(e){const t=this.rotation.x!==0||this.rotation.y!==0||this.rotation.z!==0;return t&&(this._rotation.x=D.toRadians(this.rotation.x),this._rotation.y=D.toRadians(this.rotation.y),this._rotation.z=D.toRadians(this.rotation.z),this._rotation.order="ZYX",e.applyEuler(this._rotation)),t}_vector=new b(0,0,0);_temp=new b(0,0,0);_triangle=new JS;onInitialize(e){this._vector.set(0,0,0),e.mesh=void 0,e.mesh_geometry=void 0;const t=this._temp.copy(this.position),i=this._space===1;i&&t.applyQuaternion(this.system.worldQuaternion);let n=this.radius;if(i&&(n*=this.system.worldScale.x),this.enabled){switch(this.shapeType){case 5:rp&&F.DrawWireBox(this.position,this.scale,14540253,1),this._vector.x=Math.random()*this.scale.x-this.scale.x/2,this._vector.y=Math.random()*this.scale.y-this.scale.y/2,this._vector.z=Math.random()*this.scale.z-this.scale.z/2,this._vector.add(t);break;case 4:this.randomConePoint(this.position,this.angle,n,this.radiusThickness,this.arc,this.arcMode,this._vector);break;case 0:this.randomSpherePoint(this.position,n,this.radiusThickness,this.arc,this._vector);break;case 10:this.randomCirclePoint(this.position,n,this.radiusThickness,this.arc,this._vector);break;case 13:const s=this.meshRenderer;s?.destroyed==!1&&this.setMesh(s);const r=e.mesh=this._meshObj,a=e.mesh_geometry=this._meshGeometry;if(r&&a)switch(this.meshShapeType){case 0:{const l=a.getAttribute("position"),c=Math.floor(Math.random()*l.count);this._vector.fromBufferAttribute(l,c),this._vector.applyMatrix4(r.matrixWorld),e.mesh_normal=c}break;case 1:break;case 2:{const l=a.index;if(l){let c=Math.random(),h=Math.random();c+h>1&&(c=1-c,h=1-h);const d=Math.floor(Math.random()*(l.count/3));let p=d*3,m=d*3+1,f=d*3+2;p=l.getX(p),m=l.getX(m),f=l.getX(f);const g=a.getAttribute("position");this._triangle.a.fromBufferAttribute(g,p),this._triangle.b.fromBufferAttribute(g,m),this._triangle.c.fromBufferAttribute(g,f),this._vector.set(0,0,0).addScaledVector(this._triangle.a,c).addScaledVector(this._triangle.b,h).addScaledVector(this._triangle.c,1-(c+h)),this._vector.applyMatrix4(r.matrixWorld),e.mesh_normal=d}}break}break;default:this._vector.set(0,0,0),E()&&!globalThis.__particlesystem_shapetype_unsupported&&(console.warn("ParticleSystem ShapeType is not supported:",ap[this.shapeType]),globalThis.__particlesystem_shapetype_unsupported=!0);break}this.randomizePosition(this._vector,this.randomPositionAmount)}this.applyRotation(this._vector),i&&(this._vector.applyQuaternion(this.system.worldQuaternion),this._vector.add(this.system.worldPos)),rp&&F.DrawSphere(this._vector,.03,16711680,.5,!0)}_dir=new b;getDirection(e,t){if(!this.enabled)return this._dir.set(0,0,1),this._dir;switch(this.shapeType){case 5:this._dir.set(0,0,1);break;case 4:this._dir.set(0,0,1);break;case 10:case 0:const i=t.x,n=t.y,s=t.z;this._dir.set(i,n,s),this.system?.worldspace?this._dir.sub(this.system.worldPos):this._dir.sub(this.position);break;case 13:const r=e.mesh,a=e.mesh_geometry;if(r&&a)switch(this.meshShapeType){case 0:{const l=a.getAttribute("normal"),c=e.mesh_normal;this._dir.fromBufferAttribute(l,c)}break;case 1:break;case 2:{const l=a.index;if(l){const c=e.mesh_normal,h=l.getX(c*3),d=l.getX(c*3+1),p=l.getX(c*3+2),m=a.getAttribute("position"),f=$(),g=$(),y=$();f.fromBufferAttribute(m,h),g.fromBufferAttribute(m,d),y.fromBufferAttribute(m,p),f.sub(g),y.sub(g),f.cross(y),this._dir.copy(f).multiplyScalar(-1);const _=be(r);this._dir.applyQuaternion(_)}}break}break;default:this._dir.set(0,0,1);break}return this._space===1&&this._dir.applyQuaternion(this.system.worldQuaternion),this.applyRotation(this._dir),this._dir.normalize(),this.spherizeDirection(this._dir,this.sphericalDirectionAmount),this.randomizeDirection(this._dir,this.randomDirectionAmount),rp&&(F.DrawSphere(t,.01,8925952,.5,!0),F.DrawDirection(t,this._dir,8925952,.5,!0)),this._dir}static _randomQuat=new U;static _tempVec=new b;randomizePosition(e,t){if(t<=0)return;const i=Zh._tempVec;i.set(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1),i.x*=t*this.scale.x,i.y*=t*this.scale.y,i.z*=t*this.scale.z,e.add(i)}randomizeDirection(e,t){if(t===0)return;const i=Zh._randomQuat,n=Zh._tempVec;n.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).normalize(),i.setFromAxisAngle(n,t*Math.random()*Math.PI),e.applyQuaternion(i)}spherizeDirection(e,t){if(t===0)return;const i=Math.random()*Math.PI*2,n=Math.acos(1-Math.random()*2),s=Math.sin(n)*Math.cos(i),r=Math.sin(n)*Math.sin(i),a=Math.cos(n),l=new b(s,r,a);e.lerp(l,t)}randomSpherePoint(e,t,i,n,s){const r=Math.random(),a=Math.random(),l=2*Math.PI*r*(n/360),c=Math.acos(2*a-1),h=D.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,d=e.x+this.scale.x*(-h*Math.sin(c)*Math.cos(l)),p=e.y+this.scale.y*(h*Math.sin(c)*Math.sin(l)),m=e.z+this.scale.z*(h*Math.cos(c));s.x=d,s.y=p,s.z=m}randomCirclePoint(e,t,i,n,s){const r=Math.random(),a=2*Math.PI*r*(n/360),l=D.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,c=e.x+this.scale.x*l*Math.cos(a),h=e.y+this.scale.y*l*Math.sin(a),d=e.z;s.x=c,s.y=h,s.z=d}_loopTime=0;_loopDirection=1;randomConePoint(e,t,i,n,s,r,a){let l=0,c=0;switch(r){case 0:l=Math.random(),c=Math.random();break;case 2:this._loopTime>1&&(this._loopDirection=-1),this._loopTime<0&&(this._loopDirection=1);case 1:l=.5,c=Math.random(),this._loopTime+=this.system.deltaTime*this._loopDirection;break}let h=2*Math.PI*l*(s/360);switch(r){case 2:case 1:h+=Math.PI+.5,h+=this._loopTime*Math.PI*2,h%=D.toRadians(s);break}const d=Math.acos(2*c-1),p=D.lerp(1,1-Math.pow(1-Math.random(),Math.PI),n)*i,m=e.x+-p*Math.sin(d)*Math.cos(h),f=e.y+p*Math.sin(d)*Math.sin(h),g=e.z;a.x=m*this.scale.x,a.y=f*this.scale.y,a.z=g*this.scale.z}};S([u()],Ze.prototype,"shapeType"),S([u()],Ze.prototype,"enabled"),S([u()],Ze.prototype,"alignToDirection"),S([u()],Ze.prototype,"angle"),S([u()],Ze.prototype,"arc"),S([u()],Ze.prototype,"arcSpread"),S([u()],Ze.prototype,"arcSpeedMultiplier"),S([u()],Ze.prototype,"arcMode"),S([u(b)],Ze.prototype,"boxThickness"),S([u(b)],Ze.prototype,"position"),S([u(b)],Ze.prototype,"rotation"),S([u(b)],Ze.prototype,"scale"),S([u()],Ze.prototype,"radius"),S([u()],Ze.prototype,"radiusThickness"),S([u()],Ze.prototype,"sphericalDirectionAmount"),S([u()],Ze.prototype,"randomDirectionAmount"),S([u()],Ze.prototype,"randomPositionAmount"),S([u()],Ze.prototype,"meshShapeType"),S([u(Bc)],Ze.prototype,"meshRenderer");let Ly=Ze;class _e{damping;enabled;frequency;octaveCount;octaveMultiplier;octaveScale;positionAmount;quality;remap;remapEnabled;remapMultiplier;remapX;remapXMultiplier;remapY;remapYMultiplier;remapZ;remapZMultiplier;scrollSpeedMultiplier;separateAxes;strengthMultiplier;strengthX;strengthXMultiplier;strengthY;strengthYMultiplier;strengthZ;strengthZMultiplier;_noise;_time=0;update(e){this._time+=e.time.deltaTime*this.scrollSpeedMultiplier}_temp=new b;apply(e,t,i,n,s,r){if(!this.enabled)return;this._noise||(this._noise=FC(()=>0));const a=this._temp.set(t.x,t.y,t.z).multiplyScalar(this.frequency),l=this._noise(a.x,a.y,a.z,this._time),c=this._noise(a.x,a.y,a.z,this._time+1e3*this.frequency),h=this._noise(a.x,a.y,a.z,this._time+2e3*this.frequency);this._temp.set(l,c,h).normalize();const d=s/r;let p=this.positionAmount.evaluate(d);this.separateAxes?(this._temp.x*=p*this.strengthXMultiplier,this._temp.y*=p*this.strengthYMultiplier,this._temp.z*=p*this.strengthZMultiplier):(this.strengthX&&(p*=this.strengthX.evaluate(d)*1.5),this._temp.multiplyScalar(p)),i.x+=this._temp.x,i.y+=this._temp.y,i.z+=this._temp.z}}S([u()],_e.prototype,"damping"),S([u()],_e.prototype,"enabled"),S([u()],_e.prototype,"frequency"),S([u()],_e.prototype,"octaveCount"),S([u()],_e.prototype,"octaveMultiplier"),S([u()],_e.prototype,"octaveScale"),S([u(Q)],_e.prototype,"positionAmount"),S([u()],_e.prototype,"quality"),S([u(Q)],_e.prototype,"remap"),S([u()],_e.prototype,"remapEnabled"),S([u()],_e.prototype,"remapMultiplier"),S([u(Q)],_e.prototype,"remapX"),S([u()],_e.prototype,"remapXMultiplier"),S([u(Q)],_e.prototype,"remapY"),S([u()],_e.prototype,"remapYMultiplier"),S([u(Q)],_e.prototype,"remapZ"),S([u()],_e.prototype,"remapZMultiplier"),S([u()],_e.prototype,"scrollSpeedMultiplier"),S([u()],_e.prototype,"separateAxes"),S([u()],_e.prototype,"strengthMultiplier"),S([u(Q)],_e.prototype,"strengthX"),S([u()],_e.prototype,"strengthXMultiplier"),S([u(Q)],_e.prototype,"strengthY"),S([u()],_e.prototype,"strengthYMultiplier"),S([u(Q)],_e.prototype,"strengthZ"),S([u()],_e.prototype,"strengthZMultiplier");class Fe{enabled;attachRibbonToTransform=!1;colorOverLifetime;colorOverTrail;dieWithParticles=!0;inheritParticleColor=!0;lifetime;lifetimeMultiplier;minVertexDistance=.2;mode=0;ratio=1;ribbonCount=1;shadowBias=0;sizeAffectsLifetime=!1;sizeAffectsWidth=!1;splitSubEmitterRibbons=!1;textureMode=0;widthOverTrail;widthOverTrailMultiplier;worldSpace=!1;getWidth(e,t,i,n){const s=this.widthOverTrail.evaluate(i,n);return e*=s,e}getColor(e,t,i){const n=this.colorOverTrail.evaluate(i),s=this.colorOverLifetime.evaluate(t);e.x*=n.r*s.r,e.y*=n.g*s.g,e.z*=n.b*s.b,"alpha"in n&&"alpha"in s&&(e.w*=n.alpha*s.alpha)}}S([u()],Fe.prototype,"enabled"),S([u()],Fe.prototype,"attachRibbonToTransform"),S([u($r)],Fe.prototype,"colorOverLifetime"),S([u($r)],Fe.prototype,"colorOverTrail"),S([u()],Fe.prototype,"dieWithParticles"),S([u()],Fe.prototype,"inheritParticleColor"),S([u(Q)],Fe.prototype,"lifetime"),S([u()],Fe.prototype,"lifetimeMultiplier"),S([u()],Fe.prototype,"minVertexDistance"),S([u()],Fe.prototype,"mode"),S([u()],Fe.prototype,"ratio"),S([u()],Fe.prototype,"ribbonCount"),S([u()],Fe.prototype,"shadowBias"),S([u()],Fe.prototype,"sizeAffectsLifetime"),S([u()],Fe.prototype,"sizeAffectsWidth"),S([u()],Fe.prototype,"splitSubEmitterRibbons"),S([u()],Fe.prototype,"textureMode"),S([u(Q)],Fe.prototype,"widthOverTrail"),S([u()],Fe.prototype,"widthOverTrailMultiplier"),S([u()],Fe.prototype,"worldSpace");class We{enabled;space=0;orbitalX;orbitalY;orbitalZ;orbitalXMultiplier;orbitalYMultiplier;orbitalZMultiplier;orbitalOffsetX;orbitalOffsetY;orbitalOffsetZ;speedModifier;speedModifierMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;_system;update(e){this._system=e}_temp=new b;_temp2=new b;_temp3=new b;_hasOrbital=!1;_index=0;_orbitalMatrix=new ee;init(e){this._index==0&&(e.debug=!0),this._index+=1,e.orbitx=this.orbitalX.evaluate(Math.random()),e.orbity=this.orbitalY.evaluate(Math.random()),e.orbitz=this.orbitalZ.evaluate(Math.random()),this._hasOrbital=e.orbitx!=0||e.orbity!=0||e.orbitz!=0}apply(e,t,i,n,s,r,a){if(!this.enabled)return;const l=r/a,c=this.speedModifier.evaluate(l)*this.speedModifierMultiplier,h=this.x.evaluate(l),d=this.y.evaluate(l),p=this.z.evaluate(l);if(this._temp.set(-h,d,p),this._system&&this._system.main.simulationSpace===1&&this._temp.applyQuaternion(this._system.worldQuaternion),this._hasOrbital&&this._system?.worldPos){const m=this._temp2.set(i.x,i.y,i.z),f=this.orbitalXMultiplier,g=this.orbitalYMultiplier,y=this.orbitalZMultiplier,_=c*Math.PI*2*10,v=Math.cos(_*f),P=Math.sin(_*f),R=Math.cos(_*g),k=Math.sin(_*g),A=Math.cos(_*y),L=Math.sin(_*y),N=m.x*(R*A)+m.y*(R*L)+m.z*-k,j=m.x*(P*k*A-v*L)+m.y*(P*k*L+v*A)+m.z*(P*R),q=m.x*(v*k*A+P*L)+m.y*(v*k*L-P*A)+m.z*(v*R),Y=this._temp3.set(m.x-N,m.y-j,m.z-q);Y.normalize(),Y.multiplyScalar(.2/s*Math.max(this.orbitalXMultiplier,this.orbitalYMultiplier,this.orbitalZMultiplier)),n.x+=Y.x,n.y+=Y.y,n.z+=Y.z}n.x+=this._temp.x,n.y+=this._temp.y,n.z+=this._temp.z,n.x*=c,n.y*=c,n.z*=c}}S([u()],We.prototype,"enabled"),S([u()],We.prototype,"space"),S([u(Q)],We.prototype,"orbitalX"),S([u(Q)],We.prototype,"orbitalY"),S([u(Q)],We.prototype,"orbitalZ"),S([u()],We.prototype,"orbitalXMultiplier"),S([u()],We.prototype,"orbitalYMultiplier"),S([u()],We.prototype,"orbitalZMultiplier"),S([u()],We.prototype,"orbitalOffsetX"),S([u()],We.prototype,"orbitalOffsetY"),S([u()],We.prototype,"orbitalOffsetZ"),S([u(Q)],We.prototype,"speedModifier"),S([u()],We.prototype,"speedModifierMultiplier"),S([u(Q)],We.prototype,"x"),S([u()],We.prototype,"xMultiplier"),S([u(Q)],We.prototype,"y"),S([u()],We.prototype,"yMultiplier"),S([u(Q)],We.prototype,"z"),S([u()],We.prototype,"zMultiplier");class Ft{animation;enabled;cycleCount;frameOverTime;frameOverTimeMultiplier;numTilesX;numTilesY;startFrame;startFrameMultiplier;rowMode;rowIndex;spriteCount;timeMode;sampleOnceAtStart(){if(this.timeMode===0)switch(this.frameOverTime.mode){case 0:case 3:case 2:case 1:return!0}return!1}getStartIndex(){return this.sampleOnceAtStart()?Math.random()*(this.numTilesX*this.numTilesY):0}evaluate(e){if(!this.sampleOnceAtStart())return this.getIndex(e)}getIndex(e){const t=this.numTilesX*this.numTilesY;e=e*this.cycleCount;let i=this.frameOverTime.evaluate(e%1);return i*=this.frameOverTimeMultiplier,i*=t,i=i%t,i=Math.floor(i),i}}S([u()],Ft.prototype,"animation"),S([u()],Ft.prototype,"enabled"),S([u()],Ft.prototype,"cycleCount"),S([u(Q)],Ft.prototype,"frameOverTime"),S([u()],Ft.prototype,"frameOverTimeMultiplier"),S([u()],Ft.prototype,"numTilesX"),S([u()],Ft.prototype,"numTilesY"),S([u(Q)],Ft.prototype,"startFrame"),S([u()],Ft.prototype,"startFrameMultiplier"),S([u()],Ft.prototype,"rowMode"),S([u()],Ft.prototype,"rowIndex"),S([u()],Ft.prototype,"spriteCount"),S([u()],Ft.prototype,"timeMode");class Pn{enabled;separateAxes;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t){return this.enabled?this.separateAxes?0:this.z.evaluate(e,t)*-1:0}}S([u()],Pn.prototype,"enabled"),S([u()],Pn.prototype,"separateAxes"),S([u(Q)],Pn.prototype,"x"),S([u()],Pn.prototype,"xMultiplier"),S([u(Q)],Pn.prototype,"y"),S([u()],Pn.prototype,"yMultiplier"),S([u(Q)],Pn.prototype,"z"),S([u()],Pn.prototype,"zMultiplier");class tn{enabled;range;separateAxes;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t){if(!this.enabled)return 0;if(!this.separateAxes){const i=D.lerp(this.range.x,this.range.y,t);return this.z.evaluate(i)*-1}return 0}}S([u()],tn.prototype,"enabled"),S([u()],tn.prototype,"range"),S([u()],tn.prototype,"separateAxes"),S([u(Q)],tn.prototype,"x"),S([u()],tn.prototype,"xMultiplier"),S([u(Q)],tn.prototype,"y"),S([u()],tn.prototype,"yMultiplier"),S([u(Q)],tn.prototype,"z"),S([u()],tn.prototype,"zMultiplier");class lt{enabled;dampen;drag;dragMultiplier;limit;limitMultiplier;separateAxes;limitX;limitXMultiplier;limitY;limitYMultiplier;limitZ;limitZMultiplier;multiplyDragByParticleSize=!1;multiplyDragByParticleVelocity=!1;space;_temp=new b;_temp2=new b;apply(e,t,i,n,s,r,a){if(this.enabled){const l=this.limit.evaluate(s)*this.limitMultiplier;if(t.length()>l){this._temp.copy(t).normalize().multiplyScalar(l);const c=this.dampen*.5;t.x=D.lerp(t.x,this._temp.x,c),t.y=D.lerp(t.y,this._temp.y,c),t.z=D.lerp(t.z,this._temp.z,c),i.x=D.lerp(i.x,this._temp.x,c),i.y=D.lerp(i.y,this._temp.y,c),i.z=D.lerp(i.z,this._temp.z,c)}}}}S([u()],lt.prototype,"enabled"),S([u()],lt.prototype,"dampen"),S([u(Q)],lt.prototype,"drag"),S([u()],lt.prototype,"dragMultiplier"),S([u(Q)],lt.prototype,"limit"),S([u()],lt.prototype,"limitMultiplier"),S([u()],lt.prototype,"separateAxes"),S([u(Q)],lt.prototype,"limitX"),S([u()],lt.prototype,"limitXMultiplier"),S([u(Q)],lt.prototype,"limitY"),S([u()],lt.prototype,"limitYMultiplier"),S([u(Q)],lt.prototype,"limitZ"),S([u()],lt.prototype,"limitZMultiplier"),S([u()],lt.prototype,"multiplyDragByParticleSize"),S([u()],lt.prototype,"multiplyDragByParticleVelocity"),S([u()],lt.prototype,"space");const rh=class q1{enabled;curve;curveMultiplier;mode;clone(){const e=new q1;return e.enabled=this.enabled,e.curve=this.curve?.clone(),e.curveMultiplier=this.curveMultiplier,e.mode=this.mode,e}system;get _lastWorldPosition(){return this.system._iv_lastWorldPosition||(this.system._iv_lastWorldPosition=new b),this.system._iv_lastWorldPosition}get _velocity(){return this.system._iv_velocity||(this.system._iv_velocity=new b),this.system._iv_velocity}_temp=new b;_firstUpdate=!0;awake(e){this.system=e,this.reset()}reset(){this._firstUpdate=!0}update(e){this.enabled&&this.system.worldspace!==!1&&(this._firstUpdate?(this._firstUpdate=!1,this._velocity.set(0,0,0),this._lastWorldPosition.copy(this.system.worldPos)):this._lastWorldPosition&&(this._velocity.copy(this.system.worldPos).sub(this._lastWorldPosition).multiplyScalar(1/this.system.deltaTime),this._lastWorldPosition.copy(this.system.worldPos)))}applyInitial(e){if(this.enabled&&this.system.worldspace!==!1&&this.mode===0){const t=this.curve.evaluate(Math.random(),Math.random());this._temp.copy(this._velocity).multiplyScalar(t),e.x+=this._temp.x,e.y+=this._temp.y,e.z+=this._temp.z}}_frames=0;applyCurrent(e,t,i){if(this.enabled&&this.system&&this.system.worldspace!==!1&&this.mode===1){const n=this.curve.evaluate(t,i);this._temp.copy(this._velocity).multiplyScalar(n),e.x+=this._temp.x,e.y+=this._temp.y,e.z+=this._temp.z}}};S([u()],rh.prototype,"enabled"),S([u(Q)],rh.prototype,"curve"),S([u()],rh.prototype,"curveMultiplier"),S([u()],rh.prototype,"mode");let jy=rh;class pi{enabled;range;separateAxes;size;sizeMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t,i,n){const s=e.length(),r=D.remap(s,this.range.x,this.range.y,0,1),a=this.size.evaluate(r,i);return n.x*=a,n.y*=a,n.z*=a,n}}S([u()],pi.prototype,"enabled"),S([u(J)],pi.prototype,"range"),S([u()],pi.prototype,"separateAxes"),S([u(Q)],pi.prototype,"size"),S([u()],pi.prototype,"sizeMultiplier"),S([u(Q)],pi.prototype,"x"),S([u()],pi.prototype,"xMultiplier"),S([u(Q)],pi.prototype,"y"),S([u()],pi.prototype,"yMultiplier"),S([u(Q)],pi.prototype,"z"),S([u()],pi.prototype,"zMultiplier");class fl{enabled;range;color;evaluate(e,t,i){const n=e.length(),s=D.remap(n,this.range.x,this.range.y,0,1),r=this.color.evaluate(s,t);i.x*=r.r,i.y*=r.g,i.z*=r.b,"alpha"in r&&(i.w*=r.alpha)}}S([u()],fl.prototype,"enabled"),S([u(J)],fl.prototype,"range"),S([u($r)],fl.prototype,"color"),new b(1,1,1),new b(0,0,1);class Dy{constructor(e,t,i,n){this.system=e,this.particleSystem=t,this.subSystem=i,this.subParticleSystem=n,this.subParticleSystem&&this.subParticleSystem&&(this.subParticleSystem.onlyUsedByOther=!0);const s=1e3;this._circularBuffer=new wi(()=>new ym,s)}type="NeedleParticleSubEmitter";emitterType;emitterProbability;q_=new U;v_=new b;v2_=new b;_emitterMatrix=new ym;_circularBuffer;clone(){throw new Error("Method not implemented.")}initialize(e){e.emissionState={burstIndex:0,burstWaveIndex:0,time:0,waitEmiting:0},this._emitterMatrix.copy(this.subSystem.matrixWorld).invert().premultiply(this.system.matrixWorld),this._emitterMatrix.setPosition(0,0,0),this.emitterType===By.Birth&&this.run(e)}update(e,t){this.run(e)}frameUpdate(e){}toJSON(){}reset(){}run(e){if(this.subSystem.currentParticles>=this.subSystem.main.maxParticles||!this.subParticleSystem||!e.emissionState||this.emitterProbability&&Math.random()>this.emitterProbability)return;const t=this.system.deltaTime;if(this.emitterType===By.Death){let n=e.life;if(e[yl]!==void 0&&(n=e[yl]),!(e.age+t*1.2>=n))return;const s=this.subSystem.main.maxParticles-this.subSystem.currentParticles;e.emissionState.waitEmiting=s}const i=new ym;i.set(1,0,0,e.position.x,0,1,0,e.position.y,0,0,1,e.position.z,0,0,0,1),this.particleSystem.worldSpace||i.multiplyMatrices(this._emitterMatrix,i),this.subParticleSystem.emit(t,e.emissionState,i)}}var zE=Object.defineProperty,Ue=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&zE(e,t,n),n};const Bs=w("debugparticles"),NE=w("noprogressive"),WE=w("debugprogressive");var By=(o=>(o[o.Birth=0]="Birth",o[o.Collision=1]="Collision",o[o.Death=2]="Death",o[o.Trigger=3]="Trigger",o[o.Manual=4]="Manual",o))(By||{});class nn extends M{renderMode;particleMaterial;trailMaterial;particleMesh;maxParticleSize;minParticleSize;velocityScale;cameraVelocityScale;lengthScale;start(){if(this.maxParticleSize!==.5&&this.minParticleSize!==0&&E()){const e=`ParticleSystem "${this.name}" has non-default min/max particle size. This may not render correctly. Please set min size to 0 and the max size to 0.5 and use the "StartSize" setting instead`;console.warn(e)}}get transparent(){return this.particleMaterial?.transparent??!1}getMaterial(e=!1){let t=e===!0&&this.trailMaterial?this.trailMaterial:this.particleMaterial;if(t){if(t.type==="MeshStandardMaterial"){Bs&&console.debug("ParticleSystemRenderer.getMaterial: MeshStandardMaterial detected, converting to MeshBasicMaterial. See https://github.com/Alchemist0823/three.quarks/issues/101"),"map"in t&&t.map&&(t.map.colorSpace=po,t.map.premultiplyAlpha=!1);const i=new xe;i.copy(t),e?this.trailMaterial=i:this.particleMaterial=i}t.map&&(t.map.colorSpace=po,t.map.premultiplyAlpha=!1),e&&t.side===as&&(t=t.clone(),t.side=ud,e?this.trailMaterial=t:this.particleMaterial=t)}return t&&!NE&&t._didRequestTextureLOD===void 0&&(t._didRequestTextureLOD=0,WE&&console.log("Load material LOD",t.name),Ve.assignTextureLOD(t,0)),t}getMesh(e){let t=null;if(!t&&(this.particleMesh instanceof H&&(t=this.particleMesh.geometry),t===null)){t=new In(1,1);const i=t.attributes.uv;for(let n=0;n<i.count;n++)i.setX(n,1-i.getX(n))}return new H(t,this.getMaterial())}}Ue([u()],nn.prototype,"renderMode"),Ue([u(ve)],nn.prototype,"particleMaterial"),Ue([u(ve)],nn.prototype,"trailMaterial"),Ue([u()],nn.prototype,"maxParticleSize"),Ue([u()],nn.prototype,"minParticleSize"),Ue([u()],nn.prototype,"velocityScale"),Ue([u()],nn.prototype,"cameraVelocityScale"),Ue([u()],nn.prototype,"lengthScale");class hp{_curve;_factor;constructor(e,t=1){this._curve=e,this._factor=t}type="function";startGen(e){}genValue(e,t){return this._curve.evaluate(t,Math.random())*this._factor}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}}class Fy{type="value";toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}startGen(e){}system;constructor(e){this.system=e}}class VE extends Fy{genValue(){return this.system.textureSheetAnimation.getStartIndex()}}class $E extends Fy{_lastPosition=new b;_lastDistance=0;update(){const e=Z(this.system.gameObject);this._lastDistance=this._lastPosition.distanceTo(e),this._lastPosition.copy(e)}genValue(){if(!this.system.isPlaying||!this.system.emission.enabled||this.system.currentParticles>=this.system.maxParticles)return 0;let e=this.system.emission.rateOverTime.evaluate(this.system.time/this.system.duration,Math.random());if(this.system.deltaTime>0){const n=this.system.emission.rateOverDistance.evaluate(this.system.time/this.system.duration,Math.random());let s=this._lastDistance/this.system.deltaTime*n;Number.isFinite(s)||(s=0),e+=s}const t=this.system.emission.getBurst();t>0&&(e+=t/this.system.deltaTime);const i=this.system.maxParticles-this.system.currentParticles;return D.clamp(e,0,i/this.system.deltaTime)}}class HE extends Fy{genValue(){return this.system.isPlaying,0}}class Fs{system;get context(){return this.system.context}constructor(e){this.type=Object.getPrototypeOf(this).constructor.name||"ParticleSystemBaseBehaviour",e&&(this.system=e)}type;initialize(e){}update(e,t){}frameUpdate(e){}toJSON(){throw new Error("Method not implemented.")}clone(){throw new Error("Method not implemented.")}reset(){}}class GE extends Fs{type="NeedleTextureSheet";update(e,t){const i=this.system.textureSheetAnimation;if(i.enabled){const n=e.age/e.life,s=i.evaluate(n);s!==void 0&&(e.uvTile=s)}}}const Fx=Symbol("particleRotation");class qE extends Fs{type="NeedleRotation";initialize(e){e[Fx]=Math.random()}update(e,t){if(e.rotation===void 0)return;const i=e.age/e.life;if(typeof e.rotation=="number"&&(this.system.rotationOverLifetime.enabled?e.rotation+=this.system.rotationOverLifetime.evaluate(i,e[Fx])*t:this.system.renderer.renderMode===Fo.Billboard&&(e.rotation=Math.PI),this.system.rotationBySpeed.enabled)){const n=e.velocity.length();e.rotation+=this.system.rotationBySpeed.evaluate(i,n)*t}}}const Ux=Symbol("sizeLerpFactor"),XE=new b;class QE extends Fs{type="NeedleSize";_minSize=0;_maxSize=1;initialize(e){e[Ux]=Math.random(),this._minSize=this.system.renderer.minParticleSize,this._maxSize=this.system.renderer.maxParticleSize}update(e,t){const i=e.age/e.life;let n=1;this.system.sizeOverLifetime.enabled&&(n*=this.system.sizeOverLifetime.evaluate(i,void 0,e[Ux]).x);let s=1;this.system.renderer.renderMode!==Fo.Mesh&&(s=this.system.worldScale.x/this.system.cameraScale);const r=$(e.startSize).multiplyScalar(n*s);if(e.size.set(r.x,r.y,r.z),this.system.localspace){const a=$x(this.system,XE);e.size.x*=a.x,e.size.y*=a.y,e.size.z*=a.z}}}const yl=Symbol("particleLife"),Uy=Symbol("trailLifetime"),zx=Symbol("trailStartLength"),zy=Symbol("trailWidthRandom");class YE extends Fs{type="NeedleTrail";initialize(e){e instanceof ob&&(e[yl]=e.life,this.system.trails.enabled&&this.system.trails.dieWithParticles===!1&&(e[Uy]=this.system.trails.lifetime.evaluate(Math.random(),Math.random()),e.life+=e[Uy]),e[zx]=e.length,e[zy]=Math.random())}update(e){if(this.system.trails?.enabled&&e instanceof ob){const t=e,i=e.age/e[yl],n=e.previous.values(),s=e.previous.length;for(let r=0;r<s;r++){const a=n.next().value,l=1-r/(s-1),c=e.size;if(c.x<=0&&!this.system.trails.sizeAffectsWidth){const h=20*this.system.trails.widthOverTrail.evaluate(.5,t[zy]);c.x=h,c.y=h,c.z=h}a.size=this.system.trails.getWidth(c.x,i,l,t[zy]),a.color.copy(e.color),this.system.trails.getColor(a.color,i,l)}if(e.age>e[yl]){e.velocity.set(0,0,0);const r=(e.age-e[yl])/e[Uy];t.length=D.lerp(e[zx],0,r)}}}}const dp=Symbol("startVelocity"),Nx=Symbol("gravityModifier"),Ny=Symbol("gravitySpeed"),up=Symbol("velocity lerp factor"),Wy=new b;class KE extends Fs{type="NeedleVelocity";_gravityDirection=new b;initialize(e){const t=this.system.main.simulationSpeed;e.startSpeed=this.system.main.startSpeed.evaluate(Math.random(),Math.random());const i=this.system.shape.getDirection(e,e.position);e.velocity.x=i.x*e.startSpeed,e.velocity.y=i.y*e.startSpeed,e.velocity.z=i.z*e.startSpeed,this.system.inheritVelocity?.enabled&&this.system.inheritVelocity.applyInitial(e.velocity),e[dp]?e[dp].copy(e.velocity):e[dp]=e.velocity.clone();const n=this.system.main.gravityModifier.evaluate(Math.random(),Math.random());e[Nx]=n*t,e[Ny]=n*t*.5,e[up]=Math.random(),this.system.velocityOverLifetime?.init(e),this._gravityDirection.set(0,-1,0),this.system.main.simulationSpace===sh.Local&&this._gravityDirection.applyQuaternion(this.system.worldQuaternionInverted).normalize()}update(e,t){const i=e[dp],n=e[Nx];if(n!==0){const d=n*e[Ny];Wy.copy(this._gravityDirection).multiplyScalar(d),e[Ny]+=t*.05,i.add(Wy)}e.velocity.copy(i);const s=e.age/e.life;this.system.inheritVelocity?.enabled&&this.system.inheritVelocity.applyCurrent(e.velocity,s,e[up]);const r=this.system.noise;r.enabled&&r.apply(0,e.position,e.velocity,t,e.age,e.life);const a=this.system.sizeBySpeed;a?.enabled&&(e.size=a.evaluate(e.velocity,s,e[up],e.size));const l=this.system.colorBySpeed;l?.enabled&&l.evaluate(e.velocity,e[up],e.color);const c=this.system.velocityOverLifetime;c.enabled&&c.apply(e,0,e.position,e.velocity,t,e.age,e.life);const h=this.system.limitVelocityOverLifetime;if(h.enabled&&h.apply(e.position,i,e.velocity,e.size,s,t,1),this.system.worldspace){const d=this.system.worldScale;e.velocity.x*=d.x,e.velocity.y*=d.y,e.velocity.z*=d.z}}}const Wx=Symbol("colorLerpFactor"),Vx=new se(1,1,1,1),Gr=new se(1,1,1,1);class ZE extends Fs{type="NeedleColor";initialize(e){}_init(e){const t=this.system.renderer.particleMaterial;Gr.copy(this.system.main.startColor.evaluate(Math.random())),t?.color&&(Vx.copy(t.color),Gr.multiply(Vx)),Gr.convertLinearToSRGB(),e.startColor.set(Gr.r,Gr.g,Gr.b,Gr.alpha),e.color.copy(e.startColor),e[Wx]=Math.random()}update(e,t){if(e.age===0&&this._init(e),this.system.colorOverLifetime.enabled){const i=e.age/e.life,n=this.system.colorOverLifetime.color.evaluate(i,e[Wx]);e.color.set(n.r,n.g,n.b,"alpha"in n?n.alpha:1).multiply(e.startColor)}else e.color.copy(e.startColor)}}class JE{system;emission;get anim(){return this.system.textureSheetAnimation}constructor(e){this.system=e,this.emission=new $E(this.system)}get prewarm(){return!1}get material(){return this.system.renderer.getMaterial(this.system.trails.enabled)}get layers(){return this.system.gameObject.layers}update(){this.emission.update()}autoDestroy;get looping(){return this.system.main.loop}get duration(){return this.system.duration}get shape(){return this.system.shape}get startLife(){return new hp(this.system.main.startLifetime)}get startSpeed(){return new hp(this.system.main.startSpeed)}get startRotation(){return new hp(this.system.main.startRotation)}get startSize(){return new hp(this.system.main.startSize)}startLength;get startColor(){return new NC(new WC(1,1,1,1))}get emissionOverTime(){return this.emission}get emissionOverDistance(){return new HE(this.system)}emissionBursts;onlyUsedByOther;behaviors=[];get instancingGeometry(){return this.system.renderer.getMesh(this.system.renderer.renderMode).geometry}get renderMode(){if(this.system.trails.enabled===!0)return yo.Trail;switch(this.system.renderer.renderMode){case Fo.Billboard:return yo.BillBoard;case Fo.Stretch:return yo.StretchedBillBoard;case Fo.HorizontalBillboard:return yo.HorizontalBillBoard;case Fo.VerticalBillboard:return yo.VerticalBillBoard;case Fo.Mesh:return yo.Mesh}return yo.BillBoard}rendererEmitterSettings={startLength:new VC(220),followLocalOrigin:!1};get speedFactor(){let e=this.system.main.simulationSpeed;return this.system.renderer?.renderMode===Fo.Stretch&&(e*=this.system.renderer.velocityScale??1),e}flatWhiteTexture;clonedTexture={original:void 0,clone:void 0};get texture(){const e=this.material;if(e&&e.map){const t=e.map;if(this.clonedTexture.original!==t||!this.clonedTexture.clone){const i=t.clone();i.premultiplyAlpha=!1,i.colorSpace=po,this.clonedTexture.original=t,this.clonedTexture.clone=i}return this.clonedTexture.clone}return this.flatWhiteTexture||(this.flatWhiteTexture=Fg(new se(1,1,1,1),1)),this.flatWhiteTexture}get startTileIndex(){return new VE(this.system)}get uTileCount(){return this.anim.enabled?this.anim?.numTilesX:void 0}get vTileCount(){return this.anim.enabled?this.anim?.numTilesY:void 0}get renderOrder(){return 1}get blending(){return this.system.renderer.particleMaterial?.blending??eC}get transparent(){return this.system.renderer.transparent}get worldSpace(){return this.system.main.simulationSpace===sh.World}}class eA{burstParticleIndex=0;burstParticleCount=0;isBursting=!1;travelDistance=0;previousWorldPos;burstIndex=0;burstWaveIndex=0;time=0;waitEmiting=0}const Ut=class qp extends M{play(e=!1){e&&x.foreachComponent(this.gameObject,t=>{t instanceof qp&&t!==this&&t.play(!1)},!0),this._isPlaying=!0,this._particleSystem&&(this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1),this.emission?.reset()}pause(e=!0){e&&x.foreachComponent(this.gameObject,t=>{t instanceof qp&&t!==this&&t.pause(!1)},!0),this._isPlaying=!1}stop(e=!0,t=!1){e&&x.foreachComponent(this.gameObject,i=>{i instanceof qp&&i!==this&&i.stop(!1,t)},!0),this._isPlaying=!1,this._time=0,t&&this.reset()}reset(){this._time=0,this._particleSystem&&(this._particleSystem.particleNum=0,this._particleSystem.emissionState.time=0,this._particleSystem.emitEnded=!1,this.emission?.reset())}_state;emit(e){if(this._particleSystem){this.onUpdate(),e=Math.min(e,this.maxParticles-this.currentParticles),this._state||(this._state=new eA),this._state.waitEmiting=e,this._state.time=0;const t=this._particleSystem.emitEnded;this._particleSystem.emitEnded=!1,this._particleSystem.emit(this.deltaTime,this._state,this._particleSystem.emitter.matrixWorld),this._particleSystem.emitEnded=t}}get playOnAwake(){return this.main.playOnAwake}set playOnAwake(e){this.main.playOnAwake=e}colorOverLifetime;main;emission;sizeOverLifetime;shape;noise;trails;velocityOverLifetime;limitVelocityOverLifetime;inheritVelocity;colorBySpeed;textureSheetAnimation;rotationOverLifetime;rotationBySpeed;sizeBySpeed;get renderer(){return this._renderer}get isPlaying(){return this._isPlaying}get currentParticles(){return this._particleSystem?.particleNum??0}get maxParticles(){return this.main.maxParticles}get time(){return this._time}get duration(){return this.main.duration}get deltaTime(){return this.context.time.deltaTime*this.main.simulationSpeed}get scale(){return this.gameObject.scale.x}get cameraScale(){return this._cameraScale}_cameraScale=1;get container(){return this._container}get worldspace(){return this.main.simulationSpace===sh.World}get localspace(){return this.main.simulationSpace===sh.Local}__worldQuaternion=new U;get worldQuaternion(){return this.__worldQuaternion}_worldQuaternionInverted=new U;get worldQuaternionInverted(){return this._worldQuaternionInverted}_worldScale=new b;get worldScale(){return this._worldScale}_worldPositionFrame=-1;_worldPos=new b;get worldPos(){return this._worldPositionFrame!==this.context.time.frame&&(this._worldPositionFrame=this.context.time.frame,Z(this.gameObject,this._worldPos)),this._worldPos}get matrixWorld(){return this._container.matrixWorld}get isSubsystem(){return this._isUsedAsSubsystem}addBehaviour(e){return this._particleSystem?(e instanceof Fs&&(e.system=this),Bs&&console.debug("Add custom ParticleSystem Behaviour",e),this._particleSystem.addBehavior(e),!0):!1}removeBehaviour(e){if(!this._particleSystem)return!1;const t=this._particleSystem.behaviors,i=t.indexOf(e);return i!==-1&&((E()||Bs)&&console.debug("Remove custom ParticleSystem Behaviour",i,e),t.splice(i,1)),!0}removeAllBehaviours(){return this._particleSystem?(this._particleSystem.behaviors.length=0,!0):!1}get behaviours(){return this._particleSystem?this._particleSystem.behaviors:null}get particleSystem(){return this._particleSystem??null}_renderer;_batchSystem;_particleSystem;_interface;_container;_time=0;_isPlaying=!0;_isUsedAsSubsystem=!1;_didPreWarm=!1;set bursts(e){for(let t=0;t<e.length;t++){const i=e[t];if(!(i instanceof lp)){const n=new lp;Aa(n,i),e[t]=n}}this._bursts=e}_bursts;set subEmitterSystems(e){for(let t=0;t<e.length;t++){const i=e[t];if(!(i instanceof pp)){const n=new pp;Aa(n,i),e[t]=n}}Bs&&e.length>0&&console.log("SubEmitters: ",e,this),this._subEmitterSystems=e}_subEmitterSystems;onAfterDeserialize(e){if(this._subEmitterSystems&&Array.isArray(this._subEmitterSystems))for(const t of this._subEmitterSystems)t._deserialize(this.context,this.gameObject)}awake(){if(this._worldPositionFrame=-1,this._renderer=this.gameObject.getComponent(nn),!this.main)throw new Error("Not Supported: ParticleSystem needs a serialized MainModule. Creating new particle systems at runtime is currently not supported.");this._container=new O,this._container.matrixAutoUpdate=!1,this.context.scene.add(this._container),this._batchSystem=new UC,this._batchSystem.name=this.gameObject.name,this._container.add(this._batchSystem),this._interface=new JE(this),this._particleSystem=new zC(this._interface),this._particleSystem.addBehavior(new QE(this)),this._particleSystem.addBehavior(new ZE(this)),this._particleSystem.addBehavior(new GE(this)),this._particleSystem.addBehavior(new qE(this)),this._particleSystem.addBehavior(new KE(this)),this._particleSystem.addBehavior(new YE(this)),this._batchSystem.addSystem(this._particleSystem);const e=this._particleSystem.emitter;this.context.scene.add(e),this.inheritVelocity.system&&this.inheritVelocity.system!==this&&(this.inheritVelocity=this.inheritVelocity.clone()),this.inheritVelocity.awake(this),Bs&&(console.log(this),this.gameObject.add(new _i(1)))}start(){this.addSubParticleSystems(),this.updateLayers(),this.renderer.particleMesh instanceof H&&this._interface.renderMode==yo.Mesh&&Ve.assignMeshLOD(this.renderer.particleMesh,0).then(e=>{e&&this.particleSystem&&this._interface.renderMode==yo.Mesh&&(this.particleSystem.instancingGeometry=e)})}onDestroy(){this._container?.removeFromParent(),this._batchSystem?.removeFromParent(),this._particleSystem?.emitter.removeFromParent(),this._particleSystem?.dispose()}onEnable(){this.main&&(this.inheritVelocity&&(this.inheritVelocity.system=this),this._batchSystem&&(this._batchSystem.visible=!0),this.playOnAwake&&this.play(),this._isPlaying=this.playOnAwake)}onDisable(){this._batchSystem&&(this._batchSystem.visible=!1)}onBeforeRender(){this.main&&(this._didPreWarm===!1&&this.main?.prewarm===!0&&(this._didPreWarm=!0,this.preWarm()),this.onUpdate(),this.onSimulate(this.deltaTime))}preWarm(){if(!this.emission?.enabled||this.emission.rateOverTime.getMax()<=0)return;const e=1/60,t=this.main.duration,i=this.main.startLifetime.getMax(),n=Math.min(Math.max(t,i)/Math.max(.01,this.main.simulationSpeed),1e3),s=Math.ceil(n/e),r=Date.now();Bs&&console.log(`Particles ${this.name} - Prewarm for ${s} frames (${n} sec). Duration: ${t}, Lifetime: ${i}`);for(let a=0;a<s&&!(this.currentParticles>=this.maxParticles);a++){const l=Date.now()-r;if(l>2e3){console.warn(`Particles ${this.name} - Prewarm took too long. Aborting: ${l}`);break}this.onUpdate(),this.onSimulate(e)}}_lastBatchesCount=-1;onSimulate(e){if(this._batchSystem){let t=this.context.time.frameCount%60===0;this._lastBatchesCount!==this._batchSystem.batches.length&&(this._lastBatchesCount=this._batchSystem.batches.length,t=!0),t&&this.updateLayers(),this._batchSystem.update(e)}this._time+=e,this._time>this.duration&&(this._time=0)}updateLayers(){if(this._batchSystem)for(let e=0;e<this._batchSystem.batches.length;e++){const t=this._batchSystem.batches[e];t.layers.disableAll();const i=this.layer;t.layers.mask=1<<i}}onUpdate(){if(this._bursts&&(this.emission.bursts=this._bursts,delete this._bursts),!this._isPlaying)return;const e=this.context.mainCamera;if(e){const n=$e(e);this._cameraScale=n.x}const t=!this.worldspace,i=this.gameObject;if(be(i,this.__worldQuaternion),this._worldQuaternionInverted.copy(this.__worldQuaternion).invert(),$e(this.gameObject,this._worldScale),t&&this._container&&this.gameObject?.parent){const n=$x(this,Wy);this._container.matrix.makeScale(n.x,n.y,n.z),this._container.matrix.makeRotationFromQuaternion(this.__worldQuaternion),this._container.matrix.setPosition(this.worldPos),this._container.matrix.scale(this.gameObject.scale)}this.emission.system=this,this._interface.update(),this.shape.onUpdate(this,this.context,this.main.simulationSpace,this.gameObject),this.noise.update(this.context),this.inheritVelocity?.update(this.context),this.velocityOverLifetime.update(this)}addSubParticleSystems(){if(this._subEmitterSystems&&this._particleSystem)for(const e of this._subEmitterSystems){e.particleSystem&&(e.particleSystem.__internalAwake?e.particleSystem.__internalAwake():E()&&console.warn("SubParticleSystem serialization issue(?)",e.particleSystem,e));const t=e.particleSystem?._particleSystem;if(t){e.particleSystem._isUsedAsSubsystem=!0;const i=new Dy(this,this._particleSystem,e.particleSystem,t);i.emitterType=e.type,i.emitterProbability=e.emitProbability,this._particleSystem.addBehavior(i)}else Bs&&console.warn("Could not add SubParticleSystem",e,this)}}};Ue([u(cp)],Ut.prototype,"colorOverLifetime"),Ue([u(Bt)],Ut.prototype,"main"),Ue([u(zo)],Ut.prototype,"emission"),Ue([u(Hr)],Ut.prototype,"sizeOverLifetime"),Ue([u(Ly)],Ut.prototype,"shape"),Ue([u(_e)],Ut.prototype,"noise"),Ue([u(Fe)],Ut.prototype,"trails"),Ue([u(We)],Ut.prototype,"velocityOverLifetime"),Ue([u(lt)],Ut.prototype,"limitVelocityOverLifetime"),Ue([u(jy)],Ut.prototype,"inheritVelocity"),Ue([u(fl)],Ut.prototype,"colorBySpeed"),Ue([u(Ft)],Ut.prototype,"textureSheetAnimation"),Ue([u(Pn)],Ut.prototype,"rotationOverLifetime"),Ue([u(tn)],Ut.prototype,"rotationBySpeed"),Ue([u(pi)],Ut.prototype,"sizeBySpeed");let ah=Ut;class pp{particleSystem;emitProbability=1;properties;type;_deserialize(e,t){const i=this.particleSystem;if(i instanceof ah)return;let n="";i&&typeof i.guid=="string"&&(n=i.guid,this.particleSystem=x.findByGuid(n,t)),Bs&&!(this.particleSystem instanceof ah)&&console.warn("Could not find particle system for sub emitter",n,t,this)}}function $x(o,e){if(e.set(1,1,1),o.gameObject.parent&&o.localspace)switch(o.main.scalingMode){case Iy.Local:e=$e(o.gameObject.parent,e),e.x=1/e.x,e.y=1/e.y,e.z=1/e.z;break;default:if(!o.unsupported_scaling_mode){o.unsupported_scaling_mode=!0;const t="ParticleSystem scale mode "+Iy[o.main.scalingMode]+" is not supported";E()&&ge(t),console.warn(t,o.name,o)}e=$e(o.gameObject,e);break}return e}var tA=Object.defineProperty,Vy=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&tA(e,t,n),n};class bl extends M{strength=1;radius=2;targets=[];update(){const e=this.gameObject.worldPosition,t=-this.strength*this.context.time.deltaTime;this.targets?.forEach(i=>{if(!i)return;const n=i.gameObject.worldPosition.sub(e),s=n.length();if(s>this.radius)return;let r=t;s>1?r/=s*s:r/=Math.max(.05,s),i.applyImpulse(n.multiplyScalar(r))})}}Vy([u()],bl.prototype,"strength"),Vy([u()],bl.prototype,"radius"),Vy([u(Ye)],bl.prototype,"targets");class Il extends M{_didAssignPlayerColor=!1;onEnable(){this.context.connection.beginListen(te.JoinedRoom,this.tryAssignColor),this._didAssignPlayerColor||this.startCoroutine(this.waitForConnection())}onDisable(){this.context.connection.stopListen(te.JoinedRoom,this.tryAssignColor)}*waitForConnection(){for(;!this.destroyed&&this.activeAndEnabled&&(yield Dg(.2),!this.tryAssignColor()););}tryAssignColor=()=>{const e=x.getComponentInParent(this.gameObject,xn);if(e&&e.owner)return this._didAssignPlayerColor=!0,this.assignUserColor(e.owner),!0;const t=x.getComponentInParent(this.gameObject,Le);return t?.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(t.connectionId),!0):!1};assignUserColor(e){const t=Il.hashCode(e),i=Il.colorFromHashCode(t);if(this.gameObject.type==="Mesh"){const n=this.gameObject;this.assignColor(i,e,n)}else if(this.gameObject.children)for(const n of this.gameObject.children){const s=n;s.material&&s.material.color&&this.assignColor(i,e,s)}}assignColor(e,t,i){let n=i.material;n&&(n._playerMaterial!==t&&(n=n.clone(),n._playerMaterial=t,i.material=n),n.color=e)}static hashCode(e){var t=0,i,n;if(e.length===0)return t;for(i=0;i<e.length;i++)n=e.charCodeAt(i),t=(t<<5)-t+n,t|=0;return t}static colorFromHashCode(e){const t=(e&16711680)>>16,i=(e&65280)>>8,n=e&255;return new ne(t/255,i/255,n/255)}}const lh=w("debugpost");let $y=null;function iA(o){$y=o}function Hx(o){let e=o.gameObject;for(;e;){for(const t of eu(e))if(t.isPostProcessingManager===!0)return t;e=e.parent}return null}function nA(o){let e=Hx(o);if(!e)if($y){lh&&console.warn("Adding postprocessing manager to the scene.");const t=o.scene;e=bn(t,$y)}else E()&&console.warn("No post processing manager found");return e}const ct={AT_START:-1e4,NormalPass:0,DepthDownsamplingPass:10,SSAO:20,SMAA:30,TiltShift:40,DepthOfField:50,ChromaticAberration:60,Bloom:70,Vignette:80,Pixelation:90,ToneMapping:100,HueSaturation:110,BrightnessContrast:120,Sharpening:130,AT_END:1e4};let Je=null;function oA(o){lh==="verbose"&&console.debug("Before ordering effects",[...o]),Je||(Je=new Map,Je.set(T.POSTPROCESSING.MODULE.NormalPass,ct.NormalPass),Je.set(T.POSTPROCESSING.MODULE.DepthDownsamplingPass,ct.DepthDownsamplingPass),Je.set(T.POSTPROCESSING.MODULE.SMAAEffect,ct.SMAA),Je.set(T.POSTPROCESSING.MODULE.SSAOEffect,ct.SSAO),Je.set(T.POSTPROCESSING_AO.MODULE.N8AOPostPass,ct.SSAO),Je.set(T.POSTPROCESSING_AO.MODULE.N8AOPass,ct.SSAO),Je.set(T.POSTPROCESSING.MODULE.TiltShiftEffect,ct.TiltShift),Je.set(T.POSTPROCESSING.MODULE.DepthOfFieldEffect,ct.DepthOfField),Je.set(T.POSTPROCESSING.MODULE.ChromaticAberrationEffect,ct.ChromaticAberration),Je.set(T.POSTPROCESSING.MODULE.BloomEffect,ct.Bloom),Je.set(T.POSTPROCESSING.MODULE.SelectiveBloomEffect,ct.Bloom),Je.set(T.POSTPROCESSING.MODULE.VignetteEffect,ct.Vignette),Je.set(T.POSTPROCESSING.MODULE.PixelationEffect,ct.Pixelation),Je.set(T.POSTPROCESSING.MODULE.ToneMappingEffect,ct.ToneMapping),Je.set(T.POSTPROCESSING.MODULE.HueSaturationEffect,ct.HueSaturation),Je.set(T.POSTPROCESSING.MODULE.BrightnessContrastEffect,ct.BrightnessContrast)),o.sort((e,t)=>{const i=typeof e.priority=="number"?e.priority:Je.get(e.effect.constructor)??Number.NEGATIVE_INFINITY,n=typeof t.priority=="number"?t.priority:Je.get(t.effect.constructor)??Number.NEGATIVE_INFINITY;return i===Number.NEGATIVE_INFINITY?(lh&&console.warn("Unknown effect found: ",e.constructor.name,e),1):n===Number.NEGATIVE_INFINITY?(lh&&console.warn("Unknown effect found: ",t.constructor.name,t),-1):i-n}),lh==="verbose"&&console.debug("After ordering effects",[...o])}var sA=Object.defineProperty,rA=Object.getOwnPropertyDescriptor,Gx=(o,e,t,i)=>{for(var n=rA(e,t),s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&sA(e,t,n),n};const aA=w("debugpost");class B{isVolumeParameter=!0;constructor(e){e!==void 0&&this.initialize(e)}_isInitialized=!1;get isInitialized(){return this._isInitialized}initialize(e){e!==void 0&&(this._value=e,this._defaultValue=e,this._valueRaw=e,this._isInitialized=!0)}get overrideState(){return this._active}set overrideState(e){if(this._active===e)return;this._active=e;const t=e?this._valueRaw:this._defaultValue;this.processValue(t,!0)}_active=!0;get value(){return this._valueRaw}set value(e){this.isInitialized||this.initialize(e),this.processValue(e,!1)}_value;_valueRaw;set defaultValue(e){this._defaultValue=e}_defaultValue=void 0;__init(){this.processValue(this._valueRaw,!0)}valueProcessor;onValueChanged;processValue(e,t){if(e==null||!t&&this.testIfValueChanged(e)===!1)return;const i=this._value;aA&&typeof i=="number"&&typeof e=="number"&&(i?.toFixed(4),e?.toFixed(4)),!this._active&&this._defaultValue!==void 0?(this._value=this._defaultValue,e=this._defaultValue,this._valueRaw=e):(this._valueRaw=e,this._active&&this.valueProcessor&&(e=this.valueProcessor(e)),this._value=e),this.onValueChanged&&this.onValueChanged(e,i,this)}testIfValueChanged(e){return this._valueRaw!==e}}Gx([u()],B.prototype,"overrideState"),Gx([u()],B.prototype,"value");class lA extends Xi{constructor(){super([B])}onSerialize(e,t){}onDeserialize(e,t){const i=t.target,n=t.path;let s;if(i&&n&&(s=i[n]),(typeof s!="object"||typeof s=="object"&&s.isVolumeParameter!==!0)&&(s=new B),typeof e=="object"&&"value"in e){const r=e.value;s.initialize(r),s.overrideState=e.overrideState}else s.value=e;return s}}new lA;var cA=Object.defineProperty,hA=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&cA(e,t,n),n};const Hy=w("debugpost");class et extends M{get isPostProcessingEffect(){return!0}order=void 0;constructor(e=void 0){if(super(),e)for(const t of Object.keys(e)){const i=e[t],n=this[t];n instanceof B?n.initialize(i):n!==void 0&&(this[t]=i)}}active=!0;_manager=null;onEnable(){super.onEnable(),Hy&&console.warn("Enable",this.constructor.name+(this.__internalDidAwakeAndStart?"":" (awake)")),this.__internalDidAwakeAndStart&&(this.active=!0),this.onEffectEnabled()}onDisable(){super.onDisable(),Hy&&console.warn("Disable",this.constructor.name),this._manager?.removeEffect(this),this.active=!1}onEffectEnabled(e){e&&e.isPostProcessingManager===!0?this._manager=e:this._manager||(this._manager=nA(this)),this._manager.addEffect(this),this._manager.dirty=!0}init(){}_result;_postprocessingContext=null;get postprocessingContext(){return this._postprocessingContext}apply(e){return this._postprocessingContext=e,this._result||(this.initParameters(),this._result=this.onCreateEffect?.call(this)),this._result&&this.initParameters(),this._result}unapply(){}dispose(){Hy&&console.warn("DISPOSE",this),this._result&&(Array.isArray(this._result)?this._result.forEach(e=>e.dispose()):this._result.dispose()),this._result=void 0}initParameters(){const e=Object.keys(this);for(const t of e){const i=this[t];i instanceof B&&i.__init()}}onEditorModification(e){const t=e.propertyName;if(this[t]instanceof B){const i=e.value;return this[t].value=i,!0}}}hA([u()],et.prototype,"active");var dA=Object.defineProperty,uA=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&dA(e,t,n),n};const pA=w("debugpost"),Gy={};function on(o,e){Gy[o]=e}function mA(o){return o.__type in Gy?Gy[o.__type]:(pA&&o.__type&&console.warn("Unknown postprocessing type",o.__type,o),et)}class mp{components=[];__init(e){this.components?.forEach(t=>{t.gameObject===void 0&&e.gameObject.addComponent(t),t.init()})}addEffect(e){this.components.push(e)}removeEffect(e){const t=this.components.indexOf(e);t>=0&&this.components.splice(t,1)}}uA([Qe([o=>mA(o),et])],mp.prototype,"components");var gA=Object.defineProperty,fA=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&gA(e,t,n),n};const yA=w("debugpost");class ch extends et{get typeName(){return"Antialiasing"}preset=new B(2);onCreateEffect(){const e=new T.POSTPROCESSING.MODULE.SMAAEffect({preset:this.preset?.value??T.POSTPROCESSING.MODULE.SMAAPreset.HIGH,edgeDetectionMode:T.POSTPROCESSING.MODULE.EdgeDetectionMode.LUMA});return this.preset.onValueChanged=t=>{yA&&console.log("Antialiasing preset changed to",t),e.applyPreset(t)},e}}fA([u(B)],ch.prototype,"preset"),on("Antialiasing",ch);var bA=Object.defineProperty,qy=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&bA(e,t,n),n};const gp=class X1 extends et{static useSelectiveBloom=!1;get typeName(){return"Bloom"}threshold=new B(.9);intensity=new B(1);scatter=new B(.7);selectiveBloom;init(){this.threshold.valueProcessor=e=>e,this.intensity.valueProcessor=e=>e,this.scatter.valueProcessor=e=>e}onCreateEffect(){let e;if(this.selectiveBloom==null&&(this.selectiveBloom=X1.useSelectiveBloom),this.selectiveBloom){const t=e=new T.POSTPROCESSING.MODULE.SelectiveBloomEffect(this.context.scene,this.context.mainCamera,{blendFunction:T.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});t.inverted=!0}else e=new T.POSTPROCESSING.MODULE.BloomEffect({blendFunction:T.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});return this.intensity.onValueChanged=t=>{e.intensity=t},this.threshold.onValueChanged=t=>{e.luminanceMaterial.threshold=Math.pow(t,2.2)},this.scatter.onValueChanged=t=>{e.luminancePass.enabled=!0,e.luminanceMaterial.smoothing=t,e.mipmapBlurPass&&(e.mipmapBlurPass.radius=uo.lerp(.1,.9,t))},e}};qy([u(B)],gp.prototype,"threshold"),qy([u(B)],gp.prototype,"intensity"),qy([u(B)],gp.prototype,"scatter");let fp=gp;on("Bloom",fp);var _A=Object.defineProperty,vA=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&_A(e,t,n),n};class hh extends et{get typeName(){return"ChromaticAberration"}intensity=new B(0);onCreateEffect(){const e=new T.POSTPROCESSING.MODULE.ChromaticAberrationEffect;return e.offset=new J(0,0),e.radialModulation=!0,e.modulationOffset=.15,this.intensity.valueProcessor=t=>t*.02,this.intensity.onValueChanged=t=>{e.offset.x=-t,e.offset.y=t},e}}vA([u(B)],hh.prototype,"intensity"),on("ChromaticAberration",hh);var dh=(o=>(o[o.None=0]="None",o[o.Neutral=1]="Neutral",o[o.ACES=2]="ACES",o[o.AgX=3]="AgX",o[o.KhronosNeutral=4]="KhronosNeutral",o))(dh||{});const qx=new Map;function Xy(o){switch(o){case 0:return dm;case 1:return hm;case 2:return cd;case 3:return ld;case 4:return ya;default:return qx.has(o)||(qx.set(o,!0),console.warn("[Postprocessing] Unknown tone mapping mode",o)),ya}}function wA(o){switch(o){case dm:return 0;case cd:return 2;case ld:return 3;case ya:return 1;case hm:return 1;default:return 0}}function yp(o){switch(o){case dm:return T.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR;case cd:return T.POSTPROCESSING.MODULE.ToneMappingMode.ACES_FILMIC;case ld:return T.POSTPROCESSING.MODULE.ToneMappingMode.AGX;case ya:return T.POSTPROCESSING.MODULE.ToneMappingMode.NEUTRAL;case hm:return T.POSTPROCESSING.MODULE.ToneMappingMode.REINHARD;default:return T.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR}}var xA=Object.defineProperty,Xx=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&xA(e,t,n),n};const Qy=w("debugpost");class Us extends et{get typeName(){return"ToneMapping"}mode=new B(void 0);exposure=new B(1);setMode(e){const t=dh[e];return t===void 0?(console.error("[PostProcessing] Invalid ToneMapping mode",e),this):(this.mode.value=t,this)}get isToneMapping(){return!0}onEffectEnabled(){const e=Hx(this);e&&super.onEffectEnabled(e)}_tonemappingEffect=null;onCreateEffect(){if(this.mode.isInitialized==!1){const i=wA(this.context.renderer.toneMapping);Qy&&console.log("[PostProcessing] Initializing ToneMapping mode to renderer.toneMapping",this.context.renderer.toneMapping+" \u2192 "+i),this.mode.initialize(i)}this._tonemappingEffect?.dispose();const e=Xy(this.mode.value),t=this._tonemappingEffect=new T.POSTPROCESSING.MODULE.ToneMappingEffect({mode:yp(e)});return this.mode.onValueChanged=i=>{if(typeof i=="string")i=Wv(i),t.mode=yp(i);else{const n=Xy(i);t.mode=yp(n)}t.name="ToneMapping ("+dh[i]+")",Qy&&console.log("[PostProcessing] ToneMapping mode changed to",dh[i],e,t.mode)},Qy&&console.log("[PostProcessing] Use ToneMapping",dh[this.mode.value],e,t.mode,"renderer.tonemapping: "+this.context.renderer.toneMapping),t}onBeforeRender(){if(this._tonemappingEffect&&this.postprocessingContext?.handler.getEffectIsActive(this._tonemappingEffect)&&(this.mode.overrideState&&(this.context.renderer.toneMapping=Xy(this.mode.value)),this.exposure.overrideState&&this.exposure.value!==void 0)){const e=Math.max(0,this.exposure.value);this.context.renderer.toneMappingExposure=e}}}Xx([u(B)],Us.prototype,"mode"),Xx([u(B)],Us.prototype,"exposure"),on("Tonemapping",Us);var SA=Object.defineProperty,bp=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&SA(e,t,n),n};class zs extends et{get typeName(){return"ColorAdjustments"}remap=!0;postExposure=new B(1);contrast=new B(0);hueShift=new B(0);saturation=new B(0);init(){this.postExposure.valueProcessor=e=>(this.remap&&(e=Math.pow(2,e)),e),this.contrast.valueProcessor=e=>{if(!this.remap)return e;let t=1;return e>0?t=200:e<0&&(t=100),e/t},this.contrast.defaultValue=0,this.hueShift.valueProcessor=e=>this.remap?Math.PI*e/180:e,this.hueShift.defaultValue=0,this.saturation.valueProcessor=e=>this.remap?e<0?e/100:e/(100*Math.PI):e,this.saturation.defaultValue=0}onCreateEffect(){const e=[];let t=this.postprocessingContext?.components.find(s=>s instanceof Us);t||(t=new Us,this.postprocessingContext?.components.push(t)),this.postExposure.onValueChanged=s=>{this.postExposure.overrideState&&t?t.exposure.value=s:console.warn("[PostProcessing] PostExposure is set to override but no ToneMappingEffect found in the postprocessing stack. Please add a ToneMappingEffect to your postprocessing stack to use PostExposure.")};const i=new T.POSTPROCESSING.MODULE.BrightnessContrastEffect;this.contrast.onValueChanged=s=>i.contrast=s;const n=new T.POSTPROCESSING.MODULE.HueSaturationEffect;return this.hueShift.onValueChanged=s=>n.hue=s,this.saturation.onValueChanged=s=>n.saturation=s,e.push(i),e.push(n),e}}bp([u(B)],zs.prototype,"postExposure"),bp([u(B)],zs.prototype,"contrast"),bp([u(B)],zs.prototype,"hueShift"),bp([u(B)],zs.prototype,"saturation"),on("ColorAdjustments",zs);var CA=Object.defineProperty,qr=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&CA(e,t,n),n};const PA=w("debugpost");class On extends et{get typeName(){return"DepthOfField"}mode;focusDistance=new B(1);focalLength=new B(.2);aperture=new B(20);gaussianMaxRadius=new B;resolutionScale=new B(1/window.devicePixelRatio);bokehScale=new B;init(){this.focalLength.valueProcessor=t=>{const i=t/300;return D.lerp(2,.01,i)};const e=20;this.aperture.valueProcessor=t=>{const i=1-t/32;return D.lerp(1,e,i)}}onCreateEffect(){if(this.mode===0){PA&&console.warn("DepthOfField: Mode is set to Off");return}const e=new T.POSTPROCESSING.MODULE.DepthOfFieldEffect(this.context.mainCamera,{worldFocusRange:.2,focalLength:1,bokehScale:20,resolutionScale:this.resolutionScale.value});return this.focusDistance.onValueChanged=t=>{e.cocMaterial.worldFocusDistance=t},this.focalLength.onValueChanged=t=>e.cocMaterial.worldFocusRange=t,this.aperture.onValueChanged=t=>e.bokehScale=t,this.resolutionScale&&(this.resolutionScale.onValueChanged=t=>e.resolution.scale=t),[e]}unapply(){}}qr([u()],On.prototype,"mode"),qr([u(B)],On.prototype,"focusDistance"),qr([u(B)],On.prototype,"focalLength"),qr([u(B)],On.prototype,"aperture"),qr([u(B)],On.prototype,"gaussianMaxRadius"),qr([u(B)],On.prototype,"resolutionScale"),qr([u(B)],On.prototype,"bokehScale"),on("DepthOfField",On);class uh extends et{effect;constructor(e){super(),this.effect=e}get typeName(){return this.effect.constructor.name}onCreateEffect(){return this.effect}}var OA=Object.defineProperty,kA=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&OA(e,t,n),n};class ph extends et{get typeName(){return"PixelationEffect"}granularity=new B(10);onCreateEffect(){const e=new T.POSTPROCESSING.MODULE.PixelationEffect;return this.granularity.onValueChanged=t=>{e.granularity=t},e}}kA([u(B)],ph.prototype,"granularity"),on("PixelationEffect",ph);var MA=Object.defineProperty,mh=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&MA(e,t,n),n};class No extends et{get typeName(){return"ScreenSpaceAmbientOcclusion"}intensity=new B(2);falloff=new B(1);samples=new B(9);color=new B(new ne(0,0,0));luminanceInfluence=new B(.7);onBeforeRender(){if(this._ssao&&this.context.mainCamera instanceof de){const e=this.context.mainCamera.far-this.context.mainCamera.near;this._ssao.ssaoMaterial.worldDistanceFalloff=e*.01,this._ssao.ssaoMaterial.worldDistanceThreshold=this.context.mainCamera.far}}_ssao;onCreateEffect(){const e=this.context.mainCamera,t=new T.POSTPROCESSING.MODULE.NormalPass(this.context.scene,e),i=new T.POSTPROCESSING.MODULE.DepthDownsamplingPass({normalBuffer:t.texture,resolutionScale:.5}),n=this._ssao=new T.POSTPROCESSING.MODULE.SSAOEffect(e,t.texture,{normalDepthBuffer:i.texture,worldDistanceThreshold:1,worldDistanceFalloff:1,worldProximityThreshold:.1,worldProximityFalloff:2,intensity:1,blendFunction:T.POSTPROCESSING.MODULE.BlendFunction.MULTIPLY,luminanceInfluence:.5});this.intensity.onValueChanged=r=>{n.intensity=r},this.falloff.onValueChanged=r=>{n.ssaoMaterial.radius=r*.1},this.samples.onValueChanged=r=>{n.ssaoMaterial.samples=r},this.color.onValueChanged=r=>{n.color||(n.color=new ne),n.color.copy(r)},this.luminanceInfluence.onValueChanged=r=>{n.luminanceInfluence=r};const s=new Array;return s.push(t),s.push(i),s.push(n),s}}mh([u(B)],No.prototype,"intensity"),mh([u(B)],No.prototype,"falloff"),mh([u(B)],No.prototype,"samples"),mh([u(B)],No.prototype,"color"),mh([u(B)],No.prototype,"luminanceInfluence"),on("ScreenSpaceAmbientOcclusion",No);var RA=Object.defineProperty,Xr=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&RA(e,t,n),n};const TA=w("debugN8AO");var Yy=(o=>(o[o.Performance=0]="Performance",o[o.Low=1]="Low",o[o.Medium=2]="Medium",o[o.High=3]="High",o[o.Ultra=4]="Ultra",o))(Yy||{});class kn extends et{get typeName(){return"ScreenSpaceAmbientOcclusionN8"}get pass(){return this._ssao}gammaCorrection=!0;aoRadius=new B(1);falloff=new B(1);intensity=new B(1);color=new B(new ne(0,0,0));screenspaceRadius=!1;quality=2;_ssao;onValidate(){this._ssao&&(this._ssao.setQualityMode(Yy[this.quality]),this._ssao.configuration.gammaCorrection=this.gammaCorrection,this._ssao.configuration.screenSpaceRadius=this.screenspaceRadius)}onCreateEffect(){const e=this.context.mainCamera,t=this.context.domWidth,i=this.context.domHeight,n=this._ssao=new T.POSTPROCESSING_AO.MODULE.N8AOPostPass(this.context.scene,e,t,i);n.name="SSAO_N8";const s=Yy[this.quality];n.setQualityMode(s),n.configuration.transparencyAware=!1;const r=new jn(t,i);return n.configuration.beautyRenderTarget=r,n.configuration.autoRenderBeauty=!1,n.configuration.gammaCorrection=this.gammaCorrection,n.configuration.screenSpaceRadius=this.screenspaceRadius,TA&&(n.enableDebugMode(),console.log(n),setInterval(()=>{console.log("SSAO",n.lastTime)},1e3),setInterval(()=>{console.log("SSAO",n.enabled,{ssao:n,autoRenderBeauty:n.configuration.autoRenderBeauty})},4e3)),this.intensity.onValueChanged=a=>{n.configuration.intensity=a},this.falloff.onValueChanged=a=>{n.configuration.distanceFalloff=a},this.aoRadius.onValueChanged=a=>{n.configuration.aoRadius=a},this.color.onValueChanged=a=>{n.color||(n.color=new ne),n.configuration.color.copy(a)},n}}Xr([Pt(),u()],kn.prototype,"gammaCorrection"),Xr([u(B)],kn.prototype,"aoRadius"),Xr([u(B)],kn.prototype,"falloff"),Xr([u(B)],kn.prototype,"intensity"),Xr([u(B)],kn.prototype,"color"),Xr([Pt(),u()],kn.prototype,"screenspaceRadius"),Xr([Pt(),u()],kn.prototype,"quality"),on("ScreenSpaceAmbientOcclusionN8",kn);var EA=Object.defineProperty,AA=Object.getOwnPropertyDescriptor,Qx=(o,e,t,i)=>{for(var n=AA(e,t),s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&EA(e,t,n),n};class gh extends et{get typeName(){return"Sharpening"}order=ct.Sharpening;_effect;onCreateEffect(){return this._effect??=new(IA()),this.effect}get effect(){return this._effect}set amount(e){this._amount=e,this._effect&&(this._effect.uniforms.get("amount").value=e)}get amount(){return this._effect?this._effect.uniforms.get("amount").value:this._amount}_amount=1;set radius(e){this._radius=e,this._effect&&(this._effect.uniforms.get("radius").value=e)}get radius(){return this._effect?this._effect.uniforms.get("radius").value:this._radius}_radius=1}Qx([u()],gh.prototype,"amount"),Qx([u()],gh.prototype,"radius");function IA(){const o=`
1284
1284
  void mainSupport() {
1285
1285
  vUv = uv;
1286
1286
  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
@@ -1325,7 +1325,7 @@ axisFormat %s
1325
1325
  }
1326
1326
 
1327
1327
  `;class t extends T.POSTPROCESSING.MODULE.Effect{constructor(){super("Sharpening",e,{vertexShader:o,blendFunction:T.POSTPROCESSING.MODULE.BlendFunction.NORMAL,uniforms:new Map([["amount",new Ni(1)],["radius",new Ni(1)]]),attributes:XC.CONVOLUTION})}}return t}var LA=Object.defineProperty,_l=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&LA(e,t,n),n};class no extends et{get typeName(){return"TiltShiftEffect"}offset=new B(0);rotation=new B(0);focusArea=new B(.4);feather=new B(.3);kernelSize=new B(2);resolutionScale=new B(1/window.devicePixelRatio);init(){this.offset.defaultValue=0,this.rotation.defaultValue=0,this.focusArea.defaultValue=.4,this.feather.defaultValue=.3,this.kernelSize.defaultValue=T.POSTPROCESSING.MODULE.KernelSize.MEDIUM,this.resolutionScale.defaultValue=1/window.devicePixelRatio}onCreateEffect(){const e=new T.POSTPROCESSING.MODULE.TiltShiftEffect({kernelSize:T.POSTPROCESSING.MODULE.KernelSize.VERY_LARGE,offset:this.offset.value,rotation:this.rotation.value,focusArea:this.focusArea.value,feather:this.feather.value});return this.offset.onValueChanged=t=>e.offset=t,this.rotation.onValueChanged=t=>e.rotation=t,this.focusArea.onValueChanged=t=>e.focusArea=t,this.feather.onValueChanged=t=>e.feather=t,this.kernelSize.onValueChanged=t=>e.blurPass.kernelSize=t,this.resolutionScale.onValueChanged=t=>e.resolution.scale=t/window.devicePixelRatio,e}}_l([u(B)],no.prototype,"offset"),_l([u(B)],no.prototype,"rotation"),_l([u(B)],no.prototype,"focusArea"),_l([u(B)],no.prototype,"feather"),_l([u(B)],no.prototype,"kernelSize"),_l([u(B)],no.prototype,"resolutionScale"),on("TiltShiftEffect",no);var jA=Object.defineProperty,Ky=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&jA(e,t,n),n};class Qr extends et{get typeName(){return"Vignette"}color=new B({r:0,g:0,b:0,a:1});intensity=new B(0);center=new B({x:.5,y:.5});init(){this.color.defaultValue={r:0,g:0,b:0,a:1},this.intensity.defaultValue=0,this.center.defaultValue={x:.5,y:.5}}onCreateEffect(){const e=new T.POSTPROCESSING.MODULE.VignetteEffect;return this.intensity.onValueChanged=t=>{e.offset=t,this.updateDarkness(e)},this.color.onValueChanged=t=>{this.updateDarkness(e)},e}updateDarkness(e){const t=this.intensity.value;e.darkness=t}}Ky([u(B)],Qr.prototype,"color"),Ky([u(B)],Qr.prototype,"intensity"),Ky([u(B)],Qr.prototype,"center"),on("Vignette",Qr),globalThis.NEEDLE_USE_POSTPROCESSING=globalThis.NEEDLE_USE_POSTPROCESSING!==void 0?globalThis.NEEDLE_USE_POSTPROCESSING:!0;const Wo=w("debugpost"),Zy=Symbol("needle:postprocessing-handler"),fh=Symbol("needle:previous-autoclear-state"),yh=Symbol("needle:previous-tone-mapping");class Jy{_composer=null;_lastVolumeComponents;_effects=[];getEffectIsActive(e){return e?this._isActive&&this._effects.some(t=>t.effect===e):!1}get isActive(){return this._isActive}get composer(){return this._composer}_isActive=!1;context;constructor(e){this.context=e}apply(e){return this._isActive=!0,this.onApply(this.context,e)}unapply(e=!0){if(Wo&&console.log("Unapplying postprocessing effects"),this._isActive=!1,this._lastVolumeComponents){for(const i of this._lastVolumeComponents)i.unapply();this._lastVolumeComponents.length=0}const t=this.context;t[Zy]===this&&(delete t[Zy],typeof t.renderer[fh]=="boolean"&&(t.renderer.autoClear=t.renderer[fh]),typeof t.renderer[yh]=="number"&&(t.renderer.toneMapping=t.renderer[yh])),this._composer?.removeAllPasses(),e&&this._composer?.dispose(),t.composer===this._composer&&(t.composer=null),this.handleDevicePixelRatio()}dispose(){this.unapply(!0);for(const e of this._effects)e.effect.dispose();this._effects.length=0,this._composer=null}async onApply(e,t){if(!t)return;await Promise.all([T.POSTPROCESSING.load(),T.POSTPROCESSING_AO.load()]),e[Zy]=this,Wo&&console.log("Apply Postprocessing Effects",t),this._lastVolumeComponents=[...t],this._effects.length=0;const i={handler:this,components:this._lastVolumeComponents};for(let n=0;n<this._lastVolumeComponents.length;n++){const s=this._lastVolumeComponents[n];if(s.context=e,s.apply){if(s.active){let r=function(c,h){return h?(h instanceof T.POSTPROCESSING.MODULE.Effect||h instanceof T.POSTPROCESSING.MODULE.Pass||console.warn(`PostprocessingEffect ${c} created neither Effect nor Pass - this might be caused by a bundler error or false import. Below you find some possible solutions:
1328
- - If you create custom effect try creating it like this: 'new NEEDLE_ENGINE_MODULES.POSTPROCESSING.MODULE.Effect(...)' instead of 'new Effect(...)'`),!0):!1};if(!e.mainCameraComponent){console.error("No camera in scene found or available yet - can not create postprocessing effects");return}const a=s.apply(i);if(!a)continue;const l=s.typeName||s.constructor.name;if(Array.isArray(a))for(const c of a)r(l,c)&&this._effects.push({effect:c,typeName:s.typeName,priority:s.order});else{if(!r(l,a))continue;this._effects.push({effect:a,typeName:s.typeName,priority:s.order})}}}else s.active&&ge("Volume component is not a VolumeComponent: "+s.__type)}this.applyEffects(e)}_anyPassHasDepth=!1;_anyPassHasNormal=!1;_hasSmaaEffect=!1;get anyPassHasDepth(){return this._anyPassHasDepth}get anyPassHasNormal(){return this._anyPassHasNormal}get hasSmaaEffect(){return this._hasSmaaEffect}_customInputBuffer=null;_customInputBufferId=0;_multisampling=0;set multisampling(e){this._multisampling=e}get multisampling(){return this._multisampling}applyEffects(e){if(this._anyPassHasDepth=!1,this._anyPassHasNormal=!1,this._hasSmaaEffect=!1,this._effects.length<=0)return;const t=e.mainCameraComponent,i=e.renderer,n=e.scene,s=t.threeCamera;if(typeof i[fh]=="boolean"&&(i.autoClear=i[fh]),i[fh]=i.autoClear,typeof i[yh]=="number"&&(i.toneMapping=i[yh]),i[yh]=i.toneMapping,i.toneMapping!=hd&&!this._effects.find(h=>h instanceof T.POSTPROCESSING.MODULE.ToneMappingEffect)){const h=new T.POSTPROCESSING.MODULE.ToneMappingEffect;h.name=`ToneMapping (${i.toneMapping})`,h.mode=yp(i.toneMapping),this._effects.push({typeName:"ToneMapping",effect:h,priority:ct.ToneMapping})}this._composer||(this._composer=new T.POSTPROCESSING.MODULE.EffectComposer(i,{frameBufferType:um,stencilBuffer:!0})),e.composer&&e.composer!==this._composer&&console.warn("There's already an active EffectComposer in your scene: replacing it with a new one. This might cause unexpected behaviour. Make sure to only use one PostprocessingManager/Volume in your scene."),e.composer=this._composer;const r=e.composer;r.setMainCamera(s),r.setRenderer(i),r.setMainScene(n),r.autoRenderToScreen=!0,r.multisampling=0;for(const h of r.passes)h.dispose();r.removeAllPasses();const a=new T.POSTPROCESSING.MODULE.RenderPass(n,s);a.name="RenderPass",a.mainScene=n,r.addPass(a);const l=a.render;this._customInputBuffer?.dispose(),this._customInputBuffer=null,a.render=(h,d,p,g,f)=>{d&&(d.samples=0,p&&(p.samples=0),(!this._customInputBuffer||this._customInputBuffer.width!==d.width||this._customInputBuffer.height!==d.height||this._customInputBuffer.samples!==this._multisampling||this._customInputBuffer.texture.format!==d.texture.format||this._customInputBuffer.texture.type!==um)&&(this._customInputBuffer?.dispose(),this._customInputBuffer=new jn(d.width,d.height,{format:d.texture.format,type:um,depthBuffer:d.depthBuffer,depthTexture:d.depthTexture?new F0(d.width,d.height):void 0,stencilBuffer:d.stencilBuffer,samples:Math.max(0,this._multisampling),minFilter:d.texture.minFilter??pd,magFilter:d.texture.magFilter??pd,generateMipmaps:d.texture.generateMipmaps}),this._customInputBufferId++,this._customInputBuffer.texture.name=`CustomInputBuffer-${this._customInputBufferId}`,this._customInputBuffer.depthTexture&&d.depthTexture&&(this._customInputBuffer.depthTexture.format=d.depthTexture.format,this._customInputBuffer.depthTexture.type=d.depthTexture.type),this._customInputBuffer.samples>0&&(this._customInputBuffer.ignoreDepthForMultisampleCopy=!1),Wo&&console.warn(`[PostProcessing] Input buffer created with size ${this._customInputBuffer.width}x${this._customInputBuffer.height} and samples ${this._customInputBuffer.samples}`)),l.call(a,h,this._customInputBuffer,p,g,f),Ys.blit(this._customInputBuffer.texture,d,{renderer:h,depthTexture:this._customInputBuffer.depthTexture,depthWrite:!0,depthTest:!0}))};try{oA(this._effects);let h=!1,d=null;for(let f=this._effects.length-1;f>=0;f--){const m=this._effects[f].effect;if(m instanceof T.POSTPROCESSING.MODULE.ToneMappingEffect){if(h){Wo&&console.warn(`[PostProcessing] Found multiple tonemapping effects in the scene: ${m.name} and ${d?.name}. Only the last one added will be used.`),this._effects.splice(f,1);continue}d=m,h=!0}}const p=[];let g=!1;for(let f=0;f<this._effects.length;f++){const m=this._effects[f].effect;if(m instanceof T.POSTPROCESSING.MODULE.SMAAEffect?this._hasSmaaEffect=!0:m instanceof T.POSTPROCESSING.MODULE.NormalPass&&(this._anyPassHasNormal=!0),!(m instanceof T.POSTPROCESSING.MODULE.ToneMappingEffect&&d!==m))if(m instanceof T.POSTPROCESSING.MODULE.Effect){const y=m.getAttributes(),_=T.POSTPROCESSING.MODULE.EffectAttribute.CONVOLUTION;y&_&&(Wo&&console.log("[PostProcessing] Convolution effect: "+m.name),g&&(Wo&&console.log("[PostProcessing] \u2192 Merging effects ["+p.map(v=>v.name).join(", ")+"]"),this.createPassForMergeableEffects(p,r,s,n)),g=!0),p.push(m)}else m instanceof T.POSTPROCESSING.MODULE.Pass?(g=!1,this.createPassForMergeableEffects(p,r,s,n),m.renderToScreen=!1,r.addPass(m)):(g=!1,this.createPassForMergeableEffects(p,r,s,n),r.addPass(m))}this.createPassForMergeableEffects(p,r,s,n)}catch(h){console.error("Error while applying postprocessing effects",h),r.passes.forEach(d=>d.dispose()),r.removeAllPasses()}let c=!1;for(let h=r.passes.length-1;h>=0;h--){const d=r.passes[h];let p=!1,g=!1;d.enabled&&(c||(p=!0,g=!0),c=!0),d.renderToScreen=g,d?.configuration!==void 0?d.configuration.gammaCorrection=p:"autosetGamma"in d&&(d.autosetGamma=p),this._anyPassHasDepth||=d.needsDepthTexture}this.handleDevicePixelRatio(),Wo&&console.log("[PostProcessing] Passes \u2192",[...r.passes],`
1328
+ - If you create custom effect try creating it like this: 'new NEEDLE_ENGINE_MODULES.POSTPROCESSING.MODULE.Effect(...)' instead of 'new Effect(...)'`),!0):!1};if(!e.mainCameraComponent){console.error("No camera in scene found or available yet - can not create postprocessing effects");return}const a=s.apply(i);if(!a)continue;const l=s.typeName||s.constructor.name;if(Array.isArray(a))for(const c of a)r(l,c)&&this._effects.push({effect:c,typeName:s.typeName,priority:s.order});else{if(!r(l,a))continue;this._effects.push({effect:a,typeName:s.typeName,priority:s.order})}}}else s.active&&ge("Volume component is not a VolumeComponent: "+s.__type)}this.applyEffects(e)}_anyPassHasDepth=!1;_anyPassHasNormal=!1;_hasSmaaEffect=!1;get anyPassHasDepth(){return this._anyPassHasDepth}get anyPassHasNormal(){return this._anyPassHasNormal}get hasSmaaEffect(){return this._hasSmaaEffect}_customInputBuffer=null;_customInputBufferId=0;_multisampling=0;set multisampling(e){this._multisampling=e}get multisampling(){return this._multisampling}applyEffects(e){if(this._anyPassHasDepth=!1,this._anyPassHasNormal=!1,this._hasSmaaEffect=!1,this._effects.length<=0)return;const t=e.mainCameraComponent,i=e.renderer,n=e.scene,s=t.threeCamera;if(typeof i[fh]=="boolean"&&(i.autoClear=i[fh]),i[fh]=i.autoClear,typeof i[yh]=="number"&&(i.toneMapping=i[yh]),i[yh]=i.toneMapping,i.toneMapping!=hd&&!this._effects.find(h=>h instanceof T.POSTPROCESSING.MODULE.ToneMappingEffect)){const h=new T.POSTPROCESSING.MODULE.ToneMappingEffect;h.name=`ToneMapping (${i.toneMapping})`,h.mode=yp(i.toneMapping),this._effects.push({typeName:"ToneMapping",effect:h,priority:ct.ToneMapping})}this._composer||(this._composer=new T.POSTPROCESSING.MODULE.EffectComposer(i,{frameBufferType:um,stencilBuffer:!0})),e.composer&&e.composer!==this._composer&&console.warn("There's already an active EffectComposer in your scene: replacing it with a new one. This might cause unexpected behaviour. Make sure to only use one PostprocessingManager/Volume in your scene."),e.composer=this._composer;const r=e.composer;r.setMainCamera(s),r.setRenderer(i),r.setMainScene(n),r.autoRenderToScreen=!0,r.multisampling=0;for(const h of r.passes)h.dispose();r.removeAllPasses();const a=new T.POSTPROCESSING.MODULE.RenderPass(n,s);a.name="RenderPass",a.mainScene=n,r.addPass(a);const l=a.render;this._customInputBuffer?.dispose(),this._customInputBuffer=null,a.render=(h,d,p,m,f)=>{d&&(d.samples=0,p&&(p.samples=0),(!this._customInputBuffer||this._customInputBuffer.width!==d.width||this._customInputBuffer.height!==d.height||this._customInputBuffer.samples!==this._multisampling||this._customInputBuffer.texture.format!==d.texture.format||this._customInputBuffer.texture.type!==um)&&(this._customInputBuffer?.dispose(),this._customInputBuffer=new jn(d.width,d.height,{format:d.texture.format,type:um,depthBuffer:d.depthBuffer,depthTexture:d.depthTexture?new F0(d.width,d.height):void 0,stencilBuffer:d.stencilBuffer,samples:Math.max(0,this._multisampling),minFilter:d.texture.minFilter??pd,magFilter:d.texture.magFilter??pd,generateMipmaps:d.texture.generateMipmaps}),this._customInputBufferId++,this._customInputBuffer.texture.name=`CustomInputBuffer-${this._customInputBufferId}`,this._customInputBuffer.depthTexture&&d.depthTexture&&(this._customInputBuffer.depthTexture.format=d.depthTexture.format,this._customInputBuffer.depthTexture.type=d.depthTexture.type),this._customInputBuffer.samples>0&&(this._customInputBuffer.ignoreDepthForMultisampleCopy=!1),Wo&&console.warn(`[PostProcessing] Input buffer created with size ${this._customInputBuffer.width}x${this._customInputBuffer.height} and samples ${this._customInputBuffer.samples}`)),l.call(a,h,this._customInputBuffer,p,m,f),Ys.blit(this._customInputBuffer.texture,d,{renderer:h,depthTexture:this._customInputBuffer.depthTexture,depthWrite:!0,depthTest:!0}))};try{oA(this._effects);let h=!1,d=null;for(let f=this._effects.length-1;f>=0;f--){const g=this._effects[f].effect;if(g instanceof T.POSTPROCESSING.MODULE.ToneMappingEffect){if(h){Wo&&console.warn(`[PostProcessing] Found multiple tonemapping effects in the scene: ${g.name} and ${d?.name}. Only the last one added will be used.`),this._effects.splice(f,1);continue}d=g,h=!0}}const p=[];let m=!1;for(let f=0;f<this._effects.length;f++){const g=this._effects[f].effect;if(g instanceof T.POSTPROCESSING.MODULE.SMAAEffect?this._hasSmaaEffect=!0:g instanceof T.POSTPROCESSING.MODULE.NormalPass&&(this._anyPassHasNormal=!0),!(g instanceof T.POSTPROCESSING.MODULE.ToneMappingEffect&&d!==g))if(g instanceof T.POSTPROCESSING.MODULE.Effect){const y=g.getAttributes(),_=T.POSTPROCESSING.MODULE.EffectAttribute.CONVOLUTION;y&_&&(Wo&&console.log("[PostProcessing] Convolution effect: "+g.name),m&&(Wo&&console.log("[PostProcessing] \u2192 Merging effects ["+p.map(v=>v.name).join(", ")+"]"),this.createPassForMergeableEffects(p,r,s,n)),m=!0),p.push(g)}else g instanceof T.POSTPROCESSING.MODULE.Pass?(m=!1,this.createPassForMergeableEffects(p,r,s,n),g.renderToScreen=!1,r.addPass(g)):(m=!1,this.createPassForMergeableEffects(p,r,s,n),r.addPass(g))}this.createPassForMergeableEffects(p,r,s,n)}catch(h){console.error("Error while applying postprocessing effects",h),r.passes.forEach(d=>d.dispose()),r.removeAllPasses()}let c=!1;for(let h=r.passes.length-1;h>=0;h--){const d=r.passes[h];let p=!1,m=!1;d.enabled&&(c||(p=!0,m=!0),c=!0),d.renderToScreen=m,d?.configuration!==void 0?d.configuration.gammaCorrection=p:"autosetGamma"in d&&(d.autosetGamma=p),this._anyPassHasDepth||=d.needsDepthTexture}this.handleDevicePixelRatio(),Wo&&console.log("[PostProcessing] Passes \u2192",[...r.passes],`
1329
1329
  ---------------------------------
1330
1330
  \u2022 `+r.passes.map(h=>h.name||h.constructor.name+"*").join(`
1331
1331
  \u2022 `)+`
@@ -1400,7 +1400,7 @@ To allow joining a room without a query parameter you can set "requireRoomParame
1400
1400
  Please choose one of the following options to fix this:
1401
1401
  A) Set a room name in the SyncedRoom component
1402
1402
  B) Set a room name in the URL parameter "?`+this.urlParameterName+`=my_room"
1403
- C) Set "joinRandomRoom" to true`),!1):(n0&&console.log("Join "+this.roomName),this._userWantsToBeInARoom=!0,this.context.connection.joinRoom(this.roomName),!0))}_lastPingTime=0;_lastRoomTime=-1;_userWantsToBeInARoom=!1;update(){this.context.connection.isConnected&&(this.context.time.time-this._lastPingTime>3&&(this._lastPingTime=this.context.time.time,this.context.connection.sendPing()),this.context.connection.isInRoom&&(this._lastRoomTime=this.context.time.time)),this._lastRoomTime>0&&this.context.time.time-this._lastRoomTime>.3&&(this._lastRoomTime=-1,this.autoRejoin?this._userWantsToBeInARoom&&(console.log("Disconnected from networking backend - attempt reconnecting now"),this.tryJoinRoom()):E()&&console.warn("You are not connected to a room anymore (possibly because the tab was inactive for too long and the server kicked you?)"))}getViewOnlyUrl(){if(this.context.connection.isConnected&&this.context.connection.currentRoomViewId){const e=window.location.search,t=new URLSearchParams(e);return t.has(this.urlParameterName)&&t.delete(this.urlParameterName),t.set(i0,this.context.connection.currentRoomViewId),window.location.origin+window.location.pathname+"?"+t.toString()}return null}setRandomRoomUrlParameter(){const e=Ul(),t=this.generateRoomName();w(this.urlParameterName)?e.set(this.urlParameterName,t):e.append(this.urlParameterName,t),xm(t,e)}generateRoomName(){let e="";for(let t=0;t<6;t++)e+=Math.floor(Math.random()*10).toFixed(0);return e}_roomButton;_roomButtonIconJoin;_roomButtonIconLeave;createRoomButton(){if(this._roomButton)return this._roomButton;const e=document.createElement("button");return this._roomButton=e,e.classList.add("create-room-button"),e.setAttribute("priority","90"),e.onclick=()=>{if(this.context.connection.isInRoom)this.urlParameterName&&zl(this.urlParameterName,null),this.context.connection.leaveRoom(),this._userWantsToBeInARoom=!1;else{if(this.urlParameterName){const t=w(this.urlParameterName);(!t||t===!0)&&(this._lastJoinedRoom?zl(this.urlParameterName,this._lastJoinedRoom):this.setRandomRoomUrlParameter())}this.tryJoinRoom()}},this._roomButtonIconJoin=Ct("group"),this._roomButtonIconLeave=Ct("group_off"),this.updateRoomButtonState(),this.context.connection.beginListen(te.JoinedRoom,this.updateRoomButtonState),this.context.connection.beginListen(te.LeftRoom,this.updateRoomButtonState),e}updateRoomButtonState=()=>{this._roomButton&&(this.context.connection.isInRoom?(this._roomButton.title="Leave the networked room",this._roomButton.textContent="Leave Room",this._roomButtonIconJoin?.remove(),this._roomButton.prepend(this._roomButtonIconLeave)):(this._roomButton.title="Create or join a networked room",this._roomButton.textContent="Join Room",this._roomButtonIconLeave?.remove(),this._roomButton.prepend(this._roomButtonIconJoin)))};destroyRoomButton(){this.context.connection.stopListen(te.JoinedRoom,this.updateRoomButtonState),this.context.connection.stopListen(te.LeftRoom,this.updateRoomButtonState)}_viewOnlyButton;onEnableViewOnlyButton(){this.context.connection.isConnected?this.onCreateViewOnlyButton():(this.context.connection.stopListen(te.JoinedRoom,this.onCreateViewOnlyButton),this.context.connection.beginListen(te.JoinedRoom,this.onCreateViewOnlyButton))}onDisableViewOnlyButton(){this.context.connection.stopListen(te.JoinedRoom,this.onCreateViewOnlyButton),this._viewOnlyButton?.remove()}onCreateViewOnlyButton=()=>{if(!this._viewOnlyButton){const e=document.createElement("button");this._viewOnlyButton=e,e.classList.add("view-only-button"),e.setAttribute("priority","90"),e.onclick=()=>{const t=this.getViewOnlyUrl();t?.length?navigator.canShare({url:t})?navigator.share({url:t})?.catch(i=>{console.warn(i)}):(navigator.clipboard.writeText(t),Te("View only URL copied to clipboard")):ge("Could not create view only URL")},e.title="Copy the view only URL: A page accessed by the view only URL can not be modified by visiting users.",e.textContent="Share View URL",e.prepend(Ct("visibility"))}this.context.menu.appendChild(this._viewOnlyButton)}}Vs([u()],Rn.prototype,"roomName",2),Vs([u()],Rn.prototype,"urlParameterName",2),Vs([u()],Rn.prototype,"joinRandomRoom",2),Vs([u()],Rn.prototype,"requireRoomParameter",2),Vs([u()],Rn.prototype,"autoRejoin",2),Vs([u()],Rn.prototype,"createJoinButton",2),Vs([u()],Rn.prototype,"createViewOnlyButton",2),Vs([u()],Rn.prototype,"roomPrefix",1);function w2(){const o=w("testwindowcount")||0;o&&o>0&&x2(o)}function x2(o){if(w("testwindow"))return null;const e=new URL(window.location.href);wm(e.searchParams,bR,1),wm(e.searchParams,"testwindow",1);const t=e.toString(),i=[];window.onbeforeunload=()=>{for(const l of i)l.close()};const n=.05,s=128;let r=0,a=0;for(let l=0;l<o;l++){r*s+s*.01>=window.innerWidth&&(a+=1,r=0);const c=r*(s*(1+n))+window.screenLeft,h=a*(s*(1+n))+window.screenTop+90+60*a;r+=1;const d=window.open(t,"test window "+l,`popup=yes width=${s} height=${s} top=${h} left=${c}`);if(!d){console.warn("Failed to open window");continue}i.push(d),d.onload=()=>{d.onbeforeunload=()=>{for(let p=0;p<i.length;p++){const g=i[p];g!==d&&g.close()}i.length=0}}}return i}class o0 extends M{awake(){w2()}}class s0 extends M{transformsPerFrame=10;interval=0;useFlatbuffers=!0;awake(){if(this.useFlatbuffers)this.context.connection.beginListenBinary(Cc,e=>{});else{this.models=[];for(let e=0;e<this.transformsPerFrame;e++)this.models.push(new S2(this.context.connection.connectionId+"_simulatedTransform_"+e,this))}}builder=null;models=null;update(){if(this.context.connection.isConnected){if(this.useFlatbuffers){if(!this.context.connection.connectionId||this.context.time.frameCount%this.interval!==0)return;this.builder===null&&(this.builder=new fm(1024));const e=this.builder;for(let t=0;t<this.transformsPerFrame;t++){e.clear();const i=mw(this.context.connection.connectionId,this);this.context.connection.sendBinary(i)}}else if(this.models)for(let e=0;e<this.models.length;e++){const t=this.models[e];t.dontSave=!0,t.update(this,null),this.context.connection.send("TestSimulateUserData-"+e,t)}}}}class S2{guid;fast=!1;position;rotation;velocity=void 0;dontSave;isValid(){return this.fast!==void 0||this.position!==void 0||this.rotation!==void 0||this.velocity!==void 0}constructor(e,t){this.guid=e,this.position={x:0,y:0,z:0},this.rotation={x:0,y:0,z:0,w:0},this.update(t,null)}static temp=new b;update(e,t){const i=e.worldPosition;this.position.x=i.x,this.position.y=i.y,this.position.z=i.z;const n=e.worldQuaternion;if(this.rotation.x=n.x,this.rotation.y=n.y,this.rotation.z=n.z,this.rotation.w=n.w,this.fast=!1,t){const s=t.getVelocity();this.velocity===void 0&&(this.velocity={x:0,y:0,z:0}),this.velocity.x=s.x,this.velocity.y=s.y,this.velocity.z=s.z}}}var C2=Object.defineProperty,Rp=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&C2(e,t,n),n};const P2=w("debugsignals");class Tp{guid}Rp([u()],Tp.prototype,"guid");class Ch{signal;reaction}Rp([u(Tp)],Ch.prototype,"signal"),Rp([u(ce)],Ch.prototype,"reaction");const h1=class Yo extends M{static receivers={};static invoke(e){if(Yo.receivers[e]){const t=Yo.receivers[e];if(!t)return;for(const i of t)i.invoke(e)}}events;awake(){P2&&console.log("SignalReceiver awake",this)}onEnable(){if(this.events)for(const e of this.events)Yo.receivers[e.signal.guid]||(Yo.receivers[e.signal.guid]=[]),Yo.receivers[e.signal.guid].push(this)}onDisable(){if(this.events){for(const e of this.events)if(Yo.receivers[e.signal.guid]){const t=Yo.receivers[e.signal.guid].indexOf(this);t>=0&&Yo.receivers[e.signal.guid].splice(t,1)}}}invoke(e){if(!this.events||!Array.isArray(this.events))return;const t=typeof e=="object"?e.guid:e;for(const i of this.events)if(i.signal.guid===t)try{if(i.reaction){if(!i.reaction.invoke){console.warn("Missing invoke - possibly a serialization error",i,this);continue}}else{console.warn("Missing reaction for signal",i,this);continue}i.reaction.invoke()}catch(n){console.error(n)}}};Rp([u(Ch)],h1.prototype,"events");let Ph=h1;var Bi=(o=>(o.Activation="ActivationTrack",o.Animation="AnimationTrack",o.Audio="AudioTrack",o.Control="ControlTrack",o.Marker="MarkerTrack",o.Signal="SignalTrack",o))(Bi||{}),ro=(o=>(o[o.None=0]="None",o[o.Hold=1]="Hold",o[o.Loop=2]="Loop",o[o.PingPong=3]="PingPong",o[o.Continue=4]="Continue",o))(ro||{}),r0=(o=>(o.Signal="SignalEmitter",o))(r0||{});const ao=w("debugtimeline");class Oh{director;track;get muted(){return this.track.muted}set muted(e){e!==this.track.muted&&(this.track.muted=e,this.onMuteChanged?.call(this))}*forEachClip(e=!1){if(this.track?.clips)if(e)for(let t=this.track.clips.length-1;t>=0;t--)yield this.track.clips[t];else for(const t of this.track.clips)yield t}getClipTime(e,t){return t.clipIn+(e-t.start)*t.timeScale}getClipTimeNormalized(e,t){return(e-t.start)/t.duration}evaluateWeight(e,t,i,n=!0){if(t<0||t>=i.length)return 0;const s=i[t];if(n||e>=s.start&&e<=s.end){let r=1;if(s.easeInDuration>0){const a=Math.min((e-s.start)/s.easeInDuration,1);r*=a}if(s.easeOutDuration>0){const a=Math.min((s.end-e)/s.easeOutDuration,1);r*=a}return r}return 0}}class O2{clip;rootPositionOffset;rootQuaternionOffset;get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}rootStartPosition;rootEndPosition;rootStartQuaternion;rootEndQuaternion;constructor(e){const t=e.getClip();this.clip=t;const i=e.getRoot(),n=i.name+".position",s=i.name+".quaternion";ao&&console.log(t.name,t.tracks,n);for(const r of t.tracks)if(!(r.times.length<=0)){if(r.name.endsWith(n))this.rootStartPosition=new b().fromArray(r.values,0),this.rootEndPosition=new b().fromArray(r.values,r.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),ao&&console.log(this.rootPositionOffset);else if(r.name.endsWith(s)&&(this.rootStartQuaternion=new U().fromArray(r.values,0),this.rootEndQuaternion=new U().fromArray(r.values,r.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),ao)){const a=new nt().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",a)}}}}class Ep extends Oh{models=[];trackOffset;target;mixer;clips=[];actions=[];weight=1;_actionOffsets=[];_didBind=!1;_animator=null;onDisable(){this.mixer?.stopAllAction()}onDestroy(){this.director.context.animations.unregisterAnimationMixer(this.mixer)}onStateChanged(){this._animator&&cw(this._animator.gameObject,this,this.director.isPlaying)}createHooks(e,t){if(t.tracks?.length<=0){console.warn("No tracks in AnimationClip",t);return}const i=t.tracks[0].name.split("."),n=i[i.length-2],s=n+".position",r=n+".quaternion";let a=!1,l=!1;for(const c of t.tracks)c.name.endsWith(s)?(a=!0,this.createPositionInterpolant(t,e,c)):c.name.endsWith(r)&&(l=!0,this.createRotationInterpolant(t,e,c));if(!a||!l){const c=this.mixer?.getRoot(),h=t.tracks[0],d=h.name.lastIndexOf("."),p=h.name.substring(0,d),g=p.substring(p.lastIndexOf(".")+1),f=c.getObjectByName(g);if(f)if(a){if(!l){const m=t.tracks[0].name.substring(0,d)+".quaternion";ao&&console.warn("Create quaternion track",g,f);const y=f.quaternion,_=new aC(m,[0,t.duration],[y.x,y.y,y.z,y.w,y.x,y.y,y.z,y.w]);t.tracks.push(_),this.createRotationInterpolant(t,e,_)}}else{const m=p+".position";ao&&console.warn("Create position track",g,f);const y=f.position,_=new rC(m,[0,t.duration],[y.x,y.y,y.z,y.x,y.y,y.z]);t.tracks.push(_),this.createPositionInterpolant(t,e,_)}}}bind(){if(!this._didBind){this._didBind=!0,ao&&console.log(this.models),this.mixer?this.target=this.mixer.getRoot():console.warn("No mixer was assigned to animation track");for(const e of this.actions){const t=new O2(e);this._actionOffsets.push(t)}this.target&&(this._animator=x.getComponent(this.target,ft)??null,this._animator&&cw(this._animator.gameObject,this,!0));for(const e of this.models){const t=e.asset,i=t.position,n=t.rotation;i&&i.x!==void 0&&(i.isVector3||(t.position=new b(i.x,i.y,i.z)),n.isQuaternion||(t.rotation=new U(n.x,n.y,n.z,n.w)))}this.ensureTrackOffsets()}}ensureTrackOffsets(){if(this.trackOffset){const e=this.trackOffset.position;e&&(e.isVector3||(this.trackOffset.position=new b(e.x,e.y,e.z)));const t=this.trackOffset.rotation;t&&(t.isQuaternion||(this.trackOffset.rotation=new U(t.x,t.y,t.z,t.w)))}}_useclipOffsets=!0;_totalOffsetPosition=new b;_totalOffsetRotation=new U;_totalOffsetPosition2=new b;_totalOffsetRotation2=new U;_summedPos=new b;_tempPos=new b;_summedRot=new U;_tempRot=new U;_clipRotQuat=new U;evaluate(e){if(this.track.muted||!this.mixer)return;this.bind(),this._totalOffsetPosition.set(0,0,0),this._totalOffsetRotation.set(0,0,0,1),this._totalOffsetPosition2.set(0,0,0),this._totalOffsetRotation2.set(0,0,0,1);let t=0,i=0,n=!1,s=!1,r=0;for(let a=0;a<this.clips.length;a++){const l=this.models[a],c=this.actions[a],h=l.asset;c.weight=0;const d=e>=l.start&&e<=l.end,p=l.preExtrapolationMode,g=l.postExtrapolationMode,f=a<this.clips.length-1?this.models[a+1]:null;let m=d,y=!1;if(!m&&!n&&l.end<e&&g!==ro.None?(!f||f.start>e)&&(m=!0,n=!0):a==0&&!m&&!s&&l.start>e&&p!==ro.None&&(!f||f.start<e)&&(m=!0,y=!0,s=!0),m){let _=this.weight;_*=this.evaluateWeight(e,a,this.models,m),_*=this.director.weight;let v=d;if(y)switch(p){case ro.Hold:break;case ro.Loop:e+=l.start,v=!0;break;default:e+=l.start,v=!0;break}let P=this.getClipTime(e,l),R=0;const k=h.duration;if(y&&p===ro.Hold&&(P=0),v){if(h.loop)for(R+=Math.floor(P/(k+1e-6));P>k;)P-=k}else if(!d&&n)switch(g){case ro.Hold:P=this.getClipTime(l.end,l);break;case ro.Loop:P%=k;break;case ro.PingPong:const L=Math.floor(P/k)%2!==0;P%=k,L&&(P=k-P);break}l.reversed===!0?c.time=c.getClip().duration-P:c.time=P,c.timeScale=0;const A=Math.max(0,_);if(c.weight=A,r+=A,c.clampWhenFinished=!1,c.isRunning()||c.play(),this._useclipOffsets){const L=t==0?this._totalOffsetPosition:this._totalOffsetPosition2,N=t==0?this._totalOffsetRotation:this._totalOffsetRotation2;t<1&&(i=1-_),t+=1;const j=this._summedPos.set(0,0,0),q=this._tempPos.set(0,0,0),Y=this._summedRot.identity(),I=this._tempRot.identity(),V=h.rotation;V&&(this._clipRotQuat.identity(),this._clipRotQuat.slerp(V,_));const W=this._actionOffsets[a];if(W.hasOffsets)for(let oe=0;oe<R;oe++)W.rootPositionOffset?q.copy(W.rootPositionOffset):q.set(0,0,0),q.applyQuaternion(Y),this._clipRotQuat&&q.applyQuaternion(this._clipRotQuat),W.rootQuaternionOffset&&(I.copy(W.rootQuaternionOffset),Y.multiply(I)),j.add(q);this._clipRotQuat&&N.multiply(this._clipRotQuat),N.multiply(Y),h.position&&j.add(h.position),L.add(j)}}}if(this._useclipOffsets&&(this._totalOffsetPosition.lerp(this._totalOffsetPosition2,i),this._totalOffsetRotation.slerp(this._totalOffsetRotation2,i)),this.__mixerError===void 0&&(ao||E())&&this._animator?.runtimeAnimatorController?.mixer&&this.mixer!==this._animator?.runtimeAnimatorController?.mixer&&(this.__mixerError=!0,console.error("AnimationTrack mixer is not shared with the animator controller - this might result in the timeline to not animate properly. Please report a bug to the Needle Engine team!",this)),this._animator?.runtimeAnimatorController){const a=Math.max(0,1-r);this._animator?.runtimeAnimatorController?.update(a)}else this.mixer.update(e)}createRotationInterpolant(e,t,i){const n=i.createInterpolant.bind(i),s=new U;this.ensureTrackOffsets();const r=this.trackOffset?.rotation;i.createInterpolant=()=>{const a=n(),l=a.evaluate.bind(a);return a.evaluate=c=>{const h=l(c);if(s.set(h[0],h[1],h[2],h[3]),s.premultiply(this._totalOffsetRotation),r&&s.premultiply(r),this.director.animationCallbackReceivers)for(const d of this.director.animationCallbackReceivers)d?.onTimelineRotation?.call(d,this.director,this.target,c,s);return h[0]=s.x,h[1]=s.y,h[2]=s.z,h[3]=s.w,h},a}}createPositionInterpolant(e,t,i){const n=i.createInterpolant.bind(i),s=new b;this.ensureTrackOffsets();const r=this.trackOffset?.rotation,a=this.trackOffset?.position;let l;i.createInterpolant=()=>{const c=n(),h=c.evaluate.bind(c);return c.evaluate=d=>{const p=h(d);if(s.set(p[0],p[1],p[2]),t.removeStartOffset&&(l===void 0?(l=null,l=this._actionOffsets.find(g=>g.clip===e)?.rootStartPosition?.clone()):l?.isVector3&&s.sub(l)),s.applyQuaternion(this._totalOffsetRotation),s.add(this._totalOffsetPosition),r&&s.applyQuaternion(r),a&&(s.x-=a.x,s.y+=a.y,s.z+=a.z),this.director.animationCallbackReceivers)for(const g of this.director.animationCallbackReceivers)g?.onTimelinePosition?.call(g,this.director,this.target,d,s);return p[0]=s.x,p[1]=s.y,p[2]=s.z,p},c}}}const k2=w("mutetimeline");class es extends Oh{models=[];listener;audio=[];audioContextTimeOffset=[];lastTime=0;audioSource;_audioLoader=null;getAudioFilePath(e){const t=this.director.sourceId;return ls(t,e)}onAllowAudioChanged(e){for(let t=0;t<this.models.length;t++){const i=this.models[t];this.audio[t].setVolume(e?i.asset.volume:0)}}addModel(e){const t=new lC(this.listener);this.audio.push(t);const i=e;i._didTriggerPlay=!1,this.models.push(i)}onDisable(){for(const e of this.audio)e.isPlaying&&e.stop();for(const e of this.models)e._didTriggerPlay=!1}onDestroy(){for(const e of this.audio)e.source&&e?.disconnect();this.audio.length=0}onMuteChanged(){if(this.muted)for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t?.isPlaying&&t.stop()}}stop(){for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t?.isPlaying&&t.stop()}for(const e of this.models)e._didTriggerPlay=!1}_playableDirectorResumed=!1;onPauseChanged(){for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t?.isPlaying&&t.stop()}this._playableDirectorResumed=this.director.isPlaying}evaluate(e){if(k2||this.track.muted||this.director.speed<0)return;const t=this.director.context.application.muted,i=this._playableDirectorResumed;this._playableDirectorResumed=!1;const n=t?.1:0;for(let s=0;s<this.models.length;s++){const r=this.models[s],a=this.audio[s],l=r.asset;if((!a||!a.buffer)&&this.isInTimeRange(r,e-1,e+1)&&this.handleAudioLoading(r,a),Mi.userInteractionRegistered!==!1&&!(a===null||!a.buffer))if(a.playbackRate=this.director.context.time.timeScale*this.director.speed,a.loop=l.loop,e>=r.start&&e<=r.end&&e<this.director.duration){if(!a.isPlaying||!this.director.isPlaying)(i||!r._didTriggerPlay&&this.lastTime<e)&&(r.duration*r.timeScale>.3?a.offset=r.clipIn+(e-r.start)*r.timeScale:a.offset=0,ao&&console.log("Timeline Audio ("+this.track.name+") play with offset "+a.offset+" - "+r.asset.clip),a.play(n),r._didTriggerPlay=!0);else{const h=r.clipIn+(e-r.start)*r.timeScale,d=a.context.currentTime-a._startedAt+a.offset;Math.abs(h-d)>.3&&(a.offset=h,a.stop(),a.play(n))}let c=l.volume;if(this.track.volume!==void 0&&(c*=this.track.volume),t&&(c=0),r.easeInDuration>0){const h=Math.min((e-r.start)/r.easeInDuration,1);c*=h}if(r.easeOutDuration>0){const h=Math.min((r.end-e)/r.easeOutDuration,1);c*=h}a.setVolume(c*this.director.weight)}else r._didTriggerPlay=!1,this.director.isPlaying&&a.isPlaying&&a.stop()}this.lastTime=e}loadAudio(e,t=0,i=0){let n=null;const s=e-i,r=e+t;for(const a of this.models)if(this.isInTimeRange(a,s,r)){const l=this.audio[this.models.indexOf(a)],c=this.handleAudioLoading(a,l);c!==null&&(n===null&&(n=[]),n.push(c))}return n!==null?Promise.all(n):null}isInTimeRange(e,t,i){return t<=e.start&&i>=e.end||t>=e.start&&t<=e.end||i>=e.start&&i<=e.end}static _audioBuffers=new Map;static dispose(){es._audioBuffers.clear()}handleAudioLoading(e,t){this._audioLoader||(this._audioLoader=new am);const i=this.getAudioFilePath(e.asset.clip);if(es._audioBuffers.get(i)){const s=es._audioBuffers.get(i);return s.then(r=>{r&&t.setBuffer(r)}),s}ao&&console.warn("LOAD audio track",i,this.director.sourceId);const n=new Promise((s,r)=>{this._audioLoader.load(i,a=>{t.setBuffer(a),s(a)},void 0,a=>{console.error("Error loading audio",a),s(null)})});return es._audioBuffers.set(i,n),n}}class kh extends Oh{models=[];didTrigger=[];receivers=[];evaluate(e){if(this.track.muted)return;const t=this.director.context.time.deltaTime*1.5;for(let i=0;i<this.models.length;i++){const n=this.models[i],s=this.didTrigger[i],r=n.time-e;let a=!1;if(n.retroActive)a=r<=1e-6;else{const l=Math.abs(r);(l===0||l>=1e-5&&l<t)&&(a=!0)}if(a){if(!s)if(ao&&console.log("Trigger signal",e,n.time,n),this.didTrigger[i]=!0,this.receivers?.length<=0)Ph.invoke(n.asset);else for(const l of this.receivers)l&&l.invoke(n.asset)}else n.emitOnce||(this.didTrigger[i]=!1)}}}class Ap extends Oh{models=[];timelines=[];resolveSourceObjects(e){for(let t=this.models.length-1;t>=0;t--){const i=this.models[t].asset;if(!i.sourceObject||typeof i.sourceObject!="object"){console.log("no source object, removing model",t,i),this.models.splice(t,1);continue}else{const n=x.getComponent(i.sourceObject,ea);this.timelines.push(n),n&&i.updateDirector&&(n.playOnAwake=!1)}}}_previousActiveModel=null;evaluate(e){this._previousActiveModel=null;for(let t=0;t<this.models.length;t++){const i=this.models[t],n=i.asset;if(e>=i.start&&e<=i.end){this._previousActiveModel=i;const s=this.getClipTime(e,i);if(n.controlActivation){const r=n.sourceObject;r.visible=!0}if(n.updateDirector){const r=this.timelines[t];r&&(r.isPlaying&&r.pause(),r.time=s,r.evaluate())}}else{const s=this._previousActiveModel?.asset;if(n.controlActivation){const r=n.sourceObject;s?.sourceObject!==r&&(r.visible=!1)}}}}}var M2=Object.defineProperty,d1=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&M2(e,t,n),n};const Vo=w("debugtimeline"),a0=class T0 extends M{static createTrackFunctions={};static registerCreateTrack(e,t){this.createTrackFunctions[e]=t}playableAsset;playOnAwake;extrapolationMode=1;get isPlaying(){return this._isPlaying}get isPaused(){return this._isPaused}get time(){return this._time}set time(e){typeof e=="number"&&!Number.isNaN(e)?this._time=e:(Vo||Wi())&&console.error("INVALID TIMELINE.TIME VALUE",e,this.name)}get duration(){return this._duration}set duration(e){this._duration=e}get weight(){return this._weight}set weight(e){this._weight=e}get speed(){return this._speed}set speed(e){this._speed=e}waitForAudio=!0;_visibilityChangeEvt;_clonedPlayableAsset=!1;_speed=1;awake(){Vo&&console.log(this,this.playableAsset?.tracks),this.rebuildGraph(),!this.isValid()&&(Vo||E())&&(Vo?console.warn("PlayableDirector is not valid","Asset?",this.playableAsset,"Tracks:",this.playableAsset?.tracks,"IsArray?",Array.isArray(this.playableAsset?.tracks),this):this.playableAsset?.tracks?.length?console.warn("PlayableDirector is not valid"):console.warn("PlayableDirector has no tracks"))}onEnable(){for(const e of this._audioTracks)e.onEnable?.();for(const e of this._customTracks)e.onEnable?.();for(const e of this._animationTracks)e.onEnable?.();this.playOnAwake&&this.play(),this._visibilityChangeEvt||(this._visibilityChangeEvt=()=>{switch(document.visibilityState){case"hidden":this.setAudioTracksAllowPlaying(!1);break;case"visible":this.setAudioTracksAllowPlaying(!0);break}}),window.addEventListener("visibilitychange",this._visibilityChangeEvt)}onDisable(){this.stop();for(const e of this._audioTracks)e.onDisable?.();for(const e of this._customTracks)e.onDisable?.();for(const e of this._animationTracks)e.onDisable?.();this._visibilityChangeEvt&&window.removeEventListener("visibilitychange",this._visibilityChangeEvt)}onDestroy(){for(const e of this._allTracks)for(const t of e)t.onDestroy?.()}rebuildGraph(){this.isValid()&&(this.resolveBindings(),this.updateTimelineDuration(),this.setupAndCreateTrackHandlers())}async play(){if(!this.isValid())return;const e=this._isPaused==!0;if(this._isPaused=!1,!this._isPlaying){if(this._isPlaying=!0,e&&this.invokePauseChangedMethodsOnTracks(),this.waitForAudio){const t=[];for(const i of this._audioTracks){const n=i.loadAudio(this._time,1,0);n&&t.push(n)}if(t.length>0&&(await Promise.all(t),!this._isPlaying))return;for(;this._audioTracks.length>0&&this._isPlaying&&!Mi.userInteractionRegistered&&this.waitForAudio;)await Dn(200)}this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine=this.startCoroutine(this.internalUpdate(),we.LateUpdate)}}pause(){this.isValid()&&(this._isPlaying=!1,!this._isPaused&&(this._isPaused=!0,this.internalEvaluate(),this.invokePauseChangedMethodsOnTracks(),this.invokeStateChangedMethodsOnTracks()))}stop(){this._isStopping=!0;for(const i of this._audioTracks)i.stop();const e=this._isPaused==!0,t=this._isPlaying;this._isPlaying&&(this._time=0,this._isPlaying=!1,this._isPaused=!1,this.internalEvaluate(),e&&this.invokePauseChangedMethodsOnTracks()),this._isPlaying=!1,this._isPaused=!1,e&&!t&&this.invokePauseChangedMethodsOnTracks(),t&&this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine&&this.stopCoroutine(this._internalUpdateRoutine),this._internalUpdateRoutine=null,this._isStopping=!1}evaluate(){this.internalEvaluate(!0)}isValid(){return this.playableAsset&&this.playableAsset.tracks&&Array.isArray(this.playableAsset.tracks)}*forEachTrack(){for(const e of this._allTracks)for(const t of e)yield t}get animationTracks(){return this._animationTracks}get audioTracks(){return this._audioTracks}_guidsMap;resolveGuids(e){this._guidsMap=e}_isPlaying=!1;_internalUpdateRoutine;_isPaused=!1;_isStopping=!1;_time=0;_duration=0;_weight=1;_animationTracks=[];_audioTracks=[];_signalTracks=[];_controlTracks=[];_customTracks=[];_allTracks=[this._animationTracks,this._audioTracks,this._signalTracks,this._controlTracks,this._customTracks];invokePauseChangedMethodsOnTracks(){for(const e of this.forEachTrack())e.onPauseChanged?.call(e)}invokeStateChangedMethodsOnTracks(){for(const e of this.forEachTrack())e.onStateChanged?.call(e,this._isPlaying)}*internalUpdate(){for(;this._isPlaying&&this.activeAndEnabled;)!this._isPaused&&this._isPlaying&&(this._time+=this.context.time.deltaTime*this.speed,this.internalEvaluate()),yield}internalEvaluate(e=!1){if(!this.isValid())return;let t=this._time;switch(this.extrapolationMode){case 0:this._speed>0?t=Math.min(t,this._duration):this._speed<0&&(t=Math.max(t,0)),this._time=t;break;case 1:t%=this._duration,this._time=t;break;case 2:if(t>this._duration){this.stop();return}break}const i=this._time;for(const n of this.playableAsset.tracks)if(!n.muted)switch(n.type){case Bi.Activation:if(!e&&!this._isPlaying)continue;for(let s=0;s<n.outputs.length;s++){const r=n.outputs[s];if(typeof r=="object"){let a=!1;if(n.clips)for(const c of n.clips)c.start<=i&&i<=c.end&&(a=!0);const l=r;l.visible!==void 0&&l.visible!==a&&(l.visible=a,Vo&&console.warn(this.name,"set ActivationTrack-"+s,l.name,a,i))}}break}if(!this._isStopping)for(const n of this._animationTracks)n.evaluate(i);for(const n of this._audioTracks)n.evaluate(i);for(const n of this._signalTracks)n.evaluate(i);for(const n of this._controlTracks)n.evaluate(i);for(const n of this._customTracks)n.evaluate(i)}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=Nl(this.playableAsset)),!this.playableAsset||!this.playableAsset.tracks)return;const e=this.findRoot(this.gameObject);for(const t of this.playableAsset.tracks){for(let i=t.outputs.length-1;i>=0;i--){let n=t.outputs[i];if(typeof n=="string"){this._guidsMap&&this._guidsMap[n]&&(n=this._guidsMap[n]);const s=x.findByGuid(n,e);s===null||typeof s!="object"?(t.outputs.splice(i,1),console.warn("Failed to resolve binding",n,t.name,t.type)):(Vo&&console.log("Resolved binding",n,"to",s),t.outputs[i]=s)}else if(n===null){if(t.outputs.splice(i,1),T0.createTrackFunctions[t.type])continue;t.type!==Bi.Audio&&t.type!==Bi.Control&&t.type!==Bi.Marker&&t.type!==Bi.Signal&&console.warn("Missing binding",n,t.name,t.type,this.name,this.playableAsset.name)}}if(t.type===Bi.Control&&t.clips)for(let i=0;i<t.clips.length;i++){const n=t.clips[i];let s=n.asset.sourceObject;if(typeof s=="string"){this._guidsMap&&this._guidsMap[s]&&(s=this._guidsMap[s]);const r=x.findByGuid(s,e);r===null||typeof r!="object"?console.warn("Failed to resolve sourceObject binding",s,t.name,n):(Vo&&console.log("Resolved binding",s,"to",r),n.asset.sourceObject=r)}}}}findRoot(e){return e.parent?this.findRoot(e.parent):e}updateTimelineDuration(){if(this._duration=0,!(!this.playableAsset||!this.playableAsset.tracks)){for(const e of this.playableAsset.tracks)if(e.muted!==!0){if(e.clips)for(const t of e.clips)t.end>this._duration&&(this._duration=t.end);if(e.markers)for(const t of e.markers)t.time>this._duration&&(this._duration=t.time+.001)}}}setupAndCreateTrackHandlers(){if(this._animationTracks.length=0,this._audioTracks.length=0,this._signalTracks.length=0,!this.playableAsset)return;let e=x.findObjectOfType(ko,this.context);for(const t of this.playableAsset.tracks){const i=t.type,n=T0.createTrackFunctions[i];if(n!=null){const s=n(this,t);if(typeof s.evaluate=="function"){s.director=this,s.track=t,this._customTracks.push(s);continue}}if(t.type===Bi.Animation){if(!t.clips||t.clips.length<=0){Vo&&console.warn("Animation track has no clips",t);continue}for(let s=t.outputs.length-1;s>=0;s--){let r=t.outputs[s];if(r instanceof O){const l=x.getOrAddComponent(r,ft);l&&(r=l)}const a=r?.gameObject?.animations;if(a){const l=new Ep;l.trackOffset=t.trackOffset,l.director=this,l.track=t;for(let c=0;c<t.clips.length;c++){const h=t.clips[c],d=h.asset;if(!d){console.error(`Timeline ${this.name}: clip #${c} on track "${t.name}" has no animation data`);continue}const p=d.clip;let g=p;if((typeof g=="string"||typeof g=="number")&&(g=a.find(m=>m.name===p)),Vo&&console.log(d,p,"\u2192",g),!g){console.warn("Could not find animationClip for model",h,t.name,this.name,this.playableAsset?.name,a,r);continue}r instanceof ft&&r.runtimeAnimatorController&&(r.__internalDidAwakeAndStart||r.initializeRuntimeAnimatorController(),r.runtimeAnimatorController.mixer||r.runtimeAnimatorController.bind(r),l.mixer=r.runtimeAnimatorController.mixer),l.mixer||(l.mixer=new rm(r.gameObject),this.context.animations.registerAnimationMixer(l.mixer)),l.clips.push(g),l.mixer.uncacheAction(g),l.createHooks(h.asset,g);const f=l.mixer.clipAction(g);l.actions.push(f),l.models.push(h)}this._animationTracks.push(l)}}}else if(t.type===Bi.Audio){if(!t.clips||t.clips.length<=0)continue;const s=new es;s.director=this,s.track=t,s.audioSource=t.outputs.find(r=>r instanceof Mi),this._audioTracks.push(s),e||(e=this.context.mainCameraComponent?.gameObject.addComponent(ko)),s.listener=e.listener;for(let r=0;r<t.clips.length;r++){const a=t.clips[r];s.addModel(a)}}else if(t.type===Bi.Marker){const s=new kh;if(s.director=this,s.track=t,t.markers)for(const r of t.markers)switch(r.type){case r0.Signal:s.models.push(r),s.didTrigger.push(!1);break}if(s!==null&&s.models.length>0){const r=x.getComponent(this.gameObject,Ph);r&&(s.receivers.push(r),this._signalTracks.push(s))}}else if(t.type===Bi.Signal){const s=new kh;if(s.director=this,s.track=t,t.markers)for(const r of t.markers)s.models.push(r),s.didTrigger.push(!1);for(const r of t.outputs)s.receivers.push(r);this._signalTracks.push(s)}else if(t.type===Bi.Control){const s=new Ap;if(s.director=this,s.track=t,t.clips)for(const r of t.clips)s.models.push(r);s.resolveSourceObjects(this.context),this._controlTracks.push(s)}}}setAudioTracksAllowPlaying(e){for(const t of this._audioTracks)t.onAllowAudioChanged(e)}animationCallbackReceivers=[];registerAnimationCallback(e){this.animationCallbackReceivers.push(e)}unregisterAnimationCallback(e){const t=this.animationCallbackReceivers.indexOf(e);t!==-1&&this.animationCallbackReceivers.splice(t,1)}};d1([u()],a0.prototype,"playOnAwake"),d1([u()],a0.prototype,"extrapolationMode");let ea=a0;var R2=Object.defineProperty,Ip=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&R2(e,t,n),n};class ta extends M{isGizmo=!1;translationSnap=1;rotationSnapAngle=15;scaleSnap=.25;get control(){return this._control}_control;orbit;onEnable(){if(!(this.isGizmo&&!lc)&&this.context.mainCamera&&(this._control||(this._control=new TC(this.context.mainCamera,this.context.renderer.domElement),this._control.enabled=!0,this._control.getRaycaster().layers.set(2),this._control.size=1,("_root"in this._control?this._control._root:this._control).traverse(e=>{const t=e;if(t.layers.set(2),t){const i=t.material;i&&(i.opacity=.3)}}),this.orbit=x.getComponentInParent(this.context.mainCamera,fe)??void 0),this._control)){const e=this._control.getHelper();this.context.scene.add(e),this._control.attach(this.gameObject),this._control?.addEventListener("dragging-changed",this.onControlChangedEvent),window.addEventListener("keydown",this.windowKeyDownListener),window.addEventListener("keyup",this.windowKeyUpListener)}}onDisable(){this._control?.getHelper()?.removeFromParent(),this._control?.removeEventListener("dragging-changed",this.onControlChangedEvent),window.removeEventListener("keydown",this.windowKeyDownListener),window.removeEventListener("keyup",this.windowKeyUpListener)}enableSnapping(){this._control&&(this._control.setTranslationSnap(this.translationSnap),this._control.setRotationSnap(uo.degToRad(this.rotationSnapAngle)),this._control.setScaleSnap(this.scaleSnap))}disableSnapping(){this._control&&(this._control.setTranslationSnap(null),this._control.setRotationSnap(null),this._control.setScaleSnap(null))}onControlChangedEvent=e=>{const t=this.orbit;if(t&&(t.enabled=!e.value),e.value){const i=this.gameObject.getComponentInParent(vn);i&&(i.fastMode=!0,i.requestOwnership())}else{const i=this.gameObject.getComponentInParent(vn);i&&(i.fastMode=!1)}};windowKeyDownListener=e=>{if(this.enabled&&this._control)switch(e.keyCode){case 81:this._control.setSpace(this._control.space==="local"?"world":"local");break;case 16:this.enableSnapping();break;case 87:this._control.setMode("translate");break;case 69:this._control.setMode("rotate");break;case 82:this._control.setMode("scale");break;case 187:case 107:this._control.setSize(this._control.size+.1);break;case 189:case 109:this._control.setSize(Math.max(this._control.size-.1,.1));break;case 88:this._control.showX=!this._control.showX;break;case 89:this._control.showY=!this._control.showY;break;case 90:this._control.showZ=!this._control.showZ;break;case 32:this._control.enabled=!this._control.enabled;break}};windowKeyUpListener=e=>{if(this.enabled)switch(e.keyCode){case 16:this.disableSnapping();break}}}Ip([u()],ta.prototype,"isGizmo"),Ip([u()],ta.prototype,"translationSnap"),Ip([u()],ta.prototype,"rotationSnapAngle"),Ip([u()],ta.prototype,"scaleSnap");var T2=Object.defineProperty,E2=Object.getOwnPropertyDescriptor,Lp=(o,e,t,i)=>{for(var n=i>1?void 0:i?E2(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&T2(e,t,n),n};class l0{texture=null;rect}Lp([u(Re)],l0.prototype,"texture",2);let xl=class extends Zc{set image(o){this.sprite||(this.sprite=new l0),this.sprite.texture=o,this.onAfterCreated()}get image(){return this.sprite?this.sprite.texture:null}get sprite(){return this._sprite}set sprite(o){this._sprite!==o&&(this._sprite=o,this.onAfterCreated())}_sprite;pixelsPerUnitMultiplier=1;isBuiltinSprite(){const o=this.sprite;switch(o?.texture?.name){case"InputFieldBackground":case"UISprite":case"Background":case"Knob":return!0}return!o?.texture?.name?.length&&o?.texture?.image?.width===32&&o?.texture?.image?.height===32}onBeforeCreate(o){super.onBeforeCreate(o),this.isBuiltinSprite()&&(o.borderRadius=5/this.pixelsPerUnitMultiplier,this.sprite?.texture?.name==="Knob"&&(o.borderRadius=999))}onAfterCreated(){this.__didAwake&&(super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture(this.sprite?.texture))}};Lp([u(l0)],xl.prototype,"sprite",1),Lp([u()],xl.prototype,"pixelsPerUnitMultiplier",2);class jp extends Zc{get mainTexture(){return this._mainTexture}set mainTexture(e){this._mainTexture!==e&&(this._mainTexture=e,this.onAfterCreated())}_mainTexture;onAfterCreated(){this.__didAwake&&(super.onAfterCreated(),this.setTexture(this.mainTexture))}}Lp([u(Re)],jp.prototype,"mainTexture",1);var A2=Object.defineProperty,I2=Object.getOwnPropertyDescriptor,Fi=(o,e,t,i)=>{for(var n=i>1?void 0:i?I2(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&A2(e,t,n),n};const ia=w("debugbutton");class $s{colorMultiplier;disabledColor;fadeDuration;highlightedColor;normalColor;pressedColor;selectedColor}Fi([u()],$s.prototype,"colorMultiplier",2),Fi([u(se)],$s.prototype,"disabledColor",2),Fi([u()],$s.prototype,"fadeDuration",2),Fi([u(se)],$s.prototype,"highlightedColor",2),Fi([u(se)],$s.prototype,"normalColor",2),Fi([u(se)],$s.prototype,"pressedColor",2),Fi([u(se)],$s.prototype,"selectedColor",2);class L2{disabledTrigger;highlightedTrigger;normalTrigger;pressedTrigger;selectedTrigger}class $o extends M{click(){this.onClick?.invoke()}onClick=new ce;_isHovered=0;onPointerEnter(e){const t=e.event.pointerType==="mouse"&&e.button===0;t&&(this._isHovered+=1),ia&&console.warn("Button Enter",t,this._isHovered,this.animationTriggers?.highlightedTrigger,this.animator),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.highlightedTrigger):this.transition===1&&this.colors&&this._image?.setState("hovered"),t&&this.context.input.setCursor("pointer"))}onPointerExit(){this._isHovered-=1,this._isHovered<0&&(this._isHovered=0),ia&&console.log("Button Exit",this._isHovered,this.animationTriggers?.highlightedTrigger,this.animator),this.interactable&&(this._isHovered>0||(this._isHovered=0,this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&this._image?.setState("normal"),this.context.input.unsetCursor("pointer")))}onPointerDown(e){ia&&console.log("Button Down",this.animationTriggers?.highlightedTrigger,this.animator),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.pressedTrigger):this.transition===1&&this.colors&&this._image?.setState("pressed"))}onPointerUp(e){ia&&console.warn("Button Up",this.animationTriggers?.highlightedTrigger,this.animator,this._isHovered),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this._isHovered?this.animationTriggers.highlightedTrigger:this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&this._image?.setState(this._isHovered?"hovered":"normal"))}onPointerClick(e){if(this.interactable&&!(e.button!==0&&e.event.pointerType===Rd.Mouse)&&(ia&&(console.warn("Button Click",this.onClick),Te("CLICKED button "+this.name+" at "+this.context.time.frameCount)),this.onClick&&this.onClick.listenerCount>0&&(this.onClick.invoke(),e.use(),ia))){const t=this.gameObject.worldPosition;t.add(this.gameObject.worldUp.multiplyScalar(1+Math.random()*.5)),F.DrawLabel(t,"CLICK:"+Date.now(),.1,1+Math.random()*.5)}}colors;transition;animationTriggers;animator;set interactable(e){this._interactable=e,this._image&&(this._image.setInteractable(e),e?this._image.setState("normal"):this._image.setState("disabled"))}get interactable(){return this._interactable}_interactable=!0;set_interactable(e){this.interactable=e}awake(){super.awake(),ia&&console.log(this),this._isInit=!1,this.init()}start(){this._image?.setInteractable(this.interactable),this.gameObject.getComponentInParent(Wa)||this.gameObject.addComponent(vu)}onEnable(){super.onEnable()}onDestroy(){this._isHovered&&this.context.input.unsetCursor("pointer")}_requestedAnimatorTrigger;*setAnimatorTriggerAtEndOfFrame(e){this._requestedAnimatorTrigger=e,yield,yield,this._requestedAnimatorTrigger==e&&this.animator?.setTrigger(e)}_isInit=!1;_image;init(){this._isInit||(this._isInit=!0,this._image=x.getComponent(this.gameObject,xl),this._image&&(this.stateSetup(this._image),this.interactable?this._image.setState("normal"):this._image.setState("disabled")))}stateSetup(e){e.setInteractable(this.interactable);const t=this.getFinalColor(e.color,this.colors?.normalColor),i={state:"normal",attributes:{backgroundColor:t,backgroundOpacity:t.alpha}};e.setupState(i);const n=this.getFinalColor(e.color,this.colors?.highlightedColor),s={state:"hovered",attributes:{backgroundColor:n,backgroundOpacity:n.alpha}};e.setupState(s);const r=this.getFinalColor(e.color,this.colors?.pressedColor),a={state:"pressed",attributes:{backgroundColor:r,backgroundOpacity:r.alpha}};e.setupState(a);const l=this.getFinalColor(e.color,this.colors?.selectedColor),c={state:"selected",attributes:{backgroundColor:l,backgroundOpacity:l.alpha}};e.setupState(c);const h=this.getFinalColor(e.color,this.colors?.disabledColor),d={state:"disabled",attributes:{backgroundColor:h,backgroundOpacity:h.alpha}};e.setupState(d)}getFinalColor(e,t){return t?e.clone().multiply(t).convertLinearToSRGB():e.clone().convertLinearToSRGB()}}Fi([u(ce)],$o.prototype,"onClick",2),Fi([u($s)],$o.prototype,"colors",2),Fi([u()],$o.prototype,"transition",2),Fi([u(L2)],$o.prototype,"animationTriggers",2),Fi([u(ft)],$o.prototype,"animator",2),Fi([u()],$o.prototype,"interactable",1);var j2=Object.defineProperty,Dp=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&j2(e,t,n),n};const Hs=w("debuginputfield"),Mh=class X extends M{get text(){return this.textComponent?.text??""}set text(e){this.textComponent&&(this.textComponent.text=e,this.placeholder&&(e.length>0?this.placeholder.gameObject.visible=!1:this.placeholder.gameObject.visible=!0))}get isFocused(){return X.active===this}textComponent;placeholder;onValueChanged;onEndEdit;static active=null;static activeTime=-1;static htmlField=null;static htmlFieldFocused=!1;inputEventFn;_iosEventFn;start(){Hs&&console.log(this.name,this)}onEnable(){X.htmlField||(X.htmlField=document.createElement("input"),X.htmlField.style.width="0px",X.htmlField.style.height="0px",X.htmlField.style.padding="0px",X.htmlField.style.border="none",X.htmlField.style.overflow="hidden",X.htmlField.style.caretColor="transparent",X.htmlField.style.outline="none",X.htmlField.classList.add("ar"),X.htmlField.onfocus=()=>X.htmlFieldFocused=!0,X.htmlField.onblur=()=>X.htmlFieldFocused=!1,document.body.append(X.htmlField)),this.inputEventFn||(this.inputEventFn=this.onInput.bind(this)),X.htmlField.addEventListener("keyup",this.inputEventFn),this.placeholder&&this.textComponent?.text.length&&x.setActive(this.placeholder.gameObject,!1),G.isiOS()&&(this._iosEventFn=this.processInputOniOS.bind(this),window.addEventListener("click",this._iosEventFn))}onDisable(){X.htmlField?.removeEventListener("keyup",this.inputEventFn),this.onDeselected(),this._iosEventFn&&window.removeEventListener("click",this._iosEventFn)}clear(){X.active===this&&X.htmlField?(X.htmlField.value="",this.setTextFromInputField()):(this.textComponent&&(this.textComponent.text=""),this.placeholder&&x.setActive(this.placeholder.gameObject,!0))}select(){this.onSelected()}deselect(){this.onDeselected()}onPointerEnter(e){e.event.pointerType==="mouse"&&e.button===0&&this.context.input.setCursor("text")}onPointerExit(e){this.context.input.unsetCursor("text")}onPointerClick(e){Hs&&console.log("CLICK",e,X.active),X.activeTime=this.context.time.time,X.active!==this&&this.startCoroutine(this.activeLoop(),we.LateUpdate),this.selectInputField()}*activeLoop(){for(this.onSelected();X.active===this&&!(this.context.input.getPointerClicked(0)&&this.context.time.time-X.activeTime>.2);)this.setTextFromInputField(),yield;this.onDeselected()}onSelected(){if(X.active!==this&&(Hs&&console.log("Select",this.name,this,X.htmlField,this.context.isInXR,this.context.arOverlayElement,this.textComponent?.text,X.htmlField?.value),X.active?.onDeselected(),X.active=this,this.placeholder&&x.setActive(this.placeholder.gameObject,!1),X.htmlField)){if(X.htmlField.value=this.textComponent?.text||"",Hs&&console.log("set input field value",X.htmlField.value),this.context.isInXR){const e=this.context.arOverlayElement;e&&e.append(X.htmlField)}this.selectInputField()}}onDeselected(){X.active===this&&(X.active=null,Hs&&console.log("Deselect",this.name,this),X.htmlField&&(X.htmlField.blur(),document.body.append(X.htmlField)),this.placeholder&&(!this.textComponent||this.textComponent.text.length<=0)&&x.setActive(this.placeholder.gameObject,!0),X.htmlField&&this.onEndEdit?.invoke(X.htmlField.value))}update(){X.active===this&&this.textComponent?.markDirty()}onInput(e){if(X.active===this){if(Hs&&console.log(e.code,e,X.htmlField?.value,this.textComponent?.text),e.code==="Escape"||e.code==="Enter"){this.onDeselected();return}X.htmlField&&(this.textComponent&&(this.setTextFromInputField(),this.placeholder&&x.setActive(this.placeholder.gameObject,this.textComponent.text.length<=0)),this.selectInputField())}}setTextFromInputField(){if(this.textComponent&&X.htmlField){const e=this.textComponent.text,t=X.htmlField.value,i=this.textComponent.text!==X.htmlField.value;this.textComponent.text=X.htmlField.value,i&&(Hs&&console.log("[InputField] value changed:",t,e),this.onValueChanged?.invoke(t,e))}}selectInputField(){X.htmlField&&(Hs&&console.log("Focus Inputfield",X.htmlFieldFocused),X.htmlField.setSelectionRange(X.htmlField.value.length,X.htmlField.value.length),G.isiOS()?X.htmlField.focus({preventScroll:!0}):setTimeout(()=>X.htmlField?.focus(),1))}processInputOniOS(){const e=this.context.physics.raycast();if(!e.length)return;const t=e[0].object,i=nf(t);(i?.gameObject===this.gameObject||i?.gameObject.parent===this.gameObject)&&this.selectInputField()}};Dp([u(Dt)],Mh.prototype,"textComponent"),Dp([u(Dt)],Mh.prototype,"placeholder"),Dp([u(ce)],Mh.prototype,"onValueChanged"),Dp([u(ce)],Mh.prototype,"onEndEdit");let c0=Mh;var D2=Object.defineProperty,u1=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&D2(e,t,n),n};class Rh extends M{id=null;keepAspect=!1;_object=null;onEnable(){if(this._object){this.gameObject.add(this._object);return}if(!this.id||!this.context.mainCamera)return;const e=document.getElementById(this.id);if(!e){console.warn('Could not find element with id "'+this.id+'"');return}e.style.display="block",e.style.visibility="hidden";const t=new EC;t.listenToPointerEvents(this.context.renderer,this.context.mainCamera),this.gameObject.add(t);const i=new AC(e);t.add(i),i.visible=!1;const n=i.material;n.transparent=!0,setTimeout(()=>{i.visible=!0;const s=xd(this.gameObject).clone();Hl(this.gameObject,0,0,0),this.gameObject.updateMatrixWorld();const r=new bi;r.setFromObject(t),this.setWorldRotation(s.x,s.y,s.z);const a=r.max.x-r.min.x,l=r.max.y-r.min.y;if(this.keepAspect){const h=a/l;a>l?i.scale.set(1/a,1/l/h,1):i.scale.set(1/a*h,1/l,1)}else i.scale.set(1/a,1/l,1);const c=this.gameObject.scale;i.scale.multiply(c)},1)}onDisable(){this._object?.removeFromParent()}}u1([u()],Rh.prototype,"id"),u1([u()],Rh.prototype,"keepAspect");/* @license
1403
+ C) Set "joinRandomRoom" to true`),!1):(n0&&console.log("Join "+this.roomName),this._userWantsToBeInARoom=!0,this.context.connection.joinRoom(this.roomName),!0))}_lastPingTime=0;_lastRoomTime=-1;_userWantsToBeInARoom=!1;update(){this.context.connection.isConnected&&(this.context.time.time-this._lastPingTime>3&&(this._lastPingTime=this.context.time.time,this.context.connection.sendPing()),this.context.connection.isInRoom&&(this._lastRoomTime=this.context.time.time)),this._lastRoomTime>0&&this.context.time.time-this._lastRoomTime>.3&&(this._lastRoomTime=-1,this.autoRejoin?this._userWantsToBeInARoom&&(console.log("Disconnected from networking backend - attempt reconnecting now"),this.tryJoinRoom()):E()&&console.warn("You are not connected to a room anymore (possibly because the tab was inactive for too long and the server kicked you?)"))}getViewOnlyUrl(){if(this.context.connection.isConnected&&this.context.connection.currentRoomViewId){const e=window.location.search,t=new URLSearchParams(e);return t.has(this.urlParameterName)&&t.delete(this.urlParameterName),t.set(i0,this.context.connection.currentRoomViewId),window.location.origin+window.location.pathname+"?"+t.toString()}return null}setRandomRoomUrlParameter(){const e=Ul(),t=this.generateRoomName();w(this.urlParameterName)?e.set(this.urlParameterName,t):e.append(this.urlParameterName,t),xm(t,e)}generateRoomName(){let e="";for(let t=0;t<6;t++)e+=Math.floor(Math.random()*10).toFixed(0);return e}_roomButton;_roomButtonIconJoin;_roomButtonIconLeave;createRoomButton(){if(this._roomButton)return this._roomButton;const e=document.createElement("button");return this._roomButton=e,e.classList.add("create-room-button"),e.setAttribute("priority","90"),e.onclick=()=>{if(this.context.connection.isInRoom)this.urlParameterName&&zl(this.urlParameterName,null),this.context.connection.leaveRoom(),this._userWantsToBeInARoom=!1;else{if(this.urlParameterName){const t=w(this.urlParameterName);(!t||t===!0)&&(this._lastJoinedRoom?zl(this.urlParameterName,this._lastJoinedRoom):this.setRandomRoomUrlParameter())}this.tryJoinRoom()}},this._roomButtonIconJoin=Ct("group"),this._roomButtonIconLeave=Ct("group_off"),this.updateRoomButtonState(),this.context.connection.beginListen(te.JoinedRoom,this.updateRoomButtonState),this.context.connection.beginListen(te.LeftRoom,this.updateRoomButtonState),e}updateRoomButtonState=()=>{this._roomButton&&(this.context.connection.isInRoom?(this._roomButton.title="Leave the networked room",this._roomButton.textContent="Leave Room",this._roomButtonIconJoin?.remove(),this._roomButton.prepend(this._roomButtonIconLeave)):(this._roomButton.title="Create or join a networked room",this._roomButton.textContent="Join Room",this._roomButtonIconLeave?.remove(),this._roomButton.prepend(this._roomButtonIconJoin)))};destroyRoomButton(){this.context.connection.stopListen(te.JoinedRoom,this.updateRoomButtonState),this.context.connection.stopListen(te.LeftRoom,this.updateRoomButtonState)}_viewOnlyButton;onEnableViewOnlyButton(){this.context.connection.isConnected?this.onCreateViewOnlyButton():(this.context.connection.stopListen(te.JoinedRoom,this.onCreateViewOnlyButton),this.context.connection.beginListen(te.JoinedRoom,this.onCreateViewOnlyButton))}onDisableViewOnlyButton(){this.context.connection.stopListen(te.JoinedRoom,this.onCreateViewOnlyButton),this._viewOnlyButton?.remove()}onCreateViewOnlyButton=()=>{if(!this._viewOnlyButton){const e=document.createElement("button");this._viewOnlyButton=e,e.classList.add("view-only-button"),e.setAttribute("priority","90"),e.onclick=()=>{const t=this.getViewOnlyUrl();t?.length?navigator.canShare({url:t})?navigator.share({url:t})?.catch(i=>{console.warn(i)}):(navigator.clipboard.writeText(t),Te("View only URL copied to clipboard")):ge("Could not create view only URL")},e.title="Copy the view only URL: A page accessed by the view only URL can not be modified by visiting users.",e.textContent="Share View URL",e.prepend(Ct("visibility"))}this.context.menu.appendChild(this._viewOnlyButton)}}Vs([u()],Rn.prototype,"roomName",2),Vs([u()],Rn.prototype,"urlParameterName",2),Vs([u()],Rn.prototype,"joinRandomRoom",2),Vs([u()],Rn.prototype,"requireRoomParameter",2),Vs([u()],Rn.prototype,"autoRejoin",2),Vs([u()],Rn.prototype,"createJoinButton",2),Vs([u()],Rn.prototype,"createViewOnlyButton",2),Vs([u()],Rn.prototype,"roomPrefix",1);function w2(){const o=w("testwindowcount")||0;o&&o>0&&x2(o)}function x2(o){if(w("testwindow"))return null;const e=new URL(window.location.href);wm(e.searchParams,bR,1),wm(e.searchParams,"testwindow",1);const t=e.toString(),i=[];window.onbeforeunload=()=>{for(const l of i)l.close()};const n=.05,s=128;let r=0,a=0;for(let l=0;l<o;l++){r*s+s*.01>=window.innerWidth&&(a+=1,r=0);const c=r*(s*(1+n))+window.screenLeft,h=a*(s*(1+n))+window.screenTop+90+60*a;r+=1;const d=window.open(t,"test window "+l,`popup=yes width=${s} height=${s} top=${h} left=${c}`);if(!d){console.warn("Failed to open window");continue}i.push(d),d.onload=()=>{d.onbeforeunload=()=>{for(let p=0;p<i.length;p++){const m=i[p];m!==d&&m.close()}i.length=0}}}return i}class o0 extends M{awake(){w2()}}class s0 extends M{transformsPerFrame=10;interval=0;useFlatbuffers=!0;awake(){if(this.useFlatbuffers)this.context.connection.beginListenBinary(Cc,e=>{});else{this.models=[];for(let e=0;e<this.transformsPerFrame;e++)this.models.push(new S2(this.context.connection.connectionId+"_simulatedTransform_"+e,this))}}builder=null;models=null;update(){if(this.context.connection.isConnected){if(this.useFlatbuffers){if(!this.context.connection.connectionId||this.context.time.frameCount%this.interval!==0)return;this.builder===null&&(this.builder=new fm(1024));const e=this.builder;for(let t=0;t<this.transformsPerFrame;t++){e.clear();const i=mw(this.context.connection.connectionId,this);this.context.connection.sendBinary(i)}}else if(this.models)for(let e=0;e<this.models.length;e++){const t=this.models[e];t.dontSave=!0,t.update(this,null),this.context.connection.send("TestSimulateUserData-"+e,t)}}}}class S2{guid;fast=!1;position;rotation;velocity=void 0;dontSave;isValid(){return this.fast!==void 0||this.position!==void 0||this.rotation!==void 0||this.velocity!==void 0}constructor(e,t){this.guid=e,this.position={x:0,y:0,z:0},this.rotation={x:0,y:0,z:0,w:0},this.update(t,null)}static temp=new b;update(e,t){const i=e.worldPosition;this.position.x=i.x,this.position.y=i.y,this.position.z=i.z;const n=e.worldQuaternion;if(this.rotation.x=n.x,this.rotation.y=n.y,this.rotation.z=n.z,this.rotation.w=n.w,this.fast=!1,t){const s=t.getVelocity();this.velocity===void 0&&(this.velocity={x:0,y:0,z:0}),this.velocity.x=s.x,this.velocity.y=s.y,this.velocity.z=s.z}}}var C2=Object.defineProperty,Rp=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&C2(e,t,n),n};const P2=w("debugsignals");class Tp{guid}Rp([u()],Tp.prototype,"guid");class Ch{signal;reaction}Rp([u(Tp)],Ch.prototype,"signal"),Rp([u(ce)],Ch.prototype,"reaction");const h1=class Yo extends M{static receivers={};static invoke(e){if(Yo.receivers[e]){const t=Yo.receivers[e];if(!t)return;for(const i of t)i.invoke(e)}}events;awake(){P2&&console.log("SignalReceiver awake",this)}onEnable(){if(this.events)for(const e of this.events)Yo.receivers[e.signal.guid]||(Yo.receivers[e.signal.guid]=[]),Yo.receivers[e.signal.guid].push(this)}onDisable(){if(this.events){for(const e of this.events)if(Yo.receivers[e.signal.guid]){const t=Yo.receivers[e.signal.guid].indexOf(this);t>=0&&Yo.receivers[e.signal.guid].splice(t,1)}}}invoke(e){if(!this.events||!Array.isArray(this.events))return;const t=typeof e=="object"?e.guid:e;for(const i of this.events)if(i.signal.guid===t)try{if(i.reaction){if(!i.reaction.invoke){console.warn("Missing invoke - possibly a serialization error",i,this);continue}}else{console.warn("Missing reaction for signal",i,this);continue}i.reaction.invoke()}catch(n){console.error(n)}}};Rp([u(Ch)],h1.prototype,"events");let Ph=h1;var Bi=(o=>(o.Activation="ActivationTrack",o.Animation="AnimationTrack",o.Audio="AudioTrack",o.Control="ControlTrack",o.Marker="MarkerTrack",o.Signal="SignalTrack",o))(Bi||{}),ro=(o=>(o[o.None=0]="None",o[o.Hold=1]="Hold",o[o.Loop=2]="Loop",o[o.PingPong=3]="PingPong",o[o.Continue=4]="Continue",o))(ro||{}),r0=(o=>(o.Signal="SignalEmitter",o))(r0||{});const ao=w("debugtimeline");class Oh{director;track;get muted(){return this.track.muted}set muted(e){e!==this.track.muted&&(this.track.muted=e,this.onMuteChanged?.call(this))}*forEachClip(e=!1){if(this.track?.clips)if(e)for(let t=this.track.clips.length-1;t>=0;t--)yield this.track.clips[t];else for(const t of this.track.clips)yield t}getClipTime(e,t){return t.clipIn+(e-t.start)*t.timeScale}getClipTimeNormalized(e,t){return(e-t.start)/t.duration}evaluateWeight(e,t,i,n=!0){if(t<0||t>=i.length)return 0;const s=i[t];if(n||e>=s.start&&e<=s.end){let r=1;if(s.easeInDuration>0){const a=Math.min((e-s.start)/s.easeInDuration,1);r*=a}if(s.easeOutDuration>0){const a=Math.min((s.end-e)/s.easeOutDuration,1);r*=a}return r}return 0}}class O2{clip;rootPositionOffset;rootQuaternionOffset;get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}rootStartPosition;rootEndPosition;rootStartQuaternion;rootEndQuaternion;constructor(e){const t=e.getClip();this.clip=t;const i=e.getRoot(),n=i.name+".position",s=i.name+".quaternion";ao&&console.log(t.name,t.tracks,n);for(const r of t.tracks)if(!(r.times.length<=0)){if(r.name.endsWith(n))this.rootStartPosition=new b().fromArray(r.values,0),this.rootEndPosition=new b().fromArray(r.values,r.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),ao&&console.log(this.rootPositionOffset);else if(r.name.endsWith(s)&&(this.rootStartQuaternion=new U().fromArray(r.values,0),this.rootEndQuaternion=new U().fromArray(r.values,r.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),ao)){const a=new nt().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",a)}}}}class Ep extends Oh{models=[];trackOffset;target;mixer;clips=[];actions=[];weight=1;_actionOffsets=[];_didBind=!1;_animator=null;onDisable(){this.mixer?.stopAllAction()}onDestroy(){this.director.context.animations.unregisterAnimationMixer(this.mixer)}onStateChanged(){this._animator&&cw(this._animator.gameObject,this,this.director.isPlaying)}createHooks(e,t){if(t.tracks?.length<=0){console.warn("No tracks in AnimationClip",t);return}const i=t.tracks[0].name.split("."),n=i[i.length-2],s=n+".position",r=n+".quaternion";let a=!1,l=!1;for(const c of t.tracks)c.name.endsWith(s)?(a=!0,this.createPositionInterpolant(t,e,c)):c.name.endsWith(r)&&(l=!0,this.createRotationInterpolant(t,e,c));if(!a||!l){const c=this.mixer?.getRoot(),h=t.tracks[0],d=h.name.lastIndexOf("."),p=h.name.substring(0,d),m=p.substring(p.lastIndexOf(".")+1),f=c.getObjectByName(m);if(f)if(a){if(!l){const g=t.tracks[0].name.substring(0,d)+".quaternion";ao&&console.warn("Create quaternion track",m,f);const y=f.quaternion,_=new aC(g,[0,t.duration],[y.x,y.y,y.z,y.w,y.x,y.y,y.z,y.w]);t.tracks.push(_),this.createRotationInterpolant(t,e,_)}}else{const g=p+".position";ao&&console.warn("Create position track",m,f);const y=f.position,_=new rC(g,[0,t.duration],[y.x,y.y,y.z,y.x,y.y,y.z]);t.tracks.push(_),this.createPositionInterpolant(t,e,_)}}}bind(){if(!this._didBind){this._didBind=!0,ao&&console.log(this.models),this.mixer?this.target=this.mixer.getRoot():console.warn("No mixer was assigned to animation track");for(const e of this.actions){const t=new O2(e);this._actionOffsets.push(t)}this.target&&(this._animator=x.getComponent(this.target,ft)??null,this._animator&&cw(this._animator.gameObject,this,!0));for(const e of this.models){const t=e.asset,i=t.position,n=t.rotation;i&&i.x!==void 0&&(i.isVector3||(t.position=new b(i.x,i.y,i.z)),n.isQuaternion||(t.rotation=new U(n.x,n.y,n.z,n.w)))}this.ensureTrackOffsets()}}ensureTrackOffsets(){if(this.trackOffset){const e=this.trackOffset.position;e&&(e.isVector3||(this.trackOffset.position=new b(e.x,e.y,e.z)));const t=this.trackOffset.rotation;t&&(t.isQuaternion||(this.trackOffset.rotation=new U(t.x,t.y,t.z,t.w)))}}_useclipOffsets=!0;_totalOffsetPosition=new b;_totalOffsetRotation=new U;_totalOffsetPosition2=new b;_totalOffsetRotation2=new U;_summedPos=new b;_tempPos=new b;_summedRot=new U;_tempRot=new U;_clipRotQuat=new U;evaluate(e){if(this.track.muted||!this.mixer)return;this.bind(),this._totalOffsetPosition.set(0,0,0),this._totalOffsetRotation.set(0,0,0,1),this._totalOffsetPosition2.set(0,0,0),this._totalOffsetRotation2.set(0,0,0,1);let t=0,i=0,n=!1,s=!1,r=0;for(let a=0;a<this.clips.length;a++){const l=this.models[a],c=this.actions[a],h=l.asset;c.weight=0;const d=e>=l.start&&e<=l.end,p=l.preExtrapolationMode,m=l.postExtrapolationMode,f=a<this.clips.length-1?this.models[a+1]:null;let g=d,y=!1;if(!g&&!n&&l.end<e&&m!==ro.None?(!f||f.start>e)&&(g=!0,n=!0):a==0&&!g&&!s&&l.start>e&&p!==ro.None&&(!f||f.start<e)&&(g=!0,y=!0,s=!0),g){let _=this.weight;_*=this.evaluateWeight(e,a,this.models,g),_*=this.director.weight;let v=d;if(y)switch(p){case ro.Hold:break;case ro.Loop:e+=l.start,v=!0;break;default:e+=l.start,v=!0;break}let P=this.getClipTime(e,l),R=0;const k=h.duration;if(y&&p===ro.Hold&&(P=0),v){if(h.loop)for(R+=Math.floor(P/(k+1e-6));P>k;)P-=k}else if(!d&&n)switch(m){case ro.Hold:P=this.getClipTime(l.end,l);break;case ro.Loop:P%=k;break;case ro.PingPong:const L=Math.floor(P/k)%2!==0;P%=k,L&&(P=k-P);break}l.reversed===!0?c.time=c.getClip().duration-P:c.time=P,c.timeScale=0;const A=Math.max(0,_);if(c.weight=A,r+=A,c.clampWhenFinished=!1,c.isRunning()||c.play(),this._useclipOffsets){const L=t==0?this._totalOffsetPosition:this._totalOffsetPosition2,N=t==0?this._totalOffsetRotation:this._totalOffsetRotation2;t<1&&(i=1-_),t+=1;const j=this._summedPos.set(0,0,0),q=this._tempPos.set(0,0,0),Y=this._summedRot.identity(),I=this._tempRot.identity(),V=h.rotation;V&&(this._clipRotQuat.identity(),this._clipRotQuat.slerp(V,_));const W=this._actionOffsets[a];if(W.hasOffsets)for(let oe=0;oe<R;oe++)W.rootPositionOffset?q.copy(W.rootPositionOffset):q.set(0,0,0),q.applyQuaternion(Y),this._clipRotQuat&&q.applyQuaternion(this._clipRotQuat),W.rootQuaternionOffset&&(I.copy(W.rootQuaternionOffset),Y.multiply(I)),j.add(q);this._clipRotQuat&&N.multiply(this._clipRotQuat),N.multiply(Y),h.position&&j.add(h.position),L.add(j)}}}if(this._useclipOffsets&&(this._totalOffsetPosition.lerp(this._totalOffsetPosition2,i),this._totalOffsetRotation.slerp(this._totalOffsetRotation2,i)),this.__mixerError===void 0&&(ao||E())&&this._animator?.runtimeAnimatorController?.mixer&&this.mixer!==this._animator?.runtimeAnimatorController?.mixer&&(this.__mixerError=!0,console.error("AnimationTrack mixer is not shared with the animator controller - this might result in the timeline to not animate properly. Please report a bug to the Needle Engine team!",this)),this._animator?.runtimeAnimatorController){const a=Math.max(0,1-r);this._animator?.runtimeAnimatorController?.update(a)}else this.mixer.update(e)}createRotationInterpolant(e,t,i){const n=i.createInterpolant.bind(i),s=new U;this.ensureTrackOffsets();const r=this.trackOffset?.rotation;i.createInterpolant=()=>{const a=n(),l=a.evaluate.bind(a);return a.evaluate=c=>{const h=l(c);if(s.set(h[0],h[1],h[2],h[3]),s.premultiply(this._totalOffsetRotation),r&&s.premultiply(r),this.director.animationCallbackReceivers)for(const d of this.director.animationCallbackReceivers)d?.onTimelineRotation?.call(d,this.director,this.target,c,s);return h[0]=s.x,h[1]=s.y,h[2]=s.z,h[3]=s.w,h},a}}createPositionInterpolant(e,t,i){const n=i.createInterpolant.bind(i),s=new b;this.ensureTrackOffsets();const r=this.trackOffset?.rotation,a=this.trackOffset?.position;let l;i.createInterpolant=()=>{const c=n(),h=c.evaluate.bind(c);return c.evaluate=d=>{const p=h(d);if(s.set(p[0],p[1],p[2]),t.removeStartOffset&&(l===void 0?(l=null,l=this._actionOffsets.find(m=>m.clip===e)?.rootStartPosition?.clone()):l?.isVector3&&s.sub(l)),s.applyQuaternion(this._totalOffsetRotation),s.add(this._totalOffsetPosition),r&&s.applyQuaternion(r),a&&(s.x-=a.x,s.y+=a.y,s.z+=a.z),this.director.animationCallbackReceivers)for(const m of this.director.animationCallbackReceivers)m?.onTimelinePosition?.call(m,this.director,this.target,d,s);return p[0]=s.x,p[1]=s.y,p[2]=s.z,p},c}}}const k2=w("mutetimeline");class es extends Oh{models=[];listener;audio=[];audioContextTimeOffset=[];lastTime=0;audioSource;_audioLoader=null;getAudioFilePath(e){const t=this.director.sourceId;return ls(t,e)}onAllowAudioChanged(e){for(let t=0;t<this.models.length;t++){const i=this.models[t];this.audio[t].setVolume(e?i.asset.volume:0)}}addModel(e){const t=new lC(this.listener);this.audio.push(t);const i=e;i._didTriggerPlay=!1,this.models.push(i)}onDisable(){for(const e of this.audio)e.isPlaying&&e.stop();for(const e of this.models)e._didTriggerPlay=!1}onDestroy(){for(const e of this.audio)e.source&&e?.disconnect();this.audio.length=0}onMuteChanged(){if(this.muted)for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t?.isPlaying&&t.stop()}}stop(){for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t?.isPlaying&&t.stop()}for(const e of this.models)e._didTriggerPlay=!1}_playableDirectorResumed=!1;onPauseChanged(){for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t?.isPlaying&&t.stop()}this._playableDirectorResumed=this.director.isPlaying}evaluate(e){if(k2||this.track.muted||this.director.speed<0)return;const t=this.director.context.application.muted,i=this._playableDirectorResumed;this._playableDirectorResumed=!1;const n=t?.1:0;for(let s=0;s<this.models.length;s++){const r=this.models[s],a=this.audio[s],l=r.asset;if((!a||!a.buffer)&&this.isInTimeRange(r,e-1,e+1)&&this.handleAudioLoading(r,a),Mi.userInteractionRegistered!==!1&&!(a===null||!a.buffer))if(a.playbackRate=this.director.context.time.timeScale*this.director.speed,a.loop=l.loop,e>=r.start&&e<=r.end&&e<this.director.duration){if(!a.isPlaying||!this.director.isPlaying)(i||!r._didTriggerPlay&&this.lastTime<e)&&(r.duration*r.timeScale>.3?a.offset=r.clipIn+(e-r.start)*r.timeScale:a.offset=0,ao&&console.log("Timeline Audio ("+this.track.name+") play with offset "+a.offset+" - "+r.asset.clip),a.play(n),r._didTriggerPlay=!0);else{const h=r.clipIn+(e-r.start)*r.timeScale,d=a.context.currentTime-a._startedAt+a.offset;Math.abs(h-d)>.3&&(a.offset=h,a.stop(),a.play(n))}let c=l.volume;if(this.track.volume!==void 0&&(c*=this.track.volume),t&&(c=0),r.easeInDuration>0){const h=Math.min((e-r.start)/r.easeInDuration,1);c*=h}if(r.easeOutDuration>0){const h=Math.min((r.end-e)/r.easeOutDuration,1);c*=h}a.setVolume(c*this.director.weight)}else r._didTriggerPlay=!1,this.director.isPlaying&&a.isPlaying&&a.stop()}this.lastTime=e}loadAudio(e,t=0,i=0){let n=null;const s=e-i,r=e+t;for(const a of this.models)if(this.isInTimeRange(a,s,r)){const l=this.audio[this.models.indexOf(a)],c=this.handleAudioLoading(a,l);c!==null&&(n===null&&(n=[]),n.push(c))}return n!==null?Promise.all(n):null}isInTimeRange(e,t,i){return t<=e.start&&i>=e.end||t>=e.start&&t<=e.end||i>=e.start&&i<=e.end}static _audioBuffers=new Map;static dispose(){es._audioBuffers.clear()}handleAudioLoading(e,t){this._audioLoader||(this._audioLoader=new am);const i=this.getAudioFilePath(e.asset.clip);if(es._audioBuffers.get(i)){const s=es._audioBuffers.get(i);return s.then(r=>{r&&t.setBuffer(r)}),s}ao&&console.warn("LOAD audio track",i,this.director.sourceId);const n=new Promise((s,r)=>{this._audioLoader.load(i,a=>{t.setBuffer(a),s(a)},void 0,a=>{console.error("Error loading audio",a),s(null)})});return es._audioBuffers.set(i,n),n}}class kh extends Oh{models=[];didTrigger=[];receivers=[];evaluate(e){if(this.track.muted)return;const t=this.director.context.time.deltaTime*1.5;for(let i=0;i<this.models.length;i++){const n=this.models[i],s=this.didTrigger[i],r=n.time-e;let a=!1;if(n.retroActive)a=r<=1e-6;else{const l=Math.abs(r);(l===0||l>=1e-5&&l<t)&&(a=!0)}if(a){if(!s)if(ao&&console.log("Trigger signal",e,n.time,n),this.didTrigger[i]=!0,this.receivers?.length<=0)Ph.invoke(n.asset);else for(const l of this.receivers)l&&l.invoke(n.asset)}else n.emitOnce||(this.didTrigger[i]=!1)}}}class Ap extends Oh{models=[];timelines=[];resolveSourceObjects(e){for(let t=this.models.length-1;t>=0;t--){const i=this.models[t].asset;if(!i.sourceObject||typeof i.sourceObject!="object"){console.log("no source object, removing model",t,i),this.models.splice(t,1);continue}else{const n=x.getComponent(i.sourceObject,ea);this.timelines.push(n),n&&i.updateDirector&&(n.playOnAwake=!1)}}}_previousActiveModel=null;evaluate(e){this._previousActiveModel=null;for(let t=0;t<this.models.length;t++){const i=this.models[t],n=i.asset;if(e>=i.start&&e<=i.end){this._previousActiveModel=i;const s=this.getClipTime(e,i);if(n.controlActivation){const r=n.sourceObject;r.visible=!0}if(n.updateDirector){const r=this.timelines[t];r&&(r.isPlaying&&r.pause(),r.time=s,r.evaluate())}}else{const s=this._previousActiveModel?.asset;if(n.controlActivation){const r=n.sourceObject;s?.sourceObject!==r&&(r.visible=!1)}}}}}var M2=Object.defineProperty,d1=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&M2(e,t,n),n};const Vo=w("debugtimeline"),a0=class T0 extends M{static createTrackFunctions={};static registerCreateTrack(e,t){this.createTrackFunctions[e]=t}playableAsset;playOnAwake;extrapolationMode=1;get isPlaying(){return this._isPlaying}get isPaused(){return this._isPaused}get time(){return this._time}set time(e){typeof e=="number"&&!Number.isNaN(e)?this._time=e:(Vo||Wi())&&console.error("INVALID TIMELINE.TIME VALUE",e,this.name)}get duration(){return this._duration}set duration(e){this._duration=e}get weight(){return this._weight}set weight(e){this._weight=e}get speed(){return this._speed}set speed(e){this._speed=e}waitForAudio=!0;_visibilityChangeEvt;_clonedPlayableAsset=!1;_speed=1;awake(){Vo&&console.log(this,this.playableAsset?.tracks),this.rebuildGraph(),!this.isValid()&&(Vo||E())&&(Vo?console.warn("PlayableDirector is not valid","Asset?",this.playableAsset,"Tracks:",this.playableAsset?.tracks,"IsArray?",Array.isArray(this.playableAsset?.tracks),this):this.playableAsset?.tracks?.length?console.warn("PlayableDirector is not valid"):console.warn("PlayableDirector has no tracks"))}onEnable(){for(const e of this._audioTracks)e.onEnable?.();for(const e of this._customTracks)e.onEnable?.();for(const e of this._animationTracks)e.onEnable?.();this.playOnAwake&&this.play(),this._visibilityChangeEvt||(this._visibilityChangeEvt=()=>{switch(document.visibilityState){case"hidden":this.setAudioTracksAllowPlaying(!1);break;case"visible":this.setAudioTracksAllowPlaying(!0);break}}),window.addEventListener("visibilitychange",this._visibilityChangeEvt)}onDisable(){this.stop();for(const e of this._audioTracks)e.onDisable?.();for(const e of this._customTracks)e.onDisable?.();for(const e of this._animationTracks)e.onDisable?.();this._visibilityChangeEvt&&window.removeEventListener("visibilitychange",this._visibilityChangeEvt)}onDestroy(){for(const e of this._allTracks)for(const t of e)t.onDestroy?.()}rebuildGraph(){this.isValid()&&(this.resolveBindings(),this.updateTimelineDuration(),this.setupAndCreateTrackHandlers())}async play(){if(!this.isValid())return;const e=this._isPaused==!0;if(this._isPaused=!1,!this._isPlaying){if(this._isPlaying=!0,e&&this.invokePauseChangedMethodsOnTracks(),this.waitForAudio){const t=[];for(const i of this._audioTracks){const n=i.loadAudio(this._time,1,0);n&&t.push(n)}if(t.length>0&&(await Promise.all(t),!this._isPlaying))return;for(;this._audioTracks.length>0&&this._isPlaying&&!Mi.userInteractionRegistered&&this.waitForAudio;)await Dn(200)}this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine=this.startCoroutine(this.internalUpdate(),we.LateUpdate)}}pause(){this.isValid()&&(this._isPlaying=!1,!this._isPaused&&(this._isPaused=!0,this.internalEvaluate(),this.invokePauseChangedMethodsOnTracks(),this.invokeStateChangedMethodsOnTracks()))}stop(){this._isStopping=!0;for(const i of this._audioTracks)i.stop();const e=this._isPaused==!0,t=this._isPlaying;this._isPlaying&&(this._time=0,this._isPlaying=!1,this._isPaused=!1,this.internalEvaluate(),e&&this.invokePauseChangedMethodsOnTracks()),this._isPlaying=!1,this._isPaused=!1,e&&!t&&this.invokePauseChangedMethodsOnTracks(),t&&this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine&&this.stopCoroutine(this._internalUpdateRoutine),this._internalUpdateRoutine=null,this._isStopping=!1}evaluate(){this.internalEvaluate(!0)}isValid(){return this.playableAsset&&this.playableAsset.tracks&&Array.isArray(this.playableAsset.tracks)}*forEachTrack(){for(const e of this._allTracks)for(const t of e)yield t}get animationTracks(){return this._animationTracks}get audioTracks(){return this._audioTracks}_guidsMap;resolveGuids(e){this._guidsMap=e}_isPlaying=!1;_internalUpdateRoutine;_isPaused=!1;_isStopping=!1;_time=0;_duration=0;_weight=1;_animationTracks=[];_audioTracks=[];_signalTracks=[];_controlTracks=[];_customTracks=[];_allTracks=[this._animationTracks,this._audioTracks,this._signalTracks,this._controlTracks,this._customTracks];invokePauseChangedMethodsOnTracks(){for(const e of this.forEachTrack())e.onPauseChanged?.call(e)}invokeStateChangedMethodsOnTracks(){for(const e of this.forEachTrack())e.onStateChanged?.call(e,this._isPlaying)}*internalUpdate(){for(;this._isPlaying&&this.activeAndEnabled;)!this._isPaused&&this._isPlaying&&(this._time+=this.context.time.deltaTime*this.speed,this.internalEvaluate()),yield}internalEvaluate(e=!1){if(!this.isValid())return;let t=this._time;switch(this.extrapolationMode){case 0:this._speed>0?t=Math.min(t,this._duration):this._speed<0&&(t=Math.max(t,0)),this._time=t;break;case 1:t%=this._duration,this._time=t;break;case 2:if(t>this._duration){this.stop();return}break}const i=this._time;for(const n of this.playableAsset.tracks)if(!n.muted)switch(n.type){case Bi.Activation:if(!e&&!this._isPlaying)continue;for(let s=0;s<n.outputs.length;s++){const r=n.outputs[s];if(typeof r=="object"){let a=!1;if(n.clips)for(const c of n.clips)c.start<=i&&i<=c.end&&(a=!0);const l=r;l.visible!==void 0&&l.visible!==a&&(l.visible=a,Vo&&console.warn(this.name,"set ActivationTrack-"+s,l.name,a,i))}}break}if(!this._isStopping)for(const n of this._animationTracks)n.evaluate(i);for(const n of this._audioTracks)n.evaluate(i);for(const n of this._signalTracks)n.evaluate(i);for(const n of this._controlTracks)n.evaluate(i);for(const n of this._customTracks)n.evaluate(i)}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=Nl(this.playableAsset)),!this.playableAsset||!this.playableAsset.tracks)return;const e=this.findRoot(this.gameObject);for(const t of this.playableAsset.tracks){for(let i=t.outputs.length-1;i>=0;i--){let n=t.outputs[i];if(typeof n=="string"){this._guidsMap&&this._guidsMap[n]&&(n=this._guidsMap[n]);const s=x.findByGuid(n,e);s===null||typeof s!="object"?(t.outputs.splice(i,1),console.warn("Failed to resolve binding",n,t.name,t.type)):(Vo&&console.log("Resolved binding",n,"to",s),t.outputs[i]=s)}else if(n===null){if(t.outputs.splice(i,1),T0.createTrackFunctions[t.type])continue;t.type!==Bi.Audio&&t.type!==Bi.Control&&t.type!==Bi.Marker&&t.type!==Bi.Signal&&console.warn("Missing binding",n,t.name,t.type,this.name,this.playableAsset.name)}}if(t.type===Bi.Control&&t.clips)for(let i=0;i<t.clips.length;i++){const n=t.clips[i];let s=n.asset.sourceObject;if(typeof s=="string"){this._guidsMap&&this._guidsMap[s]&&(s=this._guidsMap[s]);const r=x.findByGuid(s,e);r===null||typeof r!="object"?console.warn("Failed to resolve sourceObject binding",s,t.name,n):(Vo&&console.log("Resolved binding",s,"to",r),n.asset.sourceObject=r)}}}}findRoot(e){return e.parent?this.findRoot(e.parent):e}updateTimelineDuration(){if(this._duration=0,!(!this.playableAsset||!this.playableAsset.tracks)){for(const e of this.playableAsset.tracks)if(e.muted!==!0){if(e.clips)for(const t of e.clips)t.end>this._duration&&(this._duration=t.end);if(e.markers)for(const t of e.markers)t.time>this._duration&&(this._duration=t.time+.001)}}}setupAndCreateTrackHandlers(){if(this._animationTracks.length=0,this._audioTracks.length=0,this._signalTracks.length=0,!this.playableAsset)return;let e=x.findObjectOfType(ko,this.context);for(const t of this.playableAsset.tracks){const i=t.type,n=T0.createTrackFunctions[i];if(n!=null){const s=n(this,t);if(typeof s.evaluate=="function"){s.director=this,s.track=t,this._customTracks.push(s);continue}}if(t.type===Bi.Animation){if(!t.clips||t.clips.length<=0){Vo&&console.warn("Animation track has no clips",t);continue}for(let s=t.outputs.length-1;s>=0;s--){let r=t.outputs[s];if(r instanceof O){const l=x.getOrAddComponent(r,ft);l&&(r=l)}const a=r?.gameObject?.animations;if(a){const l=new Ep;l.trackOffset=t.trackOffset,l.director=this,l.track=t;for(let c=0;c<t.clips.length;c++){const h=t.clips[c],d=h.asset;if(!d){console.error(`Timeline ${this.name}: clip #${c} on track "${t.name}" has no animation data`);continue}const p=d.clip;let m=p;if((typeof m=="string"||typeof m=="number")&&(m=a.find(g=>g.name===p)),Vo&&console.log(d,p,"\u2192",m),!m){console.warn("Could not find animationClip for model",h,t.name,this.name,this.playableAsset?.name,a,r);continue}r instanceof ft&&r.runtimeAnimatorController&&(r.__internalDidAwakeAndStart||r.initializeRuntimeAnimatorController(),r.runtimeAnimatorController.mixer||r.runtimeAnimatorController.bind(r),l.mixer=r.runtimeAnimatorController.mixer),l.mixer||(l.mixer=new rm(r.gameObject),this.context.animations.registerAnimationMixer(l.mixer)),l.clips.push(m),l.mixer.uncacheAction(m),l.createHooks(h.asset,m);const f=l.mixer.clipAction(m);l.actions.push(f),l.models.push(h)}this._animationTracks.push(l)}}}else if(t.type===Bi.Audio){if(!t.clips||t.clips.length<=0)continue;const s=new es;s.director=this,s.track=t,s.audioSource=t.outputs.find(r=>r instanceof Mi),this._audioTracks.push(s),e||(e=this.context.mainCameraComponent?.gameObject.addComponent(ko)),s.listener=e.listener;for(let r=0;r<t.clips.length;r++){const a=t.clips[r];s.addModel(a)}}else if(t.type===Bi.Marker){const s=new kh;if(s.director=this,s.track=t,t.markers)for(const r of t.markers)switch(r.type){case r0.Signal:s.models.push(r),s.didTrigger.push(!1);break}if(s!==null&&s.models.length>0){const r=x.getComponent(this.gameObject,Ph);r&&(s.receivers.push(r),this._signalTracks.push(s))}}else if(t.type===Bi.Signal){const s=new kh;if(s.director=this,s.track=t,t.markers)for(const r of t.markers)s.models.push(r),s.didTrigger.push(!1);for(const r of t.outputs)s.receivers.push(r);this._signalTracks.push(s)}else if(t.type===Bi.Control){const s=new Ap;if(s.director=this,s.track=t,t.clips)for(const r of t.clips)s.models.push(r);s.resolveSourceObjects(this.context),this._controlTracks.push(s)}}}setAudioTracksAllowPlaying(e){for(const t of this._audioTracks)t.onAllowAudioChanged(e)}animationCallbackReceivers=[];registerAnimationCallback(e){this.animationCallbackReceivers.push(e)}unregisterAnimationCallback(e){const t=this.animationCallbackReceivers.indexOf(e);t!==-1&&this.animationCallbackReceivers.splice(t,1)}};d1([u()],a0.prototype,"playOnAwake"),d1([u()],a0.prototype,"extrapolationMode");let ea=a0;var R2=Object.defineProperty,Ip=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&R2(e,t,n),n};class ta extends M{isGizmo=!1;translationSnap=1;rotationSnapAngle=15;scaleSnap=.25;get control(){return this._control}_control;orbit;onEnable(){if(!(this.isGizmo&&!lc)&&this.context.mainCamera&&(this._control||(this._control=new TC(this.context.mainCamera,this.context.renderer.domElement),this._control.enabled=!0,this._control.getRaycaster().layers.set(2),this._control.size=1,("_root"in this._control?this._control._root:this._control).traverse(e=>{const t=e;if(t.layers.set(2),t){const i=t.material;i&&(i.opacity=.3)}}),this.orbit=x.getComponentInParent(this.context.mainCamera,fe)??void 0),this._control)){const e=this._control.getHelper();this.context.scene.add(e),this._control.attach(this.gameObject),this._control?.addEventListener("dragging-changed",this.onControlChangedEvent),window.addEventListener("keydown",this.windowKeyDownListener),window.addEventListener("keyup",this.windowKeyUpListener)}}onDisable(){this._control?.getHelper()?.removeFromParent(),this._control?.removeEventListener("dragging-changed",this.onControlChangedEvent),window.removeEventListener("keydown",this.windowKeyDownListener),window.removeEventListener("keyup",this.windowKeyUpListener)}enableSnapping(){this._control&&(this._control.setTranslationSnap(this.translationSnap),this._control.setRotationSnap(uo.degToRad(this.rotationSnapAngle)),this._control.setScaleSnap(this.scaleSnap))}disableSnapping(){this._control&&(this._control.setTranslationSnap(null),this._control.setRotationSnap(null),this._control.setScaleSnap(null))}onControlChangedEvent=e=>{const t=this.orbit;if(t&&(t.enabled=!e.value),e.value){const i=this.gameObject.getComponentInParent(vn);i&&(i.fastMode=!0,i.requestOwnership())}else{const i=this.gameObject.getComponentInParent(vn);i&&(i.fastMode=!1)}};windowKeyDownListener=e=>{if(this.enabled&&this._control)switch(e.keyCode){case 81:this._control.setSpace(this._control.space==="local"?"world":"local");break;case 16:this.enableSnapping();break;case 87:this._control.setMode("translate");break;case 69:this._control.setMode("rotate");break;case 82:this._control.setMode("scale");break;case 187:case 107:this._control.setSize(this._control.size+.1);break;case 189:case 109:this._control.setSize(Math.max(this._control.size-.1,.1));break;case 88:this._control.showX=!this._control.showX;break;case 89:this._control.showY=!this._control.showY;break;case 90:this._control.showZ=!this._control.showZ;break;case 32:this._control.enabled=!this._control.enabled;break}};windowKeyUpListener=e=>{if(this.enabled)switch(e.keyCode){case 16:this.disableSnapping();break}}}Ip([u()],ta.prototype,"isGizmo"),Ip([u()],ta.prototype,"translationSnap"),Ip([u()],ta.prototype,"rotationSnapAngle"),Ip([u()],ta.prototype,"scaleSnap");var T2=Object.defineProperty,E2=Object.getOwnPropertyDescriptor,Lp=(o,e,t,i)=>{for(var n=i>1?void 0:i?E2(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&T2(e,t,n),n};class l0{texture=null;rect}Lp([u(Re)],l0.prototype,"texture",2);let xl=class extends Zc{set image(o){this.sprite||(this.sprite=new l0),this.sprite.texture=o,this.onAfterCreated()}get image(){return this.sprite?this.sprite.texture:null}get sprite(){return this._sprite}set sprite(o){this._sprite!==o&&(this._sprite=o,this.onAfterCreated())}_sprite;pixelsPerUnitMultiplier=1;isBuiltinSprite(){const o=this.sprite;switch(o?.texture?.name){case"InputFieldBackground":case"UISprite":case"Background":case"Knob":return!0}return!o?.texture?.name?.length&&o?.texture?.image?.width===32&&o?.texture?.image?.height===32}onBeforeCreate(o){super.onBeforeCreate(o),this.isBuiltinSprite()&&(o.borderRadius=5/this.pixelsPerUnitMultiplier,this.sprite?.texture?.name==="Knob"&&(o.borderRadius=999))}onAfterCreated(){this.__didAwake&&(super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture(this.sprite?.texture))}};Lp([u(l0)],xl.prototype,"sprite",1),Lp([u()],xl.prototype,"pixelsPerUnitMultiplier",2);class jp extends Zc{get mainTexture(){return this._mainTexture}set mainTexture(e){this._mainTexture!==e&&(this._mainTexture=e,this.onAfterCreated())}_mainTexture;onAfterCreated(){this.__didAwake&&(super.onAfterCreated(),this.setTexture(this.mainTexture))}}Lp([u(Re)],jp.prototype,"mainTexture",1);var A2=Object.defineProperty,I2=Object.getOwnPropertyDescriptor,Fi=(o,e,t,i)=>{for(var n=i>1?void 0:i?I2(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&A2(e,t,n),n};const ia=w("debugbutton");class $s{colorMultiplier;disabledColor;fadeDuration;highlightedColor;normalColor;pressedColor;selectedColor}Fi([u()],$s.prototype,"colorMultiplier",2),Fi([u(se)],$s.prototype,"disabledColor",2),Fi([u()],$s.prototype,"fadeDuration",2),Fi([u(se)],$s.prototype,"highlightedColor",2),Fi([u(se)],$s.prototype,"normalColor",2),Fi([u(se)],$s.prototype,"pressedColor",2),Fi([u(se)],$s.prototype,"selectedColor",2);class L2{disabledTrigger;highlightedTrigger;normalTrigger;pressedTrigger;selectedTrigger}class $o extends M{click(){this.onClick?.invoke()}onClick=new ce;_isHovered=0;onPointerEnter(e){const t=e.event.pointerType==="mouse"&&e.button===0;t&&(this._isHovered+=1),ia&&console.warn("Button Enter",t,this._isHovered,this.animationTriggers?.highlightedTrigger,this.animator),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.highlightedTrigger):this.transition===1&&this.colors&&this._image?.setState("hovered"),t&&this.context.input.setCursor("pointer"))}onPointerExit(){this._isHovered-=1,this._isHovered<0&&(this._isHovered=0),ia&&console.log("Button Exit",this._isHovered,this.animationTriggers?.highlightedTrigger,this.animator),this.interactable&&(this._isHovered>0||(this._isHovered=0,this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&this._image?.setState("normal"),this.context.input.unsetCursor("pointer")))}onPointerDown(e){ia&&console.log("Button Down",this.animationTriggers?.highlightedTrigger,this.animator),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this.animationTriggers.pressedTrigger):this.transition===1&&this.colors&&this._image?.setState("pressed"))}onPointerUp(e){ia&&console.warn("Button Up",this.animationTriggers?.highlightedTrigger,this.animator,this._isHovered),this.interactable&&(this.transition==3&&this.animationTriggers&&this.animator?this.animator.setTrigger(this._isHovered?this.animationTriggers.highlightedTrigger:this.animationTriggers.normalTrigger):this.transition===1&&this.colors&&this._image?.setState(this._isHovered?"hovered":"normal"))}onPointerClick(e){if(this.interactable&&!(e.button!==0&&e.event.pointerType===Rd.Mouse)&&(ia&&(console.warn("Button Click",this.onClick),Te("CLICKED button "+this.name+" at "+this.context.time.frameCount)),this.onClick&&this.onClick.listenerCount>0&&(this.onClick.invoke(),e.use(),ia))){const t=this.gameObject.worldPosition;t.add(this.gameObject.worldUp.multiplyScalar(1+Math.random()*.5)),F.DrawLabel(t,"CLICK:"+Date.now(),.1,1+Math.random()*.5)}}colors;transition;animationTriggers;animator;set interactable(e){this._interactable=e,this._image&&(this._image.setInteractable(e),e?this._image.setState("normal"):this._image.setState("disabled"))}get interactable(){return this._interactable}_interactable=!0;set_interactable(e){this.interactable=e}awake(){super.awake(),ia&&console.log(this),this._isInit=!1,this.init()}start(){this._image?.setInteractable(this.interactable),this.gameObject.getComponentInParent(Wa)||this.gameObject.addComponent(vu)}onEnable(){super.onEnable()}onDestroy(){this._isHovered&&this.context.input.unsetCursor("pointer")}_requestedAnimatorTrigger;*setAnimatorTriggerAtEndOfFrame(e){this._requestedAnimatorTrigger=e,yield,yield,this._requestedAnimatorTrigger==e&&this.animator?.setTrigger(e)}_isInit=!1;_image;init(){this._isInit||(this._isInit=!0,this._image=x.getComponent(this.gameObject,xl),this._image&&(this.stateSetup(this._image),this.interactable?this._image.setState("normal"):this._image.setState("disabled")))}stateSetup(e){e.setInteractable(this.interactable);const t=this.getFinalColor(e.color,this.colors?.normalColor),i={state:"normal",attributes:{backgroundColor:t,backgroundOpacity:t.alpha}};e.setupState(i);const n=this.getFinalColor(e.color,this.colors?.highlightedColor),s={state:"hovered",attributes:{backgroundColor:n,backgroundOpacity:n.alpha}};e.setupState(s);const r=this.getFinalColor(e.color,this.colors?.pressedColor),a={state:"pressed",attributes:{backgroundColor:r,backgroundOpacity:r.alpha}};e.setupState(a);const l=this.getFinalColor(e.color,this.colors?.selectedColor),c={state:"selected",attributes:{backgroundColor:l,backgroundOpacity:l.alpha}};e.setupState(c);const h=this.getFinalColor(e.color,this.colors?.disabledColor),d={state:"disabled",attributes:{backgroundColor:h,backgroundOpacity:h.alpha}};e.setupState(d)}getFinalColor(e,t){return t?e.clone().multiply(t).convertLinearToSRGB():e.clone().convertLinearToSRGB()}}Fi([u(ce)],$o.prototype,"onClick",2),Fi([u($s)],$o.prototype,"colors",2),Fi([u()],$o.prototype,"transition",2),Fi([u(L2)],$o.prototype,"animationTriggers",2),Fi([u(ft)],$o.prototype,"animator",2),Fi([u()],$o.prototype,"interactable",1);var j2=Object.defineProperty,Dp=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&j2(e,t,n),n};const Hs=w("debuginputfield"),Mh=class X extends M{get text(){return this.textComponent?.text??""}set text(e){this.textComponent&&(this.textComponent.text=e,this.placeholder&&(e.length>0?this.placeholder.gameObject.visible=!1:this.placeholder.gameObject.visible=!0))}get isFocused(){return X.active===this}textComponent;placeholder;onValueChanged;onEndEdit;static active=null;static activeTime=-1;static htmlField=null;static htmlFieldFocused=!1;inputEventFn;_iosEventFn;start(){Hs&&console.log(this.name,this)}onEnable(){X.htmlField||(X.htmlField=document.createElement("input"),X.htmlField.style.width="0px",X.htmlField.style.height="0px",X.htmlField.style.padding="0px",X.htmlField.style.border="none",X.htmlField.style.overflow="hidden",X.htmlField.style.caretColor="transparent",X.htmlField.style.outline="none",X.htmlField.classList.add("ar"),X.htmlField.onfocus=()=>X.htmlFieldFocused=!0,X.htmlField.onblur=()=>X.htmlFieldFocused=!1,document.body.append(X.htmlField)),this.inputEventFn||(this.inputEventFn=this.onInput.bind(this)),X.htmlField.addEventListener("keyup",this.inputEventFn),this.placeholder&&this.textComponent?.text.length&&x.setActive(this.placeholder.gameObject,!1),G.isiOS()&&(this._iosEventFn=this.processInputOniOS.bind(this),window.addEventListener("click",this._iosEventFn))}onDisable(){X.htmlField?.removeEventListener("keyup",this.inputEventFn),this.onDeselected(),this._iosEventFn&&window.removeEventListener("click",this._iosEventFn)}clear(){X.active===this&&X.htmlField?(X.htmlField.value="",this.setTextFromInputField()):(this.textComponent&&(this.textComponent.text=""),this.placeholder&&x.setActive(this.placeholder.gameObject,!0))}select(){this.onSelected()}deselect(){this.onDeselected()}onPointerEnter(e){e.event.pointerType==="mouse"&&e.button===0&&this.context.input.setCursor("text")}onPointerExit(e){this.context.input.unsetCursor("text")}onPointerClick(e){Hs&&console.log("CLICK",e,X.active),X.activeTime=this.context.time.time,X.active!==this&&this.startCoroutine(this.activeLoop(),we.LateUpdate),this.selectInputField()}*activeLoop(){for(this.onSelected();X.active===this&&!(this.context.input.getPointerClicked(0)&&this.context.time.time-X.activeTime>.2);)this.setTextFromInputField(),yield;this.onDeselected()}onSelected(){if(X.active!==this&&(Hs&&console.log("Select",this.name,this,X.htmlField,this.context.isInXR,this.context.arOverlayElement,this.textComponent?.text,X.htmlField?.value),X.active?.onDeselected(),X.active=this,this.placeholder&&x.setActive(this.placeholder.gameObject,!1),X.htmlField)){if(X.htmlField.value=this.textComponent?.text||"",Hs&&console.log("set input field value",X.htmlField.value),this.context.isInXR){const e=this.context.arOverlayElement;e&&e.append(X.htmlField)}this.selectInputField()}}onDeselected(){X.active===this&&(X.active=null,Hs&&console.log("Deselect",this.name,this),X.htmlField&&(X.htmlField.blur(),document.body.append(X.htmlField)),this.placeholder&&(!this.textComponent||this.textComponent.text.length<=0)&&x.setActive(this.placeholder.gameObject,!0),X.htmlField&&this.onEndEdit?.invoke(X.htmlField.value))}update(){X.active===this&&this.textComponent?.markDirty()}onInput(e){if(X.active===this){if(Hs&&console.log(e.code,e,X.htmlField?.value,this.textComponent?.text),e.code==="Escape"||e.code==="Enter"){this.onDeselected();return}X.htmlField&&(this.textComponent&&(this.setTextFromInputField(),this.placeholder&&x.setActive(this.placeholder.gameObject,this.textComponent.text.length<=0)),this.selectInputField())}}setTextFromInputField(){if(this.textComponent&&X.htmlField){const e=this.textComponent.text,t=X.htmlField.value,i=this.textComponent.text!==X.htmlField.value;this.textComponent.text=X.htmlField.value,i&&(Hs&&console.log("[InputField] value changed:",t,e),this.onValueChanged?.invoke(t,e))}}selectInputField(){X.htmlField&&(Hs&&console.log("Focus Inputfield",X.htmlFieldFocused),X.htmlField.setSelectionRange(X.htmlField.value.length,X.htmlField.value.length),G.isiOS()?X.htmlField.focus({preventScroll:!0}):setTimeout(()=>X.htmlField?.focus(),1))}processInputOniOS(){const e=this.context.physics.raycast();if(!e.length)return;const t=e[0].object,i=nf(t);(i?.gameObject===this.gameObject||i?.gameObject.parent===this.gameObject)&&this.selectInputField()}};Dp([u(Dt)],Mh.prototype,"textComponent"),Dp([u(Dt)],Mh.prototype,"placeholder"),Dp([u(ce)],Mh.prototype,"onValueChanged"),Dp([u(ce)],Mh.prototype,"onEndEdit");let c0=Mh;var D2=Object.defineProperty,u1=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&D2(e,t,n),n};class Rh extends M{id=null;keepAspect=!1;_object=null;onEnable(){if(this._object){this.gameObject.add(this._object);return}if(!this.id||!this.context.mainCamera)return;const e=document.getElementById(this.id);if(!e){console.warn('Could not find element with id "'+this.id+'"');return}e.style.display="block",e.style.visibility="hidden";const t=new EC;t.listenToPointerEvents(this.context.renderer,this.context.mainCamera),this.gameObject.add(t);const i=new AC(e);t.add(i),i.visible=!1;const n=i.material;n.transparent=!0,setTimeout(()=>{i.visible=!0;const s=xd(this.gameObject).clone();Hl(this.gameObject,0,0,0),this.gameObject.updateMatrixWorld();const r=new bi;r.setFromObject(t),this.setWorldRotation(s.x,s.y,s.z);const a=r.max.x-r.min.x,l=r.max.y-r.min.y;if(this.keepAspect){const h=a/l;a>l?i.scale.set(1/a,1/l/h,1):i.scale.set(1/a*h,1/l,1)}else i.scale.set(1/a,1/l,1);const c=this.gameObject.scale;i.scale.multiply(c)},1)}onDisable(){this._object?.removeFromParent()}}u1([u()],Rh.prototype,"id"),u1([u()],Rh.prototype,"keepAspect");/* @license
1404
1404
  * Copyright 2021 Google LLC. All Rights Reserved.
1405
1405
  * Licensed under the Apache License, Version 2.0 (the 'License');
1406
1406
  * you may not use this file except in compliance with the License.
@@ -1420,7 +1420,7 @@ NeedleXRSession.onSessionRequestStart(evt => {
1420
1420
  evt.init.optionalFeatures = evt.init.optionalFeatures || [];
1421
1421
  evt.init.optionalFeatures.push('camera-access');
1422
1422
  });
1423
- `),E()&&Xl("No camera feed available - please request the 'camera-access' feature before starting WebXR or add the ARCameraBackground component to your scene"),!1;const n=t.getViewerPose(o.xr.getReferenceSpace());if(n)for(const s of n.views)if("camera"in s&&s.camera){let r=o.xr.getBinding();if(r||(r=new XRWebGLBinding(t.session,o.getContext())),r){let a=null;if("getCameraImage"in r){$2(o,e);const l=o.properties.get(e);if(l)return a=r.getCameraImage(s.camera),l.__webglTexture=a,!0;console.warn("No texture properties found for target texture")}}else console.error(s.camera,o.xr)}else console.error("NO CAMERA IN VIEW");else console.error(o.xr.getReferenceSpace(),t);return!1}const g1=new WeakMap;function $2(o,e){const t=g1.get(e)||new WeakSet;if(t.has(o))return;t.add(o),g1.set(e,t),console.debug("Initialize texture for camera feed");const i=new xe,n=new In,s=new yi;s.add(new H(n,i));const r=new de;i.map=e,o.render(s,r)}function H2(o,e,t,i="image/webp",n){return p0({context:o,width:e,height:t,mimeType:i,camera:n})}function p0(o){o||(o={});const{transparent:e=!1}=o;let{mimeType:t,context:i,width:n,height:s,camera:r}=o;if(!i&&(i=ue.Current,!i))return console.error("Can not save screenshot: No needle-engine context found or provided."),null;if(!r&&(r=i.mainCamera,!r))return console.error("No camera found"),null;const a=i.renderer,l=a.xr.enabled&&a.xr.isPresenting;if(l&&i.currentFrameEvent!=we.EarlyUpdate)return console.warn("Screenshot: defer to access XR frame"),new Promise(A=>{xo(L=>{const N=p0(o);A(N)},we.EarlyUpdate,{once:!0})});const c=a.domElement,h=c.width,d=c.height;n||(n=h),s||(s=d);const p=n,g=s;let f=window.devicePixelRatio||1,m=1;i.devicePixelRatio==="auto"||i.devicePixelRatio==="manual"?m=1:m=i.devicePixelRatio/window.devicePixelRatio,f*=m,n/=f,s/=f,n=Math.floor(n),s=Math.floor(s),a.xr.isPresenting&&a.xr.getFrame();const y=a.xr.enabled;a.xr.enabled=!1,a.xr.isPresenting=!1,c.style.width=`${n}px`,c.style.height=`${s}px`;const _=a.getRenderTarget(),v=a.getClearColor(new ne),P=a.getClearAlpha(),R=i.scene.background,k="aspect"in r?r.aspect:null;try{const A=o.render_events!==!1,L=new Array;A&&(Ia(i.scene,Ti,L),L.forEach(I=>{if(I?.onBeforeRender(),I.isInstancingActive&&I.instances)for(let V=0;V<I.instances?.length;V++){const W=I.instances[V];Co(W.object,!0)}})),e&&(i.scene.background=null,a.setClearColor(0,0)),o.background&&(i.scene.background=null,a.setClearColor(o.background),o.background instanceof se&&a.setClearAlpha(o.background.a)),e&&a.setClearAlpha(0),a.setSize(n,s,!1),"cam"in r&&(r=r.threeCamera),r instanceof de&&(r.aspect=n/s,r.updateProjectionMatrix());const N="type"in o&&o.type==="texture";let j=null;N&&(j=new jn(n,s,{wrapS:G0,wrapT:G0,format:1023}),a.setRenderTarget(j));let q=c;if(l?(j&&console.error('Taking XR screenshots with { type: "texture" } is currently not supported.'),q=Ih.compositeWithCameraImage({width:p,height:g,scene:i.scene,camera:r,renderer:a})):i.renderNow(r||null),r instanceof de&&k!=null&&(r.aspect=k,r.updateProjectionMatrix()),A&&L.forEach(I=>I.onAfterRender()),!t&&"download_filename"in o&&o.download_filename)switch(o.download_filename.split(".").pop()?.toLowerCase()){case"png":t="image/png";break;case"jpg":case"jpeg":t="image/jpeg";break;case"webp":t="image/webp";break}if(e&&o.trim===!0){const I=G2(q);I&&(q=I)}if("type"in o){if(o.type==="texture")return j?(o.target&&(o.target.image=j?.texture.image,o.target.needsUpdate=!0),j.texture.offset.set(0,-1),j.texture.needsUpdate=!0,j.texture):(console.error("No target texture found"),null);if(o.type==="blob")return new Promise((I,V)=>{q.toBlob(W=>{I(W)},t)});if(o.type==="share")return new Promise((I,V)=>{q.toBlob(W=>{if(W&&"share"in navigator){let oe="file_type"in o&&o.file_type||t;t||(oe="image/png");const le=oe?.split("/")[1]||"png",ye=new File([W],"filename"in o?o.filename||`screenshot.${le}`:`screenshot.${le}`,{type:oe});return navigator.share({title:"title"in o?o.title:void 0,text:"text"in o?o.text:void 0,url:"url"in o?o.url:void 0,files:[ye]}).catch(Se=>{console.warn("User cancelled share",Se.message)}).finally(()=>{I({blob:W,shared:!0})})}return{blob:W,shared:!1}},t)})}const Y=q.toDataURL(t);if("download_filename"in o&&o.download_filename){let I=o.download_filename;if(G.isMobileDevice()&&typeof window<"u"){const V=I+"_screenshots",W=I.split("."),oe=W.pop()?.toLowerCase();let le=0;localStorage.getItem(V)&&(le=parseInt(sessionStorage.getItem(V)||"0")),le>0&&(I=`${W.join()}-${le}.${oe}`),le+=1,sessionStorage.setItem(V,le.toString())}f1(Y,I)}return Y}finally{a.setRenderTarget(_),i.scene.background=R,a.setSize(h,d,!1),a.setClearColor(v,P),k!=null&&r instanceof de&&(r.aspect=k,r.updateProjectionMatrix()),a.xr.enabled=y,a.xr.isPresenting=l,l||i.updateSize(!0)}return null}function G2(o){if(!("document"in globalThis))return null;const e=document.createElement("canvas");e.width=o.width,e.height=o.height;const t=e.getContext("2d");if(!t)return null;t.drawImage(o,0,0);const i=e.width,n=e.height,s=t.getImageData(0,0,i,n).data;let r=n,a=i,l=0,c=0;for(let f=0;f<n;f++)for(let m=0;m<i;m++){const y=(f*i+m)*4;s[y+3]!==0&&(m<a&&(a=m),m>c&&(c=m),f<r&&(r=f),f>l&&(l=f))}const h=c-a+1,d=l-r+1,p=document.createElement("canvas"),g=p.getContext("2d");return g?(p.width=h,p.height=d,g.drawImage(e,a,r,h,d,0,0,h,d),p):null}let Ah=null;function f1(o,e){if(o){if(!o.startsWith("data:image")){console.error("Can not save image: Data url is not an image",o);return}Ah||(Ah=document.createElement("a")),Ah.href=o,Ah.download=e,Ah.click()}}var Ih;(o=>{let e=null,t=null,i=null,n=null,s=null;function r(c){const{renderer:h,width:d,height:p}=c,g=h.xr.enabled,f=h.getRenderTarget(),m=h.autoClear,y=d,_=p,v=d/p;(!i||i.width!==y||i.height!==_)&&(i??=new jn(y,_,{colorSpace:go}),i.width=y,i.height=_,i.samples=4,i.texture.repeat.y=-1,i.texture.offset.y=1),(!s||s.width!==y||s.height!==_)&&(s=document.createElement("canvas"),s.width=y,s.height=_,s.style.position="fixed",s.style.top="0px",s.style.right="0px",s.style.width="300px",s.style.height=`${300/v}px`,s.style.zIndex="1000",s.style.pointerEvents="none",s.style.opacity="1.0",s.style.willChange="contents"),e||(e=l({defines:{DECODE_VIDEO_TEXTURE:!0}})),t||(t=l()),n||(n=new Re),h.xr.updateCamera(c.camera),h.xr.enabled=!1,h.autoClear=!1,h.clear(),h.setSize(y,_),h.setRenderTarget(i),m1(c.renderer,n)||console.error("Could not update texture from XR frame");const P=x.findObjectOfType(Lh);return P?P.setTexture(n):(e.setTexture(n),h.render(e,c.camera)),h.clearDepth(),h.setSize(y,_),h.render(c.scene,c.camera),h.setRenderTarget(null),t.setTexture(i.texture),h.render(t,c.camera),s.getContext("2d",{alpha:!1}).drawImage(h.domElement,0,0,s.width,s.height),h.setRenderTarget(f),h.xr.enabled=g,h.autoClear=m,s}o.compositeWithCameraImage=r;const a=`
1423
+ `),E()&&Xl("No camera feed available - please request the 'camera-access' feature before starting WebXR or add the ARCameraBackground component to your scene"),!1;const n=t.getViewerPose(o.xr.getReferenceSpace());if(n)for(const s of n.views)if("camera"in s&&s.camera){let r=o.xr.getBinding();if(r||(r=new XRWebGLBinding(t.session,o.getContext())),r){let a=null;if("getCameraImage"in r){$2(o,e);const l=o.properties.get(e);if(l)return a=r.getCameraImage(s.camera),l.__webglTexture=a,!0;console.warn("No texture properties found for target texture")}}else console.error(s.camera,o.xr)}else console.error("NO CAMERA IN VIEW");else console.error(o.xr.getReferenceSpace(),t);return!1}const g1=new WeakMap;function $2(o,e){const t=g1.get(e)||new WeakSet;if(t.has(o))return;t.add(o),g1.set(e,t),console.debug("Initialize texture for camera feed");const i=new xe,n=new In,s=new yi;s.add(new H(n,i));const r=new de;i.map=e,o.render(s,r)}function H2(o,e,t,i="image/webp",n){return p0({context:o,width:e,height:t,mimeType:i,camera:n})}function p0(o){o||(o={});const{transparent:e=!1}=o;let{mimeType:t,context:i,width:n,height:s,camera:r}=o;if(!i&&(i=ue.Current,!i))return console.error("Can not save screenshot: No needle-engine context found or provided."),null;if(!r&&(r=i.mainCamera,!r))return console.error("No camera found"),null;const a=i.renderer,l=a.xr.enabled&&a.xr.isPresenting;if(l&&i.currentFrameEvent!=we.EarlyUpdate)return console.warn("Screenshot: defer to access XR frame"),new Promise(A=>{xo(L=>{const N=p0(o);A(N)},we.EarlyUpdate,{once:!0})});const c=a.domElement,h=c.width,d=c.height;n||(n=h),s||(s=d);const p=n,m=s;let f=window.devicePixelRatio||1,g=1;i.devicePixelRatio==="auto"||i.devicePixelRatio==="manual"?g=1:g=i.devicePixelRatio/window.devicePixelRatio,f*=g,n/=f,s/=f,n=Math.floor(n),s=Math.floor(s),a.xr.isPresenting&&a.xr.getFrame();const y=a.xr.enabled;a.xr.enabled=!1,a.xr.isPresenting=!1,c.style.width=`${n}px`,c.style.height=`${s}px`;const _=a.getRenderTarget(),v=a.getClearColor(new ne),P=a.getClearAlpha(),R=i.scene.background,k="aspect"in r?r.aspect:null;try{const A=o.render_events!==!1,L=new Array;A&&(Ia(i.scene,Ti,L),L.forEach(I=>{if(I?.onBeforeRender(),I.isInstancingActive&&I.instances)for(let V=0;V<I.instances?.length;V++){const W=I.instances[V];Co(W.object,!0)}})),e&&(i.scene.background=null,a.setClearColor(0,0)),o.background&&(i.scene.background=null,a.setClearColor(o.background),o.background instanceof se&&a.setClearAlpha(o.background.a)),e&&a.setClearAlpha(0),a.setSize(n,s,!1),"cam"in r&&(r=r.threeCamera),r instanceof de&&(r.aspect=n/s,r.updateProjectionMatrix());const N="type"in o&&o.type==="texture";let j=null;N&&(j=new jn(n,s,{wrapS:G0,wrapT:G0,format:1023}),a.setRenderTarget(j));let q=c;if(l?(j&&console.error('Taking XR screenshots with { type: "texture" } is currently not supported.'),q=Ih.compositeWithCameraImage({width:p,height:m,scene:i.scene,camera:r,renderer:a})):i.renderNow(r||null),r instanceof de&&k!=null&&(r.aspect=k,r.updateProjectionMatrix()),A&&L.forEach(I=>I.onAfterRender()),!t&&"download_filename"in o&&o.download_filename)switch(o.download_filename.split(".").pop()?.toLowerCase()){case"png":t="image/png";break;case"jpg":case"jpeg":t="image/jpeg";break;case"webp":t="image/webp";break}if(e&&o.trim===!0){const I=G2(q);I&&(q=I)}if("type"in o){if(o.type==="texture")return j?(o.target&&(o.target.image=j?.texture.image,o.target.needsUpdate=!0),j.texture.offset.set(0,-1),j.texture.needsUpdate=!0,j.texture):(console.error("No target texture found"),null);if(o.type==="blob")return new Promise((I,V)=>{q.toBlob(W=>{I(W)},t)});if(o.type==="share")return new Promise((I,V)=>{q.toBlob(W=>{if(W&&"share"in navigator){let oe="file_type"in o&&o.file_type||t;t||(oe="image/png");const le=oe?.split("/")[1]||"png",ye=new File([W],"filename"in o?o.filename||`screenshot.${le}`:`screenshot.${le}`,{type:oe});return navigator.share({title:"title"in o?o.title:void 0,text:"text"in o?o.text:void 0,url:"url"in o?o.url:void 0,files:[ye]}).catch(Se=>{console.warn("User cancelled share",Se.message)}).finally(()=>{I({blob:W,shared:!0})})}return{blob:W,shared:!1}},t)})}const Y=q.toDataURL(t);if("download_filename"in o&&o.download_filename){let I=o.download_filename;if(G.isMobileDevice()&&typeof window<"u"){const V=I+"_screenshots",W=I.split("."),oe=W.pop()?.toLowerCase();let le=0;localStorage.getItem(V)&&(le=parseInt(sessionStorage.getItem(V)||"0")),le>0&&(I=`${W.join()}-${le}.${oe}`),le+=1,sessionStorage.setItem(V,le.toString())}f1(Y,I)}return Y}finally{a.setRenderTarget(_),i.scene.background=R,a.setSize(h,d,!1),a.setClearColor(v,P),k!=null&&r instanceof de&&(r.aspect=k,r.updateProjectionMatrix()),a.xr.enabled=y,a.xr.isPresenting=l,l||i.updateSize(!0)}return null}function G2(o){if(!("document"in globalThis))return null;const e=document.createElement("canvas");e.width=o.width,e.height=o.height;const t=e.getContext("2d");if(!t)return null;t.drawImage(o,0,0);const i=e.width,n=e.height,s=t.getImageData(0,0,i,n).data;let r=n,a=i,l=0,c=0;for(let f=0;f<n;f++)for(let g=0;g<i;g++){const y=(f*i+g)*4;s[y+3]!==0&&(g<a&&(a=g),g>c&&(c=g),f<r&&(r=f),f>l&&(l=f))}const h=c-a+1,d=l-r+1,p=document.createElement("canvas"),m=p.getContext("2d");return m?(p.width=h,p.height=d,m.drawImage(e,a,r,h,d,0,0,h,d),p):null}let Ah=null;function f1(o,e){if(o){if(!o.startsWith("data:image")){console.error("Can not save image: Data url is not an image",o);return}Ah||(Ah=document.createElement("a")),Ah.href=o,Ah.download=e,Ah.click()}}var Ih;(o=>{let e=null,t=null,i=null,n=null,s=null;function r(c){const{renderer:h,width:d,height:p}=c,m=h.xr.enabled,f=h.getRenderTarget(),g=h.autoClear,y=d,_=p,v=d/p;(!i||i.width!==y||i.height!==_)&&(i??=new jn(y,_,{colorSpace:go}),i.width=y,i.height=_,i.samples=4,i.texture.repeat.y=-1,i.texture.offset.y=1),(!s||s.width!==y||s.height!==_)&&(s=document.createElement("canvas"),s.width=y,s.height=_,s.style.position="fixed",s.style.top="0px",s.style.right="0px",s.style.width="300px",s.style.height=`${300/v}px`,s.style.zIndex="1000",s.style.pointerEvents="none",s.style.opacity="1.0",s.style.willChange="contents"),e||(e=l({defines:{DECODE_VIDEO_TEXTURE:!0}})),t||(t=l()),n||(n=new Re),h.xr.updateCamera(c.camera),h.xr.enabled=!1,h.autoClear=!1,h.clear(),h.setSize(y,_),h.setRenderTarget(i),m1(c.renderer,n)||console.error("Could not update texture from XR frame");const P=x.findObjectOfType(Lh);return P?P.setTexture(n):(e.setTexture(n),h.render(e,c.camera)),h.clearDepth(),h.setSize(y,_),h.render(c.scene,c.camera),h.setRenderTarget(null),t.setTexture(i.texture),h.render(t,c.camera),s.getContext("2d",{alpha:!1}).drawImage(h.domElement,0,0,s.width,s.height),h.setRenderTarget(f),h.xr.enabled=m,h.autoClear=g,s}o.compositeWithCameraImage=r;const a=`
1424
1424
  uniform sampler2D t2D;
1425
1425
  varying vec2 vUv;
1426
1426
 
@@ -1459,7 +1459,7 @@ void main() {
1459
1459
  #include <colorspace_fragment>
1460
1460
  }
1461
1461
  `;var Y2=Object.defineProperty,Gs=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&Y2(e,t,n),n};const zp=w("debugimagetracking");class Ll{get url(){return this._trackedImage.image??""}get widthInMeters(){return this._trackedImage.widthInMeters??void 0}get bitmap(){return this._bitmap}get model(){return this._trackedImage}measuredSize;state;getPosition(e){return this.ensureTransformData(),e.copy(this._position),e}getQuaternion(e){return this.ensureTransformData(),e.copy(this._rotation),e}applyToObject(e,t=void 0){this.ensureTransformData();const i=e.position.distanceToSquared(this._position)/.05+e.quaternion.angleTo(this._rotation)/.05;t&&(t*=Math.max(1,i)),t===void 0||t>=1?(e.position.copy(this._position),e.quaternion.copy(this._rotation)):(t=Math.max(0,Math.min(1,t)),e.position.lerp(this._position,t),e.quaternion.slerp(this._rotation,t))}static _positionBuffer=new wi(()=>new b,20);static _rotationBuffer=new wi(()=>new U,20);_position;_rotation;ensureTransformData(){if(!this._position){this._position=Ll._positionBuffer.get(),this._rotation=Ll._rotationBuffer.get();const e=this._pose.transform,t=K.active.convertSpace(e);this._position.copy(t?.position),this._rotation.copy(t?.quaternion)}}_trackingComponent;_trackedImage;_bitmap;_pose;constructor(e,t,i,n,s,r){this._trackingComponent=e,this._trackedImage=t,this._bitmap=i,this.measuredSize=n,this.state=s,this._pose=r}}class Go{constructor(e){this.image=e.url,this.widthInMeters=e.widthInMeters,e.object instanceof O?this.object=new ie({asset:e.object}):this.object=e.object,e.createObjectInstance!==void 0&&(this.createObjectInstance=e.createObjectInstance),e.imageDoesNotMove!==void 0&&(this.imageDoesNotMove=e.imageDoesNotMove),e.hideWhenTrackingIsLost!==void 0&&(this.hideWhenTrackingIsLost=e.hideWhenTrackingIsLost)}image;widthInMeters=.25;object;createObjectInstance=!1;imageDoesNotMove=!1;hideWhenTrackingIsLost=!0;getNameFromUrl(){if(this.image){const e=this.image.split("/");return e[e.length-1]}return null}}Gs([u(URL)],Go.prototype,"image"),Gs([u()],Go.prototype,"widthInMeters"),Gs([u(ie)],Go.prototype,"object"),Gs([u()],Go.prototype,"createObjectInstance"),Gs([u()],Go.prototype,"imageDoesNotMove"),Gs([u()],Go.prototype,"hideWhenTrackingIsLost");class K2{constructor(e,t){this.exporter=e,this.component=t,zp&&console.log(this),this.exporter.anchoringType="image"}isImageTrackingExtension=!0;get extensionName(){return"image-tracking"}shouldExport=!0;filename=null;imageModel=null;onBeforeBuildDocument(e){const t=this.exporter.extensions.filter(i=>{const n=i;return n.isImageTrackingExtension&&n.component.activeAndEnabled&&n.component.trackedImages?.length>0}).indexOf(this);this.shouldExport=t===0,this.shouldExport&&this.component.trackedImages?.length>1&&(zp||E())&&(ge("USDZ: Only one tracked image is supported."),console.warn("USDZ: Only one tracked image is supported. Will choose the first one in the trackedImages list"))}onAfterHierarchy(e,t){if(!this.shouldExport)return;const i=G.getiOSVersion(),n=(i?parseInt(i.split(".")[0]):18)>=18?1:100;t.beginBlock('def Preliminary_ReferenceImage "AnchoringReferenceImage"'),t.appendLine("uniform asset image = @image_tracking/"+this.filename+"@"),t.appendLine("uniform double physicalWidth = "+(this.imageModel.widthInMeters*n).toFixed(8)),t.closeBlock()}async onAfterSerialize(e){if(!this.shouldExport)return;const t=this.imageModel,i=Dh.get(t.image),n=await(await(await ux(i)).convertToBlob({type:"image/png"})).arrayBuffer();e.files["image_tracking/"+this.filename]=new Uint8Array(n)}onExportObject(e,t,i){if(!this.shouldExport)return;const n=this.component;if(!n||!n.trackedImages?.length||!n.activeAndEnabled)return;const s=n.trackedImages[0];if(s.object?.asset===e){this.imageModel=s,this.filename=s.getNameFromUrl()||"marker.png";const{scale:r,target:a}=this.exporter.getARScaleAndTarget();let l=e;const c=new ee;if(e!==a)for(;l&&l.parent&&l.parent!==a;)l=l.parent,c.premultiply(l.matrix);const h=c.clone().invert();t.setMatrix(h.scale(new b(r,r,r)))}}}class jh extends M{setPrimaryImage(e){const t=this.trackedImages.indexOf(e);if(t>=0){const i=this.trackedImages[0];i!==e&&(this.trackedImages[0]=e,this.trackedImages[t]=i)}else console.warn(`[WebXRImageTracking] Can not set primary: image not found in 'trackedImages' array ${e.image}`)}addImage(e,t=!1){this.trackedImages.includes(e)||(this.trackedImages.push(e),b1(e.image)),t&&this.setPrimaryImage(e)}trackedImages=[];smooth=!0;trackedImageIndexMap=new Map;get supported(){return this._supported}_supported=!0;awake(){if(zp&&console.log(this),!!this.trackedImages)for(const e of this.trackedImages)e.image&&b1(e.image)}onEnable(){to.beforeExport.addEventListener(this.onBeforeUSDZExport)}onDisable(){to.beforeExport.removeEventListener(this.onBeforeUSDZExport)}onBeforeUSDZExport=e=>{this.activeAndEnabled&&this.trackedImages?.length&&e.exporter.extensions.push(new K2(e.exporter,this))};onBeforeXR(e,t){if(this.trackedImages){t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.includes("image-tracking")||t.optionalFeatures.push("image-tracking"),t.trackedImages=[];for(const i of this.trackedImages)if(i.image?.length&&i.widthInMeters>0){const n=Dh.get(i.image);n&&(this.trackedImageIndexMap.set(t.trackedImages.length,i),t.trackedImages.push({image:n,widthInMeters:i.widthInMeters}))}}}onEnterXR(e){if(this.trackedImages){for(const t of this.trackedImages)if(t.object?.asset){const i=t.object.asset;i.userData||(i.userData={});const n={visible:i.visible,parent:i.parent,matrix:i.matrix.clone()};i.userData["image-tracking"]=n}}for(const t of this.imageToObjectMap.values())t.frames=0}onLeaveXR(e){if(!this.supported&&G.isAndroidDevice()&&ge(this.webXRIncubationsWarning),this.trackedImages){for(const t of this.trackedImages)if(t.object?.asset){const i=t.object.asset;if(i.userData){const n=i.userData["image-tracking"];n&&(i.visible=n.visible,n.parent?.add(i),i.matrix.copy(n.matrix),i.matrix.decompose(i.position,i.quaternion,i.scale)),delete i.userData["image-tracking"]}}}}imageToObjectMap=new Map;currentImages=[];webXRIncubationsWarning=`Image tracking is currently not supported on this device. On Chrome for Android, you can enable the <a target="_blank" href="#" onclick="() => console.log('I')">chrome://flags/#webxr-incubations</a> flag.`;onUpdateXR(e){this.currentImages.length=0;const t=e.xr.frame;if(!t)return;if("getImageTrackingResults"in t){if(e.xr.session.enabledFeatures?.includes("image-tracking")===!1)return;if(t.session&&typeof t.getImageTrackingResults=="function"){const n=t.getImageTrackingResults();if(n.length>0){const s=this.context.renderer.xr.getReferenceSpace();if(s){for(const r of n){const a=r.trackingState,l=r.index,c=this.trackedImageIndexMap.get(l);if(c){const h=t.getPose(r.imageSpace,s),d=new Ll(this,c,r.image,r.measuredSize,a,h);this.currentImages.push(d)}else zp&&console.warn("No tracked image for index",l)}if(this.currentImages.length>0)try{this.dispatchEvent(new CustomEvent("image-tracking",{detail:this.currentImages})),this.onImageTrackingUpdate(this.currentImages)}catch(r){console.error(r)}}}}}else{this.didPrintWarning||(this.didPrintWarning=!0,console.log(this.webXRIncubationsWarning)),this._supported=!1,ge(this.webXRIncubationsWarning);return}const i=1e3;for(const[n,s]of this.imageToObjectMap){if(!s.object||!n||n.hideWhenTrackingIsLost===!1)continue;let r=!1;for(const a of this.currentImages)if(a.model===n){const l=Date.now()-s.lastTrackingTime;if(n.imageDoesNotMove||a.state==="tracked"||l<=i){r=!0;break}}r||x.setActive(s.object,!1)}}onImageTrackingUpdate=e=>{const t=K.active;if(t)for(const i of e){const n=i.model,s=i.state==="tracked";if(!n.object)continue;let r=this.imageToObjectMap.get(n);if(r===void 0)r={object:null,frames:0,lastTrackingTime:Date.now()},this.imageToObjectMap.set(n,r),n.object.loadAssetAsync().then(a=>{if(n.createObjectInstance&&a&&(a=x.instantiate(a)),a){r.object=a;for(const l of a.getComponentsInChildren(Ti))l.setInstancingEnabled(!1);t.rig?(t.rig.gameObject.add(a),i.applyToObject(a),a.activeSelf||x.setActive(a,!0)):console.warn("XRImageTracking: missing XRRig")}});else{if(r.frames++,s&&(r.lastTrackingTime=Date.now()),n.imageDoesNotMove&&r.frames>10||!r.object)continue;t.rig&&(t.rig.gameObject.add(r.object),i.applyToObject(r.object,this.smooth?this.context.time.deltaTimeUnscaled*3:void 0),r.object.activeSelf||x.setActive(r.object,!0))}}}}Gs([u(Go)],jh.prototype,"trackedImages"),Gs([u()],jh.prototype,"smooth");const Dh=new Map,Np=new Map;async function b1(o){if(Dh.has(o))return Np.has(o)?Np.get(o):Promise.resolve(!0);const e=new Promise(t=>{Dh.set(o,null);const i=document.createElement("img");i.src=o,i.addEventListener("load",async()=>{const n=await createImageBitmap(i);Dh.set(o,n),t(!0)})});return Np.set(o,e),e.finally(()=>{Np.delete(o)}),e}var Z2=Object.defineProperty,Ol=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&Z2(e,t,n),n};const oa=w("debugplanetracking");class qo extends M{dataTemplate;occluder=!0;initiateRoomCaptureIfNoData=!0;usePlaneData=!0;useMeshData=!0;runInVR=!0;get trackedPlanes(){return this._allPlanes.values()}get trackedMeshes(){return this._allMeshes.values()}onBeforeXR(e,t){e==="immersive-vr"&&!this.runInVR||(t.optionalFeatures=t.optionalFeatures||[],this.usePlaneData&&!t.optionalFeatures.includes("plane-detection")&&t.optionalFeatures.push("plane-detection"),this.useMeshData&&!t.optionalFeatures.includes("mesh-detection")&&t.optionalFeatures.push("mesh-detection"))}onEnterXR(e){for(const t of this._allPlanes.keys())this.removeData(t,this._allPlanes);for(const t of this._allMeshes.keys())this.removeData(t,this._allMeshes)}onLeaveXR(e){for(const t of this._allPlanes.keys())this.removeData(t,this._allPlanes);for(const t of this._allMeshes.keys())this.removeData(t,this._allMeshes)}onUpdateXR(e){if(!this.runInVR&&e.xr.isVR)return;const t=e.xr.rig;if(!t){console.warn("No XR rig found, cannot parent tracked planes to it");return}const i=e.xr.frame;if(!this.context.renderer.xr.getReferenceSpace())return;const n=i.detectedPlanes,s=i.detectedMeshes,r=n!==void 0&&n.size>0,a=s!==void 0&&s.size>0;if(this.initiateRoomCaptureIfNoData&&(!r&&!a&&this.firstTimeNoPlanesDetected<-10&&(this.firstTimeNoPlanesDetected=Date.now()),(r||a)&&(this.firstTimeNoPlanesDetected=-1),this.firstTimeNoPlanesDetected>0&&Date.now()-this.firstTimeNoPlanesDetected>2500&&"initiateRoomCapture"in i.session&&(i.session.initiateRoomCapture(),this.firstTimeNoPlanesDetected=-1)),n!==void 0&&this.processFrameData(e.xr,t.gameObject,i,n,this._allPlanes),s!==void 0&&this.processFrameData(e.xr,t.gameObject,i,s,this._allMeshes),oa){const l=this.context.mainCameraComponent.gameObject.worldPosition;for(const c of this._allPlanes.values())!c.mesh||!c.mesh.visible||(this.bounds.makeEmpty(),c.mesh.traverse(h=>{h instanceof H&&this.bounds.expandByObject(h)}),this.bounds.getCenter(this.center),this.labelOffset.copy(l).sub(this.center).normalize().multiplyScalar(.1),F.DrawLabel(this.center.add(this.labelOffset),(c.xrData.semanticLabel||"plane").toUpperCase()+`
1462
- `+c.xrData.lastChangedTime.toFixed(2),.02))}}bounds=new bi;center=new b;labelOffset=new b;removeData(e,t){const i=t.get(e);if(!i)return;t.delete(e),oa&&console.log("Plane no longer tracked, id="+i.id),i.mesh&&(i.mesh.removeFromParent(),i.mesh.traverse(s=>{const r=s.userData.normalsHelper;r?(r.dispose(),r.removeFromParent()):oa&&console.warn("No normals helper found for mesh",i.mesh)}),Ci(i.mesh,!0,!0));const n=new CustomEvent("plane-tracking",{detail:{type:"plane-removed",context:i}});this.dispatchEvent(n)}_dataId=1;_allPlanes=new Map;_allMeshes=new Map;firstTimeNoPlanesDetected=-100;makeOccluder=(e,t,i=!1)=>{if(t){if(t instanceof Array){for(const n of t)this.makeOccluder(e,n,i);return}!i&&!t.name.toLowerCase().includes("occlu")||(t.colorWrite=!1,t.depthTest=!0,t.depthWrite=!0,t.transparent=!1,t.polygonOffset=!0,t.polygonOffsetFactor=1,t.polygonOffsetUnits=.1,e.renderOrder=-1e3)}};processFrameData(e,t,i,n,s){const r=this.context.renderer.xr.getReferenceSpace();if(r){for(const a of s.keys())n.has(a)||this.removeData(a,s);for(const a of n){const l="planeSpace"in a?a.planeSpace:"meshSpace"in a?a.meshSpace:void 0;if(!l)continue;const c=i.getPose(l,r);let h;if(s.has(a)){const d=s.get(a);if(h=d.mesh,d.timestamp<a.lastChangedTime){if(d.timestamp=a.lastChangedTime,d.mesh){const g=this.createGeometry(a);if(d.mesh instanceof H)d.mesh.geometry.dispose(),d.mesh.geometry=g,this.makeOccluder(d.mesh,d.mesh.material);else if(d.mesh instanceof os)for(const f of d.mesh.children)f instanceof H&&(f.geometry.dispose(),f.geometry=g,this.makeOccluder(f,f.material));if(d.collider){const f=d.mesh;d.collider.sharedMesh=f,d.collider.convex=this.checkIfContextShouldBeConvex(f,d.xrData),d.collider.onDisable(),d.collider.onEnable()}oa&&(console.log("Plane updated, id="+d.id,d),d.mesh.traverse(f=>{if(!(f instanceof H))return;const m=f.userData.normalsHelper;m&&m.update()}))}const p=new CustomEvent("plane-tracking",{detail:{type:"plane-updated",context:d}});this.dispatchEvent(p)}}else{if(!this.dataTemplate){const d=new H;oa?d.material=new cC:this.occluder?(d.material=new xe,this.makeOccluder(d,d.material,!0)):d.material=new xe({wireframe:!0,opacity:.5,transparent:!0,color:3355443}),this.dataTemplate=new ie("","",d)}if(!this.dataTemplate.asset)this.dataTemplate.loadAssetAsync();else{const d=x.instantiate(this.dataTemplate.asset);if(d.name="xr-tracked-plane",h=d,Um(d,!1),d instanceof H)Pe(d.geometry),d.geometry=this.createGeometry(a),this.makeOccluder(d,d.material,this.occluder&&!this.dataTemplate);else if(d instanceof os)for(const f of d.children)f instanceof H&&(Pe(f.geometry),f.geometry=this.createGeometry(a),this.makeOccluder(f,f.material,this.occluder&&!this.dataTemplate));const p=d.getComponent(xs);if(p){const f=d;p.sharedMesh=f,p.convex=this.checkIfContextShouldBeConvex(f,a),p.onDisable(),p.onEnable()}d.matrixAutoUpdate=!1,d.matrixWorldNeedsUpdate=!0,t.add(d);const g={id:this._dataId++,xrData:a,timestamp:a.lastChangedTime,mesh:d,collider:p};s.set(a,g),oa&&console.log("New plane detected, id="+g.id,g,{hasCollider:!!p,isGroup:d instanceof os});try{const f=new CustomEvent("plane-tracking",{detail:{type:"plane-added",context:g}});this.dispatchEvent(f)}catch(f){console.error(f)}}}h&&(c?(h.visible=!0,h.matrix.fromArray(c.transform.matrix),h.matrix.premultiply(this._flipForwardMatrix)):h.visible=!1,oa&&h.traverse(d=>{if(d instanceof H)if(d.userData.normalsHelper)d.userData.normalsHelper.update();else{const p=new IC(d,.05,255);p.layers.disableAll(),p.layers.set(2),this.context.scene.add(p),d.userData.normalsHelper=p}}))}}}_flipForwardMatrix=new ee().makeRotationY(Math.PI);checkIfContextShouldBeConvex(e,t){if(!e)return!0;if(e){const i=new bi;i.expandByObject(e);const n=new b;i.getSize(n);let s=!0;return n.x>2&&n.y>2&&n.z>1.5&&(s=!1),s&&"semanticLabel"in t&&t.semanticLabel==="wall"&&(s=!0),s}return!0}createGeometry(e){return"polygon"in e?this.createPlaneGeometry(e.polygon):"vertices"in e&&"indices"in e?this.createMeshGeometry(e.vertices,e.indices):new un}_verticesCache=new Map;createMeshGeometry(e,t){const i=e.toString()+"_"+t.toString();if(this._verticesCache.has(i))return this._verticesCache.get(i);const n=new un;n.setIndex(new pt(t,1)),n.setAttribute("position",new pt(e,3));const s=Array();for(let r=0;r<e.length;r+=3)s.push(e[r],e[r+2]);return n.setAttribute("uv",new pt(e,3)),n.computeVertexNormals(),this._verticesCache.set(i,n),n}createPlaneGeometry(e){const t=new un,i=[],n=[];e.forEach(p=>{i.push(p.x,p.y,p.z),n.push(p.x,p.z)});const s=new b(i[0],i[1],i[2]),r=new b(i[3],i[4],i[5]),a=new b(i[6],i[7],i[8]),l=new b,c=new b;l.subVectors(r,s),c.subVectors(a,s),l.cross(c),l.normalize();const h=[];for(let p=0;p<i.length/3;p++)h.push(l.x,l.y,l.z);const d=[];for(let p=2;p<e.length;++p)d.push(0,p-1,p);return t.setAttribute("position",new pt(new Float32Array(i),3)),t.setAttribute("uv",new pt(new Float32Array(n),2)),t.setAttribute("normal",new pt(new Float32Array(h),3)),t.setIndex(d),t.computeBoundingBox(),t.computeBoundingSphere(),t}}Ol([u(ie)],qo.prototype,"dataTemplate"),Ol([u()],qo.prototype,"occluder"),Ol([u()],qo.prototype,"initiateRoomCaptureIfNoData"),Ol([u()],qo.prototype,"usePlaneData"),Ol([u()],qo.prototype,"useMeshData"),Ol([u()],qo.prototype,"runInVR");var J2=Object.defineProperty,eI=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&J2(e,t,n),n};const _1=w("debugwebxr");class Wp extends M{priority=0;get isActive(){return this.activeAndEnabled&&this.gameObject.visible}setAsActiveXRRig(){K.active?.setRigActive(this)}setPriority(e){this.priority=e}awake(){if(_1){const e=new O;e.position.y+=.5,this.gameObject.add(e);const t=e.addNewComponent(Nr);t&&(t.isGizmo=!1);const i=new _i(.5);this.gameObject.add(i)}}isXRRig(){return!0}supportsXR(e){return!0}_startScale;onEnterXR(e){this._startScale=this.gameObject.scale.clone(),e.xr.addRig(this),_1&&console.log("WebXR: add Rig",this.name,this.priority)}onLeaveXR(e){e.xr.removeRig(this),this._startScale&&this.gameObject&&this.gameObject.scale.copy(this._startScale)}}eI([u()],Wp.prototype,"priority");class tI extends M{toggleKey="KeyP";update(){this.context.input.isKeyDown(this.toggleKey)&&this.context.domElement.classList.toggle("presentation-mode")}}C.add("AlignmentConstraint",wc),C.add("Animation",Ht),C.add("Animator",ft),C.add("AudioListener",ko),C.add("AudioSource",Mi),C.add("Avatar_Brain_LookAt",Rc),C.add("Avatar_MouthShapes",Tc),C.add("Avatar_MustacheShake",hf),C.add("AvatarBlink_Simple",Rr),C.add("AvatarEyeLook_Rotation",uf),C.add("AxesHelper",Ha),C.add("BasicIKConstraint",mf),C.add("BoxHelperComponent",xt),C.add("Camera",si),C.add("CharacterController",Tr),C.add("CharacterControllerInput",To),C.add("Collider",ai),C.add("SphereCollider",Ga),C.add("BoxCollider",Ou),C.add("MeshCollider",xs),C.add("CapsuleCollider",Mo),C.add("ContactShadows",Ac),C.add("LogStats",yf),C.add("DeleteBox",Zs),C.add("Deletable",_f),C.add("DeviceFlag",ku),C.add("DragControls",Ir),C.add("DropListener",Eo),C.add("Duplicatable",Pf),C.add("EventListEvent",yu),C.add("EventTrigger",Eu),C.add("GltfExportBox",Bf),C.add("GltfExport",Uf),C.add("VariantAction",Qf),C.add("ChangeTransformOnClick",Br),C.add("ChangeMaterialOnClick",Kf),C.add("SetActiveOnClick",Zf),C.add("HideOnStart",cn),C.add("EmphasizeOnClick",ol),C.add("PlayAudioOnClick",Os),C.add("PlayAnimationOnClick",Nc),C.add("PreliminaryAction",sl),C.add("PreliminaryTrigger",Wc),C.add("VisibilityAction",Vc),C.add("TapGestureTrigger",ey),C.add("USDZExporter",to),C.add("Fog",pl),C.add("BoxGizmo",Nr),C.add("GridHelper",ml),C.add("GroundProjectedEnv",$n),C.add("UsageMarker",Ic),C.add("Interactable",bf),C.add("FixedJoint",My),C.add("HingeJoint",eh),C.add("Light",di),C.add("LODGroup",ih),C.add("LookAtConstraint",Pr),C.add("NeedleMenu",Jn),C.add("NestedGltf",nh),C.add("Networking",Ay),C.add("OffsetConstraint",Wr),C.add("CameraTargetReachedEvent",Mc),C.add("OrbitControls",fe),C.add("ParticleSystemRenderer",nn),C.add("ParticleSystem",ah),C.add("Attractor",bl),C.add("PlayerColor",Il),C.add("Antialiasing",ch),C.add("BloomEffect",fp),C.add("ChromaticAberration",hh),C.add("ColorAdjustments",zs),C.add("DepthOfField",On),C.add("EffectWrapper",uh),C.add("PixelationEffect",ph),C.add("ScreenSpaceAmbientOcclusion",No),C.add("ScreenSpaceAmbientOcclusionN8",kn),C.add("SharpeningEffect",gh),C.add("TiltShiftEffect",no),C.add("ToneMappingEffect",Us),C.add("Vignette",Qr),C.add("Volume",vl),C.add("ReflectionProbe",Dc),C.add("Renderer",Ti),C.add("MeshRenderer",Bc),C.add("SkinnedMeshRenderer",Df),C.add("Rigidbody",Ye),C.add("SceneSwitcher",qe),C.add("ScreenCapture",Ws),C.add("ShadowCatcher",_h),C.add("RemoteSkybox",Sp),C.add("SmoothFollow",Pp),C.add("SpatialTriggerReceiver",oo),C.add("SpatialTrigger",Op),C.add("SpectatorCamera",kp),C.add("SplineContainer",Zr),C.add("SplineWalker",Mn),C.add("SpriteRenderer",ci),C.add("SyncedCamera",t0),C.add("SyncedRoom",Rn),C.add("SyncedTransform",vn),C.add("TestRunner",o0),C.add("TestSimulateUserData",s0),C.add("PlayableDirector",ea),C.add("SignalReceiver",Ph),C.add("AnimationTrackHandler",Ep),C.add("AudioTrackHandler",es),C.add("SignalTrackHandler",kh),C.add("ControlTrackHandler",Ap),C.add("TransformGizmo",ta),C.add("BaseUIComponent",rn),C.add("UIRootComponent",Xc),C.add("Button",$o),C.add("Canvas",ul),C.add("CanvasGroup",Is),C.add("EventSystem",ei),C.add("Graphic",Kc),C.add("MaskableGraphic",Zc),C.add("Image",xl),C.add("RawImage",jp),C.add("InputField",c0),C.add("VerticalLayoutGroup",yy),C.add("HorizontalLayoutGroup",by),C.add("GridLayoutGroup",_y),C.add("Outline",hl),C.add("ObjectRaycaster",ki),C.add("GraphicRaycaster",vu),C.add("SpatialGrabRaycaster",ra),C.add("RectTransform",Cn),C.add("SpatialHtml",Rh),C.add("Text",Dt),C.add("EnvironmentScene",Bp),C.add("LookAt",h0),C.add("OpenURL",Sl),C.add("VideoPlayer",ht),C.add("Voip",ws),C.add("ClickThrough",Up),C.add("CursorFollow",Eh),C.add("ScrollFollow",u0),C.add("Avatar",Ms),C.add("XRControllerFollow",Ho),C.add("XRControllerModel",Do),C.add("XRControllerMovement",Ei),C.add("TeleportTarget",Ku),C.add("WebARCameraBackground",Lh),C.add("WebARSessionRoot",Ui),C.add("WebXR",Zu),C.add("AvatarMarker",Le),C.add("WebXRImageTracking",jh),C.add("WebXRPlaneTracking",qo),C.add("XRRig",Wp),C.add("XRFlag",Ki),C.add("PlayerSync",ry),C.add("PlayerState",xn),C.add("PresentationMode",tI);const Bh=gt,iI=w("debugtypestore");iI&&console.log(C);function nI(o,e){const t=rv(o,e);return t!==void 0?t:null}const oI=new vk,m0=Symbol("deserialize-queue");async function sI(o,e,t,i=null,n){if(!t){console.debug("Can not create component instances: gltf is null");return}const s=[];let r=i;typeof r=="number"&&(r=new At(i));const a=e.indexOf("?");e=a===-1?e:e.substring(0,a);const l=new Mg(t.scene);l.gltfId=e,l.context=o,l.gltf=t,l.nodeToObject=n?.nodeToObjectMap,l.implementationInformation=oI;let c=o[m0];if(c||(c=o[m0]=[]),t.scenes)for(const h of t.scenes)await y0(l,h,c,s,0);if(t.children)for(const h of t.children)await y0(l,h,c,s,0);o.new_scripts_pre_setup_callbacks.push(()=>{const h=o[m0];if(h){for(const d of h)rI(d,l);h.length=0}if(r){const d={},p=[];f0(t,r,d,p);for(const g of t.scenes)f0(g,r,d,p);for(const g of p)g.resolveGuids(d)}})}const g0=Symbol("original-component-name"),kl=new Map;function f0(o,e,t,i){if(e===null||!o)return;const n=o.guid,s=o.guid;s?.length&&(kl.has(s)||(Bh&&console.log('Creating InstanceIdProvider with key "'+s+'" for object '+o.name),kl.set(s,new At(s))));const r=s&&kl.get(s)||e;if(o.guid=r.generateUUID(),n&&n!=="invalid"&&(t[n]=o.guid),o&&o.userData&&o.userData.components)for(const a of o.userData.components){if(a===null)continue;const l=a.guid;l?kl.has(l)||(Bh&&console.log('Creating InstanceIdProvider with key "'+l+'" for component '+a[g0]),kl.set(l,new At(l))):Bh&&console.warn("Can not create IdProvider: component "+a[g0]+" has no guid",a.guid);const c=kl.get(l)||e,h=a.guid;a.guid=c.generateUUID(),h&&h!=="invalid"&&(t[h]=a.guid),a.resolveGuids&&i.push(a)}if(o.children)for(const a of o.children)f0(a,e,t,i)}const Fh=[];async function y0(o,e,t,i,n){if(!e)return;const s=e.userData;if(s){const r=s.builtin_components;if(r&&r.length>0)for(const a of r)try{if(a===null)continue;const l=C.get(a.name);if(l!=null){const c=new l;c.sourceId=o.gltfId,Aa(c,a,o.implementationInformation),c.context=o.context,"guid"in a&&(c[Yl]=a.guid),c[g0]=a.name,yr(e,c,!1),t.push({instance:c,compData:a,obj:e}),c.isCamera&&o.context&&o.context.mainCamera===null&&c.tag==="MainCamera"&&o.context.setCurrentCamera(c),o.context?.physics?.engine?.isInitialized===!1&&(c.isCollider||c.isRigidbody)&&o.context?.physics.engine?.initialize()}else Bh&&console.debug("unknown component: "+a.name),Fh.includes(a.name)||Fh.push(a.name)}catch(l){console.error(a.name+" - "+l.message,l)}}if(e.children)for(const r of e.children)await y0(o,r,t,i,n+1);if(Fh.length>0&&n===0){const r=Fh.join(", ");console.warn(`Unknown components in scene: ${r}`),Fh.length=0,Wi()&&Te(`<strong>Unknown components in scene</strong>:
1462
+ `+c.xrData.lastChangedTime.toFixed(2),.02))}}bounds=new bi;center=new b;labelOffset=new b;removeData(e,t){const i=t.get(e);if(!i)return;t.delete(e),oa&&console.log("Plane no longer tracked, id="+i.id),i.mesh&&(i.mesh.removeFromParent(),i.mesh.traverse(s=>{const r=s.userData.normalsHelper;r?(r.dispose(),r.removeFromParent()):oa&&console.warn("No normals helper found for mesh",i.mesh)}),Ci(i.mesh,!0,!0));const n=new CustomEvent("plane-tracking",{detail:{type:"plane-removed",context:i}});this.dispatchEvent(n)}_dataId=1;_allPlanes=new Map;_allMeshes=new Map;firstTimeNoPlanesDetected=-100;makeOccluder=(e,t,i=!1)=>{if(t){if(t instanceof Array){for(const n of t)this.makeOccluder(e,n,i);return}!i&&!t.name.toLowerCase().includes("occlu")||(t.colorWrite=!1,t.depthTest=!0,t.depthWrite=!0,t.transparent=!1,t.polygonOffset=!0,t.polygonOffsetFactor=1,t.polygonOffsetUnits=.1,e.renderOrder=-1e3)}};processFrameData(e,t,i,n,s){const r=this.context.renderer.xr.getReferenceSpace();if(r){for(const a of s.keys())n.has(a)||this.removeData(a,s);for(const a of n){const l="planeSpace"in a?a.planeSpace:"meshSpace"in a?a.meshSpace:void 0;if(!l)continue;const c=i.getPose(l,r);let h;if(s.has(a)){const d=s.get(a);if(h=d.mesh,d.timestamp<a.lastChangedTime){if(d.timestamp=a.lastChangedTime,d.mesh){const m=this.createGeometry(a);if(d.mesh instanceof H)d.mesh.geometry.dispose(),d.mesh.geometry=m,this.makeOccluder(d.mesh,d.mesh.material);else if(d.mesh instanceof os)for(const f of d.mesh.children)f instanceof H&&(f.geometry.dispose(),f.geometry=m,this.makeOccluder(f,f.material));if(d.collider){const f=d.mesh;d.collider.sharedMesh=f,d.collider.convex=this.checkIfContextShouldBeConvex(f,d.xrData),d.collider.onDisable(),d.collider.onEnable()}oa&&(console.log("Plane updated, id="+d.id,d),d.mesh.traverse(f=>{if(!(f instanceof H))return;const g=f.userData.normalsHelper;g&&g.update()}))}const p=new CustomEvent("plane-tracking",{detail:{type:"plane-updated",context:d}});this.dispatchEvent(p)}}else{if(!this.dataTemplate){const d=new H;oa?d.material=new cC:this.occluder?(d.material=new xe,this.makeOccluder(d,d.material,!0)):d.material=new xe({wireframe:!0,opacity:.5,transparent:!0,color:3355443}),this.dataTemplate=new ie("","",d)}if(!this.dataTemplate.asset)this.dataTemplate.loadAssetAsync();else{const d=x.instantiate(this.dataTemplate.asset);if(d.name="xr-tracked-plane",h=d,Um(d,!1),d instanceof H)Pe(d.geometry),d.geometry=this.createGeometry(a),this.makeOccluder(d,d.material,this.occluder&&!this.dataTemplate);else if(d instanceof os)for(const f of d.children)f instanceof H&&(Pe(f.geometry),f.geometry=this.createGeometry(a),this.makeOccluder(f,f.material,this.occluder&&!this.dataTemplate));const p=d.getComponent(xs);if(p){const f=d;p.sharedMesh=f,p.convex=this.checkIfContextShouldBeConvex(f,a),p.onDisable(),p.onEnable()}d.matrixAutoUpdate=!1,d.matrixWorldNeedsUpdate=!0,t.add(d);const m={id:this._dataId++,xrData:a,timestamp:a.lastChangedTime,mesh:d,collider:p};s.set(a,m),oa&&console.log("New plane detected, id="+m.id,m,{hasCollider:!!p,isGroup:d instanceof os});try{const f=new CustomEvent("plane-tracking",{detail:{type:"plane-added",context:m}});this.dispatchEvent(f)}catch(f){console.error(f)}}}h&&(c?(h.visible=!0,h.matrix.fromArray(c.transform.matrix),h.matrix.premultiply(this._flipForwardMatrix)):h.visible=!1,oa&&h.traverse(d=>{if(d instanceof H)if(d.userData.normalsHelper)d.userData.normalsHelper.update();else{const p=new IC(d,.05,255);p.layers.disableAll(),p.layers.set(2),this.context.scene.add(p),d.userData.normalsHelper=p}}))}}}_flipForwardMatrix=new ee().makeRotationY(Math.PI);checkIfContextShouldBeConvex(e,t){if(!e)return!0;if(e){const i=new bi;i.expandByObject(e);const n=new b;i.getSize(n);let s=!0;return n.x>2&&n.y>2&&n.z>1.5&&(s=!1),s&&"semanticLabel"in t&&t.semanticLabel==="wall"&&(s=!0),s}return!0}createGeometry(e){return"polygon"in e?this.createPlaneGeometry(e.polygon):"vertices"in e&&"indices"in e?this.createMeshGeometry(e.vertices,e.indices):new un}_verticesCache=new Map;createMeshGeometry(e,t){const i=e.toString()+"_"+t.toString();if(this._verticesCache.has(i))return this._verticesCache.get(i);const n=new un;n.setIndex(new pt(t,1)),n.setAttribute("position",new pt(e,3));const s=Array();for(let r=0;r<e.length;r+=3)s.push(e[r],e[r+2]);return n.setAttribute("uv",new pt(e,3)),n.computeVertexNormals(),this._verticesCache.set(i,n),n}createPlaneGeometry(e){const t=new un,i=[],n=[];e.forEach(p=>{i.push(p.x,p.y,p.z),n.push(p.x,p.z)});const s=new b(i[0],i[1],i[2]),r=new b(i[3],i[4],i[5]),a=new b(i[6],i[7],i[8]),l=new b,c=new b;l.subVectors(r,s),c.subVectors(a,s),l.cross(c),l.normalize();const h=[];for(let p=0;p<i.length/3;p++)h.push(l.x,l.y,l.z);const d=[];for(let p=2;p<e.length;++p)d.push(0,p-1,p);return t.setAttribute("position",new pt(new Float32Array(i),3)),t.setAttribute("uv",new pt(new Float32Array(n),2)),t.setAttribute("normal",new pt(new Float32Array(h),3)),t.setIndex(d),t.computeBoundingBox(),t.computeBoundingSphere(),t}}Ol([u(ie)],qo.prototype,"dataTemplate"),Ol([u()],qo.prototype,"occluder"),Ol([u()],qo.prototype,"initiateRoomCaptureIfNoData"),Ol([u()],qo.prototype,"usePlaneData"),Ol([u()],qo.prototype,"useMeshData"),Ol([u()],qo.prototype,"runInVR");var J2=Object.defineProperty,eI=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&J2(e,t,n),n};const _1=w("debugwebxr");class Wp extends M{priority=0;get isActive(){return this.activeAndEnabled&&this.gameObject.visible}setAsActiveXRRig(){K.active?.setRigActive(this)}setPriority(e){this.priority=e}awake(){if(_1){const e=new O;e.position.y+=.5,this.gameObject.add(e);const t=e.addNewComponent(Nr);t&&(t.isGizmo=!1);const i=new _i(.5);this.gameObject.add(i)}}isXRRig(){return!0}supportsXR(e){return!0}_startScale;onEnterXR(e){this._startScale=this.gameObject.scale.clone(),e.xr.addRig(this),_1&&console.log("WebXR: add Rig",this.name,this.priority)}onLeaveXR(e){e.xr.removeRig(this),this._startScale&&this.gameObject&&this.gameObject.scale.copy(this._startScale)}}eI([u()],Wp.prototype,"priority");class tI extends M{toggleKey="KeyP";update(){this.context.input.isKeyDown(this.toggleKey)&&this.context.domElement.classList.toggle("presentation-mode")}}C.add("AlignmentConstraint",wc),C.add("Animation",Ht),C.add("Animator",ft),C.add("AudioListener",ko),C.add("AudioSource",Mi),C.add("Avatar_Brain_LookAt",Rc),C.add("Avatar_MouthShapes",Tc),C.add("Avatar_MustacheShake",hf),C.add("AvatarBlink_Simple",Rr),C.add("AvatarEyeLook_Rotation",uf),C.add("AxesHelper",Ha),C.add("BasicIKConstraint",mf),C.add("BoxHelperComponent",xt),C.add("Camera",si),C.add("CharacterController",Tr),C.add("CharacterControllerInput",To),C.add("Collider",ai),C.add("SphereCollider",Ga),C.add("BoxCollider",Ou),C.add("MeshCollider",xs),C.add("CapsuleCollider",Mo),C.add("ContactShadows",Ac),C.add("LogStats",yf),C.add("DeleteBox",Zs),C.add("Deletable",_f),C.add("DeviceFlag",ku),C.add("DragControls",Ir),C.add("DropListener",Eo),C.add("Duplicatable",Pf),C.add("EventListEvent",yu),C.add("EventTrigger",Eu),C.add("GltfExportBox",Bf),C.add("GltfExport",Uf),C.add("VariantAction",Qf),C.add("ChangeTransformOnClick",Br),C.add("ChangeMaterialOnClick",Kf),C.add("SetActiveOnClick",Zf),C.add("HideOnStart",cn),C.add("EmphasizeOnClick",ol),C.add("PlayAudioOnClick",Os),C.add("PlayAnimationOnClick",Nc),C.add("PreliminaryAction",sl),C.add("PreliminaryTrigger",Wc),C.add("VisibilityAction",Vc),C.add("TapGestureTrigger",ey),C.add("USDZExporter",to),C.add("Fog",pl),C.add("BoxGizmo",Nr),C.add("GridHelper",ml),C.add("GroundProjectedEnv",$n),C.add("UsageMarker",Ic),C.add("Interactable",bf),C.add("FixedJoint",My),C.add("HingeJoint",eh),C.add("Light",di),C.add("LODGroup",ih),C.add("LookAtConstraint",Pr),C.add("NeedleMenu",Jn),C.add("NestedGltf",nh),C.add("Networking",Ay),C.add("OffsetConstraint",Wr),C.add("CameraTargetReachedEvent",Mc),C.add("OrbitControls",fe),C.add("ParticleSystemRenderer",nn),C.add("ParticleSystem",ah),C.add("Attractor",bl),C.add("PlayerColor",Il),C.add("Antialiasing",ch),C.add("BloomEffect",fp),C.add("ChromaticAberration",hh),C.add("ColorAdjustments",zs),C.add("DepthOfField",On),C.add("EffectWrapper",uh),C.add("PixelationEffect",ph),C.add("ScreenSpaceAmbientOcclusion",No),C.add("ScreenSpaceAmbientOcclusionN8",kn),C.add("SharpeningEffect",gh),C.add("TiltShiftEffect",no),C.add("ToneMappingEffect",Us),C.add("Vignette",Qr),C.add("Volume",vl),C.add("ReflectionProbe",Dc),C.add("Renderer",Ti),C.add("MeshRenderer",Bc),C.add("SkinnedMeshRenderer",Df),C.add("Rigidbody",Ye),C.add("SceneSwitcher",qe),C.add("ScreenCapture",Ws),C.add("ShadowCatcher",_h),C.add("RemoteSkybox",Sp),C.add("SmoothFollow",Pp),C.add("SpatialTriggerReceiver",oo),C.add("SpatialTrigger",Op),C.add("SpectatorCamera",kp),C.add("SplineContainer",Zr),C.add("SplineWalker",Mn),C.add("SpriteRenderer",ci),C.add("SyncedCamera",t0),C.add("SyncedRoom",Rn),C.add("SyncedTransform",vn),C.add("TestRunner",o0),C.add("TestSimulateUserData",s0),C.add("PlayableDirector",ea),C.add("SignalReceiver",Ph),C.add("AnimationTrackHandler",Ep),C.add("AudioTrackHandler",es),C.add("SignalTrackHandler",kh),C.add("ControlTrackHandler",Ap),C.add("TransformGizmo",ta),C.add("BaseUIComponent",rn),C.add("UIRootComponent",Xc),C.add("Button",$o),C.add("Canvas",ul),C.add("CanvasGroup",Is),C.add("EventSystem",ei),C.add("Graphic",Kc),C.add("MaskableGraphic",Zc),C.add("Image",xl),C.add("RawImage",jp),C.add("InputField",c0),C.add("VerticalLayoutGroup",yy),C.add("HorizontalLayoutGroup",by),C.add("GridLayoutGroup",_y),C.add("Outline",hl),C.add("ObjectRaycaster",ki),C.add("GraphicRaycaster",vu),C.add("SpatialGrabRaycaster",ra),C.add("RectTransform",Cn),C.add("SpatialHtml",Rh),C.add("Text",Dt),C.add("EnvironmentScene",Bp),C.add("LookAt",h0),C.add("OpenURL",Sl),C.add("VideoPlayer",ht),C.add("Voip",ws),C.add("ClickThrough",Up),C.add("CursorFollow",Eh),C.add("ScrollFollow",u0),C.add("Avatar",Ms),C.add("XRControllerFollow",Ho),C.add("XRControllerModel",Do),C.add("XRControllerMovement",Ei),C.add("TeleportTarget",Ku),C.add("WebARCameraBackground",Lh),C.add("WebARSessionRoot",Ui),C.add("WebXR",Zu),C.add("AvatarMarker",Le),C.add("WebXRImageTracking",jh),C.add("WebXRPlaneTracking",qo),C.add("XRRig",Wp),C.add("XRFlag",Ki),C.add("PlayerSync",ry),C.add("PlayerState",xn),C.add("PresentationMode",tI);const Bh=gt,iI=w("debugtypestore");iI&&console.log(C);function nI(o,e){const t=rv(o,e);return t!==void 0?t:null}const oI=new vk,m0=Symbol("deserialize-queue");async function sI(o,e,t,i=null,n){if(!t){console.debug("Can not create component instances: gltf is null");return}const s=[];let r=i;typeof r=="number"&&(r=new At(i));const a=e.indexOf("?");e=a===-1?e:e.substring(0,a);const l=new Mg(t.scene);l.gltfId=e,l.context=o,l.gltf=t,l.nodeToObject=n?.nodeToObjectMap,l.implementationInformation=oI;let c=o[m0];if(c||(c=o[m0]=[]),t.scenes)for(const h of t.scenes)await y0(l,h,c,s,0);if(t.children)for(const h of t.children)await y0(l,h,c,s,0);o.new_scripts_pre_setup_callbacks.push(()=>{const h=o[m0];if(h){for(const d of h)rI(d,l);h.length=0}if(r){const d={},p=[];f0(t,r,d,p);for(const m of t.scenes)f0(m,r,d,p);for(const m of p)m.resolveGuids(d)}})}const g0=Symbol("original-component-name"),kl=new Map;function f0(o,e,t,i){if(e===null||!o)return;const n=o.guid,s=o.guid;s?.length&&(kl.has(s)||(Bh&&console.log('Creating InstanceIdProvider with key "'+s+'" for object '+o.name),kl.set(s,new At(s))));const r=s&&kl.get(s)||e;if(o.guid=r.generateUUID(),n&&n!=="invalid"&&(t[n]=o.guid),o&&o.userData&&o.userData.components)for(const a of o.userData.components){if(a===null)continue;const l=a.guid;l?kl.has(l)||(Bh&&console.log('Creating InstanceIdProvider with key "'+l+'" for component '+a[g0]),kl.set(l,new At(l))):Bh&&console.warn("Can not create IdProvider: component "+a[g0]+" has no guid",a.guid);const c=kl.get(l)||e,h=a.guid;a.guid=c.generateUUID(),h&&h!=="invalid"&&(t[h]=a.guid),a.resolveGuids&&i.push(a)}if(o.children)for(const a of o.children)f0(a,e,t,i)}const Fh=[];async function y0(o,e,t,i,n){if(!e)return;const s=e.userData;if(s){const r=s.builtin_components;if(r&&r.length>0)for(const a of r)try{if(a===null)continue;const l=C.get(a.name);if(l!=null){const c=new l;c.sourceId=o.gltfId,Aa(c,a,o.implementationInformation),c.context=o.context,"guid"in a&&(c[Yl]=a.guid),c[g0]=a.name,yr(e,c,!1),t.push({instance:c,compData:a,obj:e}),c.isCamera&&o.context&&o.context.mainCamera===null&&c.tag==="MainCamera"&&o.context.setCurrentCamera(c),o.context?.physics?.engine?.isInitialized===!1&&(c.isCollider||c.isRigidbody)&&o.context?.physics.engine?.initialize()}else Bh&&console.debug("unknown component: "+a.name),Fh.includes(a.name)||Fh.push(a.name)}catch(l){console.error(a.name+" - "+l.message,l)}}if(e.children)for(const r of e.children)await y0(o,r,t,i,n+1);if(Fh.length>0&&n===0){const r=Fh.join(", ");console.warn(`Unknown components in scene: ${r}`),Fh.length=0,Wi()&&Te(`<strong>Unknown components in scene</strong>:
1463
1463
 
1464
1464
  ${r}
1465
1465
 
@@ -1486,29 +1486,7 @@ Please refer to the documentation on <a href="https://fwd.needle.tools/needle-en
1486
1486
  align-items: center;
1487
1487
  `,n.appendChild(s);var r=document.createElementNS("http://www.w3.org/2000/svg","path");r.setAttribute("d","M 12,12 L 28,28 M 28,12 12,28"),r.setAttribute("stroke","#000000"),r.setAttribute("stroke-width","2px"),r.style.cssText=`
1488
1488
  /**filter: drop-shadow(0 0px 1.2px rgba(0,0,0,.7));**/
1489
- `,s.appendChild(r),zh&&console.log("Created fallback close button",s,e)}appendElement(e,t){return t.shadowRoot?t.shadowRoot.appendChild(e):t.appendChild(e)}}const sa=w("debugloading"),Nh=w("debugloadingrendering"),O1=w("debuglicense");class mI{className;additionalClasses}let Wh=0,k1;function _0(o){sa&&console.log(o.progress.loaded.toFixed(0)+"/"+o.progress.total.toFixed(0),o);const e=o.count,t=o.progress.total;t===0||t===void 0?(k1!==o.name&&(Wh=0),k1=o.name,Wh+=(1-Wh)*.001,sa&&ge("Loading "+o.name+" did not report total size")):Wh=o.progress.loaded/t;const i=o.index/e+Wh/e;return D.clamp01(i)}class td{static LoadingContainerClassName="loading";loadingProgress=0;_element;_progress=0;_allowCustomLoadingElement=!0;_loadingElement;_loadingTextContainer=null;_loadingBar=null;_messageContainer=null;_loadingElementOptions;constructor(e,t){this._element=e,this._loadingElementOptions=t}async onLoadingBegin(e){const t=this._element.shadowRoot||this._element;if(sa&&console.warn("Begin Loading"),!this._loadingElement){for(let i=0;i<t.children.length;i++){const n=t.children[i];if(n.classList.contains(td.LoadingContainerClassName)){if(!this._allowCustomLoadingElement){sa&&console.warn("Remove custom loading container"),t.removeChild(n);continue}this._loadingElement=this.createLoadingElement(n)}}this._loadingElement||(this._loadingElement=this.createLoadingElement())}this._progress=0,this.loadingProgress=0,this._loadingElement.style.display="flex",t.appendChild(this._loadingElement),this.smoothProgressLoop(),this.setMessage(e??"")}onLoadingUpdate(e,t){if(!this._loadingElement?.parentNode)return;let i=0;typeof e=="number"?i=e:("index"in e&&(i=_0(e)),!t&&"name"in e&&this.setMessage("loading "+e.name)),this.loadingProgress=i,t&&this.setMessage(t),this.updateDisplay()}onLoadingFinished(){sa&&console.warn("Finished Loading"),Nh||(this.loadingProgress=1,this.onDoneLoading())}setMessage(e){this._messageContainer&&(this._messageContainer.innerText=e)}_progressLoop;smoothProgressLoop(){if(this._progressLoop)return;let e=1/12;Nh&&(e=1/500,typeof Nh=="number"&&(e*=Nh)),this._progressLoop=setInterval(()=>{this.loadingProgress>=.95&&!Nh&&(e=.9),this._progress=D.lerp(this._progress,this.loadingProgress,e*this.loadingProgress),this.updateDisplay()},e)}onDoneLoading(){if(this._loadingElement){sa&&console.log("Hiding loading element");const 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(){const e=this._progress,t=(e*100).toFixed(0)+"%";this._loadingBar&&(this._loadingBar.style.width=e*100+"%"),this._loadingTextContainer&&(this._loadingTextContainer.textContent=t)}createLoadingElement(e){sa&&!e&&console.log("Creating loading element"),this._loadingElement=e||document.createElement("div");let t=this._element.getAttribute("loading-style");(!t||t==="auto")&&(window.matchMedia("(prefers-color-scheme: dark)").matches?t="dark":t="light");const i=Wn();if(!e){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";const m=this._element.getAttribute("loading-background");m?this._loadingElement.style.background=m: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",t==="light"?this._loadingElement.style.color="rgba(0,0,0,.6)":this._loadingElement.style.color="rgba(255,255,255,.3)"}const n=this._loadingElementOptions?.className??td.LoadingContainerClassName;if(this._loadingElement.classList.add(n),this._loadingElementOptions?.additionalClasses)for(const m of this._loadingElementOptions.additionalClasses)this._loadingElement.classList.add(m);const s=document.createElement("div");s.style.cssText=`
1490
- position: relative;
1491
- display: flex;
1492
- flex-direction: column;
1493
- align-items: center;
1494
- justify-content: center;
1495
- width: 100%;
1496
- height: 100%;
1497
- pointer-events: none;
1498
- `,this._loadingElement.appendChild(s);const r=this._element.getAttribute("poster");if(r!==null&&r!=="0"){const m=document.createElement("div"),y=r?.length?"0px":"50px";m.style.cssText=`
1499
- position: absolute;
1500
- left: 0;
1501
- top: 0;
1502
- bottom: 0;
1503
- right: 0;
1504
- z-index: -1;
1505
- overflow: hidden;
1506
-
1507
- margin: -${y};
1508
- background: url('${r?.length?r:"/include/poster.webp"}') center center no-repeat;
1509
- background-size: cover;
1510
- filter: blur(${y});
1511
- `,this._loadingElement.appendChild(m)}const a=document.createElement("img"),l="80%",c="15%",h=".2s";if(a.style.userSelect="none",a.style.objectFit="contain",a.style.transform="translateY(30px)",a.style.opacity="0.0000001",a.style.transition=`transform 1s ease-out ${h}, opacity .3s ease-in-out ${h}`,a.src=hb,i&&this._element){const m=this._element.getAttribute("loading-logo-src");m&&(a.src=m,setTimeout(()=>{a.style.opacity="1",a.style.transform="translateY(0px)"},1))}a.style.width=`${l}`,a.style.height=`min(1000px, max(${c}, 50px))`,s.appendChild(a);const d=document.createElement("div");d.style.cssText=`
1489
+ `,s.appendChild(r),zh&&console.log("Created fallback close button",s,e)}appendElement(e,t){return t.shadowRoot?t.shadowRoot.appendChild(e):t.appendChild(e)}}const sa=w("debugloading"),Nh=w("debugloadingrendering"),O1=w("debuglicense");class mI{className;additionalClasses}let Wh=0,k1;function _0(o){sa&&console.log(o.progress.loaded.toFixed(0)+"/"+o.progress.total.toFixed(0),o);const e=o.count,t=o.progress.total;t===0||t===void 0?(k1!==o.name&&(Wh=0),k1=o.name,Wh+=(1-Wh)*.001,sa&&ge("Loading "+o.name+" did not report total size")):Wh=o.progress.loaded/t;const i=o.index/e+Wh/e;return D.clamp01(i)}class td{static LoadingContainerClassName="loading";loadingProgress=0;_element;_progress=0;_allowCustomLoadingElement=!0;_loadingElement;_loadingTextContainer=null;_loadingBar=null;_messageContainer=null;_loadingElementOptions;constructor(e,t){this._element=e,this._loadingElementOptions=t}async onLoadingBegin(e){const t=this._element.shadowRoot||this._element;if(sa&&console.warn("Begin Loading"),!this._loadingElement){for(let i=0;i<t.children.length;i++){const n=t.children[i];if(n.classList.contains(td.LoadingContainerClassName)){if(!this._allowCustomLoadingElement){sa&&console.warn("Remove custom loading container"),t.removeChild(n);continue}this._loadingElement=this.createLoadingElement(n)}}this._loadingElement||(this._loadingElement=this.createLoadingElement())}this._progress=0,this.loadingProgress=0,this._loadingElement.style.display="flex",t.appendChild(this._loadingElement),this.smoothProgressLoop(),this.setMessage(e??"")}onLoadingUpdate(e,t){if(!this._loadingElement?.parentNode)return;let i=0;typeof e=="number"?i=e:("index"in e&&(i=_0(e)),!t&&"name"in e&&this.setMessage("loading "+e.name)),this.loadingProgress=i,t&&this.setMessage(t),this.updateDisplay()}onLoadingFinished(){sa&&console.warn("Finished Loading"),Nh||(this.loadingProgress=1,this.onDoneLoading())}setMessage(e){this._messageContainer&&(this._messageContainer.innerText=e)}_progressLoop;smoothProgressLoop(){if(this._progressLoop)return;let e=1/12;Nh&&(e=1/500,typeof Nh=="number"&&(e*=Nh)),this._progressLoop=setInterval(()=>{this.loadingProgress>=.95&&!Nh&&(e=.9),this._progress=D.lerp(this._progress,this.loadingProgress,e*this.loadingProgress),this.updateDisplay()},e)}onDoneLoading(){this._loadingElement&&(sa&&console.log("Hiding loading element"),this._loadingElement.style.display="none",this._loadingElement.remove()),this._progressLoop&&clearInterval(this._progressLoop),this._progressLoop=null}updateDisplay(){const e=this._progress,t=(e*100).toFixed(0)+"%";this._loadingBar&&(this._loadingBar.style.width=e*100+"%"),this._loadingTextContainer&&(this._loadingTextContainer.textContent=t)}createLoadingElement(e){sa&&!e&&console.log("Creating loading element"),this._loadingElement=e||document.createElement("div");let t=this._element.getAttribute("loading-style");(!t||t==="auto")&&(window.matchMedia("(prefers-color-scheme: dark)").matches?t="dark":t="light");const i=Wn();if(!e){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";const p=this._element.getAttribute("loading-background");p?this._loadingElement.style.background=p: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",t==="light"?this._loadingElement.style.color="rgba(0,0,0,.6)":this._loadingElement.style.color="rgba(255,255,255,.3)"}const n=this._loadingElementOptions?.className??td.LoadingContainerClassName;if(this._loadingElement.classList.add(n),this._loadingElementOptions?.additionalClasses)for(const p of this._loadingElementOptions.additionalClasses)this._loadingElement.classList.add(p);const s=document.createElement("div");this._loadingElement.appendChild(s);const r=document.createElement("img"),a=120;if(r.style.width=`${a}px`,r.style.height=`${a}px`,r.style.paddingTop="20px",r.style.paddingBottom="10px",r.style.margin="0px",r.style.userSelect="none",r.style.objectFit="contain",r.style.transition="transform 1.5s ease-out, opacity .3s ease-in-out",r.style.transform="translateY(30px)",r.style.opacity="0.05",setTimeout(()=>{r.style.opacity="1",r.style.transform="translateY(0px)"},1),r.src=hb,i&&this._element){const p=this._element.getAttribute("loading-logo-src");p&&(r.src=p)}s.appendChild(r);const l=document.createElement("div");l.style.cssText=`
1512
1490
  display: flex;
1513
1491
  flex-direction: column;
1514
1492
  align-items: center;
@@ -1516,7 +1494,7 @@ Please refer to the documentation on <a href="https://fwd.needle.tools/needle-en
1516
1494
  width: 100%;
1517
1495
  opacity: 0;
1518
1496
  transition: opacity 1s ease-in-out 4s;
1519
- `,setTimeout(()=>{d.style.opacity="1"},1),this._loadingElement.appendChild(d);const p=document.createElement("div"),g=100;p.style.display="flex",p.style.width=g+"%",p.style.height="5px",p.style.position="absolute",p.style.left="0",p.style.top="0px",p.style.opacity="0",p.style.transition="opacity 1s ease-in-out",p.style.backgroundColor="rgba(240,240,240,.5)",setTimeout(()=>{p.style.opacity="1"},1),this._loadingElement.appendChild(p),this._loadingBar=document.createElement("div"),p.appendChild(this._loadingBar);const f=function(m){return D.lerp(0,g,m)+"%"};if(this._loadingBar.style.backgroundAttachment="fixed",this._loadingBar.style.background="#c4c4c4ab",this._loadingBar.style.width="0%",this._loadingBar.style.height="100%",i&&this._element){const m=this._element.getAttribute("primary-color"),y=this._element.getAttribute("secondary-color");m&&y?this._loadingBar.style.background=`linear-gradient(90deg, ${m} ${f(0)}, ${y} ${f(1)})`:m?this._loadingBar.style.background=m:y&&(this._loadingBar.style.background=y)}return this.handleRuntimeLicense(this._loadingElement),this._loadingElement}async handleRuntimeLicense(e){let t=Vn();if(t)return;O1&&console.log("Loading UI has commercial license?",t);const i=document.createElement("div");i.style.paddingTop=".6em",i.style.fontSize=".8em",i.style.textTransform="uppercase",i.innerText=`NEEDLE ENGINE NON COMMERCIAL VERSION
1497
+ `,setTimeout(()=>{l.style.opacity="1"},1),this._loadingElement.appendChild(l);const c=document.createElement("div"),h=100;c.style.display="flex",c.style.width=h+"%",c.style.height="3px",c.style.position="absolute",c.style.left="0",c.style.bottom="0px",c.style.opacity="0",c.style.transition="opacity 1s ease-in-out 2s",setTimeout(()=>{c.style.opacity="1"},1),t==="light"?c.style.backgroundColor="rgba(0,0,0,.2)":c.style.backgroundColor="rgba(255,255,255,.2)",this._loadingElement.appendChild(c),this._loadingBar=document.createElement("div"),c.appendChild(this._loadingBar);const d=function(p){return D.lerp(0,h,p)+"%"};if(this._loadingBar.style.background="#66A22F",this._loadingBar.style.backgroundAttachment="fixed",this._loadingBar.style.width="0%",this._loadingBar.style.height="100%",i&&this._element){const p=this._element.getAttribute("primary-color"),m=this._element.getAttribute("secondary-color");p&&m?this._loadingBar.style.background=`linear-gradient(90deg, ${p} ${d(0)}, ${m} ${d(1)})`:p?this._loadingBar.style.background=p:m&&(this._loadingBar.style.background=m)}return this.handleRuntimeLicense(this._loadingElement),this._loadingElement}async handleRuntimeLicense(e){let t=Vn();if(t)return;O1&&console.log("Loading UI has commercial license?",t);const i=document.createElement("div");i.style.paddingTop=".6em",i.style.fontSize=".8em",i.style.textTransform="uppercase",i.innerText=`NEEDLE ENGINE NON COMMERCIAL VERSION
1520
1498
  CLICK HERE TO GET A LICENSE`,i.style.cursor="pointer",i.style.userSelect="none",i.style.textAlign="center",i.style.pointerEvents="all",i.addEventListener("click",()=>window.open("https://needle.tools/pricing","_self")),i.style.opacity="0",e.appendChild(i),!E()&&za&&(O1&&console.log("Waiting for runtime license check"),await za,t=Vn()),!t&&(i.style.transition="opacity .5s ease-in-out",i.style.opacity="1")}}Hm(v1);const ke=w("debugwebcomponent"),M1="needle-engine",R1="vr",T1="desktop",gI=[P1,R1,T1],Vh="ar-session-active",$h="desktop-session-active",fI=["public-key","version","hash","src","camera-controls","loadstart","progress","loadfinished","dracoDecoderPath","dracoDecoderType","ktx2DecoderPath","tone-mapping","tone-mapping-exposure","background-blurriness","background-color","environment-intensity"];class v0 extends HTMLElement{static get observedAttributes(){return fI}get loadingProgress01(){return this._loadingProgress01}get loadingFinished(){return this.loadingProgress01>.999}get cameraControls(){const e=this.getAttribute("camera-controls");return e==null?null:!(e===null||e==="False"||e==="false"||e==="0"||e==="none")}getContext(){return new Promise((e,t)=>{if(this._context&&this.loadingFinished)e(this._context);else{const i=()=>{this.removeEventListener("loadfinished",i),this._context&&this.loadingFinished&&e(this._context)};this.addEventListener("loadfinished",i)}})}get context(){return this._context}_context;_overlay_ar;_loadingProgress01=0;_loadingView;_previousSrc=null;_didFullyLoad=!1;constructor(){super(),this._overlay_ar=new pI,this.addEventListener("ready",this.onReady),$v(),this.attachShadow({mode:"open"});const e=document.createElement("template");e.innerHTML=`<style>
1521
1499
  @import url('https://fonts.googleapis.com/css2?family=Roboto+Flex:opsz,wght@8..144,100..1000&display=swap');
1522
1500
 
@@ -1597,11 +1575,11 @@ CLICK HERE TO GET A LICENSE`,i.style.cursor="pointer",i.style.userSelect="none",
1597
1575
  `,this.shadowRoot&&this.shadowRoot.appendChild(e.content.cloneNode(!0)),this._context=new z({domElement:this}),this.addEventListener("error",this.onError)}async connectedCallback(){if(ke&&console.log("<needle-engine> connected"),this.setPublicKey(),this.setVersion(),(this.getAttribute("tabindex")===null||this.getAttribute("tabindex")===void 0)&&this.setAttribute("tabindex","0"),this.addEventListener("xr-session-started",this.onXRSessionStarted),this.onSetupDesktop(),!this.getAttribute("src")){const t=globalThis["needle:codegen_files"];ke&&console.log('src is null, trying to load from globalThis["needle:codegen_files"]',t),t&&(ke&&console.log('globalThis["needle:codegen_files"]',t),this.setAttribute("src",t))}ke&&console.log("src",this.getAttribute("src"));const e=this._loadId;setTimeout(()=>{this.isConnected!==!1&&e===this._loadId&&this.onLoad()},1)}disconnectedCallback(){this.removeEventListener("xr-session-started",this.onXRSessionStarted),this._didFullyLoad=!1;const e=this.getAttribute("keep-alive"),t=e==null||e?.length>0&&e!=="true"&&e!=="1";ke&&console.warn('<needle-engine> disconnected, keep-alive: "'+e+'"',typeof e,"Dispose=",t),t?(ke&&console.warn("<needle-engine> dispose"),this._context?.dispose(),this._context=null,this._lastSourceFiles=null,this._loadId+=1):ke&&console.warn("<needle-engine> is not disposed because keep-alive is set")}attributeChangedCallback(e,t,i){switch(ke&&console.log("attributeChangedCallback",e,t,i),e){case"src":ke&&console.warn(`<needle-engine src>
1598
1576
  changed from "`,t,'" to "',i,'"'),this.onLoad();break;case"hash":this._context&&(this._context.hash=i);break;case"loadstart":case"progress":case"loadfinished":typeof i=="string"&&i.length>0&&(ke&&console.log(e+" attribute changed",i),this.registerEventFromAttribute(e,i));break;case"dracoDecoderPath":ke&&console.log("dracoDecoderPath",i),ew(i);break;case"dracoDecoderType":i==="wasm"||i==="js"?(ke&&console.log("dracoDecoderType",i),tw(i)):console.error("Invalid dracoDecoderType",i,"expected js or wasm");break;case"ktx2DecoderPath":ke&&console.log("ktx2DecoderPath",i),iw(i);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":{i!=xa&&this.setPublicKey();break}case"version":{i!=mn&&this.setVersion();break}}}get toneMapping(){return this.getAttribute("tonemapping")||this.getAttribute("tone-mapping")}_loadId=0;_abortController=null;_lastSourceFiles=null;_createContextPromise=null;async onLoad(){if(!this.isConnected)return;if(this._context||(ke&&console.warn("Create new context"),this._context=new z({domElement:this})),!this._context){console.error("Needle Engine: Context not initialized");return}const e=this.getSourceFiles();if(!this.checkIfSourceHasChanged(e,this._lastSourceFiles))return;this._abortController&&(ke&&console.warn("Abort previous loading process"),this._abortController.abort(),this._abortController=null),this._lastSourceFiles=e;const t=++this._loadId;if((e==null||e.length<=0)&&(ke&&console.warn("Clear scene",e),this._context.clear(),t!==this._loadId))return;const i=this.getAttribute("alias");this.classList.add("loading");const n=Vn();this.ensureLoadStartIsRegistered();let s=this.dispatchEvent(new CustomEvent("loadstart",{detail:{context:this._context,alias:i},cancelable:!0}));if(n){const f=this.getAttribute("hide-loading-overlay");f!=null&&f!=="0"&&(s=!1)}s===!1&&!n&&(E()||(s=!0),console.warn("Needle Engine: You need a commercial license to override the default loading view. Visit https://needle.tools/pricing"),E()&&ge('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&&s&&(this._loadingView=new td(this)),s&&(this._didFullyLoad!==!0?this._loadingView?.onLoadingBegin("begin load"):setTimeout(()=>{this._loadingView&&this._loadingProgress01<.3&&this._loadId===t&&this._loadingView.onLoadingBegin("begin load")},300)),ke&&console.warn(`--------------
1599
1577
  Needle Engine: Begin loading `+t+`
1600
- `,e),this.onBeforeBeginLoading();const r=[],a={context:this._context,name:"",progress:{},index:0,count:e.length,totalProgress01:this._loadingProgress01},l=new CustomEvent("progress",{detail:a}),c=new Array,h=new AbortController;this._abortController=h;const d={files:e,abortSignal:h.signal,onLoadingProgress:f=>{if(ke&&console.debug("Loading progress: ",f),h.signal.aborted)return;const m=f.index;!c[m]&&f.name&&(c[m]=yI(f.name)),f.name=c[m],s&&this._loadingView?.onLoadingUpdate(f),a.name=f.name,a.progress=f.progress,this._loadingProgress01=_0(f),a.totalProgress01=this._loadingProgress01,this.dispatchEvent(l)},onLoadingFinished:(f,m,y)=>{ke&&console.debug(`Finished loading "${m}" (aborted? ${h.signal.aborted})`),!h.signal.aborted&&y&&r.push({src:m,file:y})}};bI(this);const p=this.getAttribute("hash");p!=null&&(this._context.hash=p),this._context.alias=i,this._createContextPromise=this._context.create(d);const g=await this._createContextPromise;if(this.applyAttributes(),ke&&console.warn(`--------------
1578
+ `,e),this.onBeforeBeginLoading();const r=[],a={context:this._context,name:"",progress:{},index:0,count:e.length,totalProgress01:this._loadingProgress01},l=new CustomEvent("progress",{detail:a}),c=new Array,h=new AbortController;this._abortController=h;const d={files:e,abortSignal:h.signal,onLoadingProgress:f=>{if(ke&&console.debug("Loading progress: ",f),h.signal.aborted)return;const g=f.index;!c[g]&&f.name&&(c[g]=yI(f.name)),f.name=c[g],s&&this._loadingView?.onLoadingUpdate(f),a.name=f.name,a.progress=f.progress,this._loadingProgress01=_0(f),a.totalProgress01=this._loadingProgress01,this.dispatchEvent(l)},onLoadingFinished:(f,g,y)=>{ke&&console.debug(`Finished loading "${g}" (aborted? ${h.signal.aborted})`),!h.signal.aborted&&y&&r.push({src:g,file:y})}};bI(this);const p=this.getAttribute("hash");p!=null&&(this._context.hash=p),this._context.alias=i,this._createContextPromise=this._context.create(d);const m=await this._createContextPromise;if(this.applyAttributes(),ke&&console.warn(`--------------
1601
1579
  Needle Engine: finished loading `+t+`
1602
- `,e,`Aborted? ${h.signal.aborted}`),h.signal.aborted){console.log("Loading finished but aborted...");return}if(this._loadId!==t){console.log("Load id changed during loading process");return}this._loadingProgress01=1,s&&g&&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:i,loadedFiles:r}}))}applyAttributes(){if(this._context?.renderer){const n=Wv(this.toneMapping);n!==void 0&&(this._context.renderer.toneMapping=n);const s=this.getAttribute("tone-mapping-exposure");if(s!=null){const r=parseFloat(s);isNaN(r)||(this._context.renderer.toneMappingExposure=r)}}const e=this.getAttribute("background-blurriness");if(e!=null){const n=parseFloat(e);!isNaN(n)&&this._context&&(this._context.scene.backgroundBlurriness=n)}const t=this.getAttribute("environment-intensity");if(t!=null&&this._context){const n=parseFloat(t);!isNaN(n)&&this._context&&(this._context.scene.environmentIntensity=n)}const i=this.getAttribute("background-color");if(this._context?.renderer&&typeof i=="string"&&i.length>0){const n=se.fromColorRepresentation(i);ke&&console.debug("<needle-engine> background-color changed, str:",i,"\u2192",n),this._context.renderer.setClearColor(n,n.alpha),this.context.scene.background=null}}onXRSessionStarted=()=>{const e=this.context.xrSessionMode;e==="immersive-ar"?this.onEnterAR(this.context.xrSession):e==="immersive-vr"&&this.onEnterVR(this.context.xrSession),this.context.xrSession?.addEventListener("end",()=>{this.dispatchEvent(new CustomEvent("xr-session-ended",{detail:{session:this.context.xrSession,context:this._context,sessionMode:e}})),e==="immersive-ar"?this.onExitAR(this.context.xrSession):e==="immersive-vr"&&this.onExitVR(this.context.xrSession)})};onReady=()=>this._loadingView?.onLoadingFinished();onError=()=>this._loadingView?.setMessage("Loading failed!");getSourceFiles(){const e=this.getAttribute("src");if(!e)return[];let t;Array.isArray(e)?t=e:e.startsWith("[")&&e.endsWith("]")?t=JSON.parse(e):e.includes(",")?t=e.split(","):t=[e];for(let i=t.length-1;i>=0;i--){const n=t[i];(n==="null"||n==="undefined"||n?.length<=0)&&t.splice(i,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 i=0;i<e?.length;i++)if(e[i]!==t[i])return!0}return!1}_previouslyRegisteredMap=new Map;ensureLoadStartIsRegistered(){const e=this.getAttribute("loadstart");e&&this.registerEventFromAttribute("loadstart",e)}registerEventFromAttribute(e,t){const i=this._previouslyRegisteredMap.get(e);if(i&&(this._previouslyRegisteredMap.delete(e),this.removeEventListener(e,i)),typeof t=="string"&&t.length>0)try{const n=(0,eval)(t);typeof n=="function"&&(this._previouslyRegisteredMap.set(e,n),this.addEventListener(e,s=>n?.call(globalThis,this._context,s)))}catch(n){console.error("Error registering event "+e+'="'+t+`" failed with the following error:
1603
- `,n)}}setPublicKey(){xa&&xa.length>0&&this.setAttribute("public-key",xa)}setVersion(){mn.length>0&&this.setAttribute("version",mn)}getAROverlayContainer(){return this._overlay_ar.createOverlayContainer(this)}getVROverlayContainer(){for(let e=0;e<this.children.length;e++){const t=this.children[e];if(t.classList.contains("vr"))return t}return null}onEnterAR(e){this.onSetupAR();const t=this.getAROverlayContainer();this._overlay_ar.onBegin(this._context,t,e),this.dispatchEvent(new CustomEvent("enter-ar",{detail:{session:e,context:this._context,htmlContainer:this._overlay_ar?.ARContainer}}))}onExitAR(e){this._overlay_ar.onEnd(this._context),this.onSetupDesktop(),this.dispatchEvent(new CustomEvent("exit-ar",{detail:{session:e,context:this._context,htmlContainer:this._overlay_ar?.ARContainer}}))}onEnterVR(e){this.onSetupVR(),this.dispatchEvent(new CustomEvent("enter-vr",{detail:{session:e,context:this._context}}))}onExitVR(e){this.onSetupDesktop(),this.dispatchEvent(new CustomEvent("exit-vr",{detail:{session:e,context:this._context}}))}onSetupAR(){this.classList.add(Vh),this.classList.remove($h);const e=this.getAROverlayContainer();ke&&console.warn("onSetupAR:",e),e&&(e.classList.add(Vh),e.classList.remove($h)),this.foreachHtmlElement(t=>this.setupElementsForMode(t,P1))}onSetupVR(){this.classList.remove(Vh),this.classList.remove($h),this.foreachHtmlElement(e=>this.setupElementsForMode(e,R1))}onSetupDesktop(){this.classList.remove(Vh),this.classList.add($h);const e=this.getAROverlayContainer();e&&(e.classList.remove(Vh),e.classList.add($h)),this.foreachHtmlElement(t=>this.setupElementsForMode(t,T1))}setupElementsForMode(e,t,i=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(const n of gI)e.classList.contains(n)&&(e.style.visibility="hidden",e.style.display="none")}foreachHtmlElement(e){for(let t=0;t<this.children.length;t++){const i=this.children[t];i.style&&e(i)}}onBeforeBeginLoading(){const e=this.getAttribute("dracoDecoderPath");e&&(ke&&console.log("using custom draco decoder path",e),ew(e));const t=this.getAttribute("dracoDecoderType");t&&(ke&&console.log("using custom draco decoder type",t),tw(t));const i=this.getAttribute("ktx2DecoderPath");i&&(ke&&console.log("using custom ktx2 decoder path",i),iw(i))}}typeof window<"u"&&!window.customElements.get(M1)&&window.customElements.define(M1,v0);function yI(o){if(o.startsWith("blob:"))return"blob";const e=o.split("/");let t=e[e.length-1];const i=t.indexOf("?");i>0&&(t=t.substring(0,i));const n=t.indexOf("=");n>0&&(t=t.substring(n));const s=t.split(".").pop(),r=s?["glb","gltf","usdz","usd","fbx","obj","mtl"].indexOf(s.toLowerCase()):-1;if(s&&r>=0&&(t=t.substring(0,t.length-s.length-1)),t=decodeURIComponent(t),t.length>3){let a="",l=!1;const c=["(",")","[","]","{","}",":",";",",",".","!","?"];for(let h=0;h<t.length;h++){let d=t[h];(d==="_"||d==="-")&&(d=" "),!(d===" "&&a.length<=0||c.includes(d)||(a.length===0&&(d=d.toUpperCase()),l&&d===" "))&&(l&&(d=d.toUpperCase()),l=!1,a+=d,d===" "&&(l=!0))}return E()&&t!==a&&console.debug('Generated display name: "'+t+'" \u2192 "'+a+'"'),a.trim()}return E()&&console.debug("Loading: use default name",t),t}function bI(o){hu(e=>{const t=o.getAttribute("loading-blur");if(t!==null&&t!=="0"&&e.domElement===o){const i=e.lodsManager.manager?.awaitLoading({frames:5,signal:AbortSignal.timeout(1e4),maxPromisesPerObject:1}).catch(r=>{});let n="20px";t.endsWith("px")&&(n=t);const s=170;if(e.scene.background===null){const r=o,a=e.renderer.domElement,l=a.style.filter,c=a.style.overflow;a.style.filter+=`blur(${n})`,r.style.overflow="hidden",i?.then(()=>{const h=a.animate([{filter:"blur(0px)"}],{duration:s,easing:"ease-in"});h.onfinish=()=>{a.style.filter=l,r.style.overflow=c}})}else{const r=document.createElement("div");e.domElement.prepend(r),r.style.cssText="position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 10; pointer-events: none",r.style.backdropFilter=`blur(${n})`,i?.then(()=>{const a=r.animate([{backdropFilter:"blur(0px)",opacity:0}],{duration:s,easing:"ease-in"});a.onfinish=()=>{r.remove()}})}}},{once:!0})}const _I=Object.freeze(Object.defineProperty({__proto__:null,NeedleEngineWebComponent:v0},Symbol.toStringTag,{value:"Module"}));function vI(){Tn.registerWaitForInteraction(()=>{const o=hC.getContext();o.addEventListener("statechange",()=>{setTimeout(()=>{const e=o.state;(e==="suspended"||e==="interrupted")&&o.resume().then(()=>{console.log("AudioContext resumed successfully")}).catch(t=>{console.log("Failed to resume AudioContext: "+t)})},500)})})}setTimeout(vI,1e3);const tt=w("debugphysics"),w0=w("debugcolliderplacement"),x0=w("debugcollisions"),wI=w("showcolliders"),Vp=w("debugraycasts"),gi=Symbol("needle component"),Kt=Symbol("physics body"),E1=Symbol("rigidbody");globalThis.NEEDLE_USE_RAPIER=globalThis.NEEDLE_USE_RAPIER!==void 0?globalThis.NEEDLE_USE_RAPIER:!0,tt&&console.log("Use Rapier",!0,globalThis.NEEDLE_USE_RAPIER),ue.registerCallback(he.ContextCreationStart,o=>{tt&&console.log("Register rapier physics backend"),o.context.physics.engine=new jl(o.context)});class jl{debugRenderColliders=!1;debugRenderRaycasts=!1;removeBody(e){if(!e)return;this.validate();const t=e[Kt];if(e[Kt]=null,t&&this.world){const i=this.objects.findIndex(n=>n===e);if(i>=0){const n=this.bodies[i];if(this.bodies.splice(i,1),this.objects.splice(i,1),n instanceof T.RAPIER_PHYSICS.MODULE.Collider){const s=n;this.world?.removeCollider(s,!0);const r=s.parent();r&&r.numColliders()<=0&&(r[gi]||this.world?.removeRigidBody(r))}else n instanceof T.RAPIER_PHYSICS.MODULE.RigidBody&&(n.numColliders()<=0?this.world?.removeRigidBody(n):E()&&(n.did_log_removing||setTimeout(()=>{n.numColliders()>0&&(n.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)))}}}updateBody(e,t,i){if(this.validate(),!!this.enabled&&!(e.destroyed||!e.gameObject)&&!(!t&&!i))if(e.isCollider===!0)console.warn("TODO: implement updating collider position");else{const n=e,s=n[Kt];s&&this.syncPhysicsBody(n.gameObject,s,t,i)}}updateProperties(e){if(this.validate(),e.isCollider){const t=e,i=t[Kt];i&&(this.internalUpdateColliderProperties(t,i),t.sharedMaterial&&this.updatePhysicsMaterial(t))}else{const t=e,i=this.internal_getRigidbody(t);i&&this.internalUpdateRigidbodyProperties(t,i)}}addForce(e,t,i){this.validate();const n=this.internal_getRigidbody(e);n?n.addForce(t,i):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,i){this.validate();const n=this.internal_getRigidbody(e);n?n.applyImpulse(t,i):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();const t=this.internal_getRigidbody(e);return t?t.linvel():null}getAngularVelocity(e){this.validate();const 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,i){this.validate();const n=this.internal_getRigidbody(e);n?n.applyImpulse(t,i):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();const 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,i){this.validate();const n=this.internal_getRigidbody(e);n?n.setAngvel(t,i):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,i){this.validate();const n=this.internal_getRigidbody(e);n?n.setLinvel(t,i):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._initializePromise=this.internalInitialization()),this._initializePromise}async internalInitialization(){return w("__nophysics")?(console.warn("Physics are disabled"),!1):(tt&&console.log("Initialize rapier physics engine"),this._hasCreatedWorld?(console.error("Invalid call to create physics world: world is already created"),!0):(this._hasCreatedWorld=!0,T.RAPIER_PHYSICS.MAYBEMODULE==null&&(tt&&console.trace("Loading rapier physics engine"),await(await T.RAPIER_PHYSICS.load()).init()),tt&&console.log("Physics engine initialized, creating world..."),this._world=new T.RAPIER_PHYSICS.MODULE.World(this._gravity),this.rapierRay=new T.RAPIER_PHYSICS.MODULE.Ray({x:0,y:0,z:0},{x:0,y:0,z:1}),this.enabled=!0,this._isInitialized=!0,tt&&console.log("Physics world created"),!0))}validate(){this._isInitialized||tt&&(this._lastWarnTime=this._lastWarnTime??0,Date.now()-this._lastWarnTime>1e3&&(this._lastWarnTime=Date.now(),console.warn("Physics engine is not initialized")))}rapierRay;raycastVectorsBuffer=new wi(()=>new b,10);raycast(e,t,i){if(!this._isInitialized)return console.log("Physics engine is not initialized"),null;let n=i?.maxDistance,s=i?.solid;n===void 0&&(n=1/0),s===void 0&&(s=!0);const r=this.getPhysicsRay(this.rapierRay,e,t);if(!r)return null;(this.debugRenderRaycasts||Vp)&&F.DrawRay(r.origin,r.dir,255,1);const a=this.world?.castRay(r,n,s,i?.queryFilterFlags,i?.filterGroups,void 0,void 0,l=>{const c=l[gi];return i?.filterPredicate?i.filterPredicate(c):i?.useIgnoreRaycastLayer!==!1?!c?.gameObject.layers.isEnabled(2):!0});if(a){const l=r.pointAt(a.timeOfImpact),c=this.raycastVectorsBuffer.get();return c.set(l.x,l.y,l.z),{point:c,collider:a.collider[gi]}}return null}raycastAndGetNormal(e,t,i){if(!this._isInitialized)return null;let n=i?.maxDistance,s=i?.solid;n===void 0&&(n=1/0),s===void 0&&(s=!0);const r=this.getPhysicsRay(this.rapierRay,e,t);if(!r)return null;(this.debugRenderRaycasts||Vp)&&F.DrawRay(r.origin,r.dir,255,1);const a=this.world?.castRayAndGetNormal(r,n,s,i?.queryFilterFlags,i?.filterGroups,void 0,void 0,l=>{const c=l[gi];return i?.filterPredicate?i.filterPredicate(c):i?.useIgnoreRaycastLayer!==!1?!c?.gameObject.layers.isEnabled(2):!0});if(a){const l=r.pointAt(a.timeOfImpact),c=a.normal,h=this.raycastVectorsBuffer.get(),d=this.raycastVectorsBuffer.get();return h.set(l.x,l.y,l.z),d.set(c.x,c.y,c.z),{point:h,normal:d,collider:a.collider[gi]}}return null}getPhysicsRay(e,t,i){const n=this.context?.mainCamera;if(t===void 0){const a=this.context?.input.getPointerPosition(0);if(a)t=a;else return null}if(t.z===void 0){if(!n)return console.error("Can not perform raycast from 2d point - no main camera found"),null;const a=this.raycastVectorsBuffer.get();a.x=t.x,a.y=t.y,a.z=0,(a.x>1||a.y>1||a.y<-1||a.x<-1)&&(tt&&console.warn("Converting screenspace to raycast space",a),this.context?.input.convertScreenspaceToRaycastSpace(a)),a.unproject(n),t=a}const s=t;e.origin.x=s.x,e.origin.y=s.y,e.origin.z=s.z;const r=this.raycastVectorsBuffer.get();if(i)r.set(i.x,i.y,i.z);else{if(!n)return console.error("Can not perform raycast - no camera found"),null;r.set(e.origin.x,e.origin.y,e.origin.z);const a=Z(n);r.sub(a)}return r.normalize(),e.dir.x=r.x,e.dir.y=r.y,e.dir.z=r.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 T.RAPIER_PHYSICS.MODULE.Ball(t),this.rapierSphere.radius=t,(this.debugRenderRaycasts||Vp)&&F.DrawWireSphere(e,t,3359999,1),this.shapeOverlap(e,this.rapierIdentityRotation,this.rapierSphere)}boxOverlap(e,t,i=null){return i===null&&(i=this.rapierIdentityRotation),this.rapierBox??=new T.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||Vp)&&F.DrawWireBox(e,t,3359999,1,!0,i),this.shapeOverlap(e,i,this.rapierBox)}shapeOverlap(e,t,i){return this.rapierColliderArray.length=0,this._isInitialized?this.world?(this.world.intersectionsWithShape(e,t,i,n=>{const s=n[gi],r=new Cw(s.gameObject,s);return this.rapierColliderArray.push(r),!0},void 0,void 0,void 0,void 0,n=>n.isSensor()?!1:n[gi].gameObject.layers.isEnabled(2)==!1),this.rapierColliderArray):this.rapierColliderArray:this.rapierColliderArray}enabled=!1;get world(){return this._world}_tempPosition=new b;_tempQuaternion=new U;_tempScale=new b;_tempMatrix=new ee;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){tt&&console.warn("Physics are disabled");return}const i=e.gameObject,n=$e(i,this._tempPosition).multiply(t);n.multiplyScalar(.5),n.x<0&&(n.x=Math.abs(n.x)),n.y<0&&(n.y=Math.abs(n.y)),n.z<0&&(n.z=Math.abs(n.z));const s=1e-7;n.x<s&&(n.x=s),n.y<s&&(n.y=s),n.z<s&&(n.z=s);const r=T.RAPIER_PHYSICS.MODULE.ColliderDesc.cuboid(n.x,n.y,n.z);this.createCollider(e,r)}async addSphereCollider(e){if(this._isInitialized||await this.initialize(),!e.activeAndEnabled)return;if(!this.enabled){tt&&console.warn("Physics are disabled");return}const t=T.RAPIER_PHYSICS.MODULE.ColliderDesc.ball(.5);this.createCollider(e,t),this.updateProperties(e)}async addCapsuleCollider(e,t,i){if(this._isInitialized||await this.initialize(),!e.activeAndEnabled)return;if(!this.enabled){tt&&console.warn("Physics are disabled");return}const n=e.gameObject.worldScale;n.x=Math.abs(n.x),n.y=Math.abs(n.y);const s=i*n.x;t=Math.max(t,s);const r=D.clamp(t*.5*n.y-i*n.x,0,Number.MAX_SAFE_INTEGER),a=T.RAPIER_PHYSICS.MODULE.ColliderDesc.capsule(r,s);this.createCollider(e,a)}async addMeshCollider(e,t,i,n){let s=t.geometry;if(!s){tt&&console.warn("Missing mesh geometry",t.name);return}s.index?.array?.length||(console.warn(`Your MeshCollider is missing vertices or indices in the assined mesh "${t.name}". Consider providing an indexed geometry.`),s=LC(s));let r=null;const a=s.getAttribute("position");if(a instanceof B0){const d=a.count;r=new Float32Array(d*3);for(let p=0;p<d;p++){const g=a.getX(p),f=a.getY(p),m=a.getZ(p);r[p*3]=g,r[p*3+1]=f,r[p*3+2]=m}}else r=a.array;if(await this.initialize(),!this.enabled){tt&&console.warn("Physics are disabled");return}if(!e.activeAndEnabled)return;const l=s.index?.array,c=e.gameObject.worldScale.clone();if(n&&c.multiply(n),Math.abs(c.x-1)>1e-4||Math.abs(c.y-1)>1e-4||Math.abs(c.z-1)>1e-4){const d=`${s.uuid}_${c.x}_${c.y}_${c.z}_${i}`;if(this._meshCache.has(d))tt&&console.warn("Use cached mesh collider"),r=this._meshCache.get(d);else{(tt||E())&&console.debug(`[Performance] Your MeshCollider "${e.name}" is scaled: consider applying the scale to the collider mesh instead (${c.x}, ${c.y}, ${c.z})`);const p=new Float32Array(r.length);for(let g=0;g<r.length;g+=3)p[g]=r[g]*c.x,p[g+1]=r[g+1]*c.y,p[g+2]=r[g+2]*c.z;r=p,this._meshCache.set(d,p)}}const h=i?T.RAPIER_PHYSICS.MODULE.ColliderDesc.convexHull(r):T.RAPIER_PHYSICS.MODULE.ColliderDesc.trimesh(r,l);h&&this.createCollider(e,h)}updatePhysicsMaterial(e){if(!e)return;const t=e.sharedMaterial,i=e[Kt];if(i&&t){if(t.bounciness!==void 0&&i.setRestitution(t.bounciness),t.bounceCombine!==void 0)switch(t.bounceCombine){case yt.Average:i.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case yt.Maximum:i.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case yt.Minimum:i.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case yt.Multiply:i.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}if(t.dynamicFriction!==void 0&&i.setFriction(t.dynamicFriction),t.frictionCombine!==void 0)switch(t.frictionCombine){case yt.Average:i.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case yt.Maximum:i.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case yt.Minimum:i.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case yt.Multiply:i.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}}}getBody(e){return e?e[Kt]:null}getComponent(e){return e?e[gi]:null}createCollider(e,t){if(!this.world)throw new Error("Physics world not initialized");const i=this._tempMatrix;let n;e.attachedRigidbody?n=this.getRigidbody(e,this._tempMatrix):(tt&&console.log("Create collider without rigidbody",e.name),i.makeRotationFromQuaternion(be(e.gameObject)),i.setPosition(Z(e.gameObject))),i.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);const s=e.sharedMaterial;if(s){if(s.bounciness!==void 0&&t.setRestitution(s.bounciness),s.bounceCombine!==void 0)switch(s.bounceCombine){case yt.Average:t.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case yt.Maximum:t.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case yt.Minimum:t.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case yt.Multiply:t.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}if(s.dynamicFriction!==void 0&&t.setFriction(s.dynamicFriction),s.frictionCombine!==void 0)switch(s.frictionCombine){case yt.Average:t.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case yt.Maximum:t.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case yt.Minimum:t.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case yt.Multiply:t.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}}e.attachedRigidbody?.autoMass===!1&&(t.setDensity(1e-6),t.setMass(1e-6));try{const r=this.world.createCollider(t,n);return r[gi]=e,e[Kt]=r,r.setActiveEvents(T.RAPIER_PHYSICS.MODULE.ActiveEvents.COLLISION_EVENTS),r.setActiveCollisionTypes(T.RAPIER_PHYSICS.MODULE.ActiveCollisionTypes.ALL),this.objects.push(e),this.bodies.push(r),this.updateColliderCollisionGroups(e),r}catch(r){return console.error('Error creating collider "'+e.name+`"
1604
- Error:`,r),null}}updateColliderCollisionGroups(e){const t=e[Kt],i=e.membership;let n=0;if(i==null)n=65535;else for(let a=0;a<i.length;a++){const l=i[a];l>31?console.error(`Rapier only supports 32 layers, layer ${l} is not supported`):n|=1<<Math.floor(l)}const s=e.filter;let r=0;if(s==null)r=65535;else for(let a=0;a<s.length;a++){const l=s[a];l>31?console.error(`Rapier only supports 32 layers, layer ${l} is not supported`):r|=1<<Math.floor(l)}t.setCollisionGroups(n<<16|r)}getRigidbody(e,t){if(!this.world)throw new Error("Physics world not initialized");let i=null;if(e.attachedRigidbody){const n=e.attachedRigidbody;if(i=n[Kt],!i){const s=n.isKinematic&&!w0;tt&&console.log("Create rigidbody",s);const r=s?T.RAPIER_PHYSICS.MODULE.RigidBodyDesc.kinematicPositionBased():T.RAPIER_PHYSICS.MODULE.RigidBodyDesc.dynamic(),a=Z(e.attachedRigidbody.gameObject);r.setTranslation(a.x,a.y,a.z),r.setRotation(be(e.attachedRigidbody.gameObject)),r.centerOfMass=new T.RAPIER_PHYSICS.MODULE.Vector3(n.centerOfMass.x,n.centerOfMass.y,n.centerOfMass.z),i=this.world.createRigidBody(r),this.bodies.push(i),this.objects.push(n)}i[gi]=n,n[Kt]=i,this.internalUpdateRigidbodyProperties(n,i),this.getRigidbodyRelativeMatrix(e.gameObject,n.gameObject,t),e[E1]=i}else{const n=T.RAPIER_PHYSICS.MODULE.RigidBodyDesc.kinematicPositionBased(),s=Z(e.gameObject);n.setTranslation(s.x,s.y,s.z),n.setRotation(be(e.gameObject)),i=this.world.createRigidBody(n),t.identity(),i[gi]=null}return i}internal_getRigidbody(e){return e.isCollider===!0?e[E1]:e[Kt]}internalUpdateColliderProperties(e,t){const i=t.shape;let n=!1;switch(i.type){case T.RAPIER_PHYSICS.MODULE.ShapeType.Ball:{const p=i,g=e,f=e.gameObject,m=$e(f,this._tempPosition),y=Math.abs(g.radius*m.x);n=p.radius!==y,p.radius=y,n&&t.setShape(p);break}case T.RAPIER_PHYSICS.MODULE.ShapeType.Cuboid:const s=i,r=e,a=e.gameObject,l=$e(a,this._tempPosition),c=Math.abs(r.size.x*.5*l.x),h=Math.abs(r.size.y*.5*l.y),d=Math.abs(r.size.z*.5*l.z);n=s.halfExtents.x!==c||s.halfExtents.y!==h||s.halfExtents.z!==d,s.halfExtents.x=c,s.halfExtents.y=h,s.halfExtents.z=d,n&&t.setShape(s);break}if(n){const s=e.attachedRigidbody;s?.autoMass&&this.getBody(s)?.recomputeMassPropertiesFromColliders()}this.updateColliderCollisionGroups(e),e.isTrigger!==t.isSensor()&&t.setSensor(e.isTrigger)}internalUpdateRigidbodyProperties(e,t){if(t.enableCcd(e.collisionDetectionMode!==gu.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 i=0;i<t.numColliders();i++)t.collider(i).setDensity(1);t.recomputeMassPropertiesFromColliders()}else{t.setAdditionalMass(e.mass,!1);for(let i=0;i<t.numColliders();i++)t.collider(i).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(T.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicPositionBased,!1):t.setBodyType(T.RAPIER_PHYSICS.MODULE.RigidBodyType.Dynamic,!1)}lines;step(e){if(this.world&&this.enabled){if(this._isUpdatingPhysicsWorld=!0,this.eventQueue||(this.eventQueue=new T.RAPIER_PHYSICS.MODULE.EventQueue(!1)),e===void 0||e<=0){this._isUpdatingPhysicsWorld=!1;return}else if(e!==void 0){const t=D.lerp(this.world.timestep,e,.8);this.world.timestep=t}try{this.world.step(this.eventQueue)}catch(t){console.warn("Error running physics step",{timestep:this.world.timestep},t)}this._isUpdatingPhysicsWorld=!1}}postStep(){this.world&&this.enabled&&(this._isUpdatingPhysicsWorld=!0,this.syncObjects(),this._isUpdatingPhysicsWorld=!1,this.eventQueue&&!this.collisionHandler&&(this.collisionHandler=new xI(this.world,this.eventQueue)),this.collisionHandler&&(this.collisionHandler.handleCollisionEvents(),this.collisionHandler.update()),this.updateDebugRendering(this.world))}updateDebugRendering(e){if(tt||w0||wI||this.debugRenderColliders===!0){if(!this.lines){const i=new im({color:7855479,fog:!1}),n=new un;this.lines=new D0(n,i),this.lines.layers.disableAll(),this.lines.layers.enable(2)}this.lines.parent!==this.context?.scene&&this.context?.scene.add(this.lines);const t=e.debugRender();this.lines.geometry.setAttribute("position",new pt(t.vertices,3)),this.lines.geometry.setAttribute("color",new pt(t.colors,4)),(this.context.time.frame%30===0||this.lines.geometry.boundingSphere?.radius===0)&&this.lines.geometry.computeBoundingSphere()}else this.lines&&this.context?.scene.remove(this.lines)}syncObjects(){if(!w0)for(let e=0;e<this.bodies.length;e++){const t=this.objects[e],i=this.bodies[e],n=t;if(n?.isCollider===!0&&!n.attachedRigidbody){const l=i.parent();l?this.syncPhysicsBody(t.gameObject,l,!0,!0):this.syncPhysicsBody(t.gameObject,i,!0,!0);continue}const s=i.translation(),r=i.rotation();if(Number.isNaN(s.x)||Number.isNaN(r.x)){!n.__COLLIDER_NAN&&E()&&(console.warn("Collider has NaN values",n.name,n.gameObject,i),n.__COLLIDER_NAN=!0);continue}const a=t.center;if(a&&a.isVector3){this._tempQuaternion.set(r.x,r.y,r.z,r.w);const l=this._tempPosition.copy(a).applyQuaternion(this._tempQuaternion),c=$e(t.gameObject);l.multiply(c),s.x-=l.x,s.y-=l.y,s.z-=l.z}sr(t.gameObject,s.x,s.y,s.z),Dm(t.gameObject,r.x,r.y,r.z,r.w)}}syncPhysicsBody(e,t,i,n){if(t instanceof T.RAPIER_PHYSICS.MODULE.RigidBody){const s=Z(e,this._tempPosition),r=be(e,this._tempQuaternion);switch(t.bodyType()){case T.RAPIER_PHYSICS.MODULE.RigidBodyType.Fixed:case T.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicPositionBased:case T.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicVelocityBased:i&&t.setNextKinematicTranslation(s),n&&t.setNextKinematicRotation(r);break;default:i&&t.setTranslation(s,!1),n&&t.setRotation(r,!1);break}}else if(t instanceof T.RAPIER_PHYSICS.MODULE.Collider){e.matrixWorldNeedsUpdate&&e.updateWorldMatrix(!0,!1),e.matrixWorld.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const s=this._tempPosition,r=this._tempQuaternion,a=t[gi];if(this.tryApplyCenter(a,s),i){const l=t.translation();(l.x!==s.x||l.y!==s.y||l.z!==s.z)&&t.setTranslation(s)}if(n){const l=t.rotation();(l.x!==r.x||l.y!==r.y||l.z!==r.z||l.w!==r.w)&&t.setRotation(r)}}}_tempCenterPos=new b;_tempCenterVec=new b;_tempCenterQuaternion=new U;tryApplyCenter(e,t){const i=e.center;i&&e.gameObject&&(i.x!==0||i.y!==0||i.z!==0)&&(this._tempCenterPos.x=i.x,this._tempCenterPos.y=i.y,this._tempCenterPos.z=i.z,$e(e.gameObject,this._tempCenterVec),this._tempCenterPos.multiply(this._tempCenterVec),e.attachedRigidbody?this._tempCenterPos.applyQuaternion(e.gameObject.quaternion):(be(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(e,t,i,n){if(n===void 0&&(n=jl._matricesBuffer,n.length=0),e===t){const s=$e(e,this._tempPosition);i.makeScale(s.x,s.y,s.z);for(let r=n.length-1;r>=0;r--)i.multiply(n[r]);return i}return n.push(e.matrix),e.parent&&this.getRigidbodyRelativeMatrix(e.parent,t,i,n),i}static centerConnectionPos={x:0,y:0,z:0};static centerConnectionRot={x:0,y:0,z:0,w:1};addFixedJoint(e,t){if(!this.world){console.error("Physics world not initialized");return}const i=e[Kt],n=t[Kt];this.calculateJointRelativeMatrices(e.gameObject,t.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const s=T.RAPIER_PHYSICS.MODULE.JointData.fixed(jl.centerConnectionPos,jl.centerConnectionRot,this._tempPosition,this._tempQuaternion),r=this.world.createImpulseJoint(s,i,n,!0);tt&&console.log("ADD FIXED JOINT",r)}addHingeJoint(e,t,i,n){if(!this.world){console.error("Physics world not initialized");return}const s=e[Kt],r=t[Kt];this.calculateJointRelativeMatrices(e.gameObject,t.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const a=T.RAPIER_PHYSICS.MODULE.JointData.revolute(i,this._tempPosition,n),l=this.world.createImpulseJoint(a,s,r,!0);tt&&console.log("ADD HINGE JOINT",l)}calculateJointRelativeMatrices(e,t,i){e.updateWorldMatrix(!0,!1),t.updateWorldMatrix(!0,!1);const n=e.matrixWorld,s=t.matrixWorld;n.elements[0]=1,n.elements[5]=1,n.elements[10]=1,s.elements[0]=1,s.elements[5]=1,s.elements[10]=1,i.copy(s).premultiply(n.invert()).invert()}}class xI{world;eventQueue;constructor(e,t){this.world=e,this.eventQueue=t}activeCollisions=[];activeCollisionsStay=[];activeTriggers=[];handleCollisionEvents(){this.eventQueue&&this.world&&this.eventQueue.drainCollisionEvents((e,t,i)=>{const n=this.world.getCollider(e),s=this.world.getCollider(t);if(!n||!s)return;const r=n[gi],a=s[gi];x0&&console.log("EVT",r.name,a.name,i,n,s),r&&a&&(i?(this.onCollisionStarted(r,n,a,s),this.onCollisionStarted(a,s,r,n)):(this.onCollisionEnded(r,a),this.onCollisionEnded(a,r)))})}update(){this.onHandleCollisionStay()}onCollisionStarted(e,t,i,n){let s=null;if(e.isTrigger||i.isTrigger)wr(e.gameObject,r=>{r.onTriggerEnter&&!r.destroyed&&r.onTriggerEnter(i),this.activeTriggers.push({collider:e,component:r,otherCollider:i})});else{const r=e.gameObject;this.world.contactPair(t,n,(a,l)=>{wr(r,c=>{if(c.destroyed)return;const h=c.onCollisionEnter||c.onCollisionStay||c.onCollisionExit;if(h||x0){if(!s){const d=[],p=a.normal();i instanceof xs&&i.convex&&(p.x=-p.x,p.y=-p.y,p.z=-p.z);for(let g=0;g<a.numSolverContacts();g++){const f=a.solverContactPoint(g),m=a.contactImpulse(g);if(f){const y=a.contactDist(g),_=a.solverContactFriction(g),v=a.solverContactTangentVelocity(g),P=new xw(f,y,p,m,_,v);d.push(P),x0&&F.DrawDirection(f,p,16711680,3,!0)}}s=new Sw(r,i,d)}if(h){const d={collider:e,component:c,collision:s};this.activeCollisions.push(d),c.onCollisionStay&&this.activeCollisionsStay.push(d),c.onCollisionEnter?.call(c,s)}}})})}}onHandleCollisionStay(){for(const e of this.activeCollisionsStay){const t=e.component;if(!t.destroyed&&t.activeAndEnabled&&t.onCollisionStay){if(e.collision.collider.destroyed)continue;const i=e.collision;t.onCollisionStay(i)}}for(const e of this.activeTriggers){const t=e.component;if(!t.destroyed&&t.activeAndEnabled&&t.onTriggerStay){const i=e.otherCollider;if(i.destroyed)continue;t.onTriggerStay(i)}}}onCollisionEnded(e,t){if(!(e.destroyed||t.destroyed)){for(let i=0;i<this.activeCollisions.length;i++){const n=this.activeCollisions[i],s=n.collider;if(s.destroyed||n.collision.collider.destroyed){this.activeCollisions.splice(i,1),i--;continue}if(s===e&&n.collision.collider===t){const r=n.component;if(this.activeCollisions.splice(i,1),i--,r.activeAndEnabled&&r.onCollisionExit){const a=n.collision;r.onCollisionExit(a)}}}for(let i=0;i<this.activeCollisionsStay.length;i++){const n=this.activeCollisionsStay[i],s=n.collider;if(s.destroyed||n.collision.collider.destroyed){this.activeCollisionsStay.splice(i,1),i--;continue}if(s===e&&n.collision.collider===t){const r=n.component;if(this.activeCollisionsStay.splice(i,1),i--,r.activeAndEnabled&&r.onCollisionExit){const a=n.collision;r.onCollisionExit(a)}}}for(let i=0;i<this.activeTriggers.length;i++){const n=this.activeTriggers[i],s=n.collider;if(s.destroyed||n.otherCollider.destroyed){this.activeTriggers.splice(i,1),i--;continue}if(s===e&&n.otherCollider===t){const r=n.component;if(this.activeTriggers.splice(i,1),i--,r.activeAndEnabled&&r.onTriggerExit){const a=n.otherCollider;r.onTriggerExit(a)}}}}}}class SI{static async createComparisonScene(e){const{files:t}=e,i=await Promise.all(t.map(f=>new ie(f).loadAssetAsync())),n=new yi;let s=0;for(const f of i)if(f instanceof O){f.position.y=s,n.add(f);const m=Wt([f]);s+=m.getSize(new b).y,s+=.1}const r=new de(20);n.add(r);const a=e.environment||"https://dl.polyhaven.org/file/ph-assets/HDRIs/exr/1k/studio_small_09_1k.exr";{let f=null;if(a.endsWith(".hdr")){const m=(await import("./three-examples-Bph291U2.min.js").then(y=>y.RGBELoader$1)).RGBELoader;f=new m}else if(a.endsWith(".exr")){const m=(await import("./three-examples-Bph291U2.min.js").then(y=>y.EXRLoader$1)).EXRLoader;f=new m}if(f){const m=await f.loadAsync(a).catch(y=>(console.error(y),null));m&&(m.mapping=mo,m.needsUpdate=!0,n.background=m,n.environment=m,n.backgroundBlurriness=.75)}else console.warn("Unsupported environment map format",a)}const l=Wt(n.children),c=l.getCenter(new b),h=l.getSize(new b),d=Math.max(h.x,h.y,h.z)/(2*Math.tan(Math.PI*r.fov/360));r.position.set(c.x,c.y,d),r.lookAt(c);const p=new Y0(r,e.domElement||document.body);p.target=c,p.update();const g=(e.domElement||document.body).getBoundingClientRect();return r.aspect=g.width/g.height,r.updateProjectionMatrix(),{scene:n,camera:r}}}let S0=0;function A1(o){o?S0++:S0--}function CI(){return S0>0}const PI={binary:!0,animations:!0};async function OI(o){if(!o.context)throw new Error("No context provided to exportAsGLTF");o.scene||(o.scene=o.context.scene);const e={...PI,...o},{context:t}=e,i=new K0;i.register(a=>new Gw(a)),i.register(a=>new $R(a)),i.register(a=>new Uw(a)),If(i,e.context);const n={binary:e.binary,animations:MI(t,e.scene,[])},s=new kI;console.debug("Exporting GLTF",n),s.onBeforeExport(e),A1(!0);const r=await i.parseAsync(e.scene,n).catch(a=>(console.error(a),null));if(A1(!1),s.onAfterExport(e),!r)throw new Error("Failed to export GLTF");if(e.downloadAs!=null){let a=null;if(r instanceof ArrayBuffer?a=new Blob([r],{type:"application/octet-stream"}):console.error("Can not download GLTF as a blob",r),a){const l=URL.createObjectURL(a),c=document.createElement("a");c.href=l;let h=e.downloadAs;!h.endsWith(".glb")&&!h.endsWith(".gltf")&&(h+=e.binary?".glb":".gltf"),c.download=h,c.click()}}return r}const I1=Symbol("needle:weight");class kI{_undo=[];onBeforeExport(e){e.context.animations.mixers.forEach(t=>{const i=Ba.tryGetActionsFromMixer(t);if(i)for(let n=0;n<i.length;n++){const s=i[n];s[I1]=s.weight,s.weight=0,this._undo.push(()=>{s.weight=s[I1]})}t.update(0)}),e.context.scene.traverse(t=>{if(!Mf(t)){const i=t.parent;i&&(t.removeFromParent(),this._undo.push(()=>i.add(t)))}})}onAfterExport(e){this._undo.forEach(t=>t()),this._undo.length=0}}function MI(o,e,t){o.animations.mixers.forEach(n=>{const s=Ba.tryGetActionsFromMixer(n);if(s)for(let r=0;r<s.length;r++){const a=s[r].getClip();t.push(a)}}),Array.isArray(e)||(e=[e]);for(const n of e)Ba.tryGetAnimationClipsFromObjectHierarchy(n,t);const i=new Set(t);return Array.from(i)}const L1="needle-button",C0=E();class j1 extends HTMLElement{static observedAttributes=["ar","vr","quicklook"];constructor(){super(),this.removeEventListener("click",this.#r),this.addEventListener("click",this.#r)}attributeChangedCallback(e,t,i){this.#a()}#t;#n;#o;#e;#i;#s;#a(){if(this.#e?.remove(),this.getAttribute("ar")!=null)this.#i??=new Qs,this.#e=this.#i.createARButton();else if(this.getAttribute("vr")!=null)this.#i??=new Qs,this.#e=this.#i.createVRButton();else if(this.getAttribute("quicklook")!=null)this.#i??=new Qs,this.#e=this.#i.createQuicklookButton();else{C0?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.");return}this.#t??=this.attachShadow({mode:"open"}),this.#n??=document.createElement("slot"),this.#o??=document.createElement("style"),this.#o.innerHTML=`
1580
+ `,e,`Aborted? ${h.signal.aborted}`),h.signal.aborted){console.log("Loading finished but aborted...");return}if(this._loadId!==t){console.log("Load id changed during loading process");return}this._loadingProgress01=1,s&&m&&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:i,loadedFiles:r}}))}applyAttributes(){if(this._context?.renderer){const n=Wv(this.toneMapping);n!==void 0&&(this._context.renderer.toneMapping=n);const s=this.getAttribute("tone-mapping-exposure");if(s!=null){const r=parseFloat(s);isNaN(r)||(this._context.renderer.toneMappingExposure=r)}}const e=this.getAttribute("background-blurriness");if(e!=null){const n=parseFloat(e);!isNaN(n)&&this._context&&(this._context.scene.backgroundBlurriness=n)}const t=this.getAttribute("environment-intensity");if(t!=null&&this._context){const n=parseFloat(t);!isNaN(n)&&this._context&&(this._context.scene.environmentIntensity=n)}const i=this.getAttribute("background-color");if(this._context?.renderer&&typeof i=="string"&&i.length>0){const n=se.fromColorRepresentation(i);ke&&console.debug("<needle-engine> background-color changed, str:",i,"\u2192",n),this._context.renderer.setClearColor(n,n.alpha),this.context.scene.background=null}}onXRSessionStarted=()=>{const e=this.context.xrSessionMode;e==="immersive-ar"?this.onEnterAR(this.context.xrSession):e==="immersive-vr"&&this.onEnterVR(this.context.xrSession),this.context.xrSession?.addEventListener("end",()=>{this.dispatchEvent(new CustomEvent("xr-session-ended",{detail:{session:this.context.xrSession,context:this._context,sessionMode:e}})),e==="immersive-ar"?this.onExitAR(this.context.xrSession):e==="immersive-vr"&&this.onExitVR(this.context.xrSession)})};onReady=()=>this._loadingView?.onLoadingFinished();onError=()=>this._loadingView?.setMessage("Loading failed!");getSourceFiles(){const e=this.getAttribute("src");if(!e)return[];let t;Array.isArray(e)?t=e:e.startsWith("[")&&e.endsWith("]")?t=JSON.parse(e):e.includes(",")?t=e.split(","):t=[e];for(let i=t.length-1;i>=0;i--){const n=t[i];(n==="null"||n==="undefined"||n?.length<=0)&&t.splice(i,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 i=0;i<e?.length;i++)if(e[i]!==t[i])return!0}return!1}_previouslyRegisteredMap=new Map;ensureLoadStartIsRegistered(){const e=this.getAttribute("loadstart");e&&this.registerEventFromAttribute("loadstart",e)}registerEventFromAttribute(e,t){const i=this._previouslyRegisteredMap.get(e);if(i&&(this._previouslyRegisteredMap.delete(e),this.removeEventListener(e,i)),typeof t=="string"&&t.length>0)try{const n=(0,eval)(t);typeof n=="function"&&(this._previouslyRegisteredMap.set(e,n),this.addEventListener(e,s=>n?.call(globalThis,this._context,s)))}catch(n){console.error("Error registering event "+e+'="'+t+`" failed with the following error:
1581
+ `,n)}}setPublicKey(){xa&&xa.length>0&&this.setAttribute("public-key",xa)}setVersion(){mn.length>0&&this.setAttribute("version",mn)}getAROverlayContainer(){return this._overlay_ar.createOverlayContainer(this)}getVROverlayContainer(){for(let e=0;e<this.children.length;e++){const t=this.children[e];if(t.classList.contains("vr"))return t}return null}onEnterAR(e){this.onSetupAR();const t=this.getAROverlayContainer();this._overlay_ar.onBegin(this._context,t,e),this.dispatchEvent(new CustomEvent("enter-ar",{detail:{session:e,context:this._context,htmlContainer:this._overlay_ar?.ARContainer}}))}onExitAR(e){this._overlay_ar.onEnd(this._context),this.onSetupDesktop(),this.dispatchEvent(new CustomEvent("exit-ar",{detail:{session:e,context:this._context,htmlContainer:this._overlay_ar?.ARContainer}}))}onEnterVR(e){this.onSetupVR(),this.dispatchEvent(new CustomEvent("enter-vr",{detail:{session:e,context:this._context}}))}onExitVR(e){this.onSetupDesktop(),this.dispatchEvent(new CustomEvent("exit-vr",{detail:{session:e,context:this._context}}))}onSetupAR(){this.classList.add(Vh),this.classList.remove($h);const e=this.getAROverlayContainer();ke&&console.warn("onSetupAR:",e),e&&(e.classList.add(Vh),e.classList.remove($h)),this.foreachHtmlElement(t=>this.setupElementsForMode(t,P1))}onSetupVR(){this.classList.remove(Vh),this.classList.remove($h),this.foreachHtmlElement(e=>this.setupElementsForMode(e,R1))}onSetupDesktop(){this.classList.remove(Vh),this.classList.add($h);const e=this.getAROverlayContainer();e&&(e.classList.remove(Vh),e.classList.add($h)),this.foreachHtmlElement(t=>this.setupElementsForMode(t,T1))}setupElementsForMode(e,t,i=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(const n of gI)e.classList.contains(n)&&(e.style.visibility="hidden",e.style.display="none")}foreachHtmlElement(e){for(let t=0;t<this.children.length;t++){const i=this.children[t];i.style&&e(i)}}onBeforeBeginLoading(){const e=this.getAttribute("dracoDecoderPath");e&&(ke&&console.log("using custom draco decoder path",e),ew(e));const t=this.getAttribute("dracoDecoderType");t&&(ke&&console.log("using custom draco decoder type",t),tw(t));const i=this.getAttribute("ktx2DecoderPath");i&&(ke&&console.log("using custom ktx2 decoder path",i),iw(i))}}typeof window<"u"&&!window.customElements.get(M1)&&window.customElements.define(M1,v0);function yI(o){if(o.startsWith("blob:"))return"blob";const e=o.split("/");let t=e[e.length-1];const i=t.indexOf("?");i>0&&(t=t.substring(0,i));const n=t.indexOf("=");n>0&&(t=t.substring(n));const s=t.split(".").pop(),r=s?["glb","gltf","usdz","usd","fbx","obj","mtl"].indexOf(s.toLowerCase()):-1;if(s&&r>=0&&(t=t.substring(0,t.length-s.length-1)),t=decodeURIComponent(t),t.length>3){let a="",l=!1;const c=["(",")","[","]","{","}",":",";",",",".","!","?"];for(let h=0;h<t.length;h++){let d=t[h];(d==="_"||d==="-")&&(d=" "),!(d===" "&&a.length<=0||c.includes(d)||(a.length===0&&(d=d.toUpperCase()),l&&d===" "))&&(l&&(d=d.toUpperCase()),l=!1,a+=d,d===" "&&(l=!0))}return E()&&t!==a&&console.debug('Generated display name: "'+t+'" \u2192 "'+a+'"'),a.trim()}return E()&&console.debug("Loading: use default name",t),t}function bI(o){hu(e=>{const t=o.getAttribute("loading-blur");if(t!==null&&t!=="0"&&e.domElement===o){const i=e.lodsManager.manager?.awaitLoading({frames:5,signal:AbortSignal.timeout(1e4),maxPromisesPerObject:1}).catch(r=>{});let n="20px";t.endsWith("px")&&(n=t);const s=170;if(e.scene.background===null){const r=o,a=e.renderer.domElement,l=a.style.filter,c=a.style.overflow;a.style.filter+=`blur(${n})`,r.style.overflow="hidden",i?.then(()=>{const h=a.animate([{filter:"blur(0px)"}],{duration:s,easing:"ease-in"});h.onfinish=()=>{a.style.filter=l,r.style.overflow=c}})}else{const r=document.createElement("div");e.domElement.prepend(r),r.style.cssText="position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 10; pointer-events: none",r.style.backdropFilter=`blur(${n})`,i?.then(()=>{const a=r.animate([{backdropFilter:"blur(0px)",opacity:0}],{duration:s,easing:"ease-in"});a.onfinish=()=>{r.remove()}})}}},{once:!0})}const _I=Object.freeze(Object.defineProperty({__proto__:null,NeedleEngineWebComponent:v0},Symbol.toStringTag,{value:"Module"}));function vI(){Tn.registerWaitForInteraction(()=>{const o=hC.getContext();o.addEventListener("statechange",()=>{setTimeout(()=>{const e=o.state;(e==="suspended"||e==="interrupted")&&o.resume().then(()=>{console.log("AudioContext resumed successfully")}).catch(t=>{console.log("Failed to resume AudioContext: "+t)})},500)})})}setTimeout(vI,1e3);const tt=w("debugphysics"),w0=w("debugcolliderplacement"),x0=w("debugcollisions"),wI=w("showcolliders"),Vp=w("debugraycasts"),gi=Symbol("needle component"),Kt=Symbol("physics body"),E1=Symbol("rigidbody");globalThis.NEEDLE_USE_RAPIER=globalThis.NEEDLE_USE_RAPIER!==void 0?globalThis.NEEDLE_USE_RAPIER:!0,tt&&console.log("Use Rapier",!0,globalThis.NEEDLE_USE_RAPIER),ue.registerCallback(he.ContextCreationStart,o=>{tt&&console.log("Register rapier physics backend"),o.context.physics.engine=new jl(o.context)});class jl{debugRenderColliders=!1;debugRenderRaycasts=!1;removeBody(e){if(!e)return;this.validate();const t=e[Kt];if(e[Kt]=null,t&&this.world){const i=this.objects.findIndex(n=>n===e);if(i>=0){const n=this.bodies[i];if(this.bodies.splice(i,1),this.objects.splice(i,1),n instanceof T.RAPIER_PHYSICS.MODULE.Collider){const s=n;this.world?.removeCollider(s,!0);const r=s.parent();r&&r.numColliders()<=0&&(r[gi]||this.world?.removeRigidBody(r))}else n instanceof T.RAPIER_PHYSICS.MODULE.RigidBody&&(n.numColliders()<=0?this.world?.removeRigidBody(n):E()&&(n.did_log_removing||setTimeout(()=>{n.numColliders()>0&&(n.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)))}}}updateBody(e,t,i){if(this.validate(),!!this.enabled&&!(e.destroyed||!e.gameObject)&&!(!t&&!i))if(e.isCollider===!0)console.warn("TODO: implement updating collider position");else{const n=e,s=n[Kt];s&&this.syncPhysicsBody(n.gameObject,s,t,i)}}updateProperties(e){if(this.validate(),e.isCollider){const t=e,i=t[Kt];i&&(this.internalUpdateColliderProperties(t,i),t.sharedMaterial&&this.updatePhysicsMaterial(t))}else{const t=e,i=this.internal_getRigidbody(t);i&&this.internalUpdateRigidbodyProperties(t,i)}}addForce(e,t,i){this.validate();const n=this.internal_getRigidbody(e);n?n.addForce(t,i):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,i){this.validate();const n=this.internal_getRigidbody(e);n?n.applyImpulse(t,i):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();const t=this.internal_getRigidbody(e);return t?t.linvel():null}getAngularVelocity(e){this.validate();const 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,i){this.validate();const n=this.internal_getRigidbody(e);n?n.applyImpulse(t,i):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();const 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,i){this.validate();const n=this.internal_getRigidbody(e);n?n.setAngvel(t,i):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,i){this.validate();const n=this.internal_getRigidbody(e);n?n.setLinvel(t,i):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._initializePromise=this.internalInitialization()),this._initializePromise}async internalInitialization(){return w("__nophysics")?(console.warn("Physics are disabled"),!1):(tt&&console.log("Initialize rapier physics engine"),this._hasCreatedWorld?(console.error("Invalid call to create physics world: world is already created"),!0):(this._hasCreatedWorld=!0,T.RAPIER_PHYSICS.MAYBEMODULE==null&&(tt&&console.trace("Loading rapier physics engine"),await(await T.RAPIER_PHYSICS.load()).init()),tt&&console.log("Physics engine initialized, creating world..."),this._world=new T.RAPIER_PHYSICS.MODULE.World(this._gravity),this.rapierRay=new T.RAPIER_PHYSICS.MODULE.Ray({x:0,y:0,z:0},{x:0,y:0,z:1}),this.enabled=!0,this._isInitialized=!0,tt&&console.log("Physics world created"),!0))}validate(){this._isInitialized||tt&&(this._lastWarnTime=this._lastWarnTime??0,Date.now()-this._lastWarnTime>1e3&&(this._lastWarnTime=Date.now(),console.warn("Physics engine is not initialized")))}rapierRay;raycastVectorsBuffer=new wi(()=>new b,10);raycast(e,t,i){if(!this._isInitialized)return console.log("Physics engine is not initialized"),null;let n=i?.maxDistance,s=i?.solid;n===void 0&&(n=1/0),s===void 0&&(s=!0);const r=this.getPhysicsRay(this.rapierRay,e,t);if(!r)return null;(this.debugRenderRaycasts||Vp)&&F.DrawRay(r.origin,r.dir,255,1);const a=this.world?.castRay(r,n,s,i?.queryFilterFlags,i?.filterGroups,void 0,void 0,l=>{const c=l[gi];return i?.filterPredicate?i.filterPredicate(c):i?.useIgnoreRaycastLayer!==!1?!c?.gameObject.layers.isEnabled(2):!0});if(a){const l=r.pointAt(a.timeOfImpact),c=this.raycastVectorsBuffer.get();return c.set(l.x,l.y,l.z),{point:c,collider:a.collider[gi]}}return null}raycastAndGetNormal(e,t,i){if(!this._isInitialized)return null;let n=i?.maxDistance,s=i?.solid;n===void 0&&(n=1/0),s===void 0&&(s=!0);const r=this.getPhysicsRay(this.rapierRay,e,t);if(!r)return null;(this.debugRenderRaycasts||Vp)&&F.DrawRay(r.origin,r.dir,255,1);const a=this.world?.castRayAndGetNormal(r,n,s,i?.queryFilterFlags,i?.filterGroups,void 0,void 0,l=>{const c=l[gi];return i?.filterPredicate?i.filterPredicate(c):i?.useIgnoreRaycastLayer!==!1?!c?.gameObject.layers.isEnabled(2):!0});if(a){const l=r.pointAt(a.timeOfImpact),c=a.normal,h=this.raycastVectorsBuffer.get(),d=this.raycastVectorsBuffer.get();return h.set(l.x,l.y,l.z),d.set(c.x,c.y,c.z),{point:h,normal:d,collider:a.collider[gi]}}return null}getPhysicsRay(e,t,i){const n=this.context?.mainCamera;if(t===void 0){const a=this.context?.input.getPointerPosition(0);if(a)t=a;else return null}if(t.z===void 0){if(!n)return console.error("Can not perform raycast from 2d point - no main camera found"),null;const a=this.raycastVectorsBuffer.get();a.x=t.x,a.y=t.y,a.z=0,(a.x>1||a.y>1||a.y<-1||a.x<-1)&&(tt&&console.warn("Converting screenspace to raycast space",a),this.context?.input.convertScreenspaceToRaycastSpace(a)),a.unproject(n),t=a}const s=t;e.origin.x=s.x,e.origin.y=s.y,e.origin.z=s.z;const r=this.raycastVectorsBuffer.get();if(i)r.set(i.x,i.y,i.z);else{if(!n)return console.error("Can not perform raycast - no camera found"),null;r.set(e.origin.x,e.origin.y,e.origin.z);const a=Z(n);r.sub(a)}return r.normalize(),e.dir.x=r.x,e.dir.y=r.y,e.dir.z=r.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 T.RAPIER_PHYSICS.MODULE.Ball(t),this.rapierSphere.radius=t,(this.debugRenderRaycasts||Vp)&&F.DrawWireSphere(e,t,3359999,1),this.shapeOverlap(e,this.rapierIdentityRotation,this.rapierSphere)}boxOverlap(e,t,i=null){return i===null&&(i=this.rapierIdentityRotation),this.rapierBox??=new T.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||Vp)&&F.DrawWireBox(e,t,3359999,1,!0,i),this.shapeOverlap(e,i,this.rapierBox)}shapeOverlap(e,t,i){return this.rapierColliderArray.length=0,this._isInitialized?this.world?(this.world.intersectionsWithShape(e,t,i,n=>{const s=n[gi],r=new Cw(s.gameObject,s);return this.rapierColliderArray.push(r),!0},void 0,void 0,void 0,void 0,n=>n.isSensor()?!1:n[gi].gameObject.layers.isEnabled(2)==!1),this.rapierColliderArray):this.rapierColliderArray:this.rapierColliderArray}enabled=!1;get world(){return this._world}_tempPosition=new b;_tempQuaternion=new U;_tempScale=new b;_tempMatrix=new ee;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){tt&&console.warn("Physics are disabled");return}const i=e.gameObject,n=$e(i,this._tempPosition).multiply(t);n.multiplyScalar(.5),n.x<0&&(n.x=Math.abs(n.x)),n.y<0&&(n.y=Math.abs(n.y)),n.z<0&&(n.z=Math.abs(n.z));const s=1e-7;n.x<s&&(n.x=s),n.y<s&&(n.y=s),n.z<s&&(n.z=s);const r=T.RAPIER_PHYSICS.MODULE.ColliderDesc.cuboid(n.x,n.y,n.z);this.createCollider(e,r)}async addSphereCollider(e){if(this._isInitialized||await this.initialize(),!e.activeAndEnabled)return;if(!this.enabled){tt&&console.warn("Physics are disabled");return}const t=T.RAPIER_PHYSICS.MODULE.ColliderDesc.ball(.5);this.createCollider(e,t),this.updateProperties(e)}async addCapsuleCollider(e,t,i){if(this._isInitialized||await this.initialize(),!e.activeAndEnabled)return;if(!this.enabled){tt&&console.warn("Physics are disabled");return}const n=e.gameObject.worldScale;n.x=Math.abs(n.x),n.y=Math.abs(n.y);const s=i*n.x;t=Math.max(t,s);const r=D.clamp(t*.5*n.y-i*n.x,0,Number.MAX_SAFE_INTEGER),a=T.RAPIER_PHYSICS.MODULE.ColliderDesc.capsule(r,s);this.createCollider(e,a)}async addMeshCollider(e,t,i,n){let s=t.geometry;if(!s){tt&&console.warn("Missing mesh geometry",t.name);return}s.index?.array?.length||(console.warn(`Your MeshCollider is missing vertices or indices in the assined mesh "${t.name}". Consider providing an indexed geometry.`),s=LC(s));let r=null;const a=s.getAttribute("position");if(a instanceof B0){const d=a.count;r=new Float32Array(d*3);for(let p=0;p<d;p++){const m=a.getX(p),f=a.getY(p),g=a.getZ(p);r[p*3]=m,r[p*3+1]=f,r[p*3+2]=g}}else r=a.array;if(await this.initialize(),!this.enabled){tt&&console.warn("Physics are disabled");return}if(!e.activeAndEnabled)return;const l=s.index?.array,c=e.gameObject.worldScale.clone();if(n&&c.multiply(n),Math.abs(c.x-1)>1e-4||Math.abs(c.y-1)>1e-4||Math.abs(c.z-1)>1e-4){const d=`${s.uuid}_${c.x}_${c.y}_${c.z}_${i}`;if(this._meshCache.has(d))tt&&console.warn("Use cached mesh collider"),r=this._meshCache.get(d);else{(tt||E())&&console.debug(`[Performance] Your MeshCollider "${e.name}" is scaled: consider applying the scale to the collider mesh instead (${c.x}, ${c.y}, ${c.z})`);const p=new Float32Array(r.length);for(let m=0;m<r.length;m+=3)p[m]=r[m]*c.x,p[m+1]=r[m+1]*c.y,p[m+2]=r[m+2]*c.z;r=p,this._meshCache.set(d,p)}}const h=i?T.RAPIER_PHYSICS.MODULE.ColliderDesc.convexHull(r):T.RAPIER_PHYSICS.MODULE.ColliderDesc.trimesh(r,l);h&&this.createCollider(e,h)}updatePhysicsMaterial(e){if(!e)return;const t=e.sharedMaterial,i=e[Kt];if(i&&t){if(t.bounciness!==void 0&&i.setRestitution(t.bounciness),t.bounceCombine!==void 0)switch(t.bounceCombine){case yt.Average:i.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case yt.Maximum:i.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case yt.Minimum:i.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case yt.Multiply:i.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}if(t.dynamicFriction!==void 0&&i.setFriction(t.dynamicFriction),t.frictionCombine!==void 0)switch(t.frictionCombine){case yt.Average:i.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case yt.Maximum:i.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case yt.Minimum:i.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case yt.Multiply:i.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}}}getBody(e){return e?e[Kt]:null}getComponent(e){return e?e[gi]:null}createCollider(e,t){if(!this.world)throw new Error("Physics world not initialized");const i=this._tempMatrix;let n;e.attachedRigidbody?n=this.getRigidbody(e,this._tempMatrix):(tt&&console.log("Create collider without rigidbody",e.name),i.makeRotationFromQuaternion(be(e.gameObject)),i.setPosition(Z(e.gameObject))),i.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);const s=e.sharedMaterial;if(s){if(s.bounciness!==void 0&&t.setRestitution(s.bounciness),s.bounceCombine!==void 0)switch(s.bounceCombine){case yt.Average:t.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case yt.Maximum:t.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case yt.Minimum:t.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case yt.Multiply:t.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}if(s.dynamicFriction!==void 0&&t.setFriction(s.dynamicFriction),s.frictionCombine!==void 0)switch(s.frictionCombine){case yt.Average:t.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case yt.Maximum:t.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case yt.Minimum:t.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case yt.Multiply:t.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}}e.attachedRigidbody?.autoMass===!1&&(t.setDensity(1e-6),t.setMass(1e-6));try{const r=this.world.createCollider(t,n);return r[gi]=e,e[Kt]=r,r.setActiveEvents(T.RAPIER_PHYSICS.MODULE.ActiveEvents.COLLISION_EVENTS),r.setActiveCollisionTypes(T.RAPIER_PHYSICS.MODULE.ActiveCollisionTypes.ALL),this.objects.push(e),this.bodies.push(r),this.updateColliderCollisionGroups(e),r}catch(r){return console.error('Error creating collider "'+e.name+`"
1582
+ Error:`,r),null}}updateColliderCollisionGroups(e){const t=e[Kt],i=e.membership;let n=0;if(i==null)n=65535;else for(let a=0;a<i.length;a++){const l=i[a];l>31?console.error(`Rapier only supports 32 layers, layer ${l} is not supported`):n|=1<<Math.floor(l)}const s=e.filter;let r=0;if(s==null)r=65535;else for(let a=0;a<s.length;a++){const l=s[a];l>31?console.error(`Rapier only supports 32 layers, layer ${l} is not supported`):r|=1<<Math.floor(l)}t.setCollisionGroups(n<<16|r)}getRigidbody(e,t){if(!this.world)throw new Error("Physics world not initialized");let i=null;if(e.attachedRigidbody){const n=e.attachedRigidbody;if(i=n[Kt],!i){const s=n.isKinematic&&!w0;tt&&console.log("Create rigidbody",s);const r=s?T.RAPIER_PHYSICS.MODULE.RigidBodyDesc.kinematicPositionBased():T.RAPIER_PHYSICS.MODULE.RigidBodyDesc.dynamic(),a=Z(e.attachedRigidbody.gameObject);r.setTranslation(a.x,a.y,a.z),r.setRotation(be(e.attachedRigidbody.gameObject)),r.centerOfMass=new T.RAPIER_PHYSICS.MODULE.Vector3(n.centerOfMass.x,n.centerOfMass.y,n.centerOfMass.z),i=this.world.createRigidBody(r),this.bodies.push(i),this.objects.push(n)}i[gi]=n,n[Kt]=i,this.internalUpdateRigidbodyProperties(n,i),this.getRigidbodyRelativeMatrix(e.gameObject,n.gameObject,t),e[E1]=i}else{const n=T.RAPIER_PHYSICS.MODULE.RigidBodyDesc.kinematicPositionBased(),s=Z(e.gameObject);n.setTranslation(s.x,s.y,s.z),n.setRotation(be(e.gameObject)),i=this.world.createRigidBody(n),t.identity(),i[gi]=null}return i}internal_getRigidbody(e){return e.isCollider===!0?e[E1]:e[Kt]}internalUpdateColliderProperties(e,t){const i=t.shape;let n=!1;switch(i.type){case T.RAPIER_PHYSICS.MODULE.ShapeType.Ball:{const p=i,m=e,f=e.gameObject,g=$e(f,this._tempPosition),y=Math.abs(m.radius*g.x);n=p.radius!==y,p.radius=y,n&&t.setShape(p);break}case T.RAPIER_PHYSICS.MODULE.ShapeType.Cuboid:const s=i,r=e,a=e.gameObject,l=$e(a,this._tempPosition),c=Math.abs(r.size.x*.5*l.x),h=Math.abs(r.size.y*.5*l.y),d=Math.abs(r.size.z*.5*l.z);n=s.halfExtents.x!==c||s.halfExtents.y!==h||s.halfExtents.z!==d,s.halfExtents.x=c,s.halfExtents.y=h,s.halfExtents.z=d,n&&t.setShape(s);break}if(n){const s=e.attachedRigidbody;s?.autoMass&&this.getBody(s)?.recomputeMassPropertiesFromColliders()}this.updateColliderCollisionGroups(e),e.isTrigger!==t.isSensor()&&t.setSensor(e.isTrigger)}internalUpdateRigidbodyProperties(e,t){if(t.enableCcd(e.collisionDetectionMode!==gu.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 i=0;i<t.numColliders();i++)t.collider(i).setDensity(1);t.recomputeMassPropertiesFromColliders()}else{t.setAdditionalMass(e.mass,!1);for(let i=0;i<t.numColliders();i++)t.collider(i).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(T.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicPositionBased,!1):t.setBodyType(T.RAPIER_PHYSICS.MODULE.RigidBodyType.Dynamic,!1)}lines;step(e){if(this.world&&this.enabled){if(this._isUpdatingPhysicsWorld=!0,this.eventQueue||(this.eventQueue=new T.RAPIER_PHYSICS.MODULE.EventQueue(!1)),e===void 0||e<=0){this._isUpdatingPhysicsWorld=!1;return}else if(e!==void 0){const t=D.lerp(this.world.timestep,e,.8);this.world.timestep=t}try{this.world.step(this.eventQueue)}catch(t){console.warn("Error running physics step",{timestep:this.world.timestep},t)}this._isUpdatingPhysicsWorld=!1}}postStep(){this.world&&this.enabled&&(this._isUpdatingPhysicsWorld=!0,this.syncObjects(),this._isUpdatingPhysicsWorld=!1,this.eventQueue&&!this.collisionHandler&&(this.collisionHandler=new xI(this.world,this.eventQueue)),this.collisionHandler&&(this.collisionHandler.handleCollisionEvents(),this.collisionHandler.update()),this.updateDebugRendering(this.world))}updateDebugRendering(e){if(tt||w0||wI||this.debugRenderColliders===!0){if(!this.lines){const i=new im({color:7855479,fog:!1}),n=new un;this.lines=new D0(n,i),this.lines.layers.disableAll(),this.lines.layers.enable(2)}this.lines.parent!==this.context?.scene&&this.context?.scene.add(this.lines);const t=e.debugRender();this.lines.geometry.setAttribute("position",new pt(t.vertices,3)),this.lines.geometry.setAttribute("color",new pt(t.colors,4)),(this.context.time.frame%30===0||this.lines.geometry.boundingSphere?.radius===0)&&this.lines.geometry.computeBoundingSphere()}else this.lines&&this.context?.scene.remove(this.lines)}syncObjects(){if(!w0)for(let e=0;e<this.bodies.length;e++){const t=this.objects[e],i=this.bodies[e],n=t;if(n?.isCollider===!0&&!n.attachedRigidbody){const l=i.parent();l?this.syncPhysicsBody(t.gameObject,l,!0,!0):this.syncPhysicsBody(t.gameObject,i,!0,!0);continue}const s=i.translation(),r=i.rotation();if(Number.isNaN(s.x)||Number.isNaN(r.x)){!n.__COLLIDER_NAN&&E()&&(console.warn("Collider has NaN values",n.name,n.gameObject,i),n.__COLLIDER_NAN=!0);continue}const a=t.center;if(a&&a.isVector3){this._tempQuaternion.set(r.x,r.y,r.z,r.w);const l=this._tempPosition.copy(a).applyQuaternion(this._tempQuaternion),c=$e(t.gameObject);l.multiply(c),s.x-=l.x,s.y-=l.y,s.z-=l.z}sr(t.gameObject,s.x,s.y,s.z),Dm(t.gameObject,r.x,r.y,r.z,r.w)}}syncPhysicsBody(e,t,i,n){if(t instanceof T.RAPIER_PHYSICS.MODULE.RigidBody){const s=Z(e,this._tempPosition),r=be(e,this._tempQuaternion);switch(t.bodyType()){case T.RAPIER_PHYSICS.MODULE.RigidBodyType.Fixed:case T.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicPositionBased:case T.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicVelocityBased:i&&t.setNextKinematicTranslation(s),n&&t.setNextKinematicRotation(r);break;default:i&&t.setTranslation(s,!1),n&&t.setRotation(r,!1);break}}else if(t instanceof T.RAPIER_PHYSICS.MODULE.Collider){e.matrixWorldNeedsUpdate&&e.updateWorldMatrix(!0,!1),e.matrixWorld.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const s=this._tempPosition,r=this._tempQuaternion,a=t[gi];if(this.tryApplyCenter(a,s),i){const l=t.translation();(l.x!==s.x||l.y!==s.y||l.z!==s.z)&&t.setTranslation(s)}if(n){const l=t.rotation();(l.x!==r.x||l.y!==r.y||l.z!==r.z||l.w!==r.w)&&t.setRotation(r)}}}_tempCenterPos=new b;_tempCenterVec=new b;_tempCenterQuaternion=new U;tryApplyCenter(e,t){const i=e.center;i&&e.gameObject&&(i.x!==0||i.y!==0||i.z!==0)&&(this._tempCenterPos.x=i.x,this._tempCenterPos.y=i.y,this._tempCenterPos.z=i.z,$e(e.gameObject,this._tempCenterVec),this._tempCenterPos.multiply(this._tempCenterVec),e.attachedRigidbody?this._tempCenterPos.applyQuaternion(e.gameObject.quaternion):(be(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(e,t,i,n){if(n===void 0&&(n=jl._matricesBuffer,n.length=0),e===t){const s=$e(e,this._tempPosition);i.makeScale(s.x,s.y,s.z);for(let r=n.length-1;r>=0;r--)i.multiply(n[r]);return i}return n.push(e.matrix),e.parent&&this.getRigidbodyRelativeMatrix(e.parent,t,i,n),i}static centerConnectionPos={x:0,y:0,z:0};static centerConnectionRot={x:0,y:0,z:0,w:1};addFixedJoint(e,t){if(!this.world){console.error("Physics world not initialized");return}const i=e[Kt],n=t[Kt];this.calculateJointRelativeMatrices(e.gameObject,t.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const s=T.RAPIER_PHYSICS.MODULE.JointData.fixed(jl.centerConnectionPos,jl.centerConnectionRot,this._tempPosition,this._tempQuaternion),r=this.world.createImpulseJoint(s,i,n,!0);tt&&console.log("ADD FIXED JOINT",r)}addHingeJoint(e,t,i,n){if(!this.world){console.error("Physics world not initialized");return}const s=e[Kt],r=t[Kt];this.calculateJointRelativeMatrices(e.gameObject,t.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const a=T.RAPIER_PHYSICS.MODULE.JointData.revolute(i,this._tempPosition,n),l=this.world.createImpulseJoint(a,s,r,!0);tt&&console.log("ADD HINGE JOINT",l)}calculateJointRelativeMatrices(e,t,i){e.updateWorldMatrix(!0,!1),t.updateWorldMatrix(!0,!1);const n=e.matrixWorld,s=t.matrixWorld;n.elements[0]=1,n.elements[5]=1,n.elements[10]=1,s.elements[0]=1,s.elements[5]=1,s.elements[10]=1,i.copy(s).premultiply(n.invert()).invert()}}class xI{world;eventQueue;constructor(e,t){this.world=e,this.eventQueue=t}activeCollisions=[];activeCollisionsStay=[];activeTriggers=[];handleCollisionEvents(){this.eventQueue&&this.world&&this.eventQueue.drainCollisionEvents((e,t,i)=>{const n=this.world.getCollider(e),s=this.world.getCollider(t);if(!n||!s)return;const r=n[gi],a=s[gi];x0&&console.log("EVT",r.name,a.name,i,n,s),r&&a&&(i?(this.onCollisionStarted(r,n,a,s),this.onCollisionStarted(a,s,r,n)):(this.onCollisionEnded(r,a),this.onCollisionEnded(a,r)))})}update(){this.onHandleCollisionStay()}onCollisionStarted(e,t,i,n){let s=null;if(e.isTrigger||i.isTrigger)wr(e.gameObject,r=>{r.onTriggerEnter&&!r.destroyed&&r.onTriggerEnter(i),this.activeTriggers.push({collider:e,component:r,otherCollider:i})});else{const r=e.gameObject;this.world.contactPair(t,n,(a,l)=>{wr(r,c=>{if(c.destroyed)return;const h=c.onCollisionEnter||c.onCollisionStay||c.onCollisionExit;if(h||x0){if(!s){const d=[],p=a.normal();i instanceof xs&&i.convex&&(p.x=-p.x,p.y=-p.y,p.z=-p.z);for(let m=0;m<a.numSolverContacts();m++){const f=a.solverContactPoint(m),g=a.contactImpulse(m);if(f){const y=a.contactDist(m),_=a.solverContactFriction(m),v=a.solverContactTangentVelocity(m),P=new xw(f,y,p,g,_,v);d.push(P),x0&&F.DrawDirection(f,p,16711680,3,!0)}}s=new Sw(r,i,d)}if(h){const d={collider:e,component:c,collision:s};this.activeCollisions.push(d),c.onCollisionStay&&this.activeCollisionsStay.push(d),c.onCollisionEnter?.call(c,s)}}})})}}onHandleCollisionStay(){for(const e of this.activeCollisionsStay){const t=e.component;if(!t.destroyed&&t.activeAndEnabled&&t.onCollisionStay){if(e.collision.collider.destroyed)continue;const i=e.collision;t.onCollisionStay(i)}}for(const e of this.activeTriggers){const t=e.component;if(!t.destroyed&&t.activeAndEnabled&&t.onTriggerStay){const i=e.otherCollider;if(i.destroyed)continue;t.onTriggerStay(i)}}}onCollisionEnded(e,t){if(!(e.destroyed||t.destroyed)){for(let i=0;i<this.activeCollisions.length;i++){const n=this.activeCollisions[i],s=n.collider;if(s.destroyed||n.collision.collider.destroyed){this.activeCollisions.splice(i,1),i--;continue}if(s===e&&n.collision.collider===t){const r=n.component;if(this.activeCollisions.splice(i,1),i--,r.activeAndEnabled&&r.onCollisionExit){const a=n.collision;r.onCollisionExit(a)}}}for(let i=0;i<this.activeCollisionsStay.length;i++){const n=this.activeCollisionsStay[i],s=n.collider;if(s.destroyed||n.collision.collider.destroyed){this.activeCollisionsStay.splice(i,1),i--;continue}if(s===e&&n.collision.collider===t){const r=n.component;if(this.activeCollisionsStay.splice(i,1),i--,r.activeAndEnabled&&r.onCollisionExit){const a=n.collision;r.onCollisionExit(a)}}}for(let i=0;i<this.activeTriggers.length;i++){const n=this.activeTriggers[i],s=n.collider;if(s.destroyed||n.otherCollider.destroyed){this.activeTriggers.splice(i,1),i--;continue}if(s===e&&n.otherCollider===t){const r=n.component;if(this.activeTriggers.splice(i,1),i--,r.activeAndEnabled&&r.onTriggerExit){const a=n.otherCollider;r.onTriggerExit(a)}}}}}}class SI{static async createComparisonScene(e){const{files:t}=e,i=await Promise.all(t.map(f=>new ie(f).loadAssetAsync())),n=new yi;let s=0;for(const f of i)if(f instanceof O){f.position.y=s,n.add(f);const g=Wt([f]);s+=g.getSize(new b).y,s+=.1}const r=new de(20);n.add(r);const a=e.environment||"https://dl.polyhaven.org/file/ph-assets/HDRIs/exr/1k/studio_small_09_1k.exr";{let f=null;if(a.endsWith(".hdr")){const g=(await import("./three-examples-Bph291U2.min.js").then(y=>y.RGBELoader$1)).RGBELoader;f=new g}else if(a.endsWith(".exr")){const g=(await import("./three-examples-Bph291U2.min.js").then(y=>y.EXRLoader$1)).EXRLoader;f=new g}if(f){const g=await f.loadAsync(a).catch(y=>(console.error(y),null));g&&(g.mapping=mo,g.needsUpdate=!0,n.background=g,n.environment=g,n.backgroundBlurriness=.75)}else console.warn("Unsupported environment map format",a)}const l=Wt(n.children),c=l.getCenter(new b),h=l.getSize(new b),d=Math.max(h.x,h.y,h.z)/(2*Math.tan(Math.PI*r.fov/360));r.position.set(c.x,c.y,d),r.lookAt(c);const p=new Y0(r,e.domElement||document.body);p.target=c,p.update();const m=(e.domElement||document.body).getBoundingClientRect();return r.aspect=m.width/m.height,r.updateProjectionMatrix(),{scene:n,camera:r}}}let S0=0;function A1(o){o?S0++:S0--}function CI(){return S0>0}const PI={binary:!0,animations:!0};async function OI(o){if(!o.context)throw new Error("No context provided to exportAsGLTF");o.scene||(o.scene=o.context.scene);const e={...PI,...o},{context:t}=e,i=new K0;i.register(a=>new Gw(a)),i.register(a=>new $R(a)),i.register(a=>new Uw(a)),If(i,e.context);const n={binary:e.binary,animations:MI(t,e.scene,[])},s=new kI;console.debug("Exporting GLTF",n),s.onBeforeExport(e),A1(!0);const r=await i.parseAsync(e.scene,n).catch(a=>(console.error(a),null));if(A1(!1),s.onAfterExport(e),!r)throw new Error("Failed to export GLTF");if(e.downloadAs!=null){let a=null;if(r instanceof ArrayBuffer?a=new Blob([r],{type:"application/octet-stream"}):console.error("Can not download GLTF as a blob",r),a){const l=URL.createObjectURL(a),c=document.createElement("a");c.href=l;let h=e.downloadAs;!h.endsWith(".glb")&&!h.endsWith(".gltf")&&(h+=e.binary?".glb":".gltf"),c.download=h,c.click()}}return r}const I1=Symbol("needle:weight");class kI{_undo=[];onBeforeExport(e){e.context.animations.mixers.forEach(t=>{const i=Ba.tryGetActionsFromMixer(t);if(i)for(let n=0;n<i.length;n++){const s=i[n];s[I1]=s.weight,s.weight=0,this._undo.push(()=>{s.weight=s[I1]})}t.update(0)}),e.context.scene.traverse(t=>{if(!Mf(t)){const i=t.parent;i&&(t.removeFromParent(),this._undo.push(()=>i.add(t)))}})}onAfterExport(e){this._undo.forEach(t=>t()),this._undo.length=0}}function MI(o,e,t){o.animations.mixers.forEach(n=>{const s=Ba.tryGetActionsFromMixer(n);if(s)for(let r=0;r<s.length;r++){const a=s[r].getClip();t.push(a)}}),Array.isArray(e)||(e=[e]);for(const n of e)Ba.tryGetAnimationClipsFromObjectHierarchy(n,t);const i=new Set(t);return Array.from(i)}const L1="needle-button",C0=E();class j1 extends HTMLElement{static observedAttributes=["ar","vr","quicklook"];constructor(){super(),this.removeEventListener("click",this.#r),this.addEventListener("click",this.#r)}attributeChangedCallback(e,t,i){this.#a()}#t;#n;#o;#e;#i;#s;#a(){if(this.#e?.remove(),this.getAttribute("ar")!=null)this.#i??=new Qs,this.#e=this.#i.createARButton();else if(this.getAttribute("vr")!=null)this.#i??=new Qs,this.#e=this.#i.createVRButton();else if(this.getAttribute("quicklook")!=null)this.#i??=new Qs,this.#e=this.#i.createQuicklookButton();else{C0?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.");return}this.#t??=this.attachShadow({mode:"open"}),this.#n??=document.createElement("slot"),this.#o??=document.createElement("style"),this.#o.innerHTML=`
1605
1583
  button {
1606
1584
  all: initial;
1607
1585
  cursor: inherit;
@@ -1635,4 +1613,4 @@ Error:`,r),null}}updateColliderCollisionGroups(e){const t=e[Kt],i=e.membership;l
1635
1613
  justify-content: center;
1636
1614
  gap: .5rem;
1637
1615
  }
1638
- `),this.#n.innerHTML=this.#e.innerHTML,this.#n.style.cssText="display: flex; align-items: center; justify-content: center;",this.#e.innerHTML=this.#n.outerHTML,this.#t.innerHTML=this.#e.outerHTML,this.#t.prepend(this.#o),ru(Wg,{element:this.#t}),this.#s?.disconnect(),this.#s??=new MutationObserver(()=>this.#l()),this.#s.observe(this.#e,{attributes:!0}),C0&&console.log("Needle Button updated")}#l(){this.#e&&(this.#e.style.display==="none"?this.style.display="none":this.style.display==="none"&&(this.style.display=""))}#r=e=>{C0&&console.log("Needle Button clicked"),!e.defaultPrevented&&this.#e&&this.#e.click()}}typeof window<"u"&&!window.customElements.get(L1)&&window.customElements.define(L1,j1);const Hh=w("debugavatar");class P0{root;head;leftHand;rigthHand;get isValid(){return this.head!==null&&this.head!==void 0}constructor(e,t,i,n){this.root=e,this.head=t,this.leftHand=i,this.rigthHand=n,this.root?.traverse(s=>s.layers.set(2))}}class D1{avatarRegistryUrl=null;async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let i=null;if(typeof t=="string"){if(i=await this.loadAvatar(e,t),!i){const s=new En;i=x.instantiate(_a(t,e.scene),s)}}else i=t;if(!i)return null;const n=this.findAvatar(i);return n.isValid?(Hh&&console.log("[Custom Avatar] valid config",t,Hh?n:""),n):(console.warn("[Custom Avatar] config isn't valid",t,Hh?n:""),null)}async loadAvatar(e,t){if(console.assert(t!=null&&typeof t=="string","Avatar id must not be null"),t.length<=0||!t)return null;if(Hh&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){const n=await fetch("./"+t);let s=null;if(n.ok){const r=await n.blob();r&&(s=await r.arrayBuffer())}return s?(await gn().parseSync(e,s,null,0))?.scene??null:null}const i=new fo;return Yg(i,e),new Promise((n,s)=>{const r=this.avatarRegistryUrl+"/"+t;i.load(r,async a=>{await gn().createBuiltinComponents(e,r,a,null,void 0),n(a.scene)},a=>{Hh&&console.log("[Custom Avatar] "+a.loaded/a.total*100+"% loaded of "+a.total/1024+"kB")},a=>{console.error("[Custom Avatar] Error when loading: "+a),n(null)})})}cacheModel(e,t){}findAvatar(e){const t=e;let i=t;i.children.length==1&&(i=e.children[0]);let n=this.findAvatarPart(i,["head"]);const s=this.findAvatarPart(i,["left","hand"]),r=this.findAvatarPart(i,["right","hand"]);if(!n){n=t;const a=new b;new bi().setFromObject(n).getSize(a);const l=Math.max(a.x,a.y,a.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+l+" meters! Should be < 0.3m"),l>.3&&n.scale.multiplyScalar(1/l*.3)}return new P0(t,n,s,r)}findAvatarPart(e,t){const i=e.name.toLowerCase();let n=!0;for(const s of t){if(!n)break;i.indexOf(s)===-1&&(n=!1)}if(n)return e;if(e.children)for(const s of e.children){const r=this.findAvatarPart(s,t);if(r)return r}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}}class B1{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(e){}}class F1{}const RI=Object.freeze(Object.defineProperty({__proto__:null,ActionBuilder:me,ActionCollection:wx,ActionModel:fi,AlignmentConstraint:wc,Animation:Ht,AnimationCurve:oh,AnimationExtension:Gu,AnimationTrackHandler:Ep,Animator:ft,AnimatorController:ln,Antialiasing:ch,Attractor:bl,AudioExtension:aa,AudioListener:ko,AudioSource:Mi,AudioTrackHandler:es,Avatar:Ms,AvatarBlink_Simple:Rr,AvatarEyeLook_Rotation:uf,AvatarLoader:D1,AvatarMarker:Le,AvatarModel:P0,Avatar_Brain_LookAt:Rc,Avatar_MouthShapes:Tc,Avatar_MustacheShake:hf,Avatar_POI:Mr,AxesHelper:Ha,BaseUIComponent:rn,BasicIKConstraint:mf,BehaviorExtension:hy,BehaviorModel:Et,BloomEffect:fp,BoxCollider:Ou,BoxGizmo:Nr,BoxHelperComponent:xt,Button:$o,CallInfo:Oo,Camera:si,CameraTargetReachedEvent:Mc,Canvas:ul,CanvasGroup:Is,CapsuleCollider:Mo,ChangeMaterialOnClick:Kf,ChangeTransformOnClick:Br,CharacterController:Tr,CharacterControllerInput:To,ChromaticAberration:hh,ClickThrough:Up,Collider:ai,ColorAdjustments:zs,ColorBySpeedModule:fl,ColorOverLifetimeModule:cp,ContactShadows:Ac,ControlTrackHandler:Ap,CursorFollow:Eh,CustomBranding:zr,Deletable:_f,DeleteBox:Zs,DepthOfField:On,DeviceFlag:ku,DocumentExtension:B1,DragControls:Ir,DropListener:Eo,Duplicatable:Pf,EffectWrapper:uh,EmissionModule:zo,EmphasizeOnClick:ol,EnvironmentScene:Bp,EventList:ce,EventListEvent:yu,EventSystem:ei,EventTrigger:Eu,FieldWithDefault:Jw,FixedJoint:My,Fog:pl,GltfExport:Uf,GltfExportBox:Bf,Gradient:Vr,Graphic:Kc,GraphicRaycaster:vu,GridHelper:ml,GridLayoutGroup:_y,GroundProjectedEnv:$n,GroupActionModel:Dr,HideOnStart:cn,HingeJoint:eh,HorizontalLayoutGroup:by,Image:xl,InheritVelocityModule:jy,InputField:c0,InstanceHandle:ua,InstancingHandler:la,Interactable:bf,Keyframe:ui,LODGroup:ih,LODModel:gl,Light:di,LimitVelocityOverLifetimeModule:lt,LogStats:yf,LookAt:h0,LookAtConstraint:Pr,MainModule:Bt,MaskableGraphic:Zc,MeshCollider:xs,MeshRenderer:Bc,MinMaxCurve:Q,MinMaxGradient:$r,NeedleMenu:Jn,NestedGltf:nh,Networking:Ay,NoiseModule:_e,ObjectRaycaster:ki,OffsetConstraint:Wr,OpenURL:Sl,OrbitControls:fe,Outline:hl,Padding:Ur,ParticleBurst:lp,ParticleSubEmitter:Dy,ParticleSystem:ah,ParticleSystemRenderer:nn,PhysicsExtension:dy,PixelationEffect:ph,PlayAnimationOnClick:Nc,PlayAudioOnClick:Os,PlayableDirector:ea,PlayerColor:Il,PointerEventData:Jh,PostProcessingHandler:Jy,PreliminaryAction:sl,PreliminaryTrigger:Wc,RawImage:jp,Rect:Mx,RectTransform:Cn,ReflectionProbe:Dc,RegisteredAnimationInfo:Js,RemoteSkybox:Sp,Renderer:Ti,RendererLightmap:Du,Rigidbody:Ye,RotationBySpeedModule:tn,RotationOverLifetimeModule:Pn,SceneSwitcher:qe,ScreenCapture:Ws,ScreenSpaceAmbientOcclusion:No,ScreenSpaceAmbientOcclusionN8:kn,ScrollFollow:u0,SetActiveOnClick:Zf,ShadowCatcher:_h,ShapeModule:Ly,SharpeningEffect:gh,SignalAsset:Tp,SignalReceiver:Ph,SignalReceiverEvent:Ch,SignalTrackHandler:kh,Size:kx,SizeBySpeedModule:pi,SizeOverLifetimeModule:Hr,SkinnedMeshRenderer:Df,SmoothFollow:Pp,SpatialGrabRaycaster:ra,SpatialHtml:Rh,SpatialTrigger:Op,SpatialTriggerReceiver:oo,SpectatorCamera:kp,SphereCollider:Ga,SplineContainer:Zr,SplineData:so,SplineWalker:Mn,Sprite:jo,SpriteData:al,SpriteRenderer:ci,SpriteSheet:rl,SubEmitterSystem:pp,SyncedCamera:t0,SyncedRoom:Rn,SyncedTransform:vn,TapGestureTrigger:ey,TeleportTarget:Ku,TestRunner:o0,TestSimulateUserData:s0,Text:Dt,TextBuilder:fy,TextExtension:ip,TextureSheetAnimationModule:Ft,TiltShiftEffect:no,ToneMappingEffect:Us,TrailModule:Fe,TransformData:Ne,TransformGizmo:ta,TriggerBuilder:jt,TriggerModel:Xs,UIRaycastUtils:tf,UIRootComponent:Xc,USDZExporter:to,USDZText:dl,USDZUIExtension:xy,UsageMarker:Ic,VariantAction:Qf,VelocityOverLifetimeModule:We,VerticalLayoutGroup:yy,VideoPlayer:ht,Vignette:Qr,VisibilityAction:Vc,Voip:ws,Volume:vl,VolumeParameter:B,VolumeProfile:mp,WebARCameraBackground:Lh,WebARSessionRoot:Ui,WebXR:Zu,WebXRImageTracking:jh,WebXRImageTrackingModel:Go,WebXRPlaneTracking:qo,WebXRTrackedImage:Ll,XRControllerFollow:Ho,XRControllerModel:Do,XRControllerMovement:Ei,XRFlag:Ki,XRRig:Wp,XRState:Jt,__Ignore:F1},Symbol.toStringTag,{value:"Module"})),$p=w("debugmissingcamera");ue.registerCallback(he.MissingCamera,o=>{$p&&console.warn("Creating missing camera");const e=o.context.scene,t=new de;t.name="Default Fallback Camera",e.add(t);const i=new si;if(i.sourceId=o.files?.[0]?.src??"unknown",i.fieldOfView=35,o.context.domElement.getAttribute("transparent")!=null)i.clearFlags=kr.Uninitialized;else if(o.context.domElement.getAttribute("background-image")?.length||o.context.lightmaps.tryGetSkybox(i.sourceId))i.clearFlags=kr.Skybox;else{if(i.clearFlags=kr.SolidColor,!o.context.domElement.getAttribute("background-color")){let s="#efefef";typeof window!==void 0&&window.matchMedia("(prefers-color-scheme: dark)").matches&&(s="#1f1f1f"),e.background=new ne(s)}if(!e.environment){const s=new dC(o.context.renderer),r=new Bp("neutral");e.environment=s.fromScene(r,.025).texture}}const n=yr(t,i,!0);return t.position.x=0,t.position.y=1,t.position.z=2,o.context.domElement?.cameraControls!=!1&&U1(o.context,n),n}),ue.registerCallback(he.ContextCreated,o=>{if(!o.context.mainCamera){$p&&console.log("Will not auto-fit because a default camera exists");return}if(o.context.domElement?.cameraControls==!0){if(Rb(o.context.mainCamera)?.isCameraController==!0){$p&&console.log("Will not auto-fit because a camera controller exists");return}U1(o.context)}});function U1(o,e){e=e??o.mainCameraComponent;const t=e?.gameObject;if($p&&console.log("Creating default camera controls",e?.name),t){const i=cc(t,fe);i.sourceId=e?.sourceId??"unknown";const n=o.domElement.getAttribute("auto-rotate");if(i.autoRotate=n!=null&&n!="0"&&n?.toLowerCase()!="false",i.autoRotateSpeed=.5,i.autoFit=!0,i.autoRotate&&n){const s=parseFloat(n);isNaN(s)||(i.autoRotateSpeed=s)}}else console.warn("Missing camera object, can not add orbit controls")}ue.registerCallback(he.ContextCreated,o=>{const e=o.context.domElement.getAttribute("autoplay");if(e!==void 0&&(e===""||e==="true"||e==="1")&&o.files)for(const t of o.files)x.foreachComponent(t.file.scene,i=>{if(i.enabled!==!1){if(i instanceof Ht&&i.playAutomatically||i instanceof ft||i instanceof ea&&i.playOnAwake===!0)return!0;if(i instanceof Ht)return i.playAutomatically=!0,!0;if(i instanceof ea)return i.playOnAwake=!0,!0}},!0)!==!0&&Ba.autoplayAnimations(t.file)});var O0;(o=>{function e(t,i=!1,n=.75){const s=new Zr,r=1-D.clamp(n,0,1);return t.forEach((a,l)=>{const c=new b;l<t.length-1?c.subVectors(t[l+1],a).normalize().multiplyScalar(r):i&&t.length>1&&c.subVectors(t[0],a).normalize().multiplyScalar(r);const h=new so;h.position.copy(a),h.tangentIn.copy(c),h.tangentOut.copy(c),s.addKnot(h)}),s.closed=i,s}o.createFromPoints=e})(O0||(O0={}));class TI extends $C{constructor(){super(new Worker(URL.createObjectURL(new Blob([`import '${new URL("./generateMeshBVH.worker-2qGLkQjg.js",import.meta.url).toString()}';`],{type:"text/javascript"})),{type:"module"})),this.name="GenerateMeshBVHWorker"}runTask(e,t,i={}){return new Promise((n,s)=>{if(t.getAttribute("position").isInterleavedBufferAttribute||t.index&&t.index.isInterleavedBufferAttribute)throw new Error("GenerateMeshBVHWorker: InterleavedBufferAttribute are not supported for the geometry attributes.");e.onerror=c=>{s(new Error(`[GenerateMeshBVHWorker] ${c.message||"Unknown error. Please check the server console. If you're using vite try adding 'three-mesh-bvh' to 'optimizeDeps.exclude' in your vite.config.js"}`))},e.onmessage=c=>{const{data:h}=c;if(h.error)s(new Error(h.error)),e.onmessage=null;else if(h.serialized){const{serialized:d,position:p}=h,g=HC.deserialize(d,t,{setIndex:!1}),f=Object.assign({setBoundingBox:!0},i);if(t.attributes.position.array=p,d.index)if(t.index)t.index.array=d.index;else{const m=new pt(d.index,1,!1);t.setIndex(m)}f.setBoundingBox&&(t.boundingBox=g.getBoundingBox(new bi)),i.onProgress&&i.onProgress(h.progress),n(g),e.onmessage=null}else i.onProgress&&i.onProgress(h.progress)};const r=t.index?t.index.array:null,a=t.attributes.position.array,l=[a];r&&l.push(r),e.postMessage({index:r,position:a,options:{...i,onProgress:null,includedProgressCallback:!!i.onProgress,groups:[...t.groups]}},l.map(c=>c.buffer).filter(c=>typeof SharedArrayBuffer>"u"||!(c instanceof SharedArrayBuffer)))})}}const EI=Object.freeze(Object.defineProperty({__proto__:null,GenerateMeshBVHWorker:TI},Symbol.toStringTag,{value:"Module"}));export{mR as $physicsKey,me as ActionBuilder,wx as ActionCollection,fi as ActionModel,kv as Addressables,wc as AlignmentConstraint,Ua as AmbientMode,Ht as Animation,oh as AnimationCurve,Gu as AnimationExtension,Ep as AnimationTrackHandler,Ba as AnimationUtils,ft as Animator,ys as AnimatorConditionMode,ln as AnimatorController,Zg as AnimatorControllerParameterType,xc as AnimatorStateInfo,ch as Antialiasing,Tn as Application,I_ as AssetDatabase,ie as AssetReference,bl as Attractor,aa as AudioExtension,ko as AudioListener,Mi as AudioSource,es as AudioTrackHandler,Ms as Avatar,Rr as AvatarBlink_Simple,uf as AvatarEyeLook_Rotation,D1 as AvatarLoader,Le as AvatarMarker,P0 as AvatarModel,Rc as Avatar_Brain_LookAt,Tc as Avatar_MouthShapes,hf as Avatar_MustacheShake,Mr as Avatar_POI,Na as Axes,Ha as AxesHelper,$m as BUILD_TIME,rn as BaseUIComponent,mf as BasicIKConstraint,hy as BehaviorExtension,Et as BehaviorModel,xr as BlobStorage,fp as BloomEffect,Ou as BoxCollider,Nr as BoxGizmo,xt as BoxHelperComponent,$o as Button,An as ButtonsFactory,Ow as CallDirection,Oo as CallInfo,si as Camera,Mc as CameraTargetReachedEvent,ul as Canvas,Is as CanvasGroup,Mo as CapsuleCollider,Kf as ChangeMaterialOnClick,Br as ChangeTransformOnClick,Tr as CharacterController,To as CharacterControllerInput,hh as ChromaticAberration,wi as CircularBuffer,kr as ClearFlags,Up as ClickThrough,ro as ClipExtrapolation,ai as Collider,Sw as Collision,gu as CollisionDetectionMode,zs as ColorAdjustments,fl as ColorBySpeedModule,cp as ColorOverLifetimeModule,SM as Component,M as Component$1,zd as ComponentLifecycleEvents,RI as Components,b_ as ConnectionEvents,xw as ContactPoint,Ac as ContactShadows,z as Context,lM as ContextArgs,he as ContextEvent,ue as ContextRegistry,Ap as ControlTrackHandler,Eh as CursorFollow,zr as CustomBranding,Me as CustomShader,ou as DefaultReflectionMode,_f as Deletable,Zs as DeleteBox,On as DepthOfField,ku as DeviceFlag,G as DeviceUtilities,B1 as DocumentExtension,Ir as DragControls,wf as DragMode,Eo as DropListener,Pf as Duplicatable,uh as EffectWrapper,zo as EmissionModule,ol as EmphasizeOnClick,td as EngineLoadingView,Bp as EnvironmentScene,ce as EventList,yu as EventListEvent,ei as EventSystem,Eu as EventTrigger,Jw as FieldWithDefault,da as FileReference,Rv as FileReferenceSerializer,BR as FileSpawnModel,Lw as File_Event,My as FixedJoint,pl as Fog,we as FrameEvent,Pd as GENERATOR,x as GameObject,F as Gizmos,Uf as GltfExport,Bf as GltfExportBox,Vr as Gradient,Kc as Graphic,vu as GraphicRaycaster,Ys as Graphics,ml as GridHelper,_y as GridLayoutGroup,$n as GroundProjectedEnv,Dr as GroupActionModel,Su as HideFlags,cn as HideOnStart,eh as HingeJoint,by as HorizontalLayoutGroup,lk as HostData,xl as Image,ha as ImageReference,Mv as ImageReferenceSerializer,jy as InheritVelocityModule,s_ as Input,ii as InputEventQueue,Ee as InputEvents,c0 as InputField,ua as InstanceHandle,la as InstancingHandler,an as InstancingUtil,X_ as InstantiateEvent,At as InstantiateIdProvider,En as InstantiateOptions,bf as Interactable,Ih as InternalScreenshotUtils,AO as JoinedRoomResponse,wO as KeyEventArgs,ui as Keyframe,ih as LODGroup,gl as LODModel,IO as LeftRoomResponse,di as Light,Bv as LightData,lt as LimitVelocityOverLifetimeModule,mI as LoadingElementOptions,yf as LogStats,xi as LogType,h0 as LookAt,Pr as LookAtConstraint,T as MODULES,Bt as MainModule,r0 as MarkerType,Zc as MaskableGraphic,D as Mathf,xs as MeshCollider,Bc as MeshRenderer,Q as MinMaxCurve,$r as MinMaxGradient,sc as NEEDLE_ENGINE_FEATURE_FLAGS,Kl as NEKeyboardEvent,vo as NEPointerEvent,j1 as NeedleButtonElement,Sf as NeedleEngineModelLoader,v0 as NeedleEngineWebComponent,Jn as NeedleMenu,kd as NeedlePatchesKey,Qm as NeedleXRController,K as NeedleXRSession,w_ as NeedleXRSync,k_ as NeedleXRUtils,nh as NestedGltf,v_ as NetworkConnection,Gn as NetworkedStreamEvents,ed as NetworkedStreams,Ay as Networking,Y_ as NewInstanceModel,_e as NoiseModule,ki as ObjectRaycaster,pr as ObjectUtils,Wr as OffsetConstraint,bd as OneEuroFilter,Tm as OneEuroFilterXYZ,Sl as OpenURL,fe as OrbitControls,hl as Outline,__ as OwnershipEvent,tg as OwnershipModel,xa as PUBLIC_KEY,Ur as Padding,lp as ParticleBurst,Dy as ParticleSubEmitter,ah as ParticleSystem,Fs as ParticleSystemBaseBehaviour,nn as ParticleSystemRenderer,ap as ParticleSystemShapeType,Jo as PeerHandle,f_ as PeerNetworking,El as Physics,dy as PhysicsExtension,yt as PhysicsMaterialCombine,ph as PixelationEffect,Nc as PlayAnimationOnClick,Os as PlayAudioOnClick,ea as PlayableDirector,Il as PlayerColor,xn as PlayerState,Px as PlayerStateEvent,ry as PlayerSync,Av as PlayerView,Iv as PlayerViewManager,Jh as PointerEventData,Rd as PointerType,et as PostProcessingEffect,ct as PostProcessingEffectOrder,Jy as PostProcessingHandler,sl as PreliminaryAction,Wc as PreliminaryTrigger,Cs as PreviewHelper,ur as PrimitiveType,re as Progress,Pm as PromiseAllWithErrors,Cm as PromiseErrorResult,se as RGBAColor,jl as RapierPhysics,jp as RawImage,us as RaycastOptions,Mx as Rect,Cn as RectTransform,Dc as ReflectionProbe,Js as RegisteredAnimationInfo,Sp as RemoteSkybox,ho as RenderTexture,fw as RenderTextureSerializer,Ti as Renderer,Dv as RendererData,Du as RendererLightmap,Ye as Rigidbody,Ge as RigidbodyConstraints,te as RoomEvents,tn as RotationBySpeedModule,Pn as RotationOverLifetimeModule,Iu as SceneLightSettings,qe as SceneSwitcher,Ws as ScreenCapture,No as ScreenSpaceAmbientOcclusion,kn as ScreenSpaceAmbientOcclusionN8,u0 as ScrollFollow,fn as SendQueue,Mg as SerializationContext,Zf as SetActiveOnClick,_h as ShadowCatcher,Ly as ShapeModule,Cw as ShapeOverlapResult,gh as SharpeningEffect,Tp as SignalAsset,Ph as SignalReceiver,Ch as SignalReceiverEvent,kh as SignalTrackHandler,kx as Size,pi as SizeBySpeedModule,Hr as SizeOverLifetimeModule,Df as SkinnedMeshRenderer,Pp as SmoothFollow,ra as SpatialGrabRaycaster,Rh as SpatialHtml,Op as SpatialTrigger,oo as SpatialTriggerReceiver,kp as SpectatorCamera,Ga as SphereCollider,dg as SphereIntersection,Zr as SplineContainer,so as SplineData,O0 as SplineUtils,Mn as SplineWalker,jo as Sprite,al as SpriteData,ci as SpriteRenderer,rl as SpriteSheet,RM as StateMachineBehaviour,lf as StreamEndedEvent,Pw as StreamReceivedEvent,pp as SubEmitterSystem,t0 as SyncedCamera,Rn as SyncedRoom,vn as SyncedTransform,ey as TapGestureTrigger,Ku as TeleportTarget,o0 as TestRunner,SI as TestSceneUtils,s0 as TestSimulateUserData,Dt as Text,fy as TextBuilder,ip as TextExtension,Ft as TextureSheetAnimationModule,no as TiltShiftEffect,Uv as Time,Us as ToneMappingEffect,Oh as TrackHandler,Bi as TrackType,Fe as TrailModule,Ne as TransformData,ta as TransformGizmo,jt as TriggerBuilder,Xs as TriggerModel,C as TypeStore,tf as UIRaycastUtils,Xc as UIRootComponent,zf as USDDocument,it as USDObject,sx as USDWriter,to as USDZExporter,rx as USDZExporter$1,dl as USDZText,xy as USDZUIExtension,yw as UriSerializer,Ic as UsageMarker,LO as UserJoinedOrLeftRoomModel,mn as VERSION,Qf as VariantAction,We as VelocityOverLifetimeModule,yy as VerticalLayoutGroup,ht as VideoPlayer,ms as ViewDevice,Qr as Vignette,Vc as VisibilityAction,ws as Voip,vl as Volume,B as VolumeParameter,mp as VolumeProfile,Nk as WaitForFrames,Tv as WaitForPromise,Dg as WaitForSeconds,Ko as Watch,Lh as WebARCameraBackground,Ui as WebARSessionRoot,Zu as WebXR,Qs as WebXRButtonFactory,jh as WebXRImageTracking,Go as WebXRImageTrackingModel,qo as WebXRPlaneTracking,Ll as WebXRTrackedImage,Ho as XRControllerFollow,Do as XRControllerModel,Ei as XRControllerMovement,Ki as XRFlag,Wp as XRRig,Jt as XRState,Xn as XRStateFlag,F1 as __Ignore,KO as __internalNotifyObjectDestroyed,_o as activeInHierarchyFieldName,_b as addAttributeChangeCallback,bn as addComponent,sT as addCustomExtensionPlugin,yr as addNewComponent,Od as addPatch,Qd as apply,xM as applyHMRChanges,uv as applyPrototypeExtensions,Q_ as beginListenDestroy,Z_ as beginListenInstantiate,Zm as binaryIdentifierCasts,aM as build_scene_functions,hr as builtinComponentKeyName,_0 as calculateProgress01,EP as clearMessages,GM as colorSerializer,iv as compareAssociation,bu as componentSerializer,Nb as copyTexture,hw as createMotion,ni as debugNet,Zl as debugOwner,dx as decompressGpuTexture,Nl as deepClone,Dn as delay,Wl as delayForFrames,qd as deserializeObject,Ci as destroy,fv as destroyComponentInstance,jw as determineMimeTypeFromExtension,Pe as disposeObjectResources,qn as disposeStream,Yl as editorGuidKeyName,ar as enableSpatialConsole,XM as euler,ZM as eventListSerializer,OI as exportAsGLTF,Ag as findByGuid,pc as findObjectOfType,_v as findObjectsOfType,ug as findResourceUsers,Vb as fitObjectIntoVolume,wr as foreachComponent,eu as foreachComponentEnumerator,XP as forward,wb as generateQRCode,K_ as generateSeed,Wt as getBoundingBox,Rb as getCameraController,br as getComponent,dc as getComponentInChildren,uc as getComponentInParent,hc as getComponents,Ia as getComponentsInChildren,Xd as getComponentsInParent,tx as getFormattedDate,Ct as getIconElement,Ng as getIconTexture,gn as getLoader,cc as getOrAddComponent,w as getParam,KP as getParentHierarchyPath,lP as getPath,MO as getPeerOptions,m_ as getPeerjsInstance,JO as getResourceUserCount,Ab as getTempColor,ti as getTempQuaternion,$ as getTempVector,Ul as getUrlParams,Wb as getVisibleInCustomShadowRendering,Db as getWorldDirection,Bm as getWorldEuler,Z as getWorldPosition,be as getWorldQuaternion,xd as getWorldRotation,$e as getWorldScale,Vn as hasCommercialLicense,bc as hasIndieLicense,fu as hasPointerEventComponent,Wn as hasProLicense,Xb as hideDebugConsole,ux as imageToCanvas,Da as instantiate,Hw as invokeLoadedImportPluginHooks,o_ as invokeXRSessionEnd,n_ as invokeXRSessionStart,vv as isActiveInHierarchy,La as isActiveSelf,mP as isAndroidDevice,zb as isAnimationAction,ww as isComponent,oP as isDebugMode,hP as isDesktop,vr as isDestroyed,E as isDevEnvironment,YO as isDisposed,CI as isExporting,vw as isGLTFModel,cb as isHostedOnGlitch,Kg as isHotReloadEnabled,vM as isHotReloading,uP as isIPad,Vv as isIconElement,Wi as isLocalNetwork,fP as isMacOS,dP as isMobileDevice,gP as isMozillaXR,_P as isQuest,j_ as isResourceTrackingEnabled,bP as isSafari,Kd as isUsingInstancing,yP as isiOS,pP as isiPad,lI as loadAsset,n1 as loadPMREM,b0 as loadSync,Sd as logHierarchy,zP as lookAtInverse,$l as lookAtObject,NP as lookAtScreenPoint,rP as makeId,fb as makeIdFromRandomWords,Zi as makeNameSafe,wv as markAsInstancedRendered,vP as microphonePermissionsGranted,nP as nameof,ub as nameofFactory,gw as objectSerializer,vO as offXRSessionEnd,_O as offXRSessionStart,bM as onAfterRender,yM as onBeforeRender,gM as onClear,fM as onDestroy,Kv as onInitialized,hu as onStart,Zv as onUpdate,Xm as onXRSessionEnd,Md as onXRSessionStart,S1 as parseSync,$b as placeOnSurface,zm as postprocessFBXMaterials,zM as prefix,pb as pushState,aP as randomNumber,Jm as registerBinaryType,lu as registerComponent,Af as registerComponentExtension,on as registerCustomEffectType,If as registerExportExtensions,ju as registerExtensions,ow as registerHotReloadType,Hm as registerLoader,ev as registerPrefabProvider,pv as registerPrototypeExtensions,pk as registerType,bb as relativePathPrefix,vb as removeAttributeChangeCallback,Eg as removeComponent,rT as removeCustomImportExtensionType,yO as removePatch,ls as resolveUrl,yb as sanitizeString,f1 as saveImage,H2 as screenshot,p0 as screenshot2,wg as sendDestroyed,u as serializable,rv as serializeObject,Qe as serializeable,mc as setActive,Cb as setAllowBalloonMessages,kP as setAllowOverlayMessages,vd as setAutoFitEnabled,Em as setCameraController,Sv as setDestroyed,sO as setDevEnvironment,B_ as setDisposable,ja as setDontDestroy,wm as setOrAddParamsToUrl,sP as setParam,zl as setParamWithoutReload,RO as setPeerOptions,QO as setResourceTrackingEnabled,xm as setState,Um as setVisibleInCustomShadowRendering,Fm as setWorldEuler,mt as setWorldPosition,sr as setWorldPositionXYZ,pn as setWorldQuaternion,Dm as setWorldQuaternionXYZW,Ub as setWorldRotation,Hl as setWorldRotationXYZ,wa as setWorldScale,Xl as showBalloonError,Te as showBalloonMessage,ge as showBalloonWarning,Vm as showDebugConsole,UP as slerp,ac as syncDestroy,sy as syncField,xg as syncInstantiate,ZP as textureToCanvas,u_ as tryCastBinary,Bw as tryDetermineMimetypeFromBinary,Dw as tryDetermineMimetypeFromURL,_a as tryFindObject,p_ as tryGetGuid,sw as unregisterHotReloadType,Sm as unwatchWrite,Tb as useForAutoFit,Pt as validate,fd as watchWrite};
1616
+ `),this.#n.innerHTML=this.#e.innerHTML,this.#n.style.cssText="display: flex; align-items: center; justify-content: center;",this.#e.innerHTML=this.#n.outerHTML,this.#t.innerHTML=this.#e.outerHTML,this.#t.prepend(this.#o),ru(Wg,{element:this.#t}),this.#s?.disconnect(),this.#s??=new MutationObserver(()=>this.#l()),this.#s.observe(this.#e,{attributes:!0}),C0&&console.log("Needle Button updated")}#l(){this.#e&&(this.#e.style.display==="none"?this.style.display="none":this.style.display==="none"&&(this.style.display=""))}#r=e=>{C0&&console.log("Needle Button clicked"),!e.defaultPrevented&&this.#e&&this.#e.click()}}typeof window<"u"&&!window.customElements.get(L1)&&window.customElements.define(L1,j1);const Hh=w("debugavatar");class P0{root;head;leftHand;rigthHand;get isValid(){return this.head!==null&&this.head!==void 0}constructor(e,t,i,n){this.root=e,this.head=t,this.leftHand=i,this.rigthHand=n,this.root?.traverse(s=>s.layers.set(2))}}class D1{avatarRegistryUrl=null;async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let i=null;if(typeof t=="string"){if(i=await this.loadAvatar(e,t),!i){const s=new En;i=x.instantiate(_a(t,e.scene),s)}}else i=t;if(!i)return null;const n=this.findAvatar(i);return n.isValid?(Hh&&console.log("[Custom Avatar] valid config",t,Hh?n:""),n):(console.warn("[Custom Avatar] config isn't valid",t,Hh?n:""),null)}async loadAvatar(e,t){if(console.assert(t!=null&&typeof t=="string","Avatar id must not be null"),t.length<=0||!t)return null;if(Hh&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){const n=await fetch("./"+t);let s=null;if(n.ok){const r=await n.blob();r&&(s=await r.arrayBuffer())}return s?(await gn().parseSync(e,s,null,0))?.scene??null:null}const i=new fo;return Yg(i,e),new Promise((n,s)=>{const r=this.avatarRegistryUrl+"/"+t;i.load(r,async a=>{await gn().createBuiltinComponents(e,r,a,null,void 0),n(a.scene)},a=>{Hh&&console.log("[Custom Avatar] "+a.loaded/a.total*100+"% loaded of "+a.total/1024+"kB")},a=>{console.error("[Custom Avatar] Error when loading: "+a),n(null)})})}cacheModel(e,t){}findAvatar(e){const t=e;let i=t;i.children.length==1&&(i=e.children[0]);let n=this.findAvatarPart(i,["head"]);const s=this.findAvatarPart(i,["left","hand"]),r=this.findAvatarPart(i,["right","hand"]);if(!n){n=t;const a=new b;new bi().setFromObject(n).getSize(a);const l=Math.max(a.x,a.y,a.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+l+" meters! Should be < 0.3m"),l>.3&&n.scale.multiplyScalar(1/l*.3)}return new P0(t,n,s,r)}findAvatarPart(e,t){const i=e.name.toLowerCase();let n=!0;for(const s of t){if(!n)break;i.indexOf(s)===-1&&(n=!1)}if(n)return e;if(e.children)for(const s of e.children){const r=this.findAvatarPart(s,t);if(r)return r}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}}class B1{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(e){}}class F1{}const RI=Object.freeze(Object.defineProperty({__proto__:null,ActionBuilder:me,ActionCollection:wx,ActionModel:fi,AlignmentConstraint:wc,Animation:Ht,AnimationCurve:oh,AnimationExtension:Gu,AnimationTrackHandler:Ep,Animator:ft,AnimatorController:ln,Antialiasing:ch,Attractor:bl,AudioExtension:aa,AudioListener:ko,AudioSource:Mi,AudioTrackHandler:es,Avatar:Ms,AvatarBlink_Simple:Rr,AvatarEyeLook_Rotation:uf,AvatarLoader:D1,AvatarMarker:Le,AvatarModel:P0,Avatar_Brain_LookAt:Rc,Avatar_MouthShapes:Tc,Avatar_MustacheShake:hf,Avatar_POI:Mr,AxesHelper:Ha,BaseUIComponent:rn,BasicIKConstraint:mf,BehaviorExtension:hy,BehaviorModel:Et,BloomEffect:fp,BoxCollider:Ou,BoxGizmo:Nr,BoxHelperComponent:xt,Button:$o,CallInfo:Oo,Camera:si,CameraTargetReachedEvent:Mc,Canvas:ul,CanvasGroup:Is,CapsuleCollider:Mo,ChangeMaterialOnClick:Kf,ChangeTransformOnClick:Br,CharacterController:Tr,CharacterControllerInput:To,ChromaticAberration:hh,ClickThrough:Up,Collider:ai,ColorAdjustments:zs,ColorBySpeedModule:fl,ColorOverLifetimeModule:cp,ContactShadows:Ac,ControlTrackHandler:Ap,CursorFollow:Eh,CustomBranding:zr,Deletable:_f,DeleteBox:Zs,DepthOfField:On,DeviceFlag:ku,DocumentExtension:B1,DragControls:Ir,DropListener:Eo,Duplicatable:Pf,EffectWrapper:uh,EmissionModule:zo,EmphasizeOnClick:ol,EnvironmentScene:Bp,EventList:ce,EventListEvent:yu,EventSystem:ei,EventTrigger:Eu,FieldWithDefault:Jw,FixedJoint:My,Fog:pl,GltfExport:Uf,GltfExportBox:Bf,Gradient:Vr,Graphic:Kc,GraphicRaycaster:vu,GridHelper:ml,GridLayoutGroup:_y,GroundProjectedEnv:$n,GroupActionModel:Dr,HideOnStart:cn,HingeJoint:eh,HorizontalLayoutGroup:by,Image:xl,InheritVelocityModule:jy,InputField:c0,InstanceHandle:ua,InstancingHandler:la,Interactable:bf,Keyframe:ui,LODGroup:ih,LODModel:gl,Light:di,LimitVelocityOverLifetimeModule:lt,LogStats:yf,LookAt:h0,LookAtConstraint:Pr,MainModule:Bt,MaskableGraphic:Zc,MeshCollider:xs,MeshRenderer:Bc,MinMaxCurve:Q,MinMaxGradient:$r,NeedleMenu:Jn,NestedGltf:nh,Networking:Ay,NoiseModule:_e,ObjectRaycaster:ki,OffsetConstraint:Wr,OpenURL:Sl,OrbitControls:fe,Outline:hl,Padding:Ur,ParticleBurst:lp,ParticleSubEmitter:Dy,ParticleSystem:ah,ParticleSystemRenderer:nn,PhysicsExtension:dy,PixelationEffect:ph,PlayAnimationOnClick:Nc,PlayAudioOnClick:Os,PlayableDirector:ea,PlayerColor:Il,PointerEventData:Jh,PostProcessingHandler:Jy,PreliminaryAction:sl,PreliminaryTrigger:Wc,RawImage:jp,Rect:Mx,RectTransform:Cn,ReflectionProbe:Dc,RegisteredAnimationInfo:Js,RemoteSkybox:Sp,Renderer:Ti,RendererLightmap:Du,Rigidbody:Ye,RotationBySpeedModule:tn,RotationOverLifetimeModule:Pn,SceneSwitcher:qe,ScreenCapture:Ws,ScreenSpaceAmbientOcclusion:No,ScreenSpaceAmbientOcclusionN8:kn,ScrollFollow:u0,SetActiveOnClick:Zf,ShadowCatcher:_h,ShapeModule:Ly,SharpeningEffect:gh,SignalAsset:Tp,SignalReceiver:Ph,SignalReceiverEvent:Ch,SignalTrackHandler:kh,Size:kx,SizeBySpeedModule:pi,SizeOverLifetimeModule:Hr,SkinnedMeshRenderer:Df,SmoothFollow:Pp,SpatialGrabRaycaster:ra,SpatialHtml:Rh,SpatialTrigger:Op,SpatialTriggerReceiver:oo,SpectatorCamera:kp,SphereCollider:Ga,SplineContainer:Zr,SplineData:so,SplineWalker:Mn,Sprite:jo,SpriteData:al,SpriteRenderer:ci,SpriteSheet:rl,SubEmitterSystem:pp,SyncedCamera:t0,SyncedRoom:Rn,SyncedTransform:vn,TapGestureTrigger:ey,TeleportTarget:Ku,TestRunner:o0,TestSimulateUserData:s0,Text:Dt,TextBuilder:fy,TextExtension:ip,TextureSheetAnimationModule:Ft,TiltShiftEffect:no,ToneMappingEffect:Us,TrailModule:Fe,TransformData:Ne,TransformGizmo:ta,TriggerBuilder:jt,TriggerModel:Xs,UIRaycastUtils:tf,UIRootComponent:Xc,USDZExporter:to,USDZText:dl,USDZUIExtension:xy,UsageMarker:Ic,VariantAction:Qf,VelocityOverLifetimeModule:We,VerticalLayoutGroup:yy,VideoPlayer:ht,Vignette:Qr,VisibilityAction:Vc,Voip:ws,Volume:vl,VolumeParameter:B,VolumeProfile:mp,WebARCameraBackground:Lh,WebARSessionRoot:Ui,WebXR:Zu,WebXRImageTracking:jh,WebXRImageTrackingModel:Go,WebXRPlaneTracking:qo,WebXRTrackedImage:Ll,XRControllerFollow:Ho,XRControllerModel:Do,XRControllerMovement:Ei,XRFlag:Ki,XRRig:Wp,XRState:Jt,__Ignore:F1},Symbol.toStringTag,{value:"Module"})),$p=w("debugmissingcamera");ue.registerCallback(he.MissingCamera,o=>{$p&&console.warn("Creating missing camera");const e=o.context.scene,t=new de;t.name="Default Fallback Camera",e.add(t);const i=new si;if(i.sourceId=o.files?.[0]?.src??"unknown",i.fieldOfView=35,o.context.domElement.getAttribute("transparent")!=null)i.clearFlags=kr.Uninitialized;else if(o.context.domElement.getAttribute("background-image")?.length||o.context.lightmaps.tryGetSkybox(i.sourceId))i.clearFlags=kr.Skybox;else{if(i.clearFlags=kr.SolidColor,!o.context.domElement.getAttribute("background-color")){let s="#efefef";typeof window!==void 0&&window.matchMedia("(prefers-color-scheme: dark)").matches&&(s="#1f1f1f"),e.background=new ne(s)}if(!e.environment){const s=new dC(o.context.renderer),r=new Bp("neutral");e.environment=s.fromScene(r,.025).texture}}const n=yr(t,i,!0);return t.position.x=0,t.position.y=1,t.position.z=2,o.context.domElement?.cameraControls!=!1&&U1(o.context,n),n}),ue.registerCallback(he.ContextCreated,o=>{if(!o.context.mainCamera){$p&&console.log("Will not auto-fit because a default camera exists");return}if(o.context.domElement?.cameraControls==!0){if(Rb(o.context.mainCamera)?.isCameraController==!0){$p&&console.log("Will not auto-fit because a camera controller exists");return}U1(o.context)}});function U1(o,e){e=e??o.mainCameraComponent;const t=e?.gameObject;if($p&&console.log("Creating default camera controls",e?.name),t){const i=cc(t,fe);i.sourceId=e?.sourceId??"unknown";const n=o.domElement.getAttribute("auto-rotate");if(i.autoRotate=n!=null&&n!="0"&&n?.toLowerCase()!="false",i.autoRotateSpeed=.5,i.autoFit=!0,i.autoRotate&&n){const s=parseFloat(n);isNaN(s)||(i.autoRotateSpeed=s)}}else console.warn("Missing camera object, can not add orbit controls")}ue.registerCallback(he.ContextCreated,o=>{const e=o.context.domElement.getAttribute("autoplay");if(e!==void 0&&(e===""||e==="true"||e==="1")&&o.files)for(const t of o.files)x.foreachComponent(t.file.scene,i=>{if(i.enabled!==!1){if(i instanceof Ht&&i.playAutomatically||i instanceof ft||i instanceof ea&&i.playOnAwake===!0)return!0;if(i instanceof Ht)return i.playAutomatically=!0,!0;if(i instanceof ea)return i.playOnAwake=!0,!0}},!0)!==!0&&Ba.autoplayAnimations(t.file)});var O0;(o=>{function e(t,i=!1,n=.75){const s=new Zr,r=1-D.clamp(n,0,1);return t.forEach((a,l)=>{const c=new b;l<t.length-1?c.subVectors(t[l+1],a).normalize().multiplyScalar(r):i&&t.length>1&&c.subVectors(t[0],a).normalize().multiplyScalar(r);const h=new so;h.position.copy(a),h.tangentIn.copy(c),h.tangentOut.copy(c),s.addKnot(h)}),s.closed=i,s}o.createFromPoints=e})(O0||(O0={}));class TI extends $C{constructor(){super(new Worker(URL.createObjectURL(new Blob([`import '${new URL("./generateMeshBVH.worker-2qGLkQjg.js",import.meta.url).toString()}';`],{type:"text/javascript"})),{type:"module"})),this.name="GenerateMeshBVHWorker"}runTask(e,t,i={}){return new Promise((n,s)=>{if(t.getAttribute("position").isInterleavedBufferAttribute||t.index&&t.index.isInterleavedBufferAttribute)throw new Error("GenerateMeshBVHWorker: InterleavedBufferAttribute are not supported for the geometry attributes.");e.onerror=c=>{s(new Error(`[GenerateMeshBVHWorker] ${c.message||"Unknown error. Please check the server console. If you're using vite try adding 'three-mesh-bvh' to 'optimizeDeps.exclude' in your vite.config.js"}`))},e.onmessage=c=>{const{data:h}=c;if(h.error)s(new Error(h.error)),e.onmessage=null;else if(h.serialized){const{serialized:d,position:p}=h,m=HC.deserialize(d,t,{setIndex:!1}),f=Object.assign({setBoundingBox:!0},i);if(t.attributes.position.array=p,d.index)if(t.index)t.index.array=d.index;else{const g=new pt(d.index,1,!1);t.setIndex(g)}f.setBoundingBox&&(t.boundingBox=m.getBoundingBox(new bi)),i.onProgress&&i.onProgress(h.progress),n(m),e.onmessage=null}else i.onProgress&&i.onProgress(h.progress)};const r=t.index?t.index.array:null,a=t.attributes.position.array,l=[a];r&&l.push(r),e.postMessage({index:r,position:a,options:{...i,onProgress:null,includedProgressCallback:!!i.onProgress,groups:[...t.groups]}},l.map(c=>c.buffer).filter(c=>typeof SharedArrayBuffer>"u"||!(c instanceof SharedArrayBuffer)))})}}const EI=Object.freeze(Object.defineProperty({__proto__:null,GenerateMeshBVHWorker:TI},Symbol.toStringTag,{value:"Module"}));export{mR as $physicsKey,me as ActionBuilder,wx as ActionCollection,fi as ActionModel,kv as Addressables,wc as AlignmentConstraint,Ua as AmbientMode,Ht as Animation,oh as AnimationCurve,Gu as AnimationExtension,Ep as AnimationTrackHandler,Ba as AnimationUtils,ft as Animator,ys as AnimatorConditionMode,ln as AnimatorController,Zg as AnimatorControllerParameterType,xc as AnimatorStateInfo,ch as Antialiasing,Tn as Application,I_ as AssetDatabase,ie as AssetReference,bl as Attractor,aa as AudioExtension,ko as AudioListener,Mi as AudioSource,es as AudioTrackHandler,Ms as Avatar,Rr as AvatarBlink_Simple,uf as AvatarEyeLook_Rotation,D1 as AvatarLoader,Le as AvatarMarker,P0 as AvatarModel,Rc as Avatar_Brain_LookAt,Tc as Avatar_MouthShapes,hf as Avatar_MustacheShake,Mr as Avatar_POI,Na as Axes,Ha as AxesHelper,$m as BUILD_TIME,rn as BaseUIComponent,mf as BasicIKConstraint,hy as BehaviorExtension,Et as BehaviorModel,xr as BlobStorage,fp as BloomEffect,Ou as BoxCollider,Nr as BoxGizmo,xt as BoxHelperComponent,$o as Button,An as ButtonsFactory,Ow as CallDirection,Oo as CallInfo,si as Camera,Mc as CameraTargetReachedEvent,ul as Canvas,Is as CanvasGroup,Mo as CapsuleCollider,Kf as ChangeMaterialOnClick,Br as ChangeTransformOnClick,Tr as CharacterController,To as CharacterControllerInput,hh as ChromaticAberration,wi as CircularBuffer,kr as ClearFlags,Up as ClickThrough,ro as ClipExtrapolation,ai as Collider,Sw as Collision,gu as CollisionDetectionMode,zs as ColorAdjustments,fl as ColorBySpeedModule,cp as ColorOverLifetimeModule,SM as Component,M as Component$1,zd as ComponentLifecycleEvents,RI as Components,b_ as ConnectionEvents,xw as ContactPoint,Ac as ContactShadows,z as Context,lM as ContextArgs,he as ContextEvent,ue as ContextRegistry,Ap as ControlTrackHandler,Eh as CursorFollow,zr as CustomBranding,Me as CustomShader,ou as DefaultReflectionMode,_f as Deletable,Zs as DeleteBox,On as DepthOfField,ku as DeviceFlag,G as DeviceUtilities,B1 as DocumentExtension,Ir as DragControls,wf as DragMode,Eo as DropListener,Pf as Duplicatable,uh as EffectWrapper,zo as EmissionModule,ol as EmphasizeOnClick,td as EngineLoadingView,Bp as EnvironmentScene,ce as EventList,yu as EventListEvent,ei as EventSystem,Eu as EventTrigger,Jw as FieldWithDefault,da as FileReference,Rv as FileReferenceSerializer,BR as FileSpawnModel,Lw as File_Event,My as FixedJoint,pl as Fog,we as FrameEvent,Pd as GENERATOR,x as GameObject,F as Gizmos,Uf as GltfExport,Bf as GltfExportBox,Vr as Gradient,Kc as Graphic,vu as GraphicRaycaster,Ys as Graphics,ml as GridHelper,_y as GridLayoutGroup,$n as GroundProjectedEnv,Dr as GroupActionModel,Su as HideFlags,cn as HideOnStart,eh as HingeJoint,by as HorizontalLayoutGroup,lk as HostData,xl as Image,ha as ImageReference,Mv as ImageReferenceSerializer,jy as InheritVelocityModule,s_ as Input,ii as InputEventQueue,Ee as InputEvents,c0 as InputField,ua as InstanceHandle,la as InstancingHandler,an as InstancingUtil,X_ as InstantiateEvent,At as InstantiateIdProvider,En as InstantiateOptions,bf as Interactable,Ih as InternalScreenshotUtils,AO as JoinedRoomResponse,wO as KeyEventArgs,ui as Keyframe,ih as LODGroup,gl as LODModel,IO as LeftRoomResponse,di as Light,Bv as LightData,lt as LimitVelocityOverLifetimeModule,mI as LoadingElementOptions,yf as LogStats,xi as LogType,h0 as LookAt,Pr as LookAtConstraint,T as MODULES,Bt as MainModule,r0 as MarkerType,Zc as MaskableGraphic,D as Mathf,xs as MeshCollider,Bc as MeshRenderer,Q as MinMaxCurve,$r as MinMaxGradient,sc as NEEDLE_ENGINE_FEATURE_FLAGS,Kl as NEKeyboardEvent,vo as NEPointerEvent,j1 as NeedleButtonElement,Sf as NeedleEngineModelLoader,v0 as NeedleEngineWebComponent,Jn as NeedleMenu,kd as NeedlePatchesKey,Qm as NeedleXRController,K as NeedleXRSession,w_ as NeedleXRSync,k_ as NeedleXRUtils,nh as NestedGltf,v_ as NetworkConnection,Gn as NetworkedStreamEvents,ed as NetworkedStreams,Ay as Networking,Y_ as NewInstanceModel,_e as NoiseModule,ki as ObjectRaycaster,pr as ObjectUtils,Wr as OffsetConstraint,bd as OneEuroFilter,Tm as OneEuroFilterXYZ,Sl as OpenURL,fe as OrbitControls,hl as Outline,__ as OwnershipEvent,tg as OwnershipModel,xa as PUBLIC_KEY,Ur as Padding,lp as ParticleBurst,Dy as ParticleSubEmitter,ah as ParticleSystem,Fs as ParticleSystemBaseBehaviour,nn as ParticleSystemRenderer,ap as ParticleSystemShapeType,Jo as PeerHandle,f_ as PeerNetworking,El as Physics,dy as PhysicsExtension,yt as PhysicsMaterialCombine,ph as PixelationEffect,Nc as PlayAnimationOnClick,Os as PlayAudioOnClick,ea as PlayableDirector,Il as PlayerColor,xn as PlayerState,Px as PlayerStateEvent,ry as PlayerSync,Av as PlayerView,Iv as PlayerViewManager,Jh as PointerEventData,Rd as PointerType,et as PostProcessingEffect,ct as PostProcessingEffectOrder,Jy as PostProcessingHandler,sl as PreliminaryAction,Wc as PreliminaryTrigger,Cs as PreviewHelper,ur as PrimitiveType,re as Progress,Pm as PromiseAllWithErrors,Cm as PromiseErrorResult,se as RGBAColor,jl as RapierPhysics,jp as RawImage,us as RaycastOptions,Mx as Rect,Cn as RectTransform,Dc as ReflectionProbe,Js as RegisteredAnimationInfo,Sp as RemoteSkybox,ho as RenderTexture,fw as RenderTextureSerializer,Ti as Renderer,Dv as RendererData,Du as RendererLightmap,Ye as Rigidbody,Ge as RigidbodyConstraints,te as RoomEvents,tn as RotationBySpeedModule,Pn as RotationOverLifetimeModule,Iu as SceneLightSettings,qe as SceneSwitcher,Ws as ScreenCapture,No as ScreenSpaceAmbientOcclusion,kn as ScreenSpaceAmbientOcclusionN8,u0 as ScrollFollow,fn as SendQueue,Mg as SerializationContext,Zf as SetActiveOnClick,_h as ShadowCatcher,Ly as ShapeModule,Cw as ShapeOverlapResult,gh as SharpeningEffect,Tp as SignalAsset,Ph as SignalReceiver,Ch as SignalReceiverEvent,kh as SignalTrackHandler,kx as Size,pi as SizeBySpeedModule,Hr as SizeOverLifetimeModule,Df as SkinnedMeshRenderer,Pp as SmoothFollow,ra as SpatialGrabRaycaster,Rh as SpatialHtml,Op as SpatialTrigger,oo as SpatialTriggerReceiver,kp as SpectatorCamera,Ga as SphereCollider,dg as SphereIntersection,Zr as SplineContainer,so as SplineData,O0 as SplineUtils,Mn as SplineWalker,jo as Sprite,al as SpriteData,ci as SpriteRenderer,rl as SpriteSheet,RM as StateMachineBehaviour,lf as StreamEndedEvent,Pw as StreamReceivedEvent,pp as SubEmitterSystem,t0 as SyncedCamera,Rn as SyncedRoom,vn as SyncedTransform,ey as TapGestureTrigger,Ku as TeleportTarget,o0 as TestRunner,SI as TestSceneUtils,s0 as TestSimulateUserData,Dt as Text,fy as TextBuilder,ip as TextExtension,Ft as TextureSheetAnimationModule,no as TiltShiftEffect,Uv as Time,Us as ToneMappingEffect,Oh as TrackHandler,Bi as TrackType,Fe as TrailModule,Ne as TransformData,ta as TransformGizmo,jt as TriggerBuilder,Xs as TriggerModel,C as TypeStore,tf as UIRaycastUtils,Xc as UIRootComponent,zf as USDDocument,it as USDObject,sx as USDWriter,to as USDZExporter,rx as USDZExporter$1,dl as USDZText,xy as USDZUIExtension,yw as UriSerializer,Ic as UsageMarker,LO as UserJoinedOrLeftRoomModel,mn as VERSION,Qf as VariantAction,We as VelocityOverLifetimeModule,yy as VerticalLayoutGroup,ht as VideoPlayer,ms as ViewDevice,Qr as Vignette,Vc as VisibilityAction,ws as Voip,vl as Volume,B as VolumeParameter,mp as VolumeProfile,Nk as WaitForFrames,Tv as WaitForPromise,Dg as WaitForSeconds,Ko as Watch,Lh as WebARCameraBackground,Ui as WebARSessionRoot,Zu as WebXR,Qs as WebXRButtonFactory,jh as WebXRImageTracking,Go as WebXRImageTrackingModel,qo as WebXRPlaneTracking,Ll as WebXRTrackedImage,Ho as XRControllerFollow,Do as XRControllerModel,Ei as XRControllerMovement,Ki as XRFlag,Wp as XRRig,Jt as XRState,Xn as XRStateFlag,F1 as __Ignore,KO as __internalNotifyObjectDestroyed,_o as activeInHierarchyFieldName,_b as addAttributeChangeCallback,bn as addComponent,sT as addCustomExtensionPlugin,yr as addNewComponent,Od as addPatch,Qd as apply,xM as applyHMRChanges,uv as applyPrototypeExtensions,Q_ as beginListenDestroy,Z_ as beginListenInstantiate,Zm as binaryIdentifierCasts,aM as build_scene_functions,hr as builtinComponentKeyName,_0 as calculateProgress01,EP as clearMessages,GM as colorSerializer,iv as compareAssociation,bu as componentSerializer,Nb as copyTexture,hw as createMotion,ni as debugNet,Zl as debugOwner,dx as decompressGpuTexture,Nl as deepClone,Dn as delay,Wl as delayForFrames,qd as deserializeObject,Ci as destroy,fv as destroyComponentInstance,jw as determineMimeTypeFromExtension,Pe as disposeObjectResources,qn as disposeStream,Yl as editorGuidKeyName,ar as enableSpatialConsole,XM as euler,ZM as eventListSerializer,OI as exportAsGLTF,Ag as findByGuid,pc as findObjectOfType,_v as findObjectsOfType,ug as findResourceUsers,Vb as fitObjectIntoVolume,wr as foreachComponent,eu as foreachComponentEnumerator,XP as forward,wb as generateQRCode,K_ as generateSeed,Wt as getBoundingBox,Rb as getCameraController,br as getComponent,dc as getComponentInChildren,uc as getComponentInParent,hc as getComponents,Ia as getComponentsInChildren,Xd as getComponentsInParent,tx as getFormattedDate,Ct as getIconElement,Ng as getIconTexture,gn as getLoader,cc as getOrAddComponent,w as getParam,KP as getParentHierarchyPath,lP as getPath,MO as getPeerOptions,m_ as getPeerjsInstance,JO as getResourceUserCount,Ab as getTempColor,ti as getTempQuaternion,$ as getTempVector,Ul as getUrlParams,Wb as getVisibleInCustomShadowRendering,Db as getWorldDirection,Bm as getWorldEuler,Z as getWorldPosition,be as getWorldQuaternion,xd as getWorldRotation,$e as getWorldScale,Vn as hasCommercialLicense,bc as hasIndieLicense,fu as hasPointerEventComponent,Wn as hasProLicense,Xb as hideDebugConsole,ux as imageToCanvas,Da as instantiate,Hw as invokeLoadedImportPluginHooks,o_ as invokeXRSessionEnd,n_ as invokeXRSessionStart,vv as isActiveInHierarchy,La as isActiveSelf,mP as isAndroidDevice,zb as isAnimationAction,ww as isComponent,oP as isDebugMode,hP as isDesktop,vr as isDestroyed,E as isDevEnvironment,YO as isDisposed,CI as isExporting,vw as isGLTFModel,cb as isHostedOnGlitch,Kg as isHotReloadEnabled,vM as isHotReloading,uP as isIPad,Vv as isIconElement,Wi as isLocalNetwork,fP as isMacOS,dP as isMobileDevice,gP as isMozillaXR,_P as isQuest,j_ as isResourceTrackingEnabled,bP as isSafari,Kd as isUsingInstancing,yP as isiOS,pP as isiPad,lI as loadAsset,n1 as loadPMREM,b0 as loadSync,Sd as logHierarchy,zP as lookAtInverse,$l as lookAtObject,NP as lookAtScreenPoint,rP as makeId,fb as makeIdFromRandomWords,Zi as makeNameSafe,wv as markAsInstancedRendered,vP as microphonePermissionsGranted,nP as nameof,ub as nameofFactory,gw as objectSerializer,vO as offXRSessionEnd,_O as offXRSessionStart,bM as onAfterRender,yM as onBeforeRender,gM as onClear,fM as onDestroy,Kv as onInitialized,hu as onStart,Zv as onUpdate,Xm as onXRSessionEnd,Md as onXRSessionStart,S1 as parseSync,$b as placeOnSurface,zm as postprocessFBXMaterials,zM as prefix,pb as pushState,aP as randomNumber,Jm as registerBinaryType,lu as registerComponent,Af as registerComponentExtension,on as registerCustomEffectType,If as registerExportExtensions,ju as registerExtensions,ow as registerHotReloadType,Hm as registerLoader,ev as registerPrefabProvider,pv as registerPrototypeExtensions,pk as registerType,bb as relativePathPrefix,vb as removeAttributeChangeCallback,Eg as removeComponent,rT as removeCustomImportExtensionType,yO as removePatch,ls as resolveUrl,yb as sanitizeString,f1 as saveImage,H2 as screenshot,p0 as screenshot2,wg as sendDestroyed,u as serializable,rv as serializeObject,Qe as serializeable,mc as setActive,Cb as setAllowBalloonMessages,kP as setAllowOverlayMessages,vd as setAutoFitEnabled,Em as setCameraController,Sv as setDestroyed,sO as setDevEnvironment,B_ as setDisposable,ja as setDontDestroy,wm as setOrAddParamsToUrl,sP as setParam,zl as setParamWithoutReload,RO as setPeerOptions,QO as setResourceTrackingEnabled,xm as setState,Um as setVisibleInCustomShadowRendering,Fm as setWorldEuler,mt as setWorldPosition,sr as setWorldPositionXYZ,pn as setWorldQuaternion,Dm as setWorldQuaternionXYZW,Ub as setWorldRotation,Hl as setWorldRotationXYZ,wa as setWorldScale,Xl as showBalloonError,Te as showBalloonMessage,ge as showBalloonWarning,Vm as showDebugConsole,UP as slerp,ac as syncDestroy,sy as syncField,xg as syncInstantiate,ZP as textureToCanvas,u_ as tryCastBinary,Bw as tryDetermineMimetypeFromBinary,Dw as tryDetermineMimetypeFromURL,_a as tryFindObject,p_ as tryGetGuid,sw as unregisterHotReloadType,Sm as unwatchWrite,Tb as useForAutoFit,Pt as validate,fd as watchWrite};