@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.
- package/dist/{needle-engine.bundle-BR5JPeY6.js → needle-engine.bundle-BAsxNKpA.js} +615 -655
- package/dist/{needle-engine.bundle-BcceMKjs.umd.cjs → needle-engine.bundle-C7LSzO5L.umd.cjs} +39 -61
- package/dist/{needle-engine.bundle-D3RtScQB.min.js → needle-engine.bundle-ugr1bBtk.min.js} +52 -74
- package/dist/needle-engine.js +2 -2
- package/dist/needle-engine.min.js +1 -1
- package/dist/needle-engine.umd.cjs +1 -1
- package/lib/engine/webcomponents/needle-engine.loading.js +23 -59
- package/lib/engine/webcomponents/needle-engine.loading.js.map +1 -1
- package/package.json +2 -2
- package/plugins/vite/alias.js +3 -5
- package/plugins/vite/poster-client.js +21 -22
- package/src/engine/webcomponents/needle-engine.loading.ts +24 -63
package/dist/{needle-engine.bundle-BcceMKjs.umd.cjs → needle-engine.bundle-C7LSzO5L.umd.cjs}
RENAMED
|
@@ -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=Co===!0?"":` (containing "${Co}")`;console.group("Available URL parameters:"+n);for(const o of Object.keys(s).sort())typeof Co=="string"&&!o.toLowerCase().includes(Co.toLowerCase())||(console.groupCollapsed(o),console.log("Reload with this flag enabled:"),console.log(s[o]),console.groupEnd());console.groupEnd()}},100);function rc(){return new URLSearchParams(globalThis.location?.search)}function w(s){Co&&!Jf.includes(s)&&Jf.push(s);const e=rc();if(e.has(s)){const t=e.get(s);if(t){const i=Number(t);return isNaN(i)?t:i}else return!0}return!1}Co=w("help");function sx(s,e){const t=rc();t.has(s)?t.set(s,e):t.append(s,e),document.location.search=t.toString()}function Wl(s,e,t=!0){const i=rc();i.has(s)?e===null?i.delete(s):i.set(s,e):e!==null&&i.append(s,e),t?ab(s,i):Qp(s,i)}function ep(s,e,t){s.has(e)?s.set(e,t.toString()):s.append(e,t.toString())}function ab(s,e,t){window.history.pushState(t,s,"?"+e.toString())}function Qp(s,e,t){window.history.replaceState(t,s,"?"+e.toString())}function ox(s){for(var e="",t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",i=t.length,n=0;n<s;n++)e+=t.charAt(Math.floor(Math.random()*i));return e}function rx(s,e){return Math.floor(Math.random()*(e-s+1))+s}const ry=["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"],ay=["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 lb(){const s=ry[Math.floor(Math.random()*ry.length)],e=ay[Math.floor(Math.random()*ay.length)];return s+"_"+e}function cb(s){return s=s.replace(/[^a-z0-9áéíóúñü \.,_-]/gim,""),s.trim()}function ra(s,e,t=!0,i=!1){if(e==null)return null;if(e.userData&&e.userData.guid===s)return e;if(e.guid==s)return e;if(i&&e.userData?.components){for(const n of e.userData.components)if(n.guid===s)return n}if(t){if(e.scenes)for(const n in e.scenes){const o=e.scenes[n],r=ra(s,o,t,i);if(r)return r}if(e.children)for(const n in e.children){const o=e.children[n],r=ra(s,o,t,i);if(r)return r}}}function ac(s,e){if(s!=null&&typeof s=="object"){let t;Array.isArray(s)?t=[]:(t=Object.create(s),Object.assign(t,s));for(const i of Object.keys(s)){const n=s[i];e&&!e(s,i,n)?t[i]=n:n?.clone!==void 0&&typeof n.clone=="function"?t[i]=n.clone():t[i]=ac(n,e)}return t}return s}function Ln(s){return new Promise((e,t)=>{setTimeout(e,s)})}function lc(s,e){if(s<=0)return Promise.resolve();if(e||(e=ae.Current),!e)return Promise.reject("No context");const t=e.time.frameCount+s;return new Promise((i,n)=>{if(!e)return n("No context");const o=()=>{e.time.frameCount>=t&&(e.pre_update_callbacks.splice(e.pre_update_callbacks.indexOf(o),1),i())};e.pre_update_callbacks.push(o)})}const lh=w("debugresolveurl"),hb="rel:";function ax(s,e){return Js(s,e)}function Js(s,e){if(e===void 0)return lh&&console.warn("getPath: uri is undefined, returning uri",e),e;if(e.startsWith("./"))return e;if(e.startsWith("http"))return lh&&console.warn("getPath: uri is absolute, returning uri",e),e;if(s===void 0)return lh&&console.warn("getPath: source is undefined, returning uri",e),e;e.startsWith(hb)&&(e=e.substring(4));const t=s.lastIndexOf("/");if(t>=0){const i=s.substring(0,t+1);for(;i.endsWith("/")&&e.startsWith("/");)e=e.substring(1);const n=i+e;return lh&&console.log("source:",s,`changed uri
|
|
4
4
|
from`,e,`
|
|
5
5
|
to `,n,`
|
|
6
|
-
basePath: `+i),n}return e}class lx{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:r=>{e[this._wrapperProp]=r;for(const a of this.writeCallbacks)a(r,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 rs{_watches=[];constructor(e,t){if(Array.isArray(t))for(const i of t)this._watches.push(new rs(e,i));else this._watches.push(new lx(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 jr=Symbol("needle:watches");function zd(s,e){if(!s[jr])if(s instanceof c.Vector2)s[jr]=new rs(s,["x","y"]);else if(s instanceof c.Vector3)s[jr]=new rs(s,["x","y","z"]);else if(s instanceof c.Vector4||s instanceof c.Quaternion)s[jr]=new rs(s,["x","y","z","w"]);else return!1;return s[jr].subscribeWrite(e),!0}function Yp(s,e){if(!s)return;const t=s[jr];t&&t.unsubscribeWrite(e)}exports.DeviceUtilities=void 0;(s=>{let e;function t(){if(e!==void 0)return e;const N=window.navigator.userAgent,K=/Windows|MacOS|Mac OS/.test(N),ee=/Windows NT/.test(N)&&/Edg/.test(N)&&!/Win64/.test(N);return e=K&&!ee&&!b()}s.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)}s.isMobileDevice=n;function o(){return a()}s.isIPad=o;let r;function a(){return r!==void 0?r:r=/iPad/.test(navigator.userAgent)}s.isiPad=a;let l;function h(){return l!==void 0?l:l=/Android/.test(navigator.userAgent)}s.isAndroidDevice=h;let d;function u(){return d!==void 0?d:d=/WebXRViewer\//i.test(navigator.userAgent)}s.isMozillaXR=u;let p;function m(){if(p!==void 0)return p;if(navigator.userAgentData)return p=navigator.userAgentData.platform==="macOS";{const N=navigator.userAgent.toLowerCase();return p=N.includes("mac os x")||N.includes("macintosh")}}s.isMacOS=m;let y;function _(){return y!==void 0?y:y=m()&&"xr"in navigator}s.isVisionOS=_;let g;const v=["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"];function b(){return g!==void 0?g:g=v.includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}s.isiOS=b;let x;function T(){return x!==void 0||(x=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)),x}s.isSafari=T;let O;function M(){return O!==void 0?O:O=navigator.userAgent.includes("OculusBrowser")}s.isQuest=M;let E;function j(){return E!==void 0||(E=document.createElement("a").relList.supports("ar")),E}s.supportsQuickLookAR=j;async function L(){try{return(await navigator.permissions.query({name:"microphone"})).state!=="denied"}catch(N){return console.error("Error querying `microphone` permissions.",N),!1}}s.microphonePermissionsGranted=L;let z;function $(){if(z!==void 0)return z;const N=navigator.userAgent.match(/iPhone OS (\d+_\d+)/);if(N&&(z=N[1].replace("_",".")),!z){const K=navigator.userAgent.match(/(?:\(Macintosh;|iPhone;|iPad;).*Version\/(\d+\.\d+)/);K&&(z=K[1])}return z||(z=null),z}s.getiOSVersion=$;let R;function U(){if(R!==void 0)return R;const N=navigator.userAgent.match(/(?:CriOS|Chrome)\/(\d+\.\d+\.\d+\.\d+)/);return N?R=N[1].replace("_","."):R=null,R}s.getChromeVersion=U})(exports.DeviceUtilities||(exports.DeviceUtilities={}));function cx(){return exports.DeviceUtilities.isDesktop()}function hx(){return exports.DeviceUtilities.isMobileDevice()}function dx(){return exports.DeviceUtilities.isiPad()}function ux(){return exports.DeviceUtilities.isiPad()}function fx(){return exports.DeviceUtilities.isAndroidDevice()}function px(){return exports.DeviceUtilities.isMozillaXR()}function mx(){return exports.DeviceUtilities.isMacOS()}function gx(){return exports.DeviceUtilities.isiOS()}function yx(){return exports.DeviceUtilities.isSafari()}function _x(){return exports.DeviceUtilities.isQuest()}async function bx(){return exports.DeviceUtilities.microphonePermissionsGranted()}const Ns=new WeakMap;function db(s,e,t){if(!Ns.get(s)){const n=new MutationObserver(o=>{vx(s,o)});Ns.set(s,{observer:n,attributeChangedListeners:new Map}),n.observe(s,{attributes:!0})}const i=Ns.get(s).attributeChangedListeners;i.has(e)||i.set(e,[]),i.get(e).push(t)}function ub(s,e,t){if(!Ns.get(s))return;const i=Ns.get(s).attributeChangedListeners;if(!i.has(e))return;const n=i.get(e),o=n.indexOf(t);o!==-1&&(n.splice(o,1),n.length<=0&&(i.delete(e),Ns.get(s)?.observer.disconnect(),Ns.delete(s)))}function vx(s,e){const t=Ns.get(s).attributeChangedListeners;for(const i of e)if(i.type==="attributes"){const n=i.attributeName,o=s.getAttribute(n);if(t.has(n))for(const r of t.get(n))r(o)}}class tp{reason;constructor(e){this.reason=e}}async function Kp(s){const e=await Promise.allSettled(s).catch(n=>[new tp(n.message)]);let t=!1;const i=e.map(n=>"value"in n?n.value:(t=!0,new tp(n.reason)));return{anyFailed:t,results:i}}async function fb(s){if(!globalThis.QRCode){const l="https://cdn.jsdelivr.net/gh/davidshimjs/qrcodejs@gh-pages/qrcode.min.js";let h=document.head.querySelector(`script[src="${l}"]`);h||(h=document.createElement("script"),h.src=l,document.head.appendChild(h)),await new Promise((d,u)=>{h.addEventListener("load",()=>{d(!0)})})}const e=globalThis.QRCode,t=s.domElement??document.createElement("div"),i=new e(t,{width:s.width??256,height:s.height??256,colorDark:"#000000",colorLight:"#ffffff",correctLevel:s.showLogo?e.CorrectionLevel.H:e.CorrectLevel.M,...s}),n=i?._oQRCode.moduleCount||0,o=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 wx(o,{showLogo:s.showLogo,logoSize:r,logoPadding:a}).catch(h=>{});l&&(t.innerHTML="",t.append(l))}catch{}if(s.showUrl!==!1&&s.text){const l=t.querySelector(".qr-code-link-label");let h=s.text.replace(/^(https?:\/\/)?(www\.)?/,"").replace(/\/+$/,"").replace(/\?+$/,"");if(h="Scan to visit "+h,l)l.textContent=h;else{const d=document.createElement("div");d.classList.add("qr-code-link-label"),s.text=h,d.textContent=s.text,d.addEventListener("click",u=>{u.stopImmediatePropagation()}),d.style.textAlign="center",d.style.fontSize="0.8em",d.style.marginTop="0.1em",d.style.color="#000000",d.style.fontFamily="'Roboto Flex', sans-serif",d.style.opacity="0.5",d.style.wordBreak="break-all",d.style.wordWrap="break-word",d.style.marginBottom="0.3em",t.style.width="calc(210px + 20px)",t.appendChild(d)}}return t}async function wx(s,e){if(!s)return;const t=8,i=20,n=e.logoPadding||1/32,o="transparent",r=0,a=new Image,h=document.querySelector("needle-engine")?.getAttribute("loading-logo-src")||ob;if(!h)return;let d=!1;e.showLogo!==!1&&(a.src=h,d=await new Promise((b,x)=>{a.onload=()=>b(!0),a.onerror=T=>{console.error("Error loading favicon image for QR code",T),b(!1)}}));const u=document.createElement("canvas");u.width=s.width+t,u.height=s.height+t;const p=u.getContext("2d");if(!p)return;p.fillStyle="#ffffff",p.fillRect(0,0,u.width,u.height),p.drawImage(s,t/2,t/2),p.imageSmoothingEnabled=!0,p.imageSmoothingQuality="high",p.mozImageSmoothingEnabled=!0,p.webkitImageSmoothingEnabled=!0,p.globalCompositeOperation="lighten";const m=p.createLinearGradient(0,0,0,u.height);m.addColorStop(0,"rgb(45, 45, 45)"),m.addColorStop(1,"rgb(45, 45, 45)"),p.fillStyle=m,p.fillRect(0,0,u.width,u.height),p.globalCompositeOperation="source-over";let y=Math.min(s.width,s.height)*(e.logoSize||.25),_=y;if(d){const b=a.width/a.height;b>1?_=y/b:y=_*b;const x=n*s.width,T=Math.max(y,_),O=Math.round(T+x),M=Math.round(T+x),E=(u.width-T)/2,j=(u.height-T)/2;p.shadowColor=o,p.shadowBlur=i;const L=r,z=Math.round(E-x/2),$=Math.round(j-x/2);p.beginPath(),p.moveTo(z+L,$),p.lineTo(z+O-L,$),p.quadraticCurveTo(z+O,$,z+O,$+L),p.lineTo(z+O,$+M-L),p.quadraticCurveTo(z+O,$+M,z+O-L,$+M),p.lineTo(z+L,$+M),p.quadraticCurveTo(z,$+M,z,$+M-L),p.lineTo(z,$+L),p.quadraticCurveTo(z,$,z+L,$),p.fillStyle="#ffffff",p.closePath(),p.fill(),p.clip(),p.shadowColor="transparent";const R=(u.width-y)/2,U=(u.height-_)/2;p.drawImage(a,R,U,y,_)}const g=u.toDataURL("image/png"),v=document.createElement("img");return v.src=g,v.style.width="100%",v.style.height="auto",v}const xx=w("debugdebug");let Zp=!1;(w("noerrors")||w("nooverlaymessages"))&&(Zp=!0);const Xu="needle_engine_global_error_container";var ci=(s=>(s[s.Log=0]="Log",s[s.Warn=1]="Warn",s[s.Error=2]="Error",s))(ci||{});function pb(){return yb}const ip=new Array;function Sx(s){ip.push(s)}let Qu=!1;function Cx(...s){if(!Qu){Qu=!0;try{for(let e=0;e<ip.length;e++)ip[e](...s)}catch(e){console.error(e)}Qu=!1}}const mb=console.error,Px=function(...s){mb.apply(console,s),kx(s),Eo(2,s),Mx(...s)};function gb(s){Zp=!s,s?console.error=Px:console.error=mb}function Ox(s){return gb(s)}let yb=0;function Mx(...s){yb+=1,Cx(...s)}function kx(s){if(Array.isArray(s))for(let e=0;e<s.length;e++){const t=s[e];typeof t=="string"&&t.startsWith("THREE.PropertyBinding: Trying to update node for track:")&&(s[e]="Some animated objects couldn't be found: see console for details")}}function Eo(s,e,t,i){if(Zp)return;const o=ae.Current?.domElement??document.querySelector("needle-engine");if(o){if(Array.isArray(e)){let r="";for(let a=0;a<e.length;a++){let l=e[a];l instanceof Error&&(l=l.message),typeof l!="object"&&(a>0&&(r+=" "),r+=l)}e=r}!e||e.length<=0||Ex(s,o,e)}}const kl=new Map;function Ex(s,e,t){if(t==null)return;const i=Ax(e);if(i.childElementCount>=20){const a=i.lastElementChild;ly(a)}t.length>400&&(t=t.substring(0,400)+"...");const n=t;if(kl.has(n))return;const o=Lx(s,t);i.prepend(o);const r=()=>{kl.delete(n),ly(o)};kl.set(n,r),setTimeout(r,1e4)}function Rx(){xx&&console.log("Clearing messages");for(const s of kl.values())s?.call(s);kl.clear()}const Tx=`
|
|
6
|
+
basePath: `+i),n}return e}class lx{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:r=>{e[this._wrapperProp]=r;for(const a of this.writeCallbacks)a(r,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 rs{_watches=[];constructor(e,t){if(Array.isArray(t))for(const i of t)this._watches.push(new rs(e,i));else this._watches.push(new lx(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 jr=Symbol("needle:watches");function zd(s,e){if(!s[jr])if(s instanceof c.Vector2)s[jr]=new rs(s,["x","y"]);else if(s instanceof c.Vector3)s[jr]=new rs(s,["x","y","z"]);else if(s instanceof c.Vector4||s instanceof c.Quaternion)s[jr]=new rs(s,["x","y","z","w"]);else return!1;return s[jr].subscribeWrite(e),!0}function Yp(s,e){if(!s)return;const t=s[jr];t&&t.unsubscribeWrite(e)}exports.DeviceUtilities=void 0;(s=>{let e;function t(){if(e!==void 0)return e;const N=window.navigator.userAgent,K=/Windows|MacOS|Mac OS/.test(N),ee=/Windows NT/.test(N)&&/Edg/.test(N)&&!/Win64/.test(N);return e=K&&!ee&&!_()}s.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)}s.isMobileDevice=n;function o(){return a()}s.isIPad=o;let r;function a(){return r!==void 0?r:r=/iPad/.test(navigator.userAgent)}s.isiPad=a;let l;function h(){return l!==void 0?l:l=/Android/.test(navigator.userAgent)}s.isAndroidDevice=h;let d;function u(){return d!==void 0?d:d=/WebXRViewer\//i.test(navigator.userAgent)}s.isMozillaXR=u;let p;function m(){if(p!==void 0)return p;if(navigator.userAgentData)return p=navigator.userAgentData.platform==="macOS";{const N=navigator.userAgent.toLowerCase();return p=N.includes("mac os x")||N.includes("macintosh")}}s.isMacOS=m;let y;function b(){return y!==void 0?y:y=m()&&"xr"in navigator}s.isVisionOS=b;let g;const v=["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"];function _(){return g!==void 0?g:g=v.includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}s.isiOS=_;let x;function T(){return x!==void 0||(x=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)),x}s.isSafari=T;let O;function M(){return O!==void 0?O:O=navigator.userAgent.includes("OculusBrowser")}s.isQuest=M;let E;function j(){return E!==void 0||(E=document.createElement("a").relList.supports("ar")),E}s.supportsQuickLookAR=j;async function L(){try{return(await navigator.permissions.query({name:"microphone"})).state!=="denied"}catch(N){return console.error("Error querying `microphone` permissions.",N),!1}}s.microphonePermissionsGranted=L;let z;function $(){if(z!==void 0)return z;const N=navigator.userAgent.match(/iPhone OS (\d+_\d+)/);if(N&&(z=N[1].replace("_",".")),!z){const K=navigator.userAgent.match(/(?:\(Macintosh;|iPhone;|iPad;).*Version\/(\d+\.\d+)/);K&&(z=K[1])}return z||(z=null),z}s.getiOSVersion=$;let R;function U(){if(R!==void 0)return R;const N=navigator.userAgent.match(/(?:CriOS|Chrome)\/(\d+\.\d+\.\d+\.\d+)/);return N?R=N[1].replace("_","."):R=null,R}s.getChromeVersion=U})(exports.DeviceUtilities||(exports.DeviceUtilities={}));function cx(){return exports.DeviceUtilities.isDesktop()}function hx(){return exports.DeviceUtilities.isMobileDevice()}function dx(){return exports.DeviceUtilities.isiPad()}function ux(){return exports.DeviceUtilities.isiPad()}function fx(){return exports.DeviceUtilities.isAndroidDevice()}function px(){return exports.DeviceUtilities.isMozillaXR()}function mx(){return exports.DeviceUtilities.isMacOS()}function gx(){return exports.DeviceUtilities.isiOS()}function yx(){return exports.DeviceUtilities.isSafari()}function _x(){return exports.DeviceUtilities.isQuest()}async function bx(){return exports.DeviceUtilities.microphonePermissionsGranted()}const Ns=new WeakMap;function db(s,e,t){if(!Ns.get(s)){const n=new MutationObserver(o=>{vx(s,o)});Ns.set(s,{observer:n,attributeChangedListeners:new Map}),n.observe(s,{attributes:!0})}const i=Ns.get(s).attributeChangedListeners;i.has(e)||i.set(e,[]),i.get(e).push(t)}function ub(s,e,t){if(!Ns.get(s))return;const i=Ns.get(s).attributeChangedListeners;if(!i.has(e))return;const n=i.get(e),o=n.indexOf(t);o!==-1&&(n.splice(o,1),n.length<=0&&(i.delete(e),Ns.get(s)?.observer.disconnect(),Ns.delete(s)))}function vx(s,e){const t=Ns.get(s).attributeChangedListeners;for(const i of e)if(i.type==="attributes"){const n=i.attributeName,o=s.getAttribute(n);if(t.has(n))for(const r of t.get(n))r(o)}}class tp{reason;constructor(e){this.reason=e}}async function Kp(s){const e=await Promise.allSettled(s).catch(n=>[new tp(n.message)]);let t=!1;const i=e.map(n=>"value"in n?n.value:(t=!0,new tp(n.reason)));return{anyFailed:t,results:i}}async function fb(s){if(!globalThis.QRCode){const l="https://cdn.jsdelivr.net/gh/davidshimjs/qrcodejs@gh-pages/qrcode.min.js";let h=document.head.querySelector(`script[src="${l}"]`);h||(h=document.createElement("script"),h.src=l,document.head.appendChild(h)),await new Promise((d,u)=>{h.addEventListener("load",()=>{d(!0)})})}const e=globalThis.QRCode,t=s.domElement??document.createElement("div"),i=new e(t,{width:s.width??256,height:s.height??256,colorDark:"#000000",colorLight:"#ffffff",correctLevel:s.showLogo?e.CorrectionLevel.H:e.CorrectLevel.M,...s}),n=i?._oQRCode.moduleCount||0,o=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 wx(o,{showLogo:s.showLogo,logoSize:r,logoPadding:a}).catch(h=>{});l&&(t.innerHTML="",t.append(l))}catch{}if(s.showUrl!==!1&&s.text){const l=t.querySelector(".qr-code-link-label");let h=s.text.replace(/^(https?:\/\/)?(www\.)?/,"").replace(/\/+$/,"").replace(/\?+$/,"");if(h="Scan to visit "+h,l)l.textContent=h;else{const d=document.createElement("div");d.classList.add("qr-code-link-label"),s.text=h,d.textContent=s.text,d.addEventListener("click",u=>{u.stopImmediatePropagation()}),d.style.textAlign="center",d.style.fontSize="0.8em",d.style.marginTop="0.1em",d.style.color="#000000",d.style.fontFamily="'Roboto Flex', sans-serif",d.style.opacity="0.5",d.style.wordBreak="break-all",d.style.wordWrap="break-word",d.style.marginBottom="0.3em",t.style.width="calc(210px + 20px)",t.appendChild(d)}}return t}async function wx(s,e){if(!s)return;const t=8,i=20,n=e.logoPadding||1/32,o="transparent",r=0,a=new Image,h=document.querySelector("needle-engine")?.getAttribute("loading-logo-src")||ob;if(!h)return;let d=!1;e.showLogo!==!1&&(a.src=h,d=await new Promise((_,x)=>{a.onload=()=>_(!0),a.onerror=T=>{console.error("Error loading favicon image for QR code",T),_(!1)}}));const u=document.createElement("canvas");u.width=s.width+t,u.height=s.height+t;const p=u.getContext("2d");if(!p)return;p.fillStyle="#ffffff",p.fillRect(0,0,u.width,u.height),p.drawImage(s,t/2,t/2),p.imageSmoothingEnabled=!0,p.imageSmoothingQuality="high",p.mozImageSmoothingEnabled=!0,p.webkitImageSmoothingEnabled=!0,p.globalCompositeOperation="lighten";const m=p.createLinearGradient(0,0,0,u.height);m.addColorStop(0,"rgb(45, 45, 45)"),m.addColorStop(1,"rgb(45, 45, 45)"),p.fillStyle=m,p.fillRect(0,0,u.width,u.height),p.globalCompositeOperation="source-over";let y=Math.min(s.width,s.height)*(e.logoSize||.25),b=y;if(d){const _=a.width/a.height;_>1?b=y/_:y=b*_;const x=n*s.width,T=Math.max(y,b),O=Math.round(T+x),M=Math.round(T+x),E=(u.width-T)/2,j=(u.height-T)/2;p.shadowColor=o,p.shadowBlur=i;const L=r,z=Math.round(E-x/2),$=Math.round(j-x/2);p.beginPath(),p.moveTo(z+L,$),p.lineTo(z+O-L,$),p.quadraticCurveTo(z+O,$,z+O,$+L),p.lineTo(z+O,$+M-L),p.quadraticCurveTo(z+O,$+M,z+O-L,$+M),p.lineTo(z+L,$+M),p.quadraticCurveTo(z,$+M,z,$+M-L),p.lineTo(z,$+L),p.quadraticCurveTo(z,$,z+L,$),p.fillStyle="#ffffff",p.closePath(),p.fill(),p.clip(),p.shadowColor="transparent";const R=(u.width-y)/2,U=(u.height-b)/2;p.drawImage(a,R,U,y,b)}const g=u.toDataURL("image/png"),v=document.createElement("img");return v.src=g,v.style.width="100%",v.style.height="auto",v}const xx=w("debugdebug");let Zp=!1;(w("noerrors")||w("nooverlaymessages"))&&(Zp=!0);const Xu="needle_engine_global_error_container";var ci=(s=>(s[s.Log=0]="Log",s[s.Warn=1]="Warn",s[s.Error=2]="Error",s))(ci||{});function pb(){return yb}const ip=new Array;function Sx(s){ip.push(s)}let Qu=!1;function Cx(...s){if(!Qu){Qu=!0;try{for(let e=0;e<ip.length;e++)ip[e](...s)}catch(e){console.error(e)}Qu=!1}}const mb=console.error,Px=function(...s){mb.apply(console,s),kx(s),Eo(2,s),Mx(...s)};function gb(s){Zp=!s,s?console.error=Px:console.error=mb}function Ox(s){return gb(s)}let yb=0;function Mx(...s){yb+=1,Cx(...s)}function kx(s){if(Array.isArray(s))for(let e=0;e<s.length;e++){const t=s[e];typeof t=="string"&&t.startsWith("THREE.PropertyBinding: Trying to update node for track:")&&(s[e]="Some animated objects couldn't be found: see console for details")}}function Eo(s,e,t,i){if(Zp)return;const o=ae.Current?.domElement??document.querySelector("needle-engine");if(o){if(Array.isArray(e)){let r="";for(let a=0;a<e.length;a++){let l=e[a];l instanceof Error&&(l=l.message),typeof l!="object"&&(a>0&&(r+=" "),r+=l)}e=r}!e||e.length<=0||Ex(s,o,e)}}const kl=new Map;function Ex(s,e,t){if(t==null)return;const i=Ax(e);if(i.childElementCount>=20){const a=i.lastElementChild;ly(a)}t.length>400&&(t=t.substring(0,400)+"...");const n=t;if(kl.has(n))return;const o=Lx(s,t);i.prepend(o);const r=()=>{kl.delete(n),ly(o)};kl.set(n,r),setTimeout(r,1e4)}function Rx(){xx&&console.log("Clearing messages");for(const s of kl.values())s?.call(s);kl.clear()}const Tx=`
|
|
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 Xs{static planeGeometry=new c.PlaneGeometry(2,2,1,1);static renderer=new c.WebGLRenderer({antialias:!1,alpha:!0});static perspectiveCam=new c.PerspectiveCamera;static orthographicCam=new c.OrthographicCamera;static scene=new c.Scene;static blitMaterial=new ud;static mesh=new c.Mesh(Xs.planeGeometry,Xs.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=ud.vertex;const o=this.mesh;o.material=i,o.frustumCulled=!1,this.scene.children.length=0,this.scene.add(o),this.renderer.setSize(e.image.width,e.image.height),this.renderer.clear(),this.renderer.render(this.scene,this.perspectiveCam);const r=new c.Texture(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:o=this.blitMaterial,flipY:r=!1,depthTexture:a=null,depthTest:l=!0,depthWrite:h=!0}=i||{};this.blitMaterial.reset(),o.uniforms.map&&(o.uniforms.map.value=e),o.uniforms.flipY&&(o.uniforms.flipY.value=r),a?(o.uniforms.writeDepth=new c.Uniform$1(!0),o.uniforms.depthTexture.value=a):(o.uniforms.writeDepth=new c.Uniform$1(!1),o.uniforms.depthTexture.value=null),o.needsUpdate=!0,o.uniformsNeedUpdate=!0;const d=this.mesh;d.material=o,d.frustumCulled=!1,this.scene.children.length=0,this.scene.add(d);const u=n.getRenderTarget(),p=n.getContext(),m=p.getParameter(p.DEPTH_TEST),y=p.getParameter(p.DEPTH_WRITEMASK),_=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(h),n.setClearColor(new c.Color(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(u);const g=n.state.buffers.depth;g.setTest(m),g.setMask(y),g.setFunc(_)}static textureToCanvas(e,t=!1){if(!e)return null;(t===!0||e.isCompressedTexture===!0)&&(e=Ob(e));const i=e.image;if(Zx(i)){const n=document.createElement("canvas");n.width=i.width,n.height=i.height;const o=n.getContext("2d");return o?(o.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 Ob(s){return Xs.copyTexture(s)}function Kx(s,e=!1){return Xs.textureToCanvas(s,e)}function Zx(s){return typeof HTMLImageElement<"u"&&s instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&s instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&s instanceof OffscreenCanvas||typeof ImageBitmap<"u"&&s instanceof ImageBitmap}function Jx(s){const e=s.type;return e==="Mesh"||e==="SkinnedMesh"}function sm(s,e){e?s["needle:rendercustomshadow"]=!0:s["needle:rendercustomshadow"]=!1}function Mb(s){if(s){if(s["needle:rendercustomshadow"]===!0)return!0;if(s["needle:rendercustomshadow"]==null)return!0}return!1}function Bt(s,e=void 0,t=void 0,i=void 0){const n=i||new c.Box3;n.makeEmpty();const o=[];function r(l){let h=!0;if(l.visible&&vb(l)!==!1&&!(l.type==="TransformControlsGizmo"||l.type==="TransformControlsPlane")){if(l instanceof c.Box3Helper&&(h=!1),l instanceof c.GridHelper&&(h=!1),l instanceof q.GroundedSkybox&&(h=!1),l.isGizmo===!0&&(h=!1),l.material instanceof c.ShadowMaterial&&(h=!1),Jx(l)||(h=!1),t&&l.layers.test(t)===!1&&(h=!1),h){if(e&&Array.isArray(e)&&e?.includes(l))return;if(typeof e=="function"&&e(l)===!0)return}if(l.isUI!==!0){if(h){const d=l.children;l.children=o;const u=l.position,p=l.scale;if(Number.isNaN(u.x)||Number.isNaN(u.y)||Number.isNaN(u.z)){console.warn(`Object "${l.name}" has NaN values in position or scale.... will ignore it`,u,p);return}l.geometry===null&&(l.geometry=void 0),n.expandByObject(l,!0),l.children=d}for(const d of l.children)r(d)}}}let a=!1;Array.isArray(s)||(s=[s]);for(const l of s)l&&(a=!0,l.updateMatrixWorld(),r(l));return a||console.warn("No objects to fit camera to..."),n}function kb(s,e,t){const i=Bt([s],t?.ignore),n=new c.Vector3;i.getSize(n);const o=new c.Vector3;i.getCenter(o);const r=new c.Vector3;e.getSize(r);const a=new c.Vector3;e.getCenter(a);const l=new c.Vector3;l.set(r.x/n.x,r.y/n.y,r.z/n.z);const h=Math.min(l.x,l.y,l.z),d=t?.scale!==!1;if(d&&aa(s,Ie(s).multiplyScalar(h)),t?.position!==!1){const u=new c.Vector3;i.getCenter(u),u.y=i.min.y;const p=new c.Vector3;e.getCenter(p),p.y=e.min.y;const m=p.clone().sub(u);d&&m.multiplyScalar(h),ot(s,X(s).add(m))}return{boundsBefore:i,scale:l}}function Eb(s,e){const t=Bt([s]),i=new c.Vector3;t.getCenter(i),i.y=t.min.y;const n=e.clone().sub(i),o=X(s);return ot(s,o.add(n)),{offset:n,bounds:t}}function om(s,e,t,i){if(Array.isArray(e)){let r=!0;for(let a=0;a<e.length;a++)om(s,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 c.MeshStandardMaterial;n["material:fbx"]=e;const o=e;return o&&(o.map?n.color.set(1,1,1):n.color.copyLinearToSRGB(o.color),n.emissive.copyLinearToSRGB(o.emissive),n.emissiveIntensity=o.emissiveIntensity,n.opacity=o.opacity,n.displacementScale=o.displacementScale,n.transparent=o.transparent,n.bumpMap=o.bumpMap,n.aoMap=o.aoMap,n.map=o.map,n.displacementMap=o.displacementMap,n.emissiveMap=o.emissiveMap,n.normalMap=o.normalMap,n.envMap=o.envMap,n.alphaMap=o.alphaMap,n.metalness=o.reflectivity,n.vertexColors=o.vertexColors,o.shininess&&(n.roughness=1-Math.sqrt(o.shininess)/10),n.needsUpdate=!0),t===void 0?s.material=n:i[t]=n,!0}let ch=!1;Sx((...s)=>{A()&&ae.Current?.isInXR&&(Lo(!0),Rb("error",...s))});function Lo(s){if(s){if(ch)return;ch=!0,tS()}else{if(!ch)return;ch=!1,iS()}}const El={log:void 0,warn:void 0,error:void 0};class eS{familyName="needle-xr";root=null;context=null;defaultFontSize=.06;constructor(){this.ensureFont()}onEnable(){this.context=ae.Current||ae.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 c.Object3D;userForwardViewPoint=new c.Vector3;oneEuroFilter=new Jp(90,.8);_lastElementRemoveTime=0;onBeforeRender=()=>{const e=this.context?.mainCamera;if(this.context&&e instanceof c.PerspectiveCamera){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,o=e.worldForward;o.y=0,o.normalize().multiplyScalar(n),this.userForwardViewPoint.copy(e.worldPosition).sub(o),this.targetObject.position.distanceTo(this.userForwardViewPoint)>2*i&&(this.targetObject.position.copy(this.userForwardViewPoint),cc(this.targetObject,e,!0,!0),this.targetObject.rotateY(Math.PI)),this.oneEuroFilter.filter(this.targetObject.position,t.position,this.context.time.time);const a=this.context.time.deltaTime;if(t.quaternion.slerp(this.targetObject.quaternion,a*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 l=Date.now();for(let h=0;h<this._activeTexts.length;h++){const d=this._activeTexts[h];if(d instanceof J.__webpack_exports__default.Text&&l-d._activatedTime>2e4){d.removeFromParent(),this._textBuffer.push(d),this._activeTexts.splice(h,1);break}}}}};addLog(e,t){const i=this.getRoot(),n=this.getText();let o=16777215,r=0;switch(e){case"log":o=16777215,r=0;break;case"warn":o=16772761,r=4465152;break;case"error":o=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:o,color:r}),J.__webpack_exports__default.update()}ensureFont(){let e=J.__webpack_exports__default.FontLibrary.getFontFamily(this.familyName);e||(e=J.__webpack_exports__default.FontLibrary.addFontFamily(this.familyName),e.addVariant("normal","normal","./include/needle/arial-msdf.json","./include/needle/arial.png")?.addEventListener("ready",()=>{J.__webpack_exports__default.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 J.__webpack_exports__default.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 o=e.children[n];o instanceof c.Object3D&&this.disableDepthTestRecursive(o,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&&J.__webpack_exports__default.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 J.__webpack_exports__default.Block(t),this.root}}let Do=null;function tS(){Do||(Do=new eS),Do.onEnable();for(const s in El){El[s]=console[s];let e=!1;console[s]=function(){if(El[s]?.apply(console,arguments),!e)try{e=!0,Rb(s,...arguments)}finally{e=!1}}}}function iS(){Do?.onDisable();for(const s in El)console[s]=El[s]}const Ha=new Map;function Rb(s,...e){try{switch(Ha.clear(),s){case"log":Do?.addLog("log",t());break;case"warn":Do?.addLog("warn",t());break;case"error":Do?.addLog("error",t());break}}catch(o){console.error("Error in spatial console",o)}finally{Ha.clear()}function t(){let o="";for(let r=0;r<e.length;r++){const a=e[r];o+=i(a),r<e.length-1&&(o+=", ")}return o}function i(o,r=0){if(typeof o=="string")return'"'+o+'"';if(typeof o=="number"){if(o%1!==0){const l=o.toFixed(5),h=l.indexOf(".");let d=l.length-1;for(;d>h&&l[d]==="0";)d--;return l.substring(0,d+1)}return o.toString()}else if(Array.isArray(o)){let a="[";for(let l=0;l<o.length;l++){const h=o[l];a+=i(h,r+1),l<o.length-1&&(a+=", ")}return a+="]",a}else{if(o===null)return"null";if(o===void 0)return"undefined";if(typeof o=="function")return o.name+"()"}if(o instanceof c.Vector2)return`(${i(o.x)}, ${i(o.y)})`;if(o instanceof c.Vector3)return`(${i(o.x)}, ${i(o.y)}, ${i(o.z)})`;if(o instanceof c.Vector4)return`(${i(o.x)}, ${i(o.y)}, ${i(o.z)}, ${i(o.w)})`;if(o instanceof c.Quaternion)return`(${i(o.x)}, ${i(o.y)}, ${i(o.z)}, ${i(o.w)})`;if(o instanceof c.Material||o instanceof c.Texture)return o.name;if(o instanceof c.Matrix3)return`[${o.elements.join(", ")}]`;if(o instanceof c.Matrix4)return`[${o.elements.join(", ")}]`;if(o instanceof c.Layers)return o.mask.toString();if(typeof o=="object"){if(Ha.has(o))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 Xs{static planeGeometry=new c.PlaneGeometry(2,2,1,1);static renderer=new c.WebGLRenderer({antialias:!1,alpha:!0});static perspectiveCam=new c.PerspectiveCamera;static orthographicCam=new c.OrthographicCamera;static scene=new c.Scene;static blitMaterial=new ud;static mesh=new c.Mesh(Xs.planeGeometry,Xs.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=ud.vertex;const o=this.mesh;o.material=i,o.frustumCulled=!1,this.scene.children.length=0,this.scene.add(o),this.renderer.setSize(e.image.width,e.image.height),this.renderer.clear(),this.renderer.render(this.scene,this.perspectiveCam);const r=new c.Texture(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:o=this.blitMaterial,flipY:r=!1,depthTexture:a=null,depthTest:l=!0,depthWrite:h=!0}=i||{};this.blitMaterial.reset(),o.uniforms.map&&(o.uniforms.map.value=e),o.uniforms.flipY&&(o.uniforms.flipY.value=r),a?(o.uniforms.writeDepth=new c.Uniform$1(!0),o.uniforms.depthTexture.value=a):(o.uniforms.writeDepth=new c.Uniform$1(!1),o.uniforms.depthTexture.value=null),o.needsUpdate=!0,o.uniformsNeedUpdate=!0;const d=this.mesh;d.material=o,d.frustumCulled=!1,this.scene.children.length=0,this.scene.add(d);const u=n.getRenderTarget(),p=n.getContext(),m=p.getParameter(p.DEPTH_TEST),y=p.getParameter(p.DEPTH_WRITEMASK),b=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(h),n.setClearColor(new c.Color(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(u);const g=n.state.buffers.depth;g.setTest(m),g.setMask(y),g.setFunc(b)}static textureToCanvas(e,t=!1){if(!e)return null;(t===!0||e.isCompressedTexture===!0)&&(e=Ob(e));const i=e.image;if(Zx(i)){const n=document.createElement("canvas");n.width=i.width,n.height=i.height;const o=n.getContext("2d");return o?(o.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 Ob(s){return Xs.copyTexture(s)}function Kx(s,e=!1){return Xs.textureToCanvas(s,e)}function Zx(s){return typeof HTMLImageElement<"u"&&s instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&s instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&s instanceof OffscreenCanvas||typeof ImageBitmap<"u"&&s instanceof ImageBitmap}function Jx(s){const e=s.type;return e==="Mesh"||e==="SkinnedMesh"}function sm(s,e){e?s["needle:rendercustomshadow"]=!0:s["needle:rendercustomshadow"]=!1}function Mb(s){if(s){if(s["needle:rendercustomshadow"]===!0)return!0;if(s["needle:rendercustomshadow"]==null)return!0}return!1}function Bt(s,e=void 0,t=void 0,i=void 0){const n=i||new c.Box3;n.makeEmpty();const o=[];function r(l){let h=!0;if(l.visible&&vb(l)!==!1&&!(l.type==="TransformControlsGizmo"||l.type==="TransformControlsPlane")){if(l instanceof c.Box3Helper&&(h=!1),l instanceof c.GridHelper&&(h=!1),l instanceof q.GroundedSkybox&&(h=!1),l.isGizmo===!0&&(h=!1),l.material instanceof c.ShadowMaterial&&(h=!1),Jx(l)||(h=!1),t&&l.layers.test(t)===!1&&(h=!1),h){if(e&&Array.isArray(e)&&e?.includes(l))return;if(typeof e=="function"&&e(l)===!0)return}if(l.isUI!==!0){if(h){const d=l.children;l.children=o;const u=l.position,p=l.scale;if(Number.isNaN(u.x)||Number.isNaN(u.y)||Number.isNaN(u.z)){console.warn(`Object "${l.name}" has NaN values in position or scale.... will ignore it`,u,p);return}l.geometry===null&&(l.geometry=void 0),n.expandByObject(l,!0),l.children=d}for(const d of l.children)r(d)}}}let a=!1;Array.isArray(s)||(s=[s]);for(const l of s)l&&(a=!0,l.updateMatrixWorld(),r(l));return a||console.warn("No objects to fit camera to..."),n}function kb(s,e,t){const i=Bt([s],t?.ignore),n=new c.Vector3;i.getSize(n);const o=new c.Vector3;i.getCenter(o);const r=new c.Vector3;e.getSize(r);const a=new c.Vector3;e.getCenter(a);const l=new c.Vector3;l.set(r.x/n.x,r.y/n.y,r.z/n.z);const h=Math.min(l.x,l.y,l.z),d=t?.scale!==!1;if(d&&aa(s,Ie(s).multiplyScalar(h)),t?.position!==!1){const u=new c.Vector3;i.getCenter(u),u.y=i.min.y;const p=new c.Vector3;e.getCenter(p),p.y=e.min.y;const m=p.clone().sub(u);d&&m.multiplyScalar(h),ot(s,X(s).add(m))}return{boundsBefore:i,scale:l}}function Eb(s,e){const t=Bt([s]),i=new c.Vector3;t.getCenter(i),i.y=t.min.y;const n=e.clone().sub(i),o=X(s);return ot(s,o.add(n)),{offset:n,bounds:t}}function om(s,e,t,i){if(Array.isArray(e)){let r=!0;for(let a=0;a<e.length;a++)om(s,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 c.MeshStandardMaterial;n["material:fbx"]=e;const o=e;return o&&(o.map?n.color.set(1,1,1):n.color.copyLinearToSRGB(o.color),n.emissive.copyLinearToSRGB(o.emissive),n.emissiveIntensity=o.emissiveIntensity,n.opacity=o.opacity,n.displacementScale=o.displacementScale,n.transparent=o.transparent,n.bumpMap=o.bumpMap,n.aoMap=o.aoMap,n.map=o.map,n.displacementMap=o.displacementMap,n.emissiveMap=o.emissiveMap,n.normalMap=o.normalMap,n.envMap=o.envMap,n.alphaMap=o.alphaMap,n.metalness=o.reflectivity,n.vertexColors=o.vertexColors,o.shininess&&(n.roughness=1-Math.sqrt(o.shininess)/10),n.needsUpdate=!0),t===void 0?s.material=n:i[t]=n,!0}let ch=!1;Sx((...s)=>{A()&&ae.Current?.isInXR&&(Lo(!0),Rb("error",...s))});function Lo(s){if(s){if(ch)return;ch=!0,tS()}else{if(!ch)return;ch=!1,iS()}}const El={log:void 0,warn:void 0,error:void 0};class eS{familyName="needle-xr";root=null;context=null;defaultFontSize=.06;constructor(){this.ensureFont()}onEnable(){this.context=ae.Current||ae.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 c.Object3D;userForwardViewPoint=new c.Vector3;oneEuroFilter=new Jp(90,.8);_lastElementRemoveTime=0;onBeforeRender=()=>{const e=this.context?.mainCamera;if(this.context&&e instanceof c.PerspectiveCamera){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,o=e.worldForward;o.y=0,o.normalize().multiplyScalar(n),this.userForwardViewPoint.copy(e.worldPosition).sub(o),this.targetObject.position.distanceTo(this.userForwardViewPoint)>2*i&&(this.targetObject.position.copy(this.userForwardViewPoint),cc(this.targetObject,e,!0,!0),this.targetObject.rotateY(Math.PI)),this.oneEuroFilter.filter(this.targetObject.position,t.position,this.context.time.time);const a=this.context.time.deltaTime;if(t.quaternion.slerp(this.targetObject.quaternion,a*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 l=Date.now();for(let h=0;h<this._activeTexts.length;h++){const d=this._activeTexts[h];if(d instanceof J.__webpack_exports__default.Text&&l-d._activatedTime>2e4){d.removeFromParent(),this._textBuffer.push(d),this._activeTexts.splice(h,1);break}}}}};addLog(e,t){const i=this.getRoot(),n=this.getText();let o=16777215,r=0;switch(e){case"log":o=16777215,r=0;break;case"warn":o=16772761,r=4465152;break;case"error":o=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:o,color:r}),J.__webpack_exports__default.update()}ensureFont(){let e=J.__webpack_exports__default.FontLibrary.getFontFamily(this.familyName);e||(e=J.__webpack_exports__default.FontLibrary.addFontFamily(this.familyName),e.addVariant("normal","normal","./include/needle/arial-msdf.json","./include/needle/arial.png")?.addEventListener("ready",()=>{J.__webpack_exports__default.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 J.__webpack_exports__default.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 o=e.children[n];o instanceof c.Object3D&&this.disableDepthTestRecursive(o,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&&J.__webpack_exports__default.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 J.__webpack_exports__default.Block(t),this.root}}let Do=null;function tS(){Do||(Do=new eS),Do.onEnable();for(const s in El){El[s]=console[s];let e=!1;console[s]=function(){if(El[s]?.apply(console,arguments),!e)try{e=!0,Rb(s,...arguments)}finally{e=!1}}}}function iS(){Do?.onDisable();for(const s in El)console[s]=El[s]}const Ha=new Map;function Rb(s,...e){try{switch(Ha.clear(),s){case"log":Do?.addLog("log",t());break;case"warn":Do?.addLog("warn",t());break;case"error":Do?.addLog("error",t());break}}catch(o){console.error("Error in spatial console",o)}finally{Ha.clear()}function t(){let o="";for(let r=0;r<e.length;r++){const a=e[r];o+=i(a),r<e.length-1&&(o+=", ")}return o}function i(o,r=0){if(typeof o=="string")return'"'+o+'"';if(typeof o=="number"){if(o%1!==0){const l=o.toFixed(5),h=l.indexOf(".");let d=l.length-1;for(;d>h&&l[d]==="0";)d--;return l.substring(0,d+1)}return o.toString()}else if(Array.isArray(o)){let a="[";for(let l=0;l<o.length;l++){const h=o[l];a+=i(h,r+1),l<o.length-1&&(a+=", ")}return a+="]",a}else{if(o===null)return"null";if(o===void 0)return"undefined";if(typeof o=="function")return o.name+"()"}if(o instanceof c.Vector2)return`(${i(o.x)}, ${i(o.y)})`;if(o instanceof c.Vector3)return`(${i(o.x)}, ${i(o.y)}, ${i(o.z)})`;if(o instanceof c.Vector4)return`(${i(o.x)}, ${i(o.y)}, ${i(o.z)}, ${i(o.w)})`;if(o instanceof c.Quaternion)return`(${i(o.x)}, ${i(o.y)}, ${i(o.z)}, ${i(o.w)})`;if(o instanceof c.Material||o instanceof c.Texture)return o.name;if(o instanceof c.Matrix3)return`[${o.elements.join(", ")}]`;if(o instanceof c.Matrix4)return`[${o.elements.join(", ")}]`;if(o instanceof c.Layers)return o.mask.toString();if(typeof o=="object"){if(Ha.has(o))return"*";let a=`{
|
|
83
83
|
`;a+=n(r);const l=Object.keys(o);let h="";for(let d=0;d<l.length;d++){const u=l[d],p=o[u];if(Ha.has(p)){h+="";continue}Ha.set(p,!0),h+=u+":"+i(p,r+1),d<l.length-1&&(h+=", "),h.length>=60&&(h+=`
|
|
84
84
|
`,h+=n(r),a+=h,h="")}return a+=h,a+=`
|
|
85
85
|
}`,a}return o}function n(o){let r="";for(let a=0;a<o;a++)r+=" ";return r}}const nS=w("nodevlogs");function Se(s,e=ci.Log){Eo(e,s)}function he(s){Se(s,ci.Warn)}function dc(s){Se(s,ci.Error)}let op,Zu;function A(){if(nS)return!1;if(op!==void 0)return op;if(Zu!==void 0)return Zu;let s=Ii();return s||(s=window.location.hostname.endsWith(".local-credentialless.webcontainer.io")),Zu=s,s}function sS(s){op=s}let Ri,yo=null,xn=null,qa=!1,my=null;const Tb="terminal",oS=w("console");oS&&rm();const rS=Symbol("consoleParent");function rm(){if(Ri){Ri.showSwitch();return}dS()}function Ab(){Ri&&(Ri.hide(),Ri.hideSwitch())}function aS(){my||(my=setInterval(lS,500))}let gy=0;function lS(){const s=pb(),e=s!==gy;gy=s,e&&cS()}function cS(){rm(),xn&&(xn.setAttribute("error","true"),xn.innerText="🤬")}function hS(){xn&&(xn.removeAttribute("error"),xn.innerText=Tb)}function dS(s=!1){if(Ri!==void 0||qa)return;qa=!0;const e=document.createElement("script");e.onload=()=>{if(!globalThis.VConsole){console.warn("🌵 Debug console failed to load."),qa=!1,Ri=null;return}qa=!1,aS(),Ri=new VConsole({pluginOrder:["default","needle-console"]});const t=globalThis["needle:codegen_files"];if(t&&t.length>0&&Ri.addPlugin(uS()),yo=pS(),yo&&(yo[rS]=yo.parentElement,yo.style.position="absolute",yo.style.zIndex=Number.MAX_SAFE_INTEGER.toString()),Ri.setSwitchPosition(20,30),xn=fS(),xn){xn.innerText=Tb,xn.addEventListener("click",hS);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
|
-
`,yo?.prepend(i),s===!0&&pb()<=0&&Ab(),console.log("🌵 Debug console has loaded")}},e.onerror=()=>{console.warn("🌵 Debug console failed to load."+(window.crossOriginIsolated?"This page is using cross-origin isolation, so external scripts can't be loaded.":"")),qa=!1,Ri=null},e.src="https://cdn.jsdelivr.net/npm/vconsole@3.15.1/dist/vconsole.min.js",document.body.appendChild(e)}function uS(){if(!globalThis.VConsole)return;const s=new VConsole.VConsolePlugin("needle-console","🌵 Inspect glTF"),e=()=>document.querySelector("#__vc_plug_"+s._id+" iframe");return s.on("renderTab",function(t){const i=globalThis["needle:codegen_files"];if(!i||i.length===0)return;let n=globalThis["needle:codegen_files"][0];const o=n.indexOf("?");o>-1&&(n=n.substring(0,o));const a=location.protocol+"//"+location.host+location.pathname+"/"+n,l=encodeURIComponent(a);s.fullUrl="https://viewer.needle.tools?inspect&file="+l;var h='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';t(h)}),s.on("show",function(){const t=e();t&&t.src!==s.fullUrl&&(t.src=s.fullUrl)}),s.on("hide",function(){const t=e();t&&(t.src="")}),s.on("addTopBar",function(t){var i=new Array;i.push({name:"Open in new window ↗",onClick:function(n){window.open(s.fullUrl,"_blank"),Ri?.hide()}}),i.push({name:"Reload",onClick:function(n){const o=e();o&&(o.src=s.fullUrl)}}),i.push({name:"Fullscreen",onClick:function(n){const o=e();o.requestFullscreen?o.requestFullscreen():o.webkitRequestFullscreen instanceof Function&&o.webkitRequestFullscreen()}}),t(i)}),s}function fS(){const s=document.querySelector("#__vconsole .vc-switch");return s||null}function pS(){const s=document.querySelector("#__vconsole");return s||null}const Lb=w("debugdefines");eo('if(!globalThis["NEEDLE_ENGINE_VERSION"]) globalThis["NEEDLE_ENGINE_VERSION"] = "0.0.0";');eo('if(!globalThis["NEEDLE_ENGINE_GENERATOR"]) globalThis["NEEDLE_ENGINE_GENERATOR"] = "unknown";');eo('if(!globalThis["NEEDLE_PROJECT_BUILD_TIME"]) globalThis["NEEDLE_PROJECT_BUILD_TIME"] = "unknown";');eo('if(!globalThis["NEEDLE_PUBLIC_KEY"]) globalThis["NEEDLE_PUBLIC_KEY"] = "unknown";');eo('globalThis["__NEEDLE_ENGINE_VERSION__"] = "4.9.3";');eo('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";');eo('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "
|
|
144
|
+
`,yo?.prepend(i),s===!0&&pb()<=0&&Ab(),console.log("🌵 Debug console has loaded")}},e.onerror=()=>{console.warn("🌵 Debug console failed to load."+(window.crossOriginIsolated?"This page is using cross-origin isolation, so external scripts can't be loaded.":"")),qa=!1,Ri=null},e.src="https://cdn.jsdelivr.net/npm/vconsole@3.15.1/dist/vconsole.min.js",document.body.appendChild(e)}function uS(){if(!globalThis.VConsole)return;const s=new VConsole.VConsolePlugin("needle-console","🌵 Inspect glTF"),e=()=>document.querySelector("#__vc_plug_"+s._id+" iframe");return s.on("renderTab",function(t){const i=globalThis["needle:codegen_files"];if(!i||i.length===0)return;let n=globalThis["needle:codegen_files"][0];const o=n.indexOf("?");o>-1&&(n=n.substring(0,o));const a=location.protocol+"//"+location.host+location.pathname+"/"+n,l=encodeURIComponent(a);s.fullUrl="https://viewer.needle.tools?inspect&file="+l;var h='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';t(h)}),s.on("show",function(){const t=e();t&&t.src!==s.fullUrl&&(t.src=s.fullUrl)}),s.on("hide",function(){const t=e();t&&(t.src="")}),s.on("addTopBar",function(t){var i=new Array;i.push({name:"Open in new window ↗",onClick:function(n){window.open(s.fullUrl,"_blank"),Ri?.hide()}}),i.push({name:"Reload",onClick:function(n){const o=e();o&&(o.src=s.fullUrl)}}),i.push({name:"Fullscreen",onClick:function(n){const o=e();o.requestFullscreen?o.requestFullscreen():o.webkitRequestFullscreen instanceof Function&&o.webkitRequestFullscreen()}}),t(i)}),s}function fS(){const s=document.querySelector("#__vconsole .vc-switch");return s||null}function pS(){const s=document.querySelector("#__vconsole");return s||null}const Lb=w("debugdefines");eo('if(!globalThis["NEEDLE_ENGINE_VERSION"]) globalThis["NEEDLE_ENGINE_VERSION"] = "0.0.0";');eo('if(!globalThis["NEEDLE_ENGINE_GENERATOR"]) globalThis["NEEDLE_ENGINE_GENERATOR"] = "unknown";');eo('if(!globalThis["NEEDLE_PROJECT_BUILD_TIME"]) globalThis["NEEDLE_PROJECT_BUILD_TIME"] = "unknown";');eo('if(!globalThis["NEEDLE_PUBLIC_KEY"]) globalThis["NEEDLE_PUBLIC_KEY"] = "unknown";');eo('globalThis["__NEEDLE_ENGINE_VERSION__"] = "4.9.3";');eo('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";');eo('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Mon Sep 15 2025 07:49:39 GMT+0000 (Coordinated Universal Time)";');eo('globalThis["__NEEDLE_PUBLIC_KEY__"] = "'+NEEDLE_PUBLIC_KEY+'";');const Ki="4.9.3",Vd="undefined",am="Mon Sep 15 2025 07:49:39 GMT+0000 (Coordinated Universal Time)";Lb&&console.log(`Engine version: ${Ki} (generator: ${Vd})
|
|
145
145
|
Project built at ${am}`);const Gr=NEEDLE_PUBLIC_KEY,as="needle_isActiveInHierarchy",Po="builtin_components",Rl="needle_editor_guid";function eo(s){try{(0,eval)(s)}catch(e){Lb&&console.error(e)}}let Db,yy=null;function en(){return Db}function lm(s){if(s==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}yy!==s&&(yy=s,Db=new s)}const ri=Symbol("shadowDomOwner"),mS=w("debugpatch");function $d(s,e,t,i){const n=mS===e;if(!t&&!i)return;const o=e+"___needle";yS(s,e,t,i);const r=Object.getOwnPropertyDescriptor(s,e),a=s[e];n&&console.log("Patch",s.constructor.name,e,r,a),r?(n&&console.log("Apply patch with existing descriptor",s.constructor.name,e,r),typeof r.value=="function"&&(s[e]=by(r.value,s,e))):(n&&console.log("Create patch with new property",s.constructor.name,e,r),Object.defineProperty(s,e,{set:function(l){if(typeof l=="function")this[o]=by(l,s,e);else{const h=this[o];Ib(s,e,this,h,l),this[o]=l,jb(s,e,this,h,l)}},get:function(){const l=this[o];return typeof l=="function"&&l[o]?l[o]:l}}))}function gS(s,e,t){const i=cm(s,e);if(i)for(let n=i.length-1;n>=0;n--){const o=i[n];o.prefix===t&&(o.prefix=null),o.postfix===t&&(o.postfix=null),!o.prefix&&!o.postfix&&i.splice(n,1)}}const _y=Symbol("Needle:Patches:WrappedFunction");function by(s,e,t){if(s[_y])return s;const i=function(...n){Ib(e,t,this,...n);const o=s.apply(this,n);return jb(e,t,this,o,...n),o};return i[_y]=!0,i}const Wh="Needle:Patches";function rp(){return globalThis[Wh]||(globalThis[Wh]=new WeakMap),globalThis[Wh]}function cm(s,e){const t=rp().get(s);return t?t.get(e):null}function yS(s,e,t,i){let n=rp().get(s);n||(n=new Map,rp().set(s,n));let o=n.get(e);o||(o=[],n.set(e,o)),o.push({prefix:t,postfix:i})}function Ib(s,e,t,...i){if(!t)return;const n=cm(s,e);if(n)for(const o of n)o.prefix?.call(t,...i)}function jb(s,e,t,i,...n){if(!t)return;const o=cm(s,e);if(o)for(const r of o)r.postfix?.call(t,i,...n)}const la=[];function Wd(s){la.indexOf(s)===-1&&la.push(s)}function _S(s){const e=la.indexOf(s);e!==-1&&la.splice(e,1)}const ca=[];function hm(s){ca.indexOf(s)===-1&&ca.push(s)}function bS(s){const e=ca.indexOf(s);e!==-1&&ca.splice(e,1)}function Bb(s){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-start",{detail:s}));for(let e=0;e<la.length;e++)la[e](s)}function Fb(s){globalThis.dispatchEvent(new CustomEvent("needle-xrsession-end",{detail:s}));for(let e=0;e<ca.length;e++)ca[e](s)}const Xe=w("debuginput");var Gd=(s=>(s.Mouse="mouse",s.Touch="touch",s.Controller="controller",s.Hand="hand",s))(Gd||{}),we=(s=>(s.PointerDown="pointerdown",s.PointerUp="pointerup",s.PointerMove="pointermove",s.KeyDown="keydown",s.KeyUp="keyup",s.KeyPressed="keypress",s))(we||{});class Kn extends PointerEvent{clientZ;deviceIndex;origin;source;mode;get isSpatial(){return this.mode!="screen"}get ray(){return this._ray||(this._ray=new c.Ray(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(),Xe&&console.warn("Stop propagation...",this.pointerId,this.pointerType)}}class ul extends KeyboardEvent{source;constructor(e,t,i){super(e,i),this.source=t}stopImmediatePropagation(){super.stopImmediatePropagation(),this.source?.stopImmediatePropagation()}}class vS{key;keyType;source;constructor(e){this.key=e.key,this.keyType=e.type,this.source=e}}var Ht=(s=>(s[s.Early=-100]="Early",s[s.Default=0]="Default",s[s.Late=100]="Late",s))(Ht||{});class Ub{_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 o=this._eventListeners[e],r=o.find(a=>a.priority===n);r?r.listeners.push({callback:t,options:i}):(o.push({priority:n,listeners:[{callback:t,options:i}]}),o.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 o=n.find(a=>a.priority===i.queue);if(!o)return;const r=o.listeners.findIndex(a=>a.callback===t);r>=0&&o.listeners.splice(r,1)}else for(const o of n){const r=o.listeners.findIndex(a=>a.callback===t);r>=0&&o.listeners.splice(r,1)}}dispatchEvent(e){let t=!1;if(e instanceof ul){const i=this._eventListeners[e.type];if(i)for(const n of i)for(let o=0;o<n.listeners.length;o++){const r=n.listeners[o];if(r.options?.signal?.aborted){n.listeners.splice(o,1),o--;continue}r.options.once&&(n.listeners.splice(o,1),o--),r.callback(e)}}if(e instanceof Kn){const i=this._eventListeners[e.type];if(i)for(const n of i){if(t)break;for(let o=0;o<n.listeners.length;o++){const r=n.listeners[o];if(r.options?.signal?.aborted){n.listeners.splice(o,1),o--;continue}if(e.immediatePropagationStopped){t=!0,Xe&&console.log("immediatePropagationStopped",e.type);break}else e.propagationStopped&&(t=!0,Xe&&console.log("propagationStopped",e.type));r.options.once&&(n.listeners.splice(o,1),o--),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 o of e)if(i===o){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 c.Vector2];_pointerPositionsLastFrame=[new c.Vector2];_pointerPositionsDelta=[new c.Vector2];_pointerPositionsRC=[new c.Vector2];_pointerPositionDown=[new c.Vector3];_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":Xe&&Se("Create Pointer down"),this.onDownButton(e.deviceIndex,e.button),this.onDown(e);break;case"pointermove":Xe&&Se("Create Pointer move"),this.onMove(e);break;case"pointerup":Xe&&Se("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&&exports.DeviceUtilities.isMozillaXR()?!0:(Xe&&console.warn("CanReceiveInput:False for",e.target),!1)}onContextMenu=e=>{this.canReceiveInput(e)!==!1&&e instanceof PointerEvent&&e.pointerType};keysPressed={};onKeyDown=e=>{if(Xe&&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 ul("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 ul("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 ul("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);Xe&&Se(`pointer down #${t}, identifier:${e.pointerId}`);const i=this.getAndUpdateSpatialObjectForScreenPosition(t,e.clientX,e.clientY),n=new Kn("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),o=new Kn("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(o)};onPointerCancel=e=>{this.context.isInAR||(Xe&&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 Kn("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,Xe&&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),o=this.getAndUpdateSpatialObjectForScreenPosition(n,i.clientX,i.clientY),r=new Kn("pointerdown",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:0,clientX:i.clientX,clientY:i.clientY,pointerType:"touch",buttonName:"unknown",device:o,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),o=this.getAndUpdateSpatialObjectForScreenPosition(n,i.clientX,i.clientY),r=new Kn("pointermove",e,{origin:this,mode:"screen",deviceIndex:0,pointerId:n,button:0,clientX:i.clientX,clientY:i.clientY,pointerType:"touch",buttonName:"unknown",device:o,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),o=new Kn("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(o),this._pointerIds[n]=-1}};tempNearPlaneVector=new c.Vector3;tempFarPlaneVector=new c.Vector3;tempLookMatrix=new c.Matrix4;getAndUpdateSpatialObjectForScreenPosition(e,t,i){let n=this._pointerSpace[e];n||(n=new c.Object3D,this._pointerSpace[e]=n),this._pointerSpace[e]=n;const o=this.context.mainCamera;if(o){const r=this.tempNearPlaneVector.set(t,i,-1);this.convertScreenspaceToRaycastSpace(r);const a=this.tempFarPlaneVector.set(r.x,r.y,1);r.unproject(o),a.unproject(o);const l=o.worldUp||V(0,1,0).applyQuaternion(ue(o));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,o=i>=t.x&&i<=t.right&&n>=t.y&&n<=t.bottom;return Xe&&!o&&console.log("Not in rect",t,i,n),o}onDown(e){const t=e.pointerId;if(this.getPointerPressed(t)&&console.warn(`Received pointerDown for pointerId that is already pressed: ${t}`,Xe?e:""),Xe&&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 c.Vector3);for(this._pointerPositionDown[t].set(e.clientX,e.clientY,e.clientZ??0);t>=this._pointerPositions.length;)this._pointerPositions.push(new c.Vector2);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)){Xe&&console.log(e.pointerType,"UP",t,"was not down");return}Xe&&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 l=this._pointerEventsPressed.length-1;l>=0;l--)if(this._pointerEventsPressed[l].pointerId===t){this._pointerEventsPressed.splice(l,1);break}if(!this._pointerPositionDown[t]){Xe&&he("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 n=this._pointerUpTime[t],o=this._pointerDownTime[t],r=this.context.time.realtimeSinceStartup,a=r-o;if(t>=this._pointerUpTime.length&&this._pointerUpTime.push(-99),this._pointerUpTime[t]=r,a<1){let l=e.clientX-this._pointerPositionDown[t].x,h=e.clientY-this._pointerPositionDown[t].y,d=0;if(e.isSpatial&&e.clientZ!=null&&(d=e.clientZ-this._pointerPositionDown[t].z,l*=200,h*=200,d*=200),Math.abs(l)<5&&Math.abs(h)<5&&Math.abs(d)<5){this.setPointerState(t,this._pointerClick,!0),e.isClick=!0;const u=r-n;Xe&&console.log("CLICK",t,l,h,d,u),u<this._doubleClickTimeThreshold&&u>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 c.Vector2);for(;t>=this._pointerPositionsLastFrame.length;)this._pointerPositionsLastFrame.push(new c.Vector2);for(;t>=this._pointerPositionsDelta.length;)this._pointerPositionsDelta.push(new c.Vector2);const i=this._pointerPositionsLastFrame[t];i.copy(this._pointerPositions[t]);const n=this._pointerPositionsDelta[t];let o=e.clientX-i.x,r=e.clientY-i.y;if(e.source instanceof MouseEvent||e.source instanceof TouchEvent){const d=e.source;o===0&&d.movementX!==0&&(o=d.movementX||0),r===0&&d.movementY!==0&&(r=d.movementY||0)}n.x+=o,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 c.Vector2);const h=this._pointerPositionsRC[t];h.set(a,l),this.convertScreenspaceToRaycastSpace(h)}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):(Xe&&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=F.Current;try{F.Current=this.context,this.dispatchEvent(e)}finally{F.Current=t}}}const Zr=new c.Matrix4().makeRotationY(Math.PI),ki=new c.Quaternion().setFromAxisAngle(new c.Vector3(0,1,0),Math.PI),wS=w("debugwebxr");class xS{priority=-1e5;gameObject;isXRRig(){return!0}get isActive(){return this.gameObject.visible}constructor(){if(this.gameObject=new c.Object3D,this.gameObject.name="Implicit XR Rig",wS){const e=ym(16733661);e.position.y+=.5,this.gameObject.add(e)}}}const Vn=w("debugwebxr"),hh=w("debugcustomgesture"),SS="https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles",CS="generic-trigger",PS=new c.Quaternion().setFromEuler(new c.Euler(c.MathUtils.degToRad(0),c.MathUtils.degToRad(-90),c.MathUtils.degToRad(-90))),OS=new c.Vector3(.04,-.04,0);class dm{xr;get context(){return this.xr.context}inputSource;index=0;emitEvents=!0;get connected(){return this._connected}_connected=!0;get isTracking(){return this._isTracking}_isTracking=!1;get gamepad(){return this.__gamepad??=this.inputSource.gamepad}__gamepad;get isHand(){return this.hand!=null}get hand(){return this.__hand??=this.inputSource.hand}__hand;get handObject(){return this.context.renderer.xr.getHand(this.index)}get profiles(){return this.inputSource.profiles}get layout(){return this._layout}get targetRayMode(){return this.inputSource.targetRayMode}get targetRaySpace(){return this.inputSource.targetRaySpace}get gripSpace(){return this.inputSource.gripSpace}get side(){return this.__side??=this.inputSource.handedness}__side=void 0;get isRight(){return this.side==="right"}get isLeft(){return this.side==="left"}get isStylus(){return this._isMxInk}getHitTestSource(){return this._hitTestSource||this._requestHitTestSource(),this._hitTestSource}get hasHitTestSource(){return this._hitTestSource}cancelHitTestSource(){this._hitTestSource&&(this._hitTestSource.cancel(),this._hitTestSource=void 0)}_hitTestSource=void 0;_hasSelectEvent=!1;get hasSelectEvent(){return this._hasSelectEvent}_isMxInk=!1;_isMetaQuestTouchController=!1;getHitTest(){return this.xr.getHitTest(this)}_handJointPoses=new Map;getHandJointPose(e,t){if(t=t||this.xr.frame,!this.hand||!t?.getJointPose||!this.xr.referenceSpace)return null;let i=this._handJointPoses?.get(e);return i||(i=t.getJointPose(e,this.xr.referenceSpace),i&&this._handJointPoses.set(e,i),i)}_gripMatrix=new c.Matrix4;_gripPosition=new c.Vector3;_gripQuaternion=new c.Quaternion;_linearVelocity=new c.Vector3;_rayPositionRaw=new c.Vector3;_rayRotationRaw=new c.Quaternion;_rayMatrix=new c.Matrix4;_rayPosition=new c.Vector3;_rayQuaternion=new c.Quaternion;get gripPosition(){return V(this._gripPosition)}get gripQuaternion(){return Gt(this._gripQuaternion)}get gripMatrix(){return this._gripMatrix}get gripLinearVelocity(){return V(this._linearVelocity).applyQuaternion(ki)}get rayPosition(){return V(this._rayPosition)}get rayQuaternion(){return Gt(this._rayQuaternion)}get gripWorldPosition(){return V(this._gripWorldPosition)}_gripWorldPosition=new c.Vector3;get gripWorldQuaternion(){return Gt(this._gripWorldQuaternion)}_gripWorldQuaternion=new c.Quaternion;get rayWorldPosition(){return V(this._rayWorldPosition)}_rayWorldPosition=new c.Vector3;updateRayWorldPosition(){const e=this.xr.context.mainCamera?.parent;this._rayWorldPosition.copy(this._rayPositionRaw),e&&this._rayWorldPosition.applyMatrix4(e.matrixWorld)}get rayWorldQuaternion(){return Gt(this._rayWorldQuaternion)}_rayWorldQuaternion=new c.Quaternion;get pinchPosition(){return V(this._pinchPosition)}_pinchPosition=new c.Vector3;updateRayWorldQuaternion(){const e=this.xr.context.mainCamera?.parent,t=e?ue(e):void 0;this._rayWorldQuaternion.copy(this._rayRotationRaw).multiply(ki),t&&this._rayWorldQuaternion.premultiply(t)}get ray(){return this._ray.origin.copy(this.rayWorldPosition),this._ray.direction.copy(V(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=V(0,1,0).applyQuaternion(e.quaternion),i=V(0,1,0).dot(t);return this._hand_wristDotUp=i}}get isHandUpsideDown(){return this.handWristDotUp!==void 0?this.handWristDotUp<-.7:!1}get isTeleportGesture(){return this.isHandUpsideDown&&this.getGesture("pinch")?.isDown}get object(){return this._object}_object;_gripSpaceObject;_raySpaceObject;model=null;_debugAxesHelper=new c.AxesHelper(.15);_debugGripAxesHelper=new c.AxesHelper(.07);_debugRayAxesHelper=new c.AxesHelper(.07);async getModelUrl(){return this.getMotionController?.then(e=>e?.assetUrl||null)}constructor(e,t,i){this.xr=e,this.inputSource=t,this.index=i,this._object=new c.Object3D,this._object.name=`NeedleXRController_${i}`,Vn&&(this._object.add(this._debugAxesHelper),this._gripSpaceObject=new c.Object3D,this._raySpaceObject=new c.Object3D,this._gripSpaceObject.name=`NeedleXRController_${i}_gripSpace`,this._raySpaceObject.name=`NeedleXRController_${i}_raySpace`,this._gripSpaceObject.add(this._debugGripAxesHelper),this._raySpaceObject.add(this._debugRayAxesHelper),this.xr.context.scene.add(this._gripSpaceObject),this.xr.context.scene.add(this._raySpaceObject)),this.xr.context.scene.add(this._object),this._ray=new c.Ray,this.pointerInit={origin:this,pointerType:this.hand?"hand":"controller",deviceIndex:this.index,pointerId:-1,mode:this.inputSource.targetRayMode,ray:this._ray,device:this._object,buttonName:"none"},this.initialize(),this.subscribeEvents()}_hitTestSourcePromise=null;_requestHitTestSource(){return this._hitTestSourcePromise?this._hitTestSourcePromise:this.xr.mode==="immersive-ar"&&this.inputSource.targetRayMode==="tracked-pointer"&&this.xr.session.requestHitTestSourceForTransientInput?this._hitTestSourcePromise=this.xr.session.requestHitTestSourceForTransientInput({profile:this.inputSource.profiles[0],offsetRay:new XRRay})?.then(e=>(this._hitTestSourcePromise=null,this.connected?this._hitTestSource=e:(e.cancel(),null)))??null:null}onPointerHits=e=>{};onUpdate(e){this.onUpdateFrame(e),this.updateInputEvents(),this.onUpdateMove()}onRenderDebug(){B.DrawSphere(this.rayWorldPosition,.003),B.DrawDirection(this.rayWorldPosition,V(0,0,10).applyQuaternion(this.rayWorldQuaternion));const t=(this.inputSource.gripSpace?this.gripWorldPosition:this.object.worldPosition).sub(this.object.worldForward.multiplyScalar(.1)),i=this.inputSource.profiles.join(`
|
|
146
146
|
`);let n=`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&&(n+=`
|
|
@@ -149,7 +149,7 @@ Pinch: ${this.getGesture("pinch")?.value.toFixed(3)}`),n+=`
|
|
|
149
149
|
`+i,n+=`
|
|
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 o=this.inputSource.gamepad;let r="[btns "+o.buttons.length+"]: "+o.buttons.map(a=>a.value.toPrecision(1)).join(",");r+=`
|
|
151
151
|
[axes `+o.axes.length+"]: "+o.axes.map(a=>a.toPrecision(1)).join(","),n+=`
|
|
152
|
-
`+r}B.DrawLabel(t,n,.006)}onUpdateFrame(e){if(this._handJointPoses.clear(),this._hand_wristDotUp=void 0,!this.xr.referenceSpace||!this.inputSource.gamepad?.connected){this._isTracking=!1;return}const t=e.getPose(this.inputSource.targetRaySpace,this.xr.referenceSpace);this._isTracking=t!=null;let i=null,n=null,o=null,r=null;if(t){const d=t.transform;this._rayMatrix.fromArray(d.matrix).premultiply(Zr),this._rayMatrix.decompose(this._rayPosition,this._rayQuaternion,V(1,1,1)),o=V(d.position),r=Gt(d.orientation),this._rayPositionRaw.copy(o),this._rayRotationRaw.copy(r)}if(this.inputSource.gripSpace){const d=e.getPose(this.inputSource.gripSpace,this.xr.referenceSpace);if(d){const u=d.transform;if(i=V(u.position),n=Gt(u.orientation),this._gripMatrix.fromArray(u.matrix).premultiply(Zr),this._gripMatrix.decompose(this._gripPosition,this._gripQuaternion,V(1,1,1)),"linearVelocity"in d&&d.linearVelocity){const p=d.linearVelocity;this._linearVelocity.set(p.x,p.y,p.z)}}}this.xr.context.mainCamera?.parent&&(this._object.parent!==this.xr.context.mainCamera?.parent&&this.xr.context.mainCamera.parent.add(this._object),this._gripSpaceObject!==void 0&&this._gripSpaceObject?.parent!==this.xr.context.mainCamera?.parent&&this.xr.context.mainCamera.parent.add(this._gripSpaceObject),this._raySpaceObject!==void 0&&this._raySpaceObject?.parent!==this.xr.context.mainCamera?.parent&&this.xr.context.mainCamera.parent.add(this._raySpaceObject));const a=this.hand;if(a){let d=!1;const u=a.get("wrist"),p=u&&this.getHandJointPose(u,e);if(p){d=!0;const _=p.transform.position,g=p.transform.orientation;this._object.position.set(_.x,_.y,_.z),this._object.quaternion.set(g.x,g.y,g.z,g.w).multiply(ki)}d||(this._object.position.copy(this._rayPosition),this._object.quaternion.copy(this._rayQuaternion).multiply(ki));const m=a.get("middle-finger-metacarpal"),y=m&&this.getHandJointPose(m,e);y&&(this._gripMatrix.fromArray(y.transform.matrix).premultiply(Zr),this._gripMatrix.decompose(this._gripPosition,this._gripQuaternion,V(1,1,1)),i=V().copy(y.transform.position),n=Gt().copy(y.transform.orientation),n.multiply(PS),i.add(V(OS).applyQuaternion(n)))}else this.inputSource.gripSpace&&this.targetRayMode==="transient-pointer"&&i&&n?(this._object.position.copy(i),this._object.quaternion.copy(n).multiply(ki)):o&&r&&(this._object.position.copy(o),this._object.quaternion.copy(r).multiply(ki));Vn&&(o&&r&&(this._raySpaceObject?.position.copy(o),this._raySpaceObject?.quaternion.copy(r).multiply(ki)),i&&n&&(this._gripSpaceObject?.position.copy(i),this._gripSpaceObject?.quaternion.copy(n).multiply(ki)));const l=this.xr.context.mainCamera?.parent,h=l?ue(l):void 0;i&&n&&(this._gripWorldPosition.copy(i),l&&this._gripWorldPosition.applyMatrix4(l.matrixWorld),this._gripWorldQuaternion.copy(n),this._gripWorldQuaternion.multiply(ki),h&&this._gripWorldQuaternion.premultiply(h)),this.updateRayWorldPosition(),this.updateRayWorldQuaternion()}onDisconnected(){this._connected=!1,Vn&&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 wy(void 0,e);return i.pressed=t.pressed,i.value=t.value,i.isDown=t.isDown,i.isUp=t.isUp,this._needleGamepadButtons[e]=i,i}getPointerId(e){if((e==="primary"||e==="pinch")&&(e=0),typeof e!="number"){const t=this._buttonMap.get(e);if(t===void 0)return;e=t}return this.index*10+e}_needleGamepadButtons={};toNeedleGamepadButton(e,t){if(!this.inputSource.gamepad?.buttons)return;const i=this.inputSource.gamepad?.buttons[e],n=this.states[e],o=this._needleGamepadButtons[e]||new wy(e,t);return i&&(o.pressed=i.pressed,o.value=i.value,o.touched=i.touched),n&&(o.isDown=n.isDown,o.isUp=n.isUp),this._needleGamepadButtons[e]=o,o}getStick(e){if(!this._layout)return{x:0,y:0,z:0};if(this.isHand)return{x:0,y:0,z:0};e==="primary"&&this._layout.components["xr-standard-thumbstick"]&&(e="xr-standard-thumbstick");const t=this._layout?.components[e];if(t?.gamepadIndices)switch(t.type){case"thumbstick":if(this.inputSource.gamepad){const i=t.gamepadIndices.xAxis,n=t.gamepadIndices.yAxis;let o=this.inputSource.gamepad.axes[i]||0,r=this.inputSource.gamepad.axes[n]||0;o*=-1,r*=-1;const a=t.gamepadIndices.button,l=this.inputSource.gamepad?.buttons[a]?.value||0;return{x:o,y:r,z:l}}}return{x:0,y:0,z:0}}_buttonMap=new Map;_motioncontroller;_layout;getMotionController;initialize(){if(this._hasSelectEvent=this.profiles.includes("generic-hand-select")||this.profiles.some(e=>e.startsWith("generic-trigger")),this._isMetaQuestTouchController=this.profiles.includes("meta-quest-touch-plus")||this.profiles.includes("oculus-touch-v3"),this._isMxInk=this.profiles.includes("logitech-mx-ink"),!this._layout){if(this.inputSource.targetRayMode==="transient-pointer")return;const e=se.fetchProfile(this.inputSource,SS,CS);this.getMotionController=e.then(t=>{if(!this.connected)return null;this._motioncontroller=new se.MotionController(this.inputSource,t.profile,t.assetPath||"");const n=t.profile.layouts[this.inputSource.handedness];if(this._layout=n,this._layout&&!this._layout.gamepad?.length){this._layout.gamepad=[];for(const o in this._layout.components){const r=this._layout.components[o];this._layout.gamepad[r.gamepadIndices.button]=o}}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),!hh&&(Vn&&B.DrawDirection(this.rayWorldPosition,V(0,.01,1).applyQuaternion(this.rayWorldQuaternion),16711680,10),this.emitPointerEvent(we.PointerDown,this._selectButtonIndex||0,"xr-standard-trigger",!0,e))};onSelectEnd=e=>{this.emitPointerUpEvent&&(hh||this.inputSource===e.inputSource&&this.emitPointerEvent(we.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&&(Vn&&B.DrawDirection(this.rayWorldPosition,V(0,.01,1).applyQuaternion(this.rayWorldQuaternion),255,10),this.emitPointerEvent(we.PointerDown,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,e)))};onSequeezeEnd=e=>{this.emitPointerUpEvent&&this.inputSource===e.inputSource&&this._squeezeButtonIndex!==void 0&&this.emitPointerEvent(we.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 vy;let n=null;this._isMxInk&&(e===4||e===5)?(t.value>0&&!i.pressed?(n="pointerdown",i.isDown=!0,i.isUp=!1):t.value===0&&i.pressed?(n="pointerup",i.isDown=!1,i.isUp=!0):i.pressed&&(n="pointermove",i.isDown=!1,i.isUp=!1),i.pressed=t.value>0,i.value=t.value):(t.pressed&&!i.pressed?(n="pointerdown",i.isDown=!0,i.isUp=!1):!t.pressed&&i.pressed?(n="pointerup",i.isDown=!1,i.isUp=!0):(i.isDown=!1,i.isUp=!1),i.pressed=t.pressed,i.value=t.value),this.states[e]=i;const o=e!==this._selectButtonIndex&&e!==this._squeezeButtonIndex;if(n!=null&&o){let r=this._layout?.gamepad[e];this._isMxInk&&e===4&&(r="stylus-touch"),this._isMxInk&&e===5&&(r="stylus-tip"),(Vn||hh)&&console.log("Emitting pointer event",n,e,r,t.value,this.gamepad,this._layout),this.emitPointerEvent(n,e,r??"none",!1,null,t.value)}}if(this._isMetaQuestTouchController){const e=this.gamepad.buttons.length-1,t=this.states[e];if(t&&t.isDown){const i=this.context.menu;i.spatialMenuIsVisible?i.setSpatialMenuVisible(!1):this.context.menu.setSpatialMenuVisible(!0)}}}if(this.hand){const e=this.handObject;if(e){const t=e.joints["index-finger-tip"],i=e.joints["thumb-tip"];if(t&&i){const n=t.position.distanceTo(i.position);this._pinchPosition.lerpVectors(t.position,i.position,.5);const o=this.xr.context.mainCamera?.parent;if(o&&this._pinchPosition.applyMatrix4(o.matrixWorld),n!==0){const l=this.states.pinch||new vy,h=(.02+.01)*1.5;l.value=1-(n-.02)/h;const d=n<.02-.01,u=n>.02+.01;d&&!l.pressed?(hh&&console.log("pinch start",n),l.isDown=!0,l.isUp=!1,l.pressed=!0):u&&l.pressed?(l.isDown=!1,l.isUp=!0,l.pressed=!1):(l.isDown=!1,l.isUp=!1),this.states.pinch=l}}}}}_didMoveLastFrame=!1;_lastPointerMovePosition=new c.Vector3;_lastPointerMoveQuaternion=new c.Quaternion;onUpdateMove(){if(!this.emitPointerMoveEvent)return;let e=!1;if(this._lastPointerMovePosition.distanceTo(this.gripWorldPosition)>this.pointerMoveDistanceThreshold*this.xr.rigScale&&(e=!0),e||this._lastPointerMoveQuaternion.angleTo(this.gripWorldQuaternion)>this.pointerMoveAngleThreshold&&(e=!0),e){this._didMoveLastFrame=!0,this._lastPointerMovePosition.copy(this.gripWorldPosition),this._lastPointerMoveQuaternion.copy(this.gripWorldQuaternion),Vn&&B.DrawLabel(this.rayWorldPosition.add(this.object.worldForward.multiplyScalar(.1)),"move",.01);let i=this.xr.context.input.getFirstPressedButtonForPointer(this.index);i===void 0&&(i=0);const n=this.gamepad?.buttons[i]?.value;this.emitPointerEvent("pointermove",i,"none",!1,null,n)}else this._didMoveLastFrame=!1}pointerInit;emitPointerEvent(e,t,i,n,o=null,r){if(!this.emitEvents){Vn&&e!==we.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=F.Current;F.Current=this.xr.context,Vn&&e!=="pointermove"&&console.warn("Pointer event",e,t,i,{...this.pointerInit}),this.xr.context.input.createInputEvent(new Kn(e,o,this.pointerInit)),F.Current=a}}}class vy{isDown=!1;isUp=!1;pressed=!1;value=0}class wy{index;name;touched=!1;pressed=!1;value=0;isDown=!1;isUp=!1;constructor(e,t){this.index=e,this.name=t}}var ap=(s=>(s.Visible="application-visible",s.Hidden="application-hidden",s.MuteChanged="application-mutechanged",s))(ap||{});let fd=!1;const Hr=[];function tr(){if(fd)return;A()&&console.debug("User interaction registered: audio can now be played"),fd=!0;const s=[...Hr];Hr.length=0,s.forEach(e=>e())}document.addEventListener("mousedown",tr);document.addEventListener("pointerup",tr);document.addEventListener("click",tr);document.addEventListener("dragstart",tr);document.addEventListener("touchend",tr);document.addEventListener("keydown",tr);class tn extends EventTarget{static get userInteractionRegistered(){return fd}static registerWaitForAllowAudio=tn.registerWaitForInteraction;static registerWaitForInteraction(e){if(e!==null){if(fd){e();return}Hr.indexOf(e)===-1&&Hr.push(e)}}static unregisterWaitForInteraction(e){const t=Hr.indexOf(e);t!==-1&&Hr.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 Jr=new Map,qr=new Map;let xy=0;function hs(s,e,t){if(Jr.has(e)||Jr.set(e,new Array),Jr.get(e).push({method:s,options:{once:!1,...t}}),xy<30){const i=qr.get(e);i&&i?.length>100&&(xy+=1,console.warn(`You have ${i.length} methods registered for Event ${e}.
|
|
152
|
+
`+r}B.DrawLabel(t,n,.006)}onUpdateFrame(e){if(this._handJointPoses.clear(),this._hand_wristDotUp=void 0,!this.xr.referenceSpace||!this.inputSource.gamepad?.connected){this._isTracking=!1;return}const t=e.getPose(this.inputSource.targetRaySpace,this.xr.referenceSpace);this._isTracking=t!=null;let i=null,n=null,o=null,r=null;if(t){const d=t.transform;this._rayMatrix.fromArray(d.matrix).premultiply(Zr),this._rayMatrix.decompose(this._rayPosition,this._rayQuaternion,V(1,1,1)),o=V(d.position),r=Gt(d.orientation),this._rayPositionRaw.copy(o),this._rayRotationRaw.copy(r)}if(this.inputSource.gripSpace){const d=e.getPose(this.inputSource.gripSpace,this.xr.referenceSpace);if(d){const u=d.transform;if(i=V(u.position),n=Gt(u.orientation),this._gripMatrix.fromArray(u.matrix).premultiply(Zr),this._gripMatrix.decompose(this._gripPosition,this._gripQuaternion,V(1,1,1)),"linearVelocity"in d&&d.linearVelocity){const p=d.linearVelocity;this._linearVelocity.set(p.x,p.y,p.z)}}}this.xr.context.mainCamera?.parent&&(this._object.parent!==this.xr.context.mainCamera?.parent&&this.xr.context.mainCamera.parent.add(this._object),this._gripSpaceObject!==void 0&&this._gripSpaceObject?.parent!==this.xr.context.mainCamera?.parent&&this.xr.context.mainCamera.parent.add(this._gripSpaceObject),this._raySpaceObject!==void 0&&this._raySpaceObject?.parent!==this.xr.context.mainCamera?.parent&&this.xr.context.mainCamera.parent.add(this._raySpaceObject));const a=this.hand;if(a){let d=!1;const u=a.get("wrist"),p=u&&this.getHandJointPose(u,e);if(p){d=!0;const b=p.transform.position,g=p.transform.orientation;this._object.position.set(b.x,b.y,b.z),this._object.quaternion.set(g.x,g.y,g.z,g.w).multiply(ki)}d||(this._object.position.copy(this._rayPosition),this._object.quaternion.copy(this._rayQuaternion).multiply(ki));const m=a.get("middle-finger-metacarpal"),y=m&&this.getHandJointPose(m,e);y&&(this._gripMatrix.fromArray(y.transform.matrix).premultiply(Zr),this._gripMatrix.decompose(this._gripPosition,this._gripQuaternion,V(1,1,1)),i=V().copy(y.transform.position),n=Gt().copy(y.transform.orientation),n.multiply(PS),i.add(V(OS).applyQuaternion(n)))}else this.inputSource.gripSpace&&this.targetRayMode==="transient-pointer"&&i&&n?(this._object.position.copy(i),this._object.quaternion.copy(n).multiply(ki)):o&&r&&(this._object.position.copy(o),this._object.quaternion.copy(r).multiply(ki));Vn&&(o&&r&&(this._raySpaceObject?.position.copy(o),this._raySpaceObject?.quaternion.copy(r).multiply(ki)),i&&n&&(this._gripSpaceObject?.position.copy(i),this._gripSpaceObject?.quaternion.copy(n).multiply(ki)));const l=this.xr.context.mainCamera?.parent,h=l?ue(l):void 0;i&&n&&(this._gripWorldPosition.copy(i),l&&this._gripWorldPosition.applyMatrix4(l.matrixWorld),this._gripWorldQuaternion.copy(n),this._gripWorldQuaternion.multiply(ki),h&&this._gripWorldQuaternion.premultiply(h)),this.updateRayWorldPosition(),this.updateRayWorldQuaternion()}onDisconnected(){this._connected=!1,Vn&&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 wy(void 0,e);return i.pressed=t.pressed,i.value=t.value,i.isDown=t.isDown,i.isUp=t.isUp,this._needleGamepadButtons[e]=i,i}getPointerId(e){if((e==="primary"||e==="pinch")&&(e=0),typeof e!="number"){const t=this._buttonMap.get(e);if(t===void 0)return;e=t}return this.index*10+e}_needleGamepadButtons={};toNeedleGamepadButton(e,t){if(!this.inputSource.gamepad?.buttons)return;const i=this.inputSource.gamepad?.buttons[e],n=this.states[e],o=this._needleGamepadButtons[e]||new wy(e,t);return i&&(o.pressed=i.pressed,o.value=i.value,o.touched=i.touched),n&&(o.isDown=n.isDown,o.isUp=n.isUp),this._needleGamepadButtons[e]=o,o}getStick(e){if(!this._layout)return{x:0,y:0,z:0};if(this.isHand)return{x:0,y:0,z:0};e==="primary"&&this._layout.components["xr-standard-thumbstick"]&&(e="xr-standard-thumbstick");const t=this._layout?.components[e];if(t?.gamepadIndices)switch(t.type){case"thumbstick":if(this.inputSource.gamepad){const i=t.gamepadIndices.xAxis,n=t.gamepadIndices.yAxis;let o=this.inputSource.gamepad.axes[i]||0,r=this.inputSource.gamepad.axes[n]||0;o*=-1,r*=-1;const a=t.gamepadIndices.button,l=this.inputSource.gamepad?.buttons[a]?.value||0;return{x:o,y:r,z:l}}}return{x:0,y:0,z:0}}_buttonMap=new Map;_motioncontroller;_layout;getMotionController;initialize(){if(this._hasSelectEvent=this.profiles.includes("generic-hand-select")||this.profiles.some(e=>e.startsWith("generic-trigger")),this._isMetaQuestTouchController=this.profiles.includes("meta-quest-touch-plus")||this.profiles.includes("oculus-touch-v3"),this._isMxInk=this.profiles.includes("logitech-mx-ink"),!this._layout){if(this.inputSource.targetRayMode==="transient-pointer")return;const e=se.fetchProfile(this.inputSource,SS,CS);this.getMotionController=e.then(t=>{if(!this.connected)return null;this._motioncontroller=new se.MotionController(this.inputSource,t.profile,t.assetPath||"");const n=t.profile.layouts[this.inputSource.handedness];if(this._layout=n,this._layout&&!this._layout.gamepad?.length){this._layout.gamepad=[];for(const o in this._layout.components){const r=this._layout.components[o];this._layout.gamepad[r.gamepadIndices.button]=o}}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),!hh&&(Vn&&B.DrawDirection(this.rayWorldPosition,V(0,.01,1).applyQuaternion(this.rayWorldQuaternion),16711680,10),this.emitPointerEvent(we.PointerDown,this._selectButtonIndex||0,"xr-standard-trigger",!0,e))};onSelectEnd=e=>{this.emitPointerUpEvent&&(hh||this.inputSource===e.inputSource&&this.emitPointerEvent(we.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&&(Vn&&B.DrawDirection(this.rayWorldPosition,V(0,.01,1).applyQuaternion(this.rayWorldQuaternion),255,10),this.emitPointerEvent(we.PointerDown,this._squeezeButtonIndex||0,"xr-standard-squeeze",!0,e)))};onSequeezeEnd=e=>{this.emitPointerUpEvent&&this.inputSource===e.inputSource&&this._squeezeButtonIndex!==void 0&&this.emitPointerEvent(we.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 vy;let n=null;this._isMxInk&&(e===4||e===5)?(t.value>0&&!i.pressed?(n="pointerdown",i.isDown=!0,i.isUp=!1):t.value===0&&i.pressed?(n="pointerup",i.isDown=!1,i.isUp=!0):i.pressed&&(n="pointermove",i.isDown=!1,i.isUp=!1),i.pressed=t.value>0,i.value=t.value):(t.pressed&&!i.pressed?(n="pointerdown",i.isDown=!0,i.isUp=!1):!t.pressed&&i.pressed?(n="pointerup",i.isDown=!1,i.isUp=!0):(i.isDown=!1,i.isUp=!1),i.pressed=t.pressed,i.value=t.value),this.states[e]=i;const o=e!==this._selectButtonIndex&&e!==this._squeezeButtonIndex;if(n!=null&&o){let r=this._layout?.gamepad[e];this._isMxInk&&e===4&&(r="stylus-touch"),this._isMxInk&&e===5&&(r="stylus-tip"),(Vn||hh)&&console.log("Emitting pointer event",n,e,r,t.value,this.gamepad,this._layout),this.emitPointerEvent(n,e,r??"none",!1,null,t.value)}}if(this._isMetaQuestTouchController){const e=this.gamepad.buttons.length-1,t=this.states[e];if(t&&t.isDown){const i=this.context.menu;i.spatialMenuIsVisible?i.setSpatialMenuVisible(!1):this.context.menu.setSpatialMenuVisible(!0)}}}if(this.hand){const e=this.handObject;if(e){const t=e.joints["index-finger-tip"],i=e.joints["thumb-tip"];if(t&&i){const n=t.position.distanceTo(i.position);this._pinchPosition.lerpVectors(t.position,i.position,.5);const o=this.xr.context.mainCamera?.parent;if(o&&this._pinchPosition.applyMatrix4(o.matrixWorld),n!==0){const l=this.states.pinch||new vy,h=(.02+.01)*1.5;l.value=1-(n-.02)/h;const d=n<.02-.01,u=n>.02+.01;d&&!l.pressed?(hh&&console.log("pinch start",n),l.isDown=!0,l.isUp=!1,l.pressed=!0):u&&l.pressed?(l.isDown=!1,l.isUp=!0,l.pressed=!1):(l.isDown=!1,l.isUp=!1),this.states.pinch=l}}}}}_didMoveLastFrame=!1;_lastPointerMovePosition=new c.Vector3;_lastPointerMoveQuaternion=new c.Quaternion;onUpdateMove(){if(!this.emitPointerMoveEvent)return;let e=!1;if(this._lastPointerMovePosition.distanceTo(this.gripWorldPosition)>this.pointerMoveDistanceThreshold*this.xr.rigScale&&(e=!0),e||this._lastPointerMoveQuaternion.angleTo(this.gripWorldQuaternion)>this.pointerMoveAngleThreshold&&(e=!0),e){this._didMoveLastFrame=!0,this._lastPointerMovePosition.copy(this.gripWorldPosition),this._lastPointerMoveQuaternion.copy(this.gripWorldQuaternion),Vn&&B.DrawLabel(this.rayWorldPosition.add(this.object.worldForward.multiplyScalar(.1)),"move",.01);let i=this.xr.context.input.getFirstPressedButtonForPointer(this.index);i===void 0&&(i=0);const n=this.gamepad?.buttons[i]?.value;this.emitPointerEvent("pointermove",i,"none",!1,null,n)}else this._didMoveLastFrame=!1}pointerInit;emitPointerEvent(e,t,i,n,o=null,r){if(!this.emitEvents){Vn&&e!==we.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=F.Current;F.Current=this.xr.context,Vn&&e!=="pointermove"&&console.warn("Pointer event",e,t,i,{...this.pointerInit}),this.xr.context.input.createInputEvent(new Kn(e,o,this.pointerInit)),F.Current=a}}}class vy{isDown=!1;isUp=!1;pressed=!1;value=0}class wy{index;name;touched=!1;pressed=!1;value=0;isDown=!1;isUp=!1;constructor(e,t){this.index=e,this.name=t}}var ap=(s=>(s.Visible="application-visible",s.Hidden="application-hidden",s.MuteChanged="application-mutechanged",s))(ap||{});let fd=!1;const Hr=[];function tr(){if(fd)return;A()&&console.debug("User interaction registered: audio can now be played"),fd=!0;const s=[...Hr];Hr.length=0,s.forEach(e=>e())}document.addEventListener("mousedown",tr);document.addEventListener("pointerup",tr);document.addEventListener("click",tr);document.addEventListener("dragstart",tr);document.addEventListener("touchend",tr);document.addEventListener("keydown",tr);class tn extends EventTarget{static get userInteractionRegistered(){return fd}static registerWaitForAllowAudio=tn.registerWaitForInteraction;static registerWaitForInteraction(e){if(e!==null){if(fd){e();return}Hr.indexOf(e)===-1&&Hr.push(e)}}static unregisterWaitForInteraction(e){const t=Hr.indexOf(e);t!==-1&&Hr.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 Jr=new Map,qr=new Map;let xy=0;function hs(s,e,t){if(Jr.has(e)||Jr.set(e,new Array),Jr.get(e).push({method:s,options:{once:!1,...t}}),xy<30){const i=qr.get(e);i&&i?.length>100&&(xy+=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 to(s,e){const t=qr.get(e);if(t){for(let n=0;n<t.length;n++)if(t[n].method===s){t.splice(n,1);return}}const i=Jr.get(e);if(i){for(let n=0;n<i.length;n++)if(i[n].method===s){i.splice(n,1);return}}}function un(s,e){e===re.ContextCreated&&lp.delete(s),zb(s,e)}function zb(s,e){e===pe.Start&&Jr.get(re.ContextCreated)&&zb(s,re.ContextCreated);const t=e===pe.Start||e===re.ContextCreated,i=qr.get(e);i&&i.length>0&&Cy(s,i,t);const n=Jr.get(e);if(n&&n.length>0){const o=[...n];n.length=0,Cy(s,o,t),o.length>0&&(qr.has(e)||qr.set(e,new Array),qr.get(e).push(...o))}}const dh=new Array,Sy={context:null};function Cy(s,e,t){dh.length=0;for(let n=0;n<e.length;n++)dh.push(e[n]);let i=lp.get(s);for(let n=0;n<dh.length;n++){const o=dh[n];let r=!0;if(i&&i.has(o)&&(r=!1),r)try{Sy.context=s,o.method?.call(Sy,s)}catch(a){console.error("Error in lifecycle method",a)}if(o.options?.once){for(let a=0;a<e.length;a++)if(e[a]===o){e.splice(a,1);break}}else t&&(i||(i=new Set,lp.set(s,i)),i.add(o))}}const lp=new WeakMap,um={};function fm(s,e){um[s]=e}function Nb(s){const e=s.getBufferIdentifier(),t=um[e];return t(s)}function Vb(s){return typeof s.guid=="function"?s.guid():null}let pm;function MS(){return pm}function kS(s){pm=s}function $b(s,e){return e||(e={}),e={...pm,...e},s?new se.$70d766613f57b014$export$2e2bcd8739ae039(s,e):new se.$70d766613f57b014$export$2e2bcd8739ae039(e)}async function Py(){const s=await Promise.resolve().then(()=>require("./vendor-BtJpSuCj.umd.cjs")).then(e=>e.bundler);return console.log(s),s.default===void 0?s:s.default}class Wb{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 Py(),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 RS(i)})}async trySetupClient(e){const t=await Py();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 ES{_peer;constructor(e){this._peer=e}}class RS extends ES{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 Xi=(s=>(s[s.OnConnection=0]="OnConnection",s[s.OnRoomJoin=1]="OnRoomJoin",s[s.Queued=2]="Queued",s[s.Immediate=3]="Immediate",s))(Xi||{});const Oy="https://urls.needle.tools/default-networking-backend/index";let xi="wss://networking.needle.tools/socket";const zt=!!w("debugnet"),fl=!!(zt||w("debugowner")),uh=w("debugnetbin");var Gb=(s=>(s.ConnectionInfo="connection-start-info",s))(Gb||{}),Q=(s=>(s.Join="join-room",s.Leave="leave-room",s.JoinedRoom="joined-room",s.LeftRoom="left-room",s.UserJoinedRoom="user-joined-room",s.UserLeftRoom="user-left-room",s.RoomStateSent="room-state-sent",s))(Q||{});class TS{room;viewId;allowEditing;inRoom}class AS{room}class LS{userId}var Hb=(s=>(s.RequestHasOwner="request-has-owner",s.ResponseHasOwner="response-has-owner",s.RequestIsOwner="request-is-owner",s.ResponseIsOwner="response-is-owner",s.RequestOwnership="request-ownership",s.GainedOwnership="gained-ownership",s.RemoveOwnership="remove-ownership",s.LostOwnership="lost-ownership",s.GainedOwnershipBroadcast="gained-ownership-broadcast",s.LostOwnershipBroadcast="lost-ownership-broadcast",s))(Hb||{});class mm{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||(fl&&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 fl&&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?(fl&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(fl&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}}class qb{context;_peer=null;constructor(e){this.context=e}get peer(){return this._peer||(this._peer=new Wb),this._peer}tryGetState(e){return e==="invalid"?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return zt}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(),zt&&console.log("join: "+e),this.send("join-room",{room:e,viewOnly:t},Xi.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=Xi.Queued){if(t===null&&(t={}),i===Xi.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){uh&&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,Xi.Immediate);break}const o=this.toMessage(n.key,n.value);this._defaultMessagesBufferArray.push(o)}if(this._defaultMessagesBuffer.length=0,this._defaultMessagesBufferArray.length>0&&zt&&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!==xi)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?xi=t:sb()&&(xi="wss://"+window.location.host+"/socket"),this.connectWebsocket()}disconnect(){this._ws?.close(),this._ws=void 0,xi=void 0,this._currentRoomAllowEditing=!0,this._currentRoomName=null,this._currentRoomViewId=null,this._isInRoom=!1,this._currentInRoom.length=0,this._state={},this._currentDelay=-1}_listeners={};_listenersBinary={};connected=!1;channelId;_connectionId=null;_ws;_waitingForSocket={};_isInRoom=!1;_currentRoomName=null;_currentRoomViewId=null;_currentRoomAllowEditing=!0;_currentInRoom=[];_state={};_currentDelay=-1;_connectingToWebsocketPromise=null;connectWebsocket(){return this._connectingToWebsocketPromise?this._connectingToWebsocketPromise:this._connectingToWebsocketPromise=new Promise(async(e,t)=>{let i=!1;const n=h=>{i||(i=!0,e(h))};if(xi===void 0&&(console.log("Fetch default backend url: "+Oy),xi=await(await fetch(Oy)).text()),xi===void 0){n(!1);return}console.debug(`⊡ Connecting to networking backend on
|
|
162
162
|
`+xi);const o=await Promise.resolve().then(()=>require("./vendor-BtJpSuCj.umd.cjs")).then(h=>h.index),r=o.default?.WebsocketBuilder??o.WebsocketBuilder,a=o.default?.ExponentialBackoff??o.ExponentialBackoff,l=new r(xi).withMaxRetries(10).withBackoff(new a(2e3,4)).onOpen(()=>{this._connectingToWebsocketPromise=null,this._ws=l,this.connected=!0,A()||zt?console.log(`⊞ Connected to networking backend
|
|
163
163
|
`+xi):console.debug("⊞ Connected to networking backend",xi),n(!0),this.onSendQueued(Xi.OnConnection)}).onClose(h=>{this._connectingToWebsocketPromise=null,this.connected=!1,this._isInRoom=!1,n(!1);let d="Websocket connection closed...";xi?.includes("/socket")||(d+=' Do you perhaps mean to connect to "/socket"?'),console.error(d)}).onError(h=>{console.error("⊠ Websocket connection failed..."),n(!1)}).onRetry(()=>{console.log("→ Retry connecting to networking websocket")}).build();l.addEventListener(o.WebsocketEvent.message,(h,d)=>{this.onMessage(h,d)})})}onMessage(e,t){const i=t.data;try{if(typeof i!="string"){i.size&&this.handleIncomingBinaryMessage(i);return}const n=JSON.parse(i);if(Array.isArray(n))for(const o of n)this.handleIncomingStringMessage(o);else this.handleIncomingStringMessage(n);return}catch(n){zt&&i==="pong"?console.log("<<",i):A()&&console.error("Failed to parse message",n)}}async handleIncomingBinaryMessage(e){uh&&console.log("<< bin",this.context.time.frame);const t=await e.arrayBuffer();var i=new Uint8Array(t);const n=new se.ByteBuffer(i),o=n.getBufferIdentifier(),r=this._listenersBinary[o],a=Nb(n),l=Vb(a);if(l&&typeof l=="string"&&(this._state[l]=a),!r)return;const h=a??n;for(const d of r)d(h)}handleIncomingStringMessage(e){if(zt&&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(zt&&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),(uh||A())&&console.debug("Joined Needle Engine Room: "+r.room);const a=new URL(window.location.href);a.searchParams.has("room")&&a.searchParams.delete("room"),a.searchParams.set("view",this._currentRoomViewId),console.debug(`Room view id: ${this._currentRoomViewId}
|
|
164
|
-
${a.href}`)}this.onSendQueued(Xi.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,(uh||A())&&console.debug("Left Needle Engine Room: "+n.room));break;case"user-joined-room":if(e.data){const r=e.data;this._currentInRoom.push(r.userId),zt&&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&&(zt&&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":zt&&console.log("RECEIVED all-room-state-deleted"),this._state={};break;case"ping":case"pong":const o=e.data?.time;o&&(this._currentDelay=this.context.time.time-o),zt&&console.log(`Current latency: ${(this._currentDelay*1e3).toFixed()} ms`,"Clients in room: "+this._currentInRoom?.length);break}const t=e.data;t&&(this._state[t.guid]=t);let i=this._listeners[e.key];if(i){i=[...i];for(const n of i)try{n(e.data)}catch(o){console.error('Error invoking callback for "'+e.key+'"',o)}}}toMessage(e,t){return{key:e,data:t}}sendWithWebsocket(e,t,i=Xi.OnRoomJoin){if(!this._ws){const o=this._waitingForSocket[i]||[];o.push(()=>this.sendWithWebsocket(e,t,i)),this._waitingForSocket[i]=o;return}const n=JSON.stringify(this.toMessage(e,t));zt&&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 Tl=w("debugwebxr");class Ju{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=>{Tl&&console.log(`XRSync: Received change for ${this.userId}: ${e.type} ${e.handedness}; tracked=${e.isTracking}`);let t=!1;for(let i=0;i<this.controllerStates.length;i++)if(this.controllerStates[i].index===e.index){this.controllerStates[i]=e,t=!0;break}t||this.controllerStates.push(e)};update(e){if(this.context.connection.isConnected!=!1){for(let t=this.controllerStates.length-1;t>=0;t--){const i=this.controllerStates[t];let n=!1;for(let o=0;o<e.controllers.length;o++)e.controllers[o].index===i.index&&(n=!0);n||(Tl&&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),Tl&&console.log(`XRSync: ${i.type} ${i.handedness} added`,i.index)}}}class Xb{hasState(e){return e?this._states.has(e):!1}isTracking(e,t){if(!e)return;const i=this._states.get(e);return i?i.controllerStates.find(o=>o.handedness===t)?.isTracking||!1:void 0}getDeviceType(e,t){if(!e)return;const i=this._states.get(e);return i?i.controllerStates.find(o=>o.handedness===t)?.type||"unknown":void 0}context;constructor(e){this.context=e,this.context.connection.beginListen(Q.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(Q.LeftRoom,this.onLeftRoom),this.context.connection.beginListen(Q.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.beginListen(Q.UserLeftRoom,this.onOtherUserLeftRoom)}destroy(){this.context.connection.stopListen(Q.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(Q.LeftRoom,this.onLeftRoom),this.context.connection.stopListen(Q.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.stopListen(Q.UserLeftRoom,this.onOtherUserLeftRoom)}onJoinedRoom=()=>{if(this.context.connection.connectionId){this._states.has(this.context.connection.connectionId)||(Tl&&console.log("XRSync: Local user joined room",this.context.connection.connectionId),this._states.set(this.context.connection.connectionId,new Ju(this.context.connection.connectionId,this.context)));for(const e of this.context.connection.usersInRoom())this._states.has(e)||this._states.set(e,new Ju(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)||(Tl&&console.log("XRSync: Remote user joined room",t),this._states.set(t,new Ju(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 My{_fadeToColorQuad;_fadeToColorMaterial;constructor(){this._fadeToColorMaterial=new c.MeshBasicMaterial({color:0,transparent:!0,depthTest:!1,fog:!1,side:c.DoubleSide}),this._fadeToColorQuad=new c.Mesh(new c.PlaneGeometry(10,10),this._fadeToColorMaterial)}dispose(){this._fadeToColorQuad.geometry.dispose(),this._fadeToColorMaterial.dispose()}update(e,t){const i=this._fadeToColorQuad,n=this._fadeToColorMaterial;i.parent!==e&&n.opacity>0?e.add(i):n.opacity===0&&i.removeFromParent(),i.layers.set(2),i.material=this._fadeToColorMaterial,i.position.z=-1,i.renderOrder=1/0;const o=this._requestedFadeValue;n.opacity=D.lerp(n.opacity,o,t/.03),Math.abs(n.opacity-o)<=.01&&this._transitionResolve&&(this._transitionResolve(),this._transitionResolve=null,this._transitionPromise=null,this._requestedFadeValue=0)}remove(){this._fadeToColorQuad.removeFromParent()}fadeTransition(){if(this._transitionPromise)return this._transitionPromise;this._requestedFadeValue=1;const e=new Promise(t=>{this._transitionResolve=t});return this._transitionPromise=e,e}_requestedFadeValue=0;_transitionPromise=null;_transitionResolve=null}var Go=(s=>(s[s.Quad=0]="Quad",s[s.Cube=1]="Cube",s[s.Sphere=2]="Sphere",s[s.Cylinder=3]="Cylinder",s[s.RoundedCube=10]="RoundedCube",s))(Go||{});class ir{static createText(e,t){let i=null;const n=t?.font||IS(t?.familyFamily||null);n instanceof q.Font?i=this.#t(e,n,t):i==null&&(i=new c.BufferGeometry);const o=t?.color||16777215,r=new c.Mesh(i,t?.material??new c.MeshStandardMaterial({color:o}));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 q.TextGeometry(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 c.MeshBasicMaterial({colorWrite:!1,depthWrite:!0,side:c.DoubleSide});return this.createPrimitive(e,{material:t})}static createPrimitive(e,t){let i;const n=t?.color||16777215;switch(e){case"Quad":case 0:{const o=new c.PlaneGeometry(1,1,1,1),r=t?.material??new c.MeshStandardMaterial({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new c.Mesh(o,r),i.name="Quad"}break;case"Cube":case 1:{const o=new c.BoxGeometry(1,1,1),r=t?.material??new c.MeshStandardMaterial({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new c.Mesh(o,r),i.name="Cube"}break;case 10:case"RoundedCube":{const o=DS(1,1,1,.1,2),r=t?.material??new c.MeshStandardMaterial({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new c.Mesh(o,r),i.name="RoundedCube"}break;case"Sphere":case 2:{const o=new c.SphereGeometry(.5,16,16),r=t?.material??new c.MeshStandardMaterial({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new c.Mesh(o,r),i.name="Sphere"}break;case"Cylinder":case 3:{const o=new c.CylinderGeometry(.5,.5,1,32),r=t?.material??new c.MeshStandardMaterial({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new c.Mesh(o,r),i.name="Cylinder"}break;case"ShaderBall":i=new c.Group,i.name="ShaderBall",jS(i,t);break}return this.applyDefaultObjectOptions(i,t),i}static createSprite(e){const i=new c.SpriteMaterial({color:16777215});e?.texture&&"map"in i&&(i.map=e.texture);const n=new c.Sprite(i);return this.applyDefaultObjectOptions(n,e),n}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 DS(s,e,t,i,n){const o=new c.Shape,r=1e-5,a=i-r;o.absarc(r,r,r,-Math.PI/2,-Math.PI,!0),o.absarc(r,e-a*2,r,Math.PI,Math.PI/2,!0),o.absarc(s-a*2,e-a*2,r,Math.PI/2,0,!0),o.absarc(s-a*2,r,r,0,-Math.PI/2,!0);const l=new c.ExtrudeGeometry(o,{bevelEnabled:!0,bevelSegments:n*2,steps:1,bevelSize:a,bevelThickness:i,curveSegments:n,UVGenerator:{generateTopUV:(h,d)=>{const u=[];for(let p=0;p<d.length;p+=3)u.push(new c.Vector2(d[p]/s,d[p+1]/e));return u},generateSideWallUV:(h,d,u,p,m,y)=>{const _=[];return _.push(new c.Vector2(d[u]/s,d[u+1]/e)),_.push(new c.Vector2(d[p]/s,d[p+1]/e)),_.push(new c.Vector2(d[m]/s,d[m+1]/e)),_.push(new c.Vector2(d[y]/s,d[y+1]/e)),_}}});return l.scale(1,1,1-i),l.center(),l.index||l.setIndex(Array.from({length:l.attributes.position.count},(h,d)=>d)),l.computeVertexNormals(),l}const fh=new Map;function IS(s){let e="";switch(s){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(fh.has(e)){const n=fh.get(e);if(n)return n}const t=new q.FontLoader,i=new Promise((n,o)=>{t.load(e,r=>{fh.set(e,r),n(r)},void 0,o)});return fh.set(e,i),i}let ef=!1,tf=null;function jS(s,e){if(tf===null){const t="https://cdn.needle.tools/static/models/shaderball.glb",i=new q.GLTFLoader,n=ne.createLoaders(null);i.setDRACOLoader(n.dracoLoader),i.setKTX2Loader(n.ktx2Loader),ef=!0,tf=i.loadAsync(t).then(o=>{const r=o.scene;return r.position.y-=.5,r}).catch(o=>(console.warn("Failed to load shaderball mesh: "+o.message),Ey())).finally(()=>{ef=!1})}if(ef){const t=Ey();t.name="ShaderBall-Placeholder";const i=t.children[0];i?.type==="Mesh"&&ky(i,e),s.add(t)}tf.then(t=>{s.children.forEach(o=>{o.name==="ShaderBall-Placeholder"&&s.remove(o)});const i=t.clone(),n=i.children[0];n?.type==="Mesh"&&(n.geometry.attributes.tangent||n.geometry.computeTangents(),ky(n,e)),s.add(i)})}function ky(s,e){if(e?.color||e?.material||e?.texture){const i=e?.material??s.material?.clone()??new c.MeshStandardMaterial;e.color&&"color"in i&&i.color instanceof c.Color&&i.color.set(e.color),e?.texture&&"map"in i&&(i.map=e.texture),s.material=i}}function Ey(){return new c.Group().add(ir.createPrimitive("Sphere",{material:new c.MeshBasicMaterial({transparent:!0,opacity:.1})}))}class ha{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 ha(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 Ln(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 c.WebGLRenderer({alpha:!0}),this._renderer.setAnimationLoop(this.onFrame),this._renderer.xr.setSession(i),this._renderer.xr.enabled=!0,this._camera=new c.PerspectiveCamera,this._scene=new c.Scene,this._scene.fog=new c.Fog(4473924,10,250),this._scene.add(this._camera),this.setupScene()}end(){return this._session?this._session.end():Promise.resolve()}async handoff(){if(!this._session)throw new Error("Cannot handoff a session that has already ended");const e={session:this._session,mode:this._mode,init:this._init};return await this.onBeforeHandoff(),this.onEnd(),this._session=null,e}onEnd=()=>{this._session?.removeEventListener("end",this.onEnd),this._renderer.setAnimationLoop(null),this._renderer.dispose(),this._scene.clear()};_lastTime=0;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 Ln(1e3),this._scene.clear()}_objects=[];setupScene(){this._scene.background=new c.Color(0),this._scene.add(new c.GridHelper(5,10,1118481,1118481));const e=new c.DirectionalLight(16777215,1);e.position.set(0,20,0),e.castShadow=!1,this._scene.add(e);const t=new c.DirectionalLight(16777215,1);t.position.set(0,-1,0),t.castShadow=!1,this._scene.add(t);const i=new c.PointLight(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 o=0;o<100;o++){const r=new c.MeshStandardMaterial({color:2236962,metalness:1,roughness:.8});this.isAR&&(r.emissive=new c.Color(Math.random(),Math.random(),Math.random()),r.emissiveIntensity=Math.random());const a=D.random(0,1)>.5?Go.Sphere:Go.Cube,l=ir.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 h=l.position.distanceTo(this._camera.position)-l.scale.x;h<1&&l.position.multiplyScalar(1+1/h),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 o=this._objects[n];o.position.y+=Math.sin(i+n*.5)*.005,o.rotateY(.002)}}}var Gl;(s=>{const e=[];function t(){if(!e?.length)return!1;for(const o of e)o.exportAndOpen();return!0}s.exportAndOpen=t;function i(o){e.push(o)}s.registerExporter=i;function n(o){if(!e)return;const r=e.indexOf(o);r>=0&&e.splice(r,1)}s.unregisterExporter=n})(Gl||(Gl={}));const Le=w("debugwebxr"),Ry=w("stats");let nf=0;function BS(s){let e=null;const t=s;return t.getAROverlayContainer?e=t.getAROverlayContainer():e=s,e}FS();async function FS(){if(w("debugasap")){let s=globalThis["needle:XRSession"];if(s instanceof Promise){delete globalThis["needle:XRSession"],ae.addContextCreatedCallback(async e=>{if(!s)return;Lo(!0);const t=await s;if(t){const i=H.getDefaultSessionInit("immersive-vr");H.setSession("immersive-vr",t,i,e.context)}else console.error("NeedleXRSession: ASAP session was rejected");s=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()=>{Lo(!0),console.log("Received Session Granted..."),await Ln(100);const s=sessionStorage.getItem("needle_xr_session_mode"),e=sessionStorage.getItem("needle_xr_session_init")??null,t=e?JSON.parse(e):null;let i=null;if(Qb()&&(await ha.start(s||"immersive-vr",t||H.getDefaultSessionInit("immersive-vr")),await NS(),i=await ha.handoff()),i)H.setSession(i.mode,i.session,i.init,F.Current);else if(s&&e){console.log("Session Granted: Restore last session");const n=JSON.parse(e);H.start(s,n).catch(o=>console.warn(o))}else H.start("immersive-vr").catch(n=>console.warn("Session Granted failed:",n))},{once:!0})}}function US(s,e){sessionStorage.setItem("needle_xr_session_mode",s),sessionStorage.setItem("needle_xr_session_init",JSON.stringify(e))}function zS(){sessionStorage.removeItem("needle_xr_session_mode"),sessionStorage.removeItem("needle_xr_session_init")}const gm=new Set;ae.registerCallback(re.ContextCreationStart,async s=>{gm.add(s.context)});ae.registerCallback(re.ContextCreated,async s=>{gm.delete(s.context);const e=s.context?.domElement.getAttribute("autostart")||null;VS(e)});function Qb(){return gm.size>0}function NS(){return new Promise(s=>{const e=Date.now(),t=setInterval(()=>{(!Qb()||Date.now()-e>6e4)&&(clearInterval(t),s())},100)})}exports.DeviceUtilities.isDesktop()&&A()&&window.addEventListener("keydown",s=>{(s.key==="x"||s.key==="Escape")&&H.active&&H.stop()});function VS(s){if(s)switch(s?.toLowerCase()){case"ar":tn.registerWaitForInteraction(()=>{H.start("ar")});break}}const ph=Symbol("initial-fov");class H{static _sync=null;static getXRSync(e){return this._sync||(this._sync=new Xb(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=>(Le&&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=>H.setSession(e,n,t,i)).catch(n=>{console.log("XRSession offer rejected (perhaps because another call to offerSession was made or a call to requestSession was made)")})),!0):!1}static getDefaultSessionInit(e){switch(e){case"immersive-ar":const t=["anchors","local-floor","layers","dom-overlay","hit-test","unbounded"];return exports.DeviceUtilities.isVisionOS()||t.push("hand-tracking"),{optionalFeatures:t};case"immersive-vr":const i=["local-floor","bounded-floor","high-fixed-foveation-level","layers"];return exports.DeviceUtilities.isVisionOS()||i.push("hand-tracking"),{optionalFeatures:i};default:return console.warn("No default session init for mode",e),{}}}static async start(e,t,i){if(exports.DeviceUtilities.isiOS()){if(e==="ar")if(await this.isARSupported())e="immersive-ar";else return Gl.exportAndOpen(),null}else e=="ar"&&(e="immersive-ar");if(A()&&w("debugxrpreroom"))return console.warn("Debug: Starting temporary XR session"),await ha.start(e,t||H.getDefaultSessionInit(e)),null;if(this._currentSessionRequest)return console.warn("A XRSession is already being requested"),(Le||A())&&he("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=F.Current),i||(i=ae.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 l=this.getDefaultSessionInit(e),h=BS(i.domElement);h&&!exports.DeviceUtilities.isQuest()&&(l.domOverlay={root:h},l.optionalFeatures.push("dom-overlay")),t={...l,...t}}break;case"immersive-vr":{if(await this.xrSystem?.isSessionSupported("immersive-vr")!==!0)return console.error(e+" is not supported by this browser."),null;t={...this.getDefaultSessionInit(e),...t}}break;default:console.warn("No default session init for mode",e);break}t.optionalFeatures??=[],t.requiredFeatures??=[],await ha.stop();const n=e=="immersive-ar"?i.scripts_immersive_ar:i.scripts_immersive_vr;Le?console.log(`%cRequesting ${e} session`,"font-weight:bold;",t,n):console.log(`%cRequesting ${e} session`,"font-weight:bold;");for(const a of n)a.onBeforeXR&&a.onBeforeXR(e,t);for(const a of this._sessionRequestStartListeners)a({mode:e,init:t});Le&&Se("Requesting "+e+" session ("+Date.now()+")"),this._currentSessionRequest=navigator?.xr?.requestSession(e,t),this._currentSessionRequestMode=e;const o=await this._currentSessionRequest?.catch(a=>{console.error(a,"Code: "+a.code),a.code===9&&he("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:"&&he("XR requires a secure connection (HTTPS)")});this._currentSessionRequest=void 0,this._currentSessionRequestMode=null;for(const a of this._sessionRequestEndListeners)a({mode:e,init:t,newSession:o||null});return o?this.setSession(e,o,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 o=e=="immersive-ar"?n.scripts_immersive_ar:n.scripts_immersive_vr;return this._activeSession=new H(e,t,n,{scripts:o,controller_added:this._controllerAddedListeners,controller_removed:this._controllerRemovedListeners,init:i}),t.addEventListener("end",this.onEnd),Le?console.log(`%cStarted ${e} session`,"font-weight:bold;",o):console.log(`%cStarted ${e} session`,"font-weight:bold;"),this._activeSession}static $_stop_request=Symbol();static stop(){const e=this._activeSession;e&&(e[this.$_stop_request]===void 0?(Le&&console.log("[NeedleXRSession] Stopping XR Session... (new)"),e[this.$_stop_request]=setTimeout(()=>{e.end()})):Le&&console.warn("[NeedleXRSession] XR Session stop already requested"))}static onEnd=()=>{Le&&console.log("XR Session ended"),this._activeSession=null};context;get sync(){return H._sync}get running(){return!this._ended&&this.session!=null}session;mode;get interactionMode(){return this.session.interactionMode}get visibilityState(){return this.session.visibilityState}get isVisibleBlurred(){return this.session.visibilityState==="visible-blurred"}get isSystemKeyboardSupported(){return this.session.isSystemKeyboardSupported}get environmentBlendMode(){return this.session.environmentBlendMode}get frame(){return this.context.xrFrame}controllers=[];get leftController(){return this.controllers.find(e=>e.side==="left")}get rightController(){return this.controllers.find(e=>e.side==="right")}getController(e){return typeof e=="number"?this.controllers[e]||null:this.controllers.find(t=>t.side===e)||null}get isPassThrough(){return!!(this.environmentBlendMode!=="opaque"&&this.interactionMode==="world-space"||this.mode==="immersive-ar"&&this.environmentBlendMode!=="opaque"&&this.controllers.some(e=>e.inputSource.targetRayMode==="tracked-pointer")||A()&&exports.DeviceUtilities.isDesktop()&&this.mode==="immersive-ar")}get isAR(){return this.mode==="immersive-ar"}get isVR(){return this.mode==="immersive-vr"}get isScreenBasedAR(){return this.isAR&&!this.isPassThrough}get posePosition(){return this._transformPosition}get poseOrientation(){return this._transformOrientation}get referenceSpace(){return this.context.renderer.xr.getReferenceSpace()}get viewerPose(){return this._viewerPose}get isTrackingImages(){if(this.frame&&"getImageTrackingResults"in this.frame&&typeof this.frame.getImageTrackingResults=="function")try{const e=this.frame.getImageTrackingResults();for(const t of e)if(t.trackingState==="tracked")return!0}catch{return!1}return!1}get rig(){const e=this._rigs[0]??null;return e?.gameObject&&Ho(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 V(0,0,0);const t=V(e);return t.x*=-1,t.z*=-1,t.applyQuaternion(Gt(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(Ho(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)}Le&&(e===t?console.log("Updated Active XR Rig:",t,"prev:",e):console.log("Updated Active XRRig:",t," (the same as before)"))}_rigs=[];_viewerHitTestSource=null;getHitTest(e){if(e)return this.getControllerHitTest(e);if(!this._viewerHitTestSource)return null;const t=this._viewerHitTestSource,i=this.frame.getHitTestResults(t);if(i.length>0){const n=i[0];return this.convertHitTestResult(n)}return null}getControllerHitTest(e){const t=e.getHitTestSource();if(!t)return null;const i=this.frame.getHitTestResultsForTransientInput(t);for(const n of i)if(n.inputSource===e.inputSource)for(const o of n.results)return this.convertHitTestResult(o);return null}convertHitTestResult(e){const t=this.context.renderer.xr.getReferenceSpace(),i=t&&e.getPose(t);if(i){const n=V(i.transform.position),o=Gt(i.transform.orientation),r=this.context.mainCamera;if(r?.parent!==this._cameraRenderParent&&n.applyMatrix4(Zr),r?.parent){n.applyMatrix4(r.parent.matrixWorld),o.multiply(ki);const a=ue(r.parent);a.premultiply(ki),o.premultiply(a)}return{hit:e,position:n,quaternion:o}}return null}convertSpace(e){const t=V(e.position);t.applyMatrix4(Zr);const i=Gt(e.orientation);return i.premultiply(ki),{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){US(e,n.init),this.session=t,this.mode=e,this.context=i,(Le||w("console"))&&Lo(!0),this._xr_scripts=[...n.scripts],this._xr_update_scripts=this._xr_scripts.filter(o=>typeof o.onUpdateXR=="function"),this._controllerAdded=n.controller_added,this._controllerRemoved=n.controller_removed,hs(this.onBefore,pe.LateUpdate),this.context.pre_render_callbacks.push(this.onBeforeRender),this.context.post_render_callbacks.push(this.onAfterRender),(n.init.optionalFeatures?.includes("hit-test")||n.init.requiredFeatures?.includes("hit-test"))&&t.requestReferenceSpace("viewer").then(o=>t.requestHitTestSource?.call(t,{space:o})?.then(r=>this._viewerHitTestSource=r).catch(r=>console.error(r))).catch(o=>console.error(o)),this.context.mainCamera&&(this._originalCameraWorldPosition=X(this.context.mainCamera,new c.Vector3),this._originalCameraWorldRotation=ue(this.context.mainCamera,new c.Quaternion),this._originalCameraWorldScale=Ie(this.context.mainCamera,new c.Vector3),this._originalCameraParent=this.context.mainCamera.parent,this.context.mainCamera instanceof c.PerspectiveCamera&&(this.context.mainCamera[ph]=this.context.mainCamera.fov)),this._defaultRig=new xS,this.context.scene.add(this._defaultRig.gameObject),this.addRig(this._defaultRig);for(let o=0;o<t.inputSources.length;o++){const r=t.inputSources[o];if(!r.handedness){console.warn("Input source in xr session has no handedness - ignoring",o);continue}this.onInputSourceAdded(r)}this.session.addEventListener("end",this.onEnd),this.session.addEventListener("inputsourceschange",o=>{for(const r of o.removed)this.disconnectInputSource(r);for(const r of o.added)this.onInputSourceAdded(r)}),this.context.xr=this,this.context.renderer.xr.setSession(this.session).then(this.onRendererSessionSet),"controllerAutoUpdate"in this.context.renderer.xr?(console.debug("Disabling three.js controllerAutoUpdate"),this.context.renderer.xr.controllerAutoUpdate=!1):Le&&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 dm(this,e,t);this._newControllers.push(i)};disconnectInputSource(e){const t=(o,r)=>{if(o.inputSource===e){Le&&console.log("Disconnecting controller",o.index);const a=r.indexOf(o);a>=0&&r.splice(a,1),this.invokeControllerEvent(o,this._controllerRemoved,"removed");const l={xr:this,controller:o,change:"removed"};for(const h of this._xr_scripts)h.onXRControllerRemoved&&h.onXRControllerRemoved(l);o.onDisconnected()}},i=[...this.controllers];for(let o=i.length-1;o>=0;o--){const r=i[o];t(r,this.controllers)}const n=[...this._newControllers];for(let o=n.length-1;o>=0;o--){const r=n[o];t(r,this._newControllers)}}end(){this._ended||this.session.end().catch(e=>console.warn(e))}_ended=!1;_newControllers=[];onEnd=e=>{if(this._ended)return;this._ended=!0,console.debug("XR Session ended"),zS(),this.onAfterRender(),this.revertCustomForward(),this._didStart=!1,this._previousCameraParent=null,this.requestedCameraNearPlane=null,to(this.onBefore,pe.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()}),Fb({session:this});for(const o of H._xrEndListeners)o({xr:this});const n=[...this.controllers];for(let o=0;o<n.length;o++)this.disconnectInputSource(n[o].inputSource);this.controllers.length=0,this._newControllers.length=0;for(const o of this._xr_scripts)o?.onLeaveXR?.({xr:this});this.sync?.onExitXR(this),this.context.mainCamera&&(this._originalCameraParent?.add(this.context.mainCamera),this._originalCameraWorldPosition&&ot(this.context.mainCamera,this._originalCameraWorldPosition),this._originalCameraWorldRotation&&Ji(this.context.mainCamera,this._originalCameraWorldRotation),this._originalCameraWorldScale&&aa(this.context.mainCamera,this._originalCameraWorldScale),this.context.mainCamera instanceof c.PerspectiveCamera&&this.context.mainCamera[ph]&&(this.context.mainCamera.fov=this.context.mainCamera[ph],this.context.mainCamera[ph]=0)),this.context.requestSizeUpdate(),this._defaultRig.gameObject.removeFromParent(),Lo(!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&&(Le&&console.warn("Latest rig is not active - trying to activate a different rig",this.rig),this.updateActiveXRRig()),this.rig&&this._mainCamera?.gameObject&&this._mainCamera?.gameObject?.parent!==this.rig.gameObject&&this.rig.gameObject.add(this._mainCamera?.gameObject),this.internalUpdateState(),this.applyCustomForward();const i={xr:this};if(this._didStart){if(this.context.new_scripts_xr.length>0){const n=[...this.context.new_scripts_xr];for(let o=0;o<n.length;o++){const r=this.context.new_scripts_xr[o];if(!r||r.destroyed||r.supportsXR?.(this.mode)==!1){this.context.new_scripts_xr.splice(o,1);continue}if(!r.activeAndEnabled){this.context.new_scripts_xr.splice(o,1),this.markInactive(r);continue}if(this.addScript(r)){this.invokeCallback_EnterXR(r);for(const a of this.controllers)this.invokeCallback_ControllerAdded(r,a)}}}}else{if(this._didStart=!0,this.mode==="immersive-vr"){const o=Bt(this.context.scene.children);if(o){const r=o.getSize(V());if(r.length()>0){const a=this._defaultRig.gameObject;a.position.set(o.min.x+r.x*.5,o.min.y,o.max.z+r.z*.5+1.5);const l=o.getCenter(V());l.y=a.position.y,a.lookAt(l)}}}Bb({session:this}),tr();for(const o of H._xrStartListeners)o(i);const n=[...this._xr_scripts];Le&&console.log("NeedleXRSession start, handle scripts:",n);for(const o of n){if(o.destroyed){this._script_to_remove.push(o);continue}if(!o.activeAndEnabled){this.markInactive(o);continue}this.invokeCallback_EnterXR(o);for(const r of this.controllers)this.invokeCallback_ControllerAdded(o,r)}}this.syncCameraCullingMask();for(const n of this.controllers)n.onUpdate(t);if(this._newControllers.length>0){const n=[...this._newControllers];this._newControllers.length=0;for(const o of n){if(!o.connected){console.warn("New controller is not connected",o);continue}this.controllers.push(o);for(const r of this._xr_scripts){if(r.destroyed){this._script_to_remove.push(r);continue}r.activeAndEnabled!==!1&&this.invokeCallback_ControllerAdded(r,o)}}this.controllers.sort((o,r)=>o.index-r.index)}Le&&this.context.time.frame%30===0&&this.controllers.length<=0&&this.session.inputSources.length>0&&(Lo(!0),console.error("XRControllers are not added but inputSources are present"));for(const n of this._xr_update_scripts){if(n.destroyed===!0){this._script_to_remove.push(n);continue}if(n.activeAndEnabled===!1){this.markInactive(n);continue}n.onUpdateXR&&n.onUpdateXR(i)}if(this.handleInactiveScripts(),this._script_to_remove.length>0){const n=[...new Set(this._script_to_remove)];this._script_to_remove.length=0;for(const o of n)!o.destroyed&&this.running&&o.onLeaveXR?.(i),this.removeScript(o)}this.sync?.onUpdate(this),this.onRenderDebug()};onRenderDebug(){if(Le)for(const e of this.controllers)e.onRenderDebug();if((Le||Ry)&&this.rig&&(nf++,nf>=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()}`,Le||Ry)for(const o of this.controllers)n+=`
|
|
165
|
-
${o.hand?"hand":"ctrl"} ${o.inputSource.handedness}[${o.index}] con:${o.connected} tr:${o.isTracking} hts:${o.hasHitTestSource?"yes":"no"}`;nf=0,B.DrawLabel(e,n,void 0,1/60*20)}}onBeforeRender=()=>{this.context.mainCamera&&(this.updateFade(this.context.mainCamera),this.requestedCameraNearPlane!==null&&this.context.mainCamera instanceof c.PerspectiveCamera&&(this.context.mainCamera.near=this.requestedCameraNearPlane,this.requestedCameraNearPlane=null))};onAfterRender=()=>{if(this.onUpdateFade_PostRender(),exports.DeviceUtilities.isDesktop()||!this._renderOnceOnDevice){const e=this.context.renderer;if(e.xr.isPresenting&&this.context.mainCamera){this._renderOnceOnDevice=!0;const t=e.xr.enabled,i=e.getRenderTarget(),n=this.context.scene.background;e.xr.enabled=!1,e.setRenderTarget(null),this.isPassThrough&&(this.context.scene.background=null),this.context.composer?this.context.composer.render(this.context.time.deltaTime):e.render(this.context.scene,this.context.mainCamera),e.xr.enabled=t,e.setRenderTarget(i),this.context.scene.background=n}}};addScript(e){return this._xr_scripts.includes(e)?!1:(Le&&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){Le&&console.log("Remove XRScript",e);const i=this._xr_scripts.indexOf(e);i>=0&&this._xr_scripts.splice(i,1);const n=this._xr_update_scripts.indexOf(e);if(n>=0&&this._xr_update_scripts.splice(n,1),t){const o=this._inactive_scripts.indexOf(e);o>=0&&this._inactive_scripts.splice(o,1)}}invokeCallback_EnterXR(e){e.onEnterXR&&e.onEnterXR({xr:this})}invokeCallback_ControllerAdded(e,t){e.onXRControllerAdded&&e.onXRControllerAdded({xr:this,controller:t,change:"added"})}invokeCallback_ControllerRemoved(e,t){e.onXRControllerRemoved&&e.onXRControllerRemoved({xr:this,controller:t,change:"removed"})}invokeCallback_LeaveXR(e){e.onLeaveXR&&!e.destroyed&&e.onLeaveXR({xr:this})}syncCameraCullingMask(){const e=this.context.xrCamera,t=this.context.mainCameraComponent?.cullingMask;if(e&&t!==void 0){for(const i of e.cameras)i.layers.mask=t;e.layers.mask=t}else if(e){for(const i of e.cameras)i.layers.enableAll();e.layers.enableAll()}}invokeControllerEvent(e,t,i){for(let n=t.length-1;n>=0;n--){const o=t[n];if(o)try{o({xr:this,controller:e,change:i})}catch(r){console.error(r)}}}_camera;_cameraRenderParent=new c.Object3D().rotateY(Math.PI);_previousCameraParent;_customforward=!0;originalCameraNearPlane;requestedCameraNearPlane=null;applyCustomForward(){if(this.context.mainCamera&&this._customforward){this._camera=this.context.mainCamera,this._camera.parent!==this._cameraRenderParent&&(this._previousCameraParent=this._camera.parent,this._previousCameraParent?.add(this._cameraRenderParent)),this._cameraRenderParent.name="XR Camera Render Parent",this._cameraRenderParent.add(this._camera);{let e=.02;const t=.001;if(this.rig){const i=Ie(this.rig.gameObject);e*=i.x}this._camera instanceof c.PerspectiveCamera&&Math.abs(this._camera.near-e)>t&&(this.isAR?this.originalCameraNearPlane=this._camera.near:this._camera.near=e,Le&&console.debug(`Setting camera near plane to ${e} (was ${this.originalCameraNearPlane}) to account for XR rendering scale`))}}}revertCustomForward(){this._camera&&this._previousCameraParent&&this._previousCameraParent.add(this._camera),this._previousCameraParent=null,this._camera instanceof c.PerspectiveCamera&&this.originalCameraNearPlane!=null&&(this._camera.near=this.originalCameraNearPlane,this.originalCameraNearPlane=void 0)}_viewerPose;_transformOrientation=new c.Quaternion;_transformPosition=new c.Vector3;internalUpdateState(){const e=this.context.renderer.xr.getReferenceSpace();if(!e){this._viewerPose=void 0;return}if(this._viewerPose=this.frame.getViewerPose(e),this._viewerPose){const t=this._viewerPose.transform;this._transformPosition.set(t.position.x,t.position.y,t.position.z),this._transformOrientation.set(t.orientation.x,t.orientation.y,t.orientation.z,t.orientation.w)}}_transition;get transition(){return this._transition||(this._transition=new My),this._transition}fadeTransition(){return this._transition||(this._transition=new My),this._transition.fadeTransition()}updateFade(e){this._transition&&e instanceof c.PerspectiveCamera&&this._transition.update(e,this.context.time.deltaTime)}onUpdateFade_PostRender(){this._transition?.remove()}}const sf=w("debugwebxr");class Yb{static tryFindAvatarObjects(e,t,i){if(i.head&&i.leftHand&&i.rightHand)return;const n=e.name.toLocaleLowerCase();!i.head&&n.includes("head")&&(sf&&console.log("FOUND AVATAR HEAD",e.name),i.head=new Y("",t,e)),n.includes("hand")&&(!i.leftHand&&n.includes("left")&&(sf&&console.log("FOUND AVATAR LEFT HAND",e.name),i.leftHand=new Y("",t,e)),!i.rightHand&&n.includes("right")&&(sf&&console.log("FOUND AVATAR RIGHT HAND",e.name),i.rightHand=new Y("",t,e)));for(let o=0;o<e.children.length;o++){if(i.head&&i.leftHand&&i.rightHand)return;const r=e.children[o];this.tryFindAvatarObjects(r,t,i)}}}const bt=new c.Vector3,Ty=new c.Vector3,Ay=new c.Quaternion,$S=w("debuggizmos"),Gi=8947848,of=32;class B{constructor(){}static enabled=!0;static isGizmo(e){return e[cp]!==void 0}static setVisible(e){for(const t of Si.timedObjectsBuffer)t.visible=e}static DrawLabel(e,t,i=.05,n=0,o,r,a){if(!B.enabled)return null;o||(o=Gi);const l=H.active?.rigScale??1,h=Si.getTextLabel(n,t,i*l,o,r);return a instanceof c.Object3D&&a.add(h),h.position.x=e.x,h.position.y=e.y,h.position.z=e.z,h}static DrawRay(e,t,i=Gi,n=0,o=!0){if(!B.enabled)return;const r=Si.getLine(n),a=r.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),bt.set(t.x,t.y,t.z).multiplyScalar(999999999),a.setXYZ(1,e.x+bt.x,e.y+bt.y,e.z+bt.z),a.needsUpdate=!0,r.material.color.set(i),r.material.depthTest=o,r.material.depthWrite=!1}static DrawDirection(e,t,i=Gi,n=0,o=!0,r=1){if(!B.enabled)return;const a=Si.getLine(n),l=a.geometry.getAttribute("position");l.setXYZ(0,e.x,e.y,e.z),t.w!==void 0?(bt.set(0,0,-r),Ay.set(t.x,t.y,t.z,t.w),bt.applyQuaternion(Ay)):(bt.set(t.x,t.y,t.z),bt.multiplyScalar(r)),l.setXYZ(1,e.x+bt.x,e.y+bt.y,e.z+bt.z),l.needsUpdate=!0,a.material.color.set(i),a.material.depthTest=o,a.material.depthWrite=!1}static DrawLine(e,t,i=Gi,n=0,o=!0){if(!B.enabled)return;const r=Si.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=o,r.material.depthWrite=!1,r.material.fog=!1}static DrawCircle(e,t,i,n=Gi,o=0,r=!0){if(!B.enabled)return;const a=Si.getCircle(o);a.position.set(e.x,e.y,e.z),a.scale.set(i,i,i),a.quaternion.setFromUnitVectors(this._up,bt.set(t.x,t.y,t.z).normalize()),a.material.color.set(n),a.material.depthTest=r,a.material.depthWrite=!1,a.material.fog=!1}static DrawWireSphere(e,t,i=Gi,n=0,o=!0){if(!B.enabled)return;const r=Si.getSphere(t,n,!0);Wo(r,e.x,e.y,e.z),r.material.color.set(i),r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1}static DrawSphere(e,t,i=Gi,n=0,o=!0){if(!B.enabled)return;const r=Si.getSphere(t,n,!1);Wo(r,e.x,e.y,e.z),r.material.color.set(i),r.material.depthTest=o,r.material.depthWrite=!1}static DrawWireBox(e,t,i=Gi,n=0,o=!0,r=void 0){if(!B.enabled)return;const a=Si.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=o,a.material.wireframe=!0,a.material.depthWrite=!1,a.material.fog=!1}static DrawWireBox3(e,t=Gi,i=0,n=!0){if(!B.enabled)return;const o=Si.getBox(i);o.position.copy(e.getCenter(bt)),o.scale.copy(e.getSize(bt)),o.material.color.set(t),o.material.depthTest=n,o.material.wireframe=!0,o.material.depthWrite=!1,o.material.fog=!1}static _up=new c.Vector3(0,1,0);static DrawArrow(e,t,i=Gi,n=0,o=!0,r=!1){if(!B.enabled)return;const a=Si.getArrowHead(n);a.position.set(t.x,t.y,t.z),a.quaternion.setFromUnitVectors(this._up.set(0,1,0),bt.set(t.x,t.y,t.z).sub(Ty.set(e.x,e.y,e.z)).normalize());const h=bt.set(t.x,t.y,t.z).sub(Ty.set(e.x,e.y,e.z)).length()*.1;a.scale.set(h,h,h),a.material.color.set(i),a.material.depthTest=o,a.material.wireframe=r,this.DrawLine(e,t,i,n,o)}static DrawWireMesh(e){const t=Si.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??Gi),t.material.depthTest=e.depthTest??!0,t.material.wireframe=!0}}const WS=new c.BoxGeometry(1,1,1);function ym(s=null){const e=new c.Color(s??14540253),t=new c.EdgesGeometry(WS);return new c.LineSegments(t,new c.LineBasicMaterial({color:e}))}const cp=Symbol("GizmoCache");class Si{static familyName="needle-gizmos";static ensureFont(){let e=J.__webpack_exports__default.FontLibrary.getFontFamily(this.familyName);e||(e=J.__webpack_exports__default.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",()=>{J.__webpack_exports__default.update()}))}static getTextLabel(e,t,i,n,o){this.ensureFont();let r=this.textLabelCache.pop(),a=1;o&&typeof o=="string"&&o?.length>=8&&o.startsWith("#")?(a=parseInt(o.substring(7),16)/255,o=o.substring(0,7),$S&&console.log(o,a)):typeof o=="object"&&o.a!==void 0&&(a=o.a);const l={boxSizing:"border-box",fontFamily:this.familyName,width:"auto",fontSize:i,color:n,lineHeight:1,backgroundColor:o??void 0,backgroundOpacity:a,textContent:t,borderRadius:.5*i,padding:.8*i,whiteSpace:"pre",offset:.05*i};if(r)r.set(l);else{r=new J.__webpack_exports__Text(l);const h=this,d=r;d.setText=function(u){this.set({textContent:u}),h.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(F.Current,r,e,this.textLabelCache),r}static getBox(e){let t=this.boxesCache.pop();if(!t){const i=new c.BoxGeometry(1,1,1);t=new c.Mesh(i)}return this.registerTimedObject(F.Current,t,e,this.boxesCache),t}static getLine(e){let t=this.linesCache.pop();if(!t){t=new c.Line;let i=t.geometry.getAttribute("position");i||(i=new c.BufferAttribute(new Float32Array(6),3),t.geometry.setAttribute("position",i))}return t.frustumCulled=!1,this.registerTimedObject(F.Current,t,e,this.linesCache),t}static getCircle(e){let t=this.circlesCache.pop();if(!t){t=new c.Line;let i=t.geometry.getAttribute("position");if(!i){i=new c.BufferAttribute(new Float32Array(of*3),3),t.geometry.setAttribute("position",i);const n=V(0,1,0),o=V(0,0,1),r=V(o);r.cross(n).normalize();const a=V(r),l=Math.PI*2/(of-1);for(let h=0;h<of+1;h++){const d=l*h;n.copy(a).multiplyScalar(Math.cos(d)*1),r.copy(o).multiplyScalar(Math.sin(d)*1);const u=n.add(r);i.setXYZ(h,u.x,u.y,u.z)}}}return t.frustumCulled=!1,this.registerTimedObject(F.Current,t,e,this.circlesCache),t}static getSphere(e,t,i){let n=this.spheresCache.pop();return n||(n=new c.Mesh(new c.SphereGeometry(1,8,8))),n.scale.set(e,e,e),n.material.wireframe=i,this.registerTimedObject(F.Current,n,t,this.spheresCache),n}static getArrowHead(e){let t=this.arrowHeadsCache.pop();return t||(t=new c.Mesh(new c.CylinderGeometry(0,.5,1,8))),this.registerTimedObject(F.Current,t,e,this.arrowHeadsCache),t}static getMesh(e){let t=this.mesh.pop();return t||(t=new c.Mesh,t.material=new c.MeshBasicMaterial),this.registerTimedObject(F.Current,t,e,this.mesh),t}static linesCache=[];static circlesCache=[];static spheresCache=[];static boxesCache=[];static arrowHeadsCache=[];static mesh=[];static textLabelCache=[];static registerTimedObject(e,t,i,n){if(!e){console.error("No Needle Engine context available. Did you call a Gizmos function in global scope?");return}const o=this.contextBeforeRenderCallbacks.get(e),r=this.contextPostRenderCallbacks.get(e);if(o){if(e.pre_render_callbacks[e.pre_render_callbacks.length-1]!==o){const a=e.pre_render_callbacks.indexOf(o);a>=0&&e.pre_render_callbacks.splice(a,1),e.pre_render_callbacks.push(o)}}else{const a=()=>{this.onBeforeRender(e,this.timedObjectsBuffer)};this.contextBeforeRenderCallbacks.set(e,a),e.pre_render_callbacks.push(a)}if(r){if(e.post_render_callbacks[e.post_render_callbacks.length-1]!==r){const a=e.post_render_callbacks.indexOf(r);a>=0&&e.post_render_callbacks.splice(a,1),e.post_render_callbacks.push(r)}}else{const a=()=>{this.onPostRender(e,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(e,a),e.post_render_callbacks.push(a)}t.traverse(a=>{a.layers.disableAll(),a.layers.enable(2)}),t.renderOrder=999999,t[cp]=n,t.castShadow=!1,t.receiveShadow=!1,t.isGizmo=!0,this.timedObjectsBuffer.push(t),this.timesBuffer.push(F.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,J.__webpack_exports__default.update());for(let i=0;i<t.length;i++){const n=t[i];if(e.mainCamera&&n instanceof J.__webpack_exports__default.MeshUIBaseElement){if(Ho(n))continue;const o=e.isInVR,r=!1,a=!o;cc(n,e.mainCamera,r,a)}}}static onPostRender(e,t,i){const n=e.time.realtimeSinceStartup;for(let o=t.length-1;o>=0;o--){const r=t[o];n>=i[o]-1e-6&&(t.splice(o,1),i.splice(o,1),r.removeFromParent(),Ho(r)!=!0&&r[cp].push(r))}}}const Dt=w("debugphysics"),Ly=new c.Layers;class io{static AllLayers=4294967295;ray;cam;screenPoint;raycaster;results;targets;recursive=!0;minDistance;maxDistance;lineThreshold;layerMask;ignore;testObject;useAcceleratedRaycast;allowSlowRaycastFallback=!0;screenPointFromOffset(e,t){this.screenPoint===void 0&&(this.screenPoint=new c.Vector2),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setLayer(e){Ly.set(e),this.layerMask=Ly}setMask(e){this.layerMask||(this.layerMask=new c.Layers);const t=this.layerMask;t?t.mask=e:this.layerMask=e}}class _m{distance;point;object;constructor(e,t,i){this.object=e,this.distance=t,this.point=i}}class da{static _raycasting=0;static get raycasting(){return this._raycasting>0}raycastPhysicsFast(e,t=void 0,i=1/0,n=!0){return this.context.physics.engine?.raycast(e,t,{maxDistance:i,solid:n})??null}raycastPhysicsFastAndGetNormal(e,t=void 0,i=1/0,n=!0){return this.context.physics.engine?.raycastAndGetNormal(e,t,{maxDistance:i,solid:n})??null}sphereOverlapPhysics(e,t){return this.context.physics.engine?.sphereOverlap(e,t)??null}context;engine;constructor(e){this.context=e}raycaster=new c.Raycaster;defaultRaycastOptions=new io;targetBuffer=new Array(1);defaultThresholds={Mesh:{},Line:{threshold:-1},LOD:{},Points:{threshold:0},Sprite:{}};sphereResults=new Array;sphereMask=new c.Layers;sphere=new c.Sphere;sphereOverlap(e,t,i=!0,n=!1,o=null){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;const r=this.sphereMask;r.enableAll(),r.disable(2);for(const a of this.context.scene.children)this.intersectSphere(a,e,t,r,this.sphereResults,i,n,o);return this.sphereResults.sort((a,l)=>a.distance-l.distance)}raycastFromRay(e,t=null){const i=t??this.defaultRaycastOptions;i.ray=e;const n=this.raycast(i);return i===this.defaultRaycastOptions&&(i.ray=void 0),n}raycast(e=null){Dt&&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 Dt&&console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];const l=this.context.xrCamera;this.context.isInXR&&l instanceof c.ArrayCamera&&l.cameras.length>0?i.setFromCamera(t,l.cameras[0]):i.setFromCamera(t,a)}let n=e.targets;n||(n=this.targetBuffer,n.length=1,n[0]=this.context.scene);let o=e.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),o||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),o=this.defaultRaycastOptions.results),e.layerMask!==void 0?e.layerMask instanceof c.Layers?i.layers.mask=e.layerMask.mask:i.layers.mask=e.layerMask:(i.layers.enableAll(),i.layers.disable(2)),Dt&&console.time("raycast"),o.length=0,da._raycasting++,this.intersect(this.raycaster,n,o,e),o.sort((a,l)=>a.distance-l.distance);const r=e.ignore;return r!==void 0&&r.length>0&&(o=o.filter(a=>!r.includes(a.object))),da._raycasting--,Dt&&(console.timeEnd("raycast"),console.warn("#"+this.context.time.frame+", hits:",o?.length?[...o]:"nothing"),performance.mark("raycast.end"),performance.measure("raycast","raycast.start","raycast.end")),o}intersect(e,t,i,n){for(const o of t){if(!o||o.visible===!1||B.isGizmo(o)||n.lineThreshold!==void 0&&n.lineThreshold<0&&o instanceof c.Line)continue;let r=!0;const a=o,l=a.geometry;if(n.testObject){const h=n.testObject?.(o);if(h===!1)continue;h==="continue in children"&&(r=!1)}if(r&&(l&&Dy(l)||(r=!1)),r){const h=ne.getRaycastMesh(o);h&&(a.geometry=h);const d=i.length;let u=!0;if(n.precise===!1&&(u=!1),u||=l.getAttribute("position")?.array?.length<64,a instanceof q.GroundedSkybox&&(u=!1),!u&&HS(a,e,i)||(n.useAcceleratedRaycast!==!1?pd.runMeshBVHRaycast(e,a,i,this.context,n):e.intersectObject(a,!1,i)),Dt&&i.length!=d){const p=i[i.length-1],m=h?8969557:7798784;B.DrawWireSphere(p.point,.1,m,1,!1),B.DrawWireMesh({mesh:o,depthTest:!1,duration:.2,color:m})}a.geometry=l}n.recursive!==!1&&this.intersect(e,o.children,i,n)}return i}tempBoundingBox=new c.Box3;intersectSphere(e,t,i,n,o,r,a,l){let h=e&&e.isMesh&&e.layers.test(n)&&!B.isGizmo(e);h&&=e.visible,h&&=!(e instanceof c.Line),h&&=!(e instanceof q.GroundedSkybox);const d=e,u=d.geometry;if(h&&l){const p=l(e);if(p===!1)return;p==="continue in children"&&(h=!1)}if(u&&Dy(u)||(h=!1),h){if(a){const p=this.sphere;p.center.copy(t),p.radius=i;const m=o.length;if(pd.runMeshBVHRaycast(this.sphere,d,o,this.context,{}),m!=o.length&&!r)return}else if(u.boundingBox||u.computeBoundingBox(),u.boundingBox){d.matrixWorldNeedsUpdate&&d.updateWorldMatrix(!1,!1);const p=this.tempBoundingBox.copy(u.boundingBox).applyMatrix4(d.matrixWorld),m=this.sphere;if(m.center.copy(t),m.radius=i,m.intersectsBox(p)){const y=X(e),_=y.distanceTo(m.center),g=new _m(e,_,y);if(o.push(g),!r)return}}}if(e.children)for(const p of e.children){const m=o.length;if(this.intersectSphere(p,t,i,n,o,r,a,l),m!=o.length&&!r)return}}}function Dy(s){return!(s.index&&s.index.array.length<3)}const _o=new c.Sphere,mh=new c.Plane,GS=new c.Matrix3;function HS(s,e,t){const i=s._computeIntersections;if(!i)return!1;let n=s["_computeIntersections:Needle"];return n||(n=s["_computeIntersections:Needle"]=function(o,r,a){const l=this,h=l.geometry.boundingSphere;if(h){if(l instanceof q.GroundedSkybox){mh.setFromNormalAndCoplanarPoint(V(0,1,0),V(0,-l.position.y,0)),mh.applyMatrix4(l.matrixWorld,GS);const u=o.ray.intersectPlane(mh,V());if(u){_o.copy(h),_o.applyMatrix4(l.matrixWorld);const m=V(u).sub(o.ray.origin).length(),y=_o.radius*.5;m<y&&r.push({distance:m,point:u,object:l,normal:mh.normal.clone()})}return}_o.copy(h),_o.applyMatrix4(l.matrixWorld);const d=o.ray.intersectSphere(_o,V());if(d){const u=V(d).sub(o.ray.origin),p=u.length();if(p>_o.radius){const m=u.clone().normalize();r.push({distance:p,point:d,object:l,normal:m})}}}}),s._computeIntersections=n,e.intersectObject(s,!1,t),s._computeIntersections=i,!0}var pd;(s=>{function e(v,b,x,T,O){if(!b.geometry||!b.geometry.hasAttribute("position"))return!1;const M=b.geometry;if(b?.isSkinnedMesh){const E=b,j=E.bvhNeedsUpdate;if(!E.staticGenerator)a(),o&&(E.staticGenerator=new o(b),E.staticGenerator.applyWorldTransforms=!1,E.staticGeometry=E.staticGenerator.generate(),M.boundsTree=r?.call(E.staticGeometry),E.staticGeometryLastUpdate=performance.now()+Math.random()*200,E.bvhNeedsUpdate=!0);else if(M.boundsTree&&(E.autoUpdateMeshBvhInterval!==void 0&&E.autoUpdateMeshBvhInterval>=0||j===!0)){const L=performance.now(),z=L-E.staticGeometryLastUpdate,$=E.autoUpdateMeshBvhInterval??100;(j||z>$)&&(Dt&&console.warn(`Physics: updating skinned mesh bvh for ${b.name} after ${z.toFixed(2)}ms`),E.bvhNeedsUpdate=!1,E.staticGeometryLastUpdate=L,E.staticGenerator?.generate(E.staticGeometry),M.boundsTree.refit())}}else if(!M.boundsTree){h||g();let E=!0;if((T.xr||M[m]===!1||M.getAttribute("position")?.isInterleavedBufferAttribute||M.index&&M.index?.isInterleavedBufferAttribute)&&(E=!1),E&&u){if(M[p]===void 0){let j=null;if(_.length>0){const L=_.shift();L&&!L.running&&(j=L)}if(!j&&y.length<3&&(j=new u,y.push(j)),j!=null&&!j.running){const L=b.name;Dt&&console.log("<<<< worker start",L,j),M[p]="queued",performance.mark("bvh.create.start");const z=M.clone();try{j.generate(z).then($=>{M[p]="done",M.boundsTree=$}).catch($=>{M[p]="failed - "+$?.message,M[m]=!1,Dt&&console.error("Failed to generate mesh bvh on worker",$)}).finally(()=>{Dt&&console.log(">>>>> worker done",L,{hasBoundsTre:M.boundsTree!=null}),_.push(j),z.dispose(),performance.mark("bvh.create.end"),performance.measure("bvh.create (worker)","bvh.create.start","bvh.create.end")})}catch($){console.error("Failed to generate mesh bvh on worker",$)}}else Dt&&console.warn("No worker available")}}else(!d||!E)&&(a(),n&&(performance.mark("bvh.create.start"),M.boundsTree=new n(M),performance.mark("bvh.create.end"),performance.measure("bvh.create","bvh.create.start","bvh.create.end")))}if(v instanceof c.Raycaster){const E=v,j=b.raycast;if(M.boundsTree)a(),i&&(b.acceleratedRaycast||(b.acceleratedRaycast=i.bind(b),Dt&&console.debug(`Physics: bind acceleratedRaycast fn to "${b.name}"`)),b.raycast=b.acceleratedRaycast);else if(Dt&&console.warn("No bounds tree found for mesh",b.name,{workerTask:M[p],hasAcceleratedRaycast:i!=null}),O.allowSlowRaycastFallback===!1)return Dt&&console.warn("Skipping raycast because no bounds tree is available and allowSlowRaycastFallback is false"),!1;const L=E.firstHitOnly;return E.firstHitOnly=!1,E.intersectObject(b,!1,x),E.firstHitOnly=L,b.raycast=j,!0}else if(v instanceof c.Sphere){const E=M.boundsTree;if(E){const j=v;if(l.copy(b.matrixWorld).invert(),j.applyMatrix4(l),E.intersectsSphere(j)){const z=X(b),$=z.distanceTo(j.center),R=new _m(b,$,z);x.push(R)}}return!0}return!1}s.runMeshBVHRaycast=e;let t=!1,i=null,n=null,o=null,r=null;function a(){t||(t=!0,Promise.resolve().then(()=>require("./vendor-BtJpSuCj.umd.cjs")).then(v=>v.index$1).then(v=>{i=v.acceleratedRaycast,n=v.MeshBVH,o=v.StaticGeometryGenerator,r=v.computeBoundsTree}).catch(v=>{(Dt||A())&&console.error("Failed to load BVH library...",v.message)}))}const l=new c.Matrix4;let h=!1,d=!1,u=null;const p=Symbol("Needle:MeshBVH-Worker"),m=Symbol("Needle:MeshBVH-CanUseWorker"),y=[],_=[];function g(){h=!0,d=!0,Promise.resolve().then(()=>RR).then(v=>{u=v.GenerateMeshBVHWorker}).catch(v=>{(Dt||A())&&console.warn("Failed to setup mesh bvh worker")}).finally(()=>{d=!1})}})(pd||(pd={}));const Iy=Symbol("gltf-loader-internal-usage-tracker"),qS=w("debugusers");class ea{get name(){return"NEEDLE_internal_usage_tracker"}static isLoading(e){return ea._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(){ea._loadingProcesses++;const e=this,t=this._getDependency;return this.parser.getDependency=function(i,n){const o=t.call(this,i,n);return o.then(r=>(r&&(e._loadedObjects.add(r),r[Iy]=e._loadingId),r)),o},null}afterRoot(e){ea._loadingProcesses--,this.parser.getDependency=this._getDependency;for(const t of this._loadedObjects)delete t[Iy],t instanceof c.Object3D&&(t.parent||t instanceof c.Mesh&&setTimeout(()=>{qS&&console.warn("> GLTF LOADER: Mesh not used in scene!",t),t.material=null,t.geometry=null},1e3));return null}}class Kb{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(Xi.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,(uh||A())&&console.debug("Left Needle Engine Room: "+n.room));break;case"user-joined-room":if(e.data){const r=e.data;this._currentInRoom.push(r.userId),zt&&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&&(zt&&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":zt&&console.log("RECEIVED all-room-state-deleted"),this._state={};break;case"ping":case"pong":const o=e.data?.time;o&&(this._currentDelay=this.context.time.time-o),zt&&console.log(`Current latency: ${(this._currentDelay*1e3).toFixed()} ms`,"Clients in room: "+this._currentInRoom?.length);break}const t=e.data;t&&(this._state[t.guid]=t);let i=this._listeners[e.key];if(i){i=[...i];for(const n of i)try{n(e.data)}catch(o){console.error('Error invoking callback for "'+e.key+'"',o)}}}toMessage(e,t){return{key:e,data:t}}sendWithWebsocket(e,t,i=Xi.OnRoomJoin){if(!this._ws){const o=this._waitingForSocket[i]||[];o.push(()=>this.sendWithWebsocket(e,t,i)),this._waitingForSocket[i]=o;return}const n=JSON.stringify(this.toMessage(e,t));zt&&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 Tl=w("debugwebxr");class Ju{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=>{Tl&&console.log(`XRSync: Received change for ${this.userId}: ${e.type} ${e.handedness}; tracked=${e.isTracking}`);let t=!1;for(let i=0;i<this.controllerStates.length;i++)if(this.controllerStates[i].index===e.index){this.controllerStates[i]=e,t=!0;break}t||this.controllerStates.push(e)};update(e){if(this.context.connection.isConnected!=!1){for(let t=this.controllerStates.length-1;t>=0;t--){const i=this.controllerStates[t];let n=!1;for(let o=0;o<e.controllers.length;o++)e.controllers[o].index===i.index&&(n=!0);n||(Tl&&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),Tl&&console.log(`XRSync: ${i.type} ${i.handedness} added`,i.index)}}}class Xb{hasState(e){return e?this._states.has(e):!1}isTracking(e,t){if(!e)return;const i=this._states.get(e);return i?i.controllerStates.find(o=>o.handedness===t)?.isTracking||!1:void 0}getDeviceType(e,t){if(!e)return;const i=this._states.get(e);return i?i.controllerStates.find(o=>o.handedness===t)?.type||"unknown":void 0}context;constructor(e){this.context=e,this.context.connection.beginListen(Q.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(Q.LeftRoom,this.onLeftRoom),this.context.connection.beginListen(Q.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.beginListen(Q.UserLeftRoom,this.onOtherUserLeftRoom)}destroy(){this.context.connection.stopListen(Q.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(Q.LeftRoom,this.onLeftRoom),this.context.connection.stopListen(Q.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.stopListen(Q.UserLeftRoom,this.onOtherUserLeftRoom)}onJoinedRoom=()=>{if(this.context.connection.connectionId){this._states.has(this.context.connection.connectionId)||(Tl&&console.log("XRSync: Local user joined room",this.context.connection.connectionId),this._states.set(this.context.connection.connectionId,new Ju(this.context.connection.connectionId,this.context)));for(const e of this.context.connection.usersInRoom())this._states.has(e)||this._states.set(e,new Ju(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)||(Tl&&console.log("XRSync: Remote user joined room",t),this._states.set(t,new Ju(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 My{_fadeToColorQuad;_fadeToColorMaterial;constructor(){this._fadeToColorMaterial=new c.MeshBasicMaterial({color:0,transparent:!0,depthTest:!1,fog:!1,side:c.DoubleSide}),this._fadeToColorQuad=new c.Mesh(new c.PlaneGeometry(10,10),this._fadeToColorMaterial)}dispose(){this._fadeToColorQuad.geometry.dispose(),this._fadeToColorMaterial.dispose()}update(e,t){const i=this._fadeToColorQuad,n=this._fadeToColorMaterial;i.parent!==e&&n.opacity>0?e.add(i):n.opacity===0&&i.removeFromParent(),i.layers.set(2),i.material=this._fadeToColorMaterial,i.position.z=-1,i.renderOrder=1/0;const o=this._requestedFadeValue;n.opacity=D.lerp(n.opacity,o,t/.03),Math.abs(n.opacity-o)<=.01&&this._transitionResolve&&(this._transitionResolve(),this._transitionResolve=null,this._transitionPromise=null,this._requestedFadeValue=0)}remove(){this._fadeToColorQuad.removeFromParent()}fadeTransition(){if(this._transitionPromise)return this._transitionPromise;this._requestedFadeValue=1;const e=new Promise(t=>{this._transitionResolve=t});return this._transitionPromise=e,e}_requestedFadeValue=0;_transitionPromise=null;_transitionResolve=null}var Go=(s=>(s[s.Quad=0]="Quad",s[s.Cube=1]="Cube",s[s.Sphere=2]="Sphere",s[s.Cylinder=3]="Cylinder",s[s.RoundedCube=10]="RoundedCube",s))(Go||{});class ir{static createText(e,t){let i=null;const n=t?.font||IS(t?.familyFamily||null);n instanceof q.Font?i=this.#t(e,n,t):i==null&&(i=new c.BufferGeometry);const o=t?.color||16777215,r=new c.Mesh(i,t?.material??new c.MeshStandardMaterial({color:o}));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 q.TextGeometry(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 c.MeshBasicMaterial({colorWrite:!1,depthWrite:!0,side:c.DoubleSide});return this.createPrimitive(e,{material:t})}static createPrimitive(e,t){let i;const n=t?.color||16777215;switch(e){case"Quad":case 0:{const o=new c.PlaneGeometry(1,1,1,1),r=t?.material??new c.MeshStandardMaterial({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new c.Mesh(o,r),i.name="Quad"}break;case"Cube":case 1:{const o=new c.BoxGeometry(1,1,1),r=t?.material??new c.MeshStandardMaterial({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new c.Mesh(o,r),i.name="Cube"}break;case 10:case"RoundedCube":{const o=DS(1,1,1,.1,2),r=t?.material??new c.MeshStandardMaterial({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new c.Mesh(o,r),i.name="RoundedCube"}break;case"Sphere":case 2:{const o=new c.SphereGeometry(.5,16,16),r=t?.material??new c.MeshStandardMaterial({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new c.Mesh(o,r),i.name="Sphere"}break;case"Cylinder":case 3:{const o=new c.CylinderGeometry(.5,.5,1,32),r=t?.material??new c.MeshStandardMaterial({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new c.Mesh(o,r),i.name="Cylinder"}break;case"ShaderBall":i=new c.Group,i.name="ShaderBall",jS(i,t);break}return this.applyDefaultObjectOptions(i,t),i}static createSprite(e){const i=new c.SpriteMaterial({color:16777215});e?.texture&&"map"in i&&(i.map=e.texture);const n=new c.Sprite(i);return this.applyDefaultObjectOptions(n,e),n}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 DS(s,e,t,i,n){const o=new c.Shape,r=1e-5,a=i-r;o.absarc(r,r,r,-Math.PI/2,-Math.PI,!0),o.absarc(r,e-a*2,r,Math.PI,Math.PI/2,!0),o.absarc(s-a*2,e-a*2,r,Math.PI/2,0,!0),o.absarc(s-a*2,r,r,0,-Math.PI/2,!0);const l=new c.ExtrudeGeometry(o,{bevelEnabled:!0,bevelSegments:n*2,steps:1,bevelSize:a,bevelThickness:i,curveSegments:n,UVGenerator:{generateTopUV:(h,d)=>{const u=[];for(let p=0;p<d.length;p+=3)u.push(new c.Vector2(d[p]/s,d[p+1]/e));return u},generateSideWallUV:(h,d,u,p,m,y)=>{const b=[];return b.push(new c.Vector2(d[u]/s,d[u+1]/e)),b.push(new c.Vector2(d[p]/s,d[p+1]/e)),b.push(new c.Vector2(d[m]/s,d[m+1]/e)),b.push(new c.Vector2(d[y]/s,d[y+1]/e)),b}}});return l.scale(1,1,1-i),l.center(),l.index||l.setIndex(Array.from({length:l.attributes.position.count},(h,d)=>d)),l.computeVertexNormals(),l}const fh=new Map;function IS(s){let e="";switch(s){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(fh.has(e)){const n=fh.get(e);if(n)return n}const t=new q.FontLoader,i=new Promise((n,o)=>{t.load(e,r=>{fh.set(e,r),n(r)},void 0,o)});return fh.set(e,i),i}let ef=!1,tf=null;function jS(s,e){if(tf===null){const t="https://cdn.needle.tools/static/models/shaderball.glb",i=new q.GLTFLoader,n=ne.createLoaders(null);i.setDRACOLoader(n.dracoLoader),i.setKTX2Loader(n.ktx2Loader),ef=!0,tf=i.loadAsync(t).then(o=>{const r=o.scene;return r.position.y-=.5,r}).catch(o=>(console.warn("Failed to load shaderball mesh: "+o.message),Ey())).finally(()=>{ef=!1})}if(ef){const t=Ey();t.name="ShaderBall-Placeholder";const i=t.children[0];i?.type==="Mesh"&&ky(i,e),s.add(t)}tf.then(t=>{s.children.forEach(o=>{o.name==="ShaderBall-Placeholder"&&s.remove(o)});const i=t.clone(),n=i.children[0];n?.type==="Mesh"&&(n.geometry.attributes.tangent||n.geometry.computeTangents(),ky(n,e)),s.add(i)})}function ky(s,e){if(e?.color||e?.material||e?.texture){const i=e?.material??s.material?.clone()??new c.MeshStandardMaterial;e.color&&"color"in i&&i.color instanceof c.Color&&i.color.set(e.color),e?.texture&&"map"in i&&(i.map=e.texture),s.material=i}}function Ey(){return new c.Group().add(ir.createPrimitive("Sphere",{material:new c.MeshBasicMaterial({transparent:!0,opacity:.1})}))}class ha{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 ha(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 Ln(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 c.WebGLRenderer({alpha:!0}),this._renderer.setAnimationLoop(this.onFrame),this._renderer.xr.setSession(i),this._renderer.xr.enabled=!0,this._camera=new c.PerspectiveCamera,this._scene=new c.Scene,this._scene.fog=new c.Fog(4473924,10,250),this._scene.add(this._camera),this.setupScene()}end(){return this._session?this._session.end():Promise.resolve()}async handoff(){if(!this._session)throw new Error("Cannot handoff a session that has already ended");const e={session:this._session,mode:this._mode,init:this._init};return await this.onBeforeHandoff(),this.onEnd(),this._session=null,e}onEnd=()=>{this._session?.removeEventListener("end",this.onEnd),this._renderer.setAnimationLoop(null),this._renderer.dispose(),this._scene.clear()};_lastTime=0;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 Ln(1e3),this._scene.clear()}_objects=[];setupScene(){this._scene.background=new c.Color(0),this._scene.add(new c.GridHelper(5,10,1118481,1118481));const e=new c.DirectionalLight(16777215,1);e.position.set(0,20,0),e.castShadow=!1,this._scene.add(e);const t=new c.DirectionalLight(16777215,1);t.position.set(0,-1,0),t.castShadow=!1,this._scene.add(t);const i=new c.PointLight(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 o=0;o<100;o++){const r=new c.MeshStandardMaterial({color:2236962,metalness:1,roughness:.8});this.isAR&&(r.emissive=new c.Color(Math.random(),Math.random(),Math.random()),r.emissiveIntensity=Math.random());const a=D.random(0,1)>.5?Go.Sphere:Go.Cube,l=ir.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 h=l.position.distanceTo(this._camera.position)-l.scale.x;h<1&&l.position.multiplyScalar(1+1/h),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 o=this._objects[n];o.position.y+=Math.sin(i+n*.5)*.005,o.rotateY(.002)}}}var Gl;(s=>{const e=[];function t(){if(!e?.length)return!1;for(const o of e)o.exportAndOpen();return!0}s.exportAndOpen=t;function i(o){e.push(o)}s.registerExporter=i;function n(o){if(!e)return;const r=e.indexOf(o);r>=0&&e.splice(r,1)}s.unregisterExporter=n})(Gl||(Gl={}));const Le=w("debugwebxr"),Ry=w("stats");let nf=0;function BS(s){let e=null;const t=s;return t.getAROverlayContainer?e=t.getAROverlayContainer():e=s,e}FS();async function FS(){if(w("debugasap")){let s=globalThis["needle:XRSession"];if(s instanceof Promise){delete globalThis["needle:XRSession"],ae.addContextCreatedCallback(async e=>{if(!s)return;Lo(!0);const t=await s;if(t){const i=H.getDefaultSessionInit("immersive-vr");H.setSession("immersive-vr",t,i,e.context)}else console.error("NeedleXRSession: ASAP session was rejected");s=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()=>{Lo(!0),console.log("Received Session Granted..."),await Ln(100);const s=sessionStorage.getItem("needle_xr_session_mode"),e=sessionStorage.getItem("needle_xr_session_init")??null,t=e?JSON.parse(e):null;let i=null;if(Qb()&&(await ha.start(s||"immersive-vr",t||H.getDefaultSessionInit("immersive-vr")),await NS(),i=await ha.handoff()),i)H.setSession(i.mode,i.session,i.init,F.Current);else if(s&&e){console.log("Session Granted: Restore last session");const n=JSON.parse(e);H.start(s,n).catch(o=>console.warn(o))}else H.start("immersive-vr").catch(n=>console.warn("Session Granted failed:",n))},{once:!0})}}function US(s,e){sessionStorage.setItem("needle_xr_session_mode",s),sessionStorage.setItem("needle_xr_session_init",JSON.stringify(e))}function zS(){sessionStorage.removeItem("needle_xr_session_mode"),sessionStorage.removeItem("needle_xr_session_init")}const gm=new Set;ae.registerCallback(re.ContextCreationStart,async s=>{gm.add(s.context)});ae.registerCallback(re.ContextCreated,async s=>{gm.delete(s.context);const e=s.context?.domElement.getAttribute("autostart")||null;VS(e)});function Qb(){return gm.size>0}function NS(){return new Promise(s=>{const e=Date.now(),t=setInterval(()=>{(!Qb()||Date.now()-e>6e4)&&(clearInterval(t),s())},100)})}exports.DeviceUtilities.isDesktop()&&A()&&window.addEventListener("keydown",s=>{(s.key==="x"||s.key==="Escape")&&H.active&&H.stop()});function VS(s){if(s)switch(s?.toLowerCase()){case"ar":tn.registerWaitForInteraction(()=>{H.start("ar")});break}}const ph=Symbol("initial-fov");class H{static _sync=null;static getXRSync(e){return this._sync||(this._sync=new Xb(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=>(Le&&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=>H.setSession(e,n,t,i)).catch(n=>{console.log("XRSession offer rejected (perhaps because another call to offerSession was made or a call to requestSession was made)")})),!0):!1}static getDefaultSessionInit(e){switch(e){case"immersive-ar":const t=["anchors","local-floor","layers","dom-overlay","hit-test","unbounded"];return exports.DeviceUtilities.isVisionOS()||t.push("hand-tracking"),{optionalFeatures:t};case"immersive-vr":const i=["local-floor","bounded-floor","high-fixed-foveation-level","layers"];return exports.DeviceUtilities.isVisionOS()||i.push("hand-tracking"),{optionalFeatures:i};default:return console.warn("No default session init for mode",e),{}}}static async start(e,t,i){if(exports.DeviceUtilities.isiOS()){if(e==="ar")if(await this.isARSupported())e="immersive-ar";else return Gl.exportAndOpen(),null}else e=="ar"&&(e="immersive-ar");if(A()&&w("debugxrpreroom"))return console.warn("Debug: Starting temporary XR session"),await ha.start(e,t||H.getDefaultSessionInit(e)),null;if(this._currentSessionRequest)return console.warn("A XRSession is already being requested"),(Le||A())&&he("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=F.Current),i||(i=ae.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 l=this.getDefaultSessionInit(e),h=BS(i.domElement);h&&!exports.DeviceUtilities.isQuest()&&(l.domOverlay={root:h},l.optionalFeatures.push("dom-overlay")),t={...l,...t}}break;case"immersive-vr":{if(await this.xrSystem?.isSessionSupported("immersive-vr")!==!0)return console.error(e+" is not supported by this browser."),null;t={...this.getDefaultSessionInit(e),...t}}break;default:console.warn("No default session init for mode",e);break}t.optionalFeatures??=[],t.requiredFeatures??=[],await ha.stop();const n=e=="immersive-ar"?i.scripts_immersive_ar:i.scripts_immersive_vr;Le?console.log(`%cRequesting ${e} session`,"font-weight:bold;",t,n):console.log(`%cRequesting ${e} session`,"font-weight:bold;");for(const a of n)a.onBeforeXR&&a.onBeforeXR(e,t);for(const a of this._sessionRequestStartListeners)a({mode:e,init:t});Le&&Se("Requesting "+e+" session ("+Date.now()+")"),this._currentSessionRequest=navigator?.xr?.requestSession(e,t),this._currentSessionRequestMode=e;const o=await this._currentSessionRequest?.catch(a=>{console.error(a,"Code: "+a.code),a.code===9&&he("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:"&&he("XR requires a secure connection (HTTPS)")});this._currentSessionRequest=void 0,this._currentSessionRequestMode=null;for(const a of this._sessionRequestEndListeners)a({mode:e,init:t,newSession:o||null});return o?this.setSession(e,o,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 o=e=="immersive-ar"?n.scripts_immersive_ar:n.scripts_immersive_vr;return this._activeSession=new H(e,t,n,{scripts:o,controller_added:this._controllerAddedListeners,controller_removed:this._controllerRemovedListeners,init:i}),t.addEventListener("end",this.onEnd),Le?console.log(`%cStarted ${e} session`,"font-weight:bold;",o):console.log(`%cStarted ${e} session`,"font-weight:bold;"),this._activeSession}static $_stop_request=Symbol();static stop(){const e=this._activeSession;e&&(e[this.$_stop_request]===void 0?(Le&&console.log("[NeedleXRSession] Stopping XR Session... (new)"),e[this.$_stop_request]=setTimeout(()=>{e.end()})):Le&&console.warn("[NeedleXRSession] XR Session stop already requested"))}static onEnd=()=>{Le&&console.log("XR Session ended"),this._activeSession=null};context;get sync(){return H._sync}get running(){return!this._ended&&this.session!=null}session;mode;get interactionMode(){return this.session.interactionMode}get visibilityState(){return this.session.visibilityState}get isVisibleBlurred(){return this.session.visibilityState==="visible-blurred"}get isSystemKeyboardSupported(){return this.session.isSystemKeyboardSupported}get environmentBlendMode(){return this.session.environmentBlendMode}get frame(){return this.context.xrFrame}controllers=[];get leftController(){return this.controllers.find(e=>e.side==="left")}get rightController(){return this.controllers.find(e=>e.side==="right")}getController(e){return typeof e=="number"?this.controllers[e]||null:this.controllers.find(t=>t.side===e)||null}get isPassThrough(){return!!(this.environmentBlendMode!=="opaque"&&this.interactionMode==="world-space"||this.mode==="immersive-ar"&&this.environmentBlendMode!=="opaque"&&this.controllers.some(e=>e.inputSource.targetRayMode==="tracked-pointer")||A()&&exports.DeviceUtilities.isDesktop()&&this.mode==="immersive-ar")}get isAR(){return this.mode==="immersive-ar"}get isVR(){return this.mode==="immersive-vr"}get isScreenBasedAR(){return this.isAR&&!this.isPassThrough}get posePosition(){return this._transformPosition}get poseOrientation(){return this._transformOrientation}get referenceSpace(){return this.context.renderer.xr.getReferenceSpace()}get viewerPose(){return this._viewerPose}get isTrackingImages(){if(this.frame&&"getImageTrackingResults"in this.frame&&typeof this.frame.getImageTrackingResults=="function")try{const e=this.frame.getImageTrackingResults();for(const t of e)if(t.trackingState==="tracked")return!0}catch{return!1}return!1}get rig(){const e=this._rigs[0]??null;return e?.gameObject&&Ho(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 V(0,0,0);const t=V(e);return t.x*=-1,t.z*=-1,t.applyQuaternion(Gt(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(Ho(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)}Le&&(e===t?console.log("Updated Active XR Rig:",t,"prev:",e):console.log("Updated Active XRRig:",t," (the same as before)"))}_rigs=[];_viewerHitTestSource=null;getHitTest(e){if(e)return this.getControllerHitTest(e);if(!this._viewerHitTestSource)return null;const t=this._viewerHitTestSource,i=this.frame.getHitTestResults(t);if(i.length>0){const n=i[0];return this.convertHitTestResult(n)}return null}getControllerHitTest(e){const t=e.getHitTestSource();if(!t)return null;const i=this.frame.getHitTestResultsForTransientInput(t);for(const n of i)if(n.inputSource===e.inputSource)for(const o of n.results)return this.convertHitTestResult(o);return null}convertHitTestResult(e){const t=this.context.renderer.xr.getReferenceSpace(),i=t&&e.getPose(t);if(i){const n=V(i.transform.position),o=Gt(i.transform.orientation),r=this.context.mainCamera;if(r?.parent!==this._cameraRenderParent&&n.applyMatrix4(Zr),r?.parent){n.applyMatrix4(r.parent.matrixWorld),o.multiply(ki);const a=ue(r.parent);a.premultiply(ki),o.premultiply(a)}return{hit:e,position:n,quaternion:o}}return null}convertSpace(e){const t=V(e.position);t.applyMatrix4(Zr);const i=Gt(e.orientation);return i.premultiply(ki),{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){US(e,n.init),this.session=t,this.mode=e,this.context=i,(Le||w("console"))&&Lo(!0),this._xr_scripts=[...n.scripts],this._xr_update_scripts=this._xr_scripts.filter(o=>typeof o.onUpdateXR=="function"),this._controllerAdded=n.controller_added,this._controllerRemoved=n.controller_removed,hs(this.onBefore,pe.LateUpdate),this.context.pre_render_callbacks.push(this.onBeforeRender),this.context.post_render_callbacks.push(this.onAfterRender),(n.init.optionalFeatures?.includes("hit-test")||n.init.requiredFeatures?.includes("hit-test"))&&t.requestReferenceSpace("viewer").then(o=>t.requestHitTestSource?.call(t,{space:o})?.then(r=>this._viewerHitTestSource=r).catch(r=>console.error(r))).catch(o=>console.error(o)),this.context.mainCamera&&(this._originalCameraWorldPosition=X(this.context.mainCamera,new c.Vector3),this._originalCameraWorldRotation=ue(this.context.mainCamera,new c.Quaternion),this._originalCameraWorldScale=Ie(this.context.mainCamera,new c.Vector3),this._originalCameraParent=this.context.mainCamera.parent,this.context.mainCamera instanceof c.PerspectiveCamera&&(this.context.mainCamera[ph]=this.context.mainCamera.fov)),this._defaultRig=new xS,this.context.scene.add(this._defaultRig.gameObject),this.addRig(this._defaultRig);for(let o=0;o<t.inputSources.length;o++){const r=t.inputSources[o];if(!r.handedness){console.warn("Input source in xr session has no handedness - ignoring",o);continue}this.onInputSourceAdded(r)}this.session.addEventListener("end",this.onEnd),this.session.addEventListener("inputsourceschange",o=>{for(const r of o.removed)this.disconnectInputSource(r);for(const r of o.added)this.onInputSourceAdded(r)}),this.context.xr=this,this.context.renderer.xr.setSession(this.session).then(this.onRendererSessionSet),"controllerAutoUpdate"in this.context.renderer.xr?(console.debug("Disabling three.js controllerAutoUpdate"),this.context.renderer.xr.controllerAutoUpdate=!1):Le&&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 dm(this,e,t);this._newControllers.push(i)};disconnectInputSource(e){const t=(o,r)=>{if(o.inputSource===e){Le&&console.log("Disconnecting controller",o.index);const a=r.indexOf(o);a>=0&&r.splice(a,1),this.invokeControllerEvent(o,this._controllerRemoved,"removed");const l={xr:this,controller:o,change:"removed"};for(const h of this._xr_scripts)h.onXRControllerRemoved&&h.onXRControllerRemoved(l);o.onDisconnected()}},i=[...this.controllers];for(let o=i.length-1;o>=0;o--){const r=i[o];t(r,this.controllers)}const n=[...this._newControllers];for(let o=n.length-1;o>=0;o--){const r=n[o];t(r,this._newControllers)}}end(){this._ended||this.session.end().catch(e=>console.warn(e))}_ended=!1;_newControllers=[];onEnd=e=>{if(this._ended)return;this._ended=!0,console.debug("XR Session ended"),zS(),this.onAfterRender(),this.revertCustomForward(),this._didStart=!1,this._previousCameraParent=null,this.requestedCameraNearPlane=null,to(this.onBefore,pe.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()}),Fb({session:this});for(const o of H._xrEndListeners)o({xr:this});const n=[...this.controllers];for(let o=0;o<n.length;o++)this.disconnectInputSource(n[o].inputSource);this.controllers.length=0,this._newControllers.length=0;for(const o of this._xr_scripts)o?.onLeaveXR?.({xr:this});this.sync?.onExitXR(this),this.context.mainCamera&&(this._originalCameraParent?.add(this.context.mainCamera),this._originalCameraWorldPosition&&ot(this.context.mainCamera,this._originalCameraWorldPosition),this._originalCameraWorldRotation&&Ji(this.context.mainCamera,this._originalCameraWorldRotation),this._originalCameraWorldScale&&aa(this.context.mainCamera,this._originalCameraWorldScale),this.context.mainCamera instanceof c.PerspectiveCamera&&this.context.mainCamera[ph]&&(this.context.mainCamera.fov=this.context.mainCamera[ph],this.context.mainCamera[ph]=0)),this.context.requestSizeUpdate(),this._defaultRig.gameObject.removeFromParent(),Lo(!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&&(Le&&console.warn("Latest rig is not active - trying to activate a different rig",this.rig),this.updateActiveXRRig()),this.rig&&this._mainCamera?.gameObject&&this._mainCamera?.gameObject?.parent!==this.rig.gameObject&&this.rig.gameObject.add(this._mainCamera?.gameObject),this.internalUpdateState(),this.applyCustomForward();const i={xr:this};if(this._didStart){if(this.context.new_scripts_xr.length>0){const n=[...this.context.new_scripts_xr];for(let o=0;o<n.length;o++){const r=this.context.new_scripts_xr[o];if(!r||r.destroyed||r.supportsXR?.(this.mode)==!1){this.context.new_scripts_xr.splice(o,1);continue}if(!r.activeAndEnabled){this.context.new_scripts_xr.splice(o,1),this.markInactive(r);continue}if(this.addScript(r)){this.invokeCallback_EnterXR(r);for(const a of this.controllers)this.invokeCallback_ControllerAdded(r,a)}}}}else{if(this._didStart=!0,this.mode==="immersive-vr"){const o=Bt(this.context.scene.children);if(o){const r=o.getSize(V());if(r.length()>0){const a=this._defaultRig.gameObject;a.position.set(o.min.x+r.x*.5,o.min.y,o.max.z+r.z*.5+1.5);const l=o.getCenter(V());l.y=a.position.y,a.lookAt(l)}}}Bb({session:this}),tr();for(const o of H._xrStartListeners)o(i);const n=[...this._xr_scripts];Le&&console.log("NeedleXRSession start, handle scripts:",n);for(const o of n){if(o.destroyed){this._script_to_remove.push(o);continue}if(!o.activeAndEnabled){this.markInactive(o);continue}this.invokeCallback_EnterXR(o);for(const r of this.controllers)this.invokeCallback_ControllerAdded(o,r)}}this.syncCameraCullingMask();for(const n of this.controllers)n.onUpdate(t);if(this._newControllers.length>0){const n=[...this._newControllers];this._newControllers.length=0;for(const o of n){if(!o.connected){console.warn("New controller is not connected",o);continue}this.controllers.push(o);for(const r of this._xr_scripts){if(r.destroyed){this._script_to_remove.push(r);continue}r.activeAndEnabled!==!1&&this.invokeCallback_ControllerAdded(r,o)}}this.controllers.sort((o,r)=>o.index-r.index)}Le&&this.context.time.frame%30===0&&this.controllers.length<=0&&this.session.inputSources.length>0&&(Lo(!0),console.error("XRControllers are not added but inputSources are present"));for(const n of this._xr_update_scripts){if(n.destroyed===!0){this._script_to_remove.push(n);continue}if(n.activeAndEnabled===!1){this.markInactive(n);continue}n.onUpdateXR&&n.onUpdateXR(i)}if(this.handleInactiveScripts(),this._script_to_remove.length>0){const n=[...new Set(this._script_to_remove)];this._script_to_remove.length=0;for(const o of n)!o.destroyed&&this.running&&o.onLeaveXR?.(i),this.removeScript(o)}this.sync?.onUpdate(this),this.onRenderDebug()};onRenderDebug(){if(Le)for(const e of this.controllers)e.onRenderDebug();if((Le||Ry)&&this.rig&&(nf++,nf>=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()}`,Le||Ry)for(const o of this.controllers)n+=`
|
|
165
|
+
${o.hand?"hand":"ctrl"} ${o.inputSource.handedness}[${o.index}] con:${o.connected} tr:${o.isTracking} hts:${o.hasHitTestSource?"yes":"no"}`;nf=0,B.DrawLabel(e,n,void 0,1/60*20)}}onBeforeRender=()=>{this.context.mainCamera&&(this.updateFade(this.context.mainCamera),this.requestedCameraNearPlane!==null&&this.context.mainCamera instanceof c.PerspectiveCamera&&(this.context.mainCamera.near=this.requestedCameraNearPlane,this.requestedCameraNearPlane=null))};onAfterRender=()=>{if(this.onUpdateFade_PostRender(),exports.DeviceUtilities.isDesktop()||!this._renderOnceOnDevice){const e=this.context.renderer;if(e.xr.isPresenting&&this.context.mainCamera){this._renderOnceOnDevice=!0;const t=e.xr.enabled,i=e.getRenderTarget(),n=this.context.scene.background;e.xr.enabled=!1,e.setRenderTarget(null),this.isPassThrough&&(this.context.scene.background=null),this.context.composer?this.context.composer.render(this.context.time.deltaTime):e.render(this.context.scene,this.context.mainCamera),e.xr.enabled=t,e.setRenderTarget(i),this.context.scene.background=n}}};addScript(e){return this._xr_scripts.includes(e)?!1:(Le&&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){Le&&console.log("Remove XRScript",e);const i=this._xr_scripts.indexOf(e);i>=0&&this._xr_scripts.splice(i,1);const n=this._xr_update_scripts.indexOf(e);if(n>=0&&this._xr_update_scripts.splice(n,1),t){const o=this._inactive_scripts.indexOf(e);o>=0&&this._inactive_scripts.splice(o,1)}}invokeCallback_EnterXR(e){e.onEnterXR&&e.onEnterXR({xr:this})}invokeCallback_ControllerAdded(e,t){e.onXRControllerAdded&&e.onXRControllerAdded({xr:this,controller:t,change:"added"})}invokeCallback_ControllerRemoved(e,t){e.onXRControllerRemoved&&e.onXRControllerRemoved({xr:this,controller:t,change:"removed"})}invokeCallback_LeaveXR(e){e.onLeaveXR&&!e.destroyed&&e.onLeaveXR({xr:this})}syncCameraCullingMask(){const e=this.context.xrCamera,t=this.context.mainCameraComponent?.cullingMask;if(e&&t!==void 0){for(const i of e.cameras)i.layers.mask=t;e.layers.mask=t}else if(e){for(const i of e.cameras)i.layers.enableAll();e.layers.enableAll()}}invokeControllerEvent(e,t,i){for(let n=t.length-1;n>=0;n--){const o=t[n];if(o)try{o({xr:this,controller:e,change:i})}catch(r){console.error(r)}}}_camera;_cameraRenderParent=new c.Object3D().rotateY(Math.PI);_previousCameraParent;_customforward=!0;originalCameraNearPlane;requestedCameraNearPlane=null;applyCustomForward(){if(this.context.mainCamera&&this._customforward){this._camera=this.context.mainCamera,this._camera.parent!==this._cameraRenderParent&&(this._previousCameraParent=this._camera.parent,this._previousCameraParent?.add(this._cameraRenderParent)),this._cameraRenderParent.name="XR Camera Render Parent",this._cameraRenderParent.add(this._camera);{let e=.02;const t=.001;if(this.rig){const i=Ie(this.rig.gameObject);e*=i.x}this._camera instanceof c.PerspectiveCamera&&Math.abs(this._camera.near-e)>t&&(this.isAR?this.originalCameraNearPlane=this._camera.near:this._camera.near=e,Le&&console.debug(`Setting camera near plane to ${e} (was ${this.originalCameraNearPlane}) to account for XR rendering scale`))}}}revertCustomForward(){this._camera&&this._previousCameraParent&&this._previousCameraParent.add(this._camera),this._previousCameraParent=null,this._camera instanceof c.PerspectiveCamera&&this.originalCameraNearPlane!=null&&(this._camera.near=this.originalCameraNearPlane,this.originalCameraNearPlane=void 0)}_viewerPose;_transformOrientation=new c.Quaternion;_transformPosition=new c.Vector3;internalUpdateState(){const e=this.context.renderer.xr.getReferenceSpace();if(!e){this._viewerPose=void 0;return}if(this._viewerPose=this.frame.getViewerPose(e),this._viewerPose){const t=this._viewerPose.transform;this._transformPosition.set(t.position.x,t.position.y,t.position.z),this._transformOrientation.set(t.orientation.x,t.orientation.y,t.orientation.z,t.orientation.w)}}_transition;get transition(){return this._transition||(this._transition=new My),this._transition}fadeTransition(){return this._transition||(this._transition=new My),this._transition.fadeTransition()}updateFade(e){this._transition&&e instanceof c.PerspectiveCamera&&this._transition.update(e,this.context.time.deltaTime)}onUpdateFade_PostRender(){this._transition?.remove()}}const sf=w("debugwebxr");class Yb{static tryFindAvatarObjects(e,t,i){if(i.head&&i.leftHand&&i.rightHand)return;const n=e.name.toLocaleLowerCase();!i.head&&n.includes("head")&&(sf&&console.log("FOUND AVATAR HEAD",e.name),i.head=new Y("",t,e)),n.includes("hand")&&(!i.leftHand&&n.includes("left")&&(sf&&console.log("FOUND AVATAR LEFT HAND",e.name),i.leftHand=new Y("",t,e)),!i.rightHand&&n.includes("right")&&(sf&&console.log("FOUND AVATAR RIGHT HAND",e.name),i.rightHand=new Y("",t,e)));for(let o=0;o<e.children.length;o++){if(i.head&&i.leftHand&&i.rightHand)return;const r=e.children[o];this.tryFindAvatarObjects(r,t,i)}}}const bt=new c.Vector3,Ty=new c.Vector3,Ay=new c.Quaternion,$S=w("debuggizmos"),Gi=8947848,of=32;class B{constructor(){}static enabled=!0;static isGizmo(e){return e[cp]!==void 0}static setVisible(e){for(const t of Si.timedObjectsBuffer)t.visible=e}static DrawLabel(e,t,i=.05,n=0,o,r,a){if(!B.enabled)return null;o||(o=Gi);const l=H.active?.rigScale??1,h=Si.getTextLabel(n,t,i*l,o,r);return a instanceof c.Object3D&&a.add(h),h.position.x=e.x,h.position.y=e.y,h.position.z=e.z,h}static DrawRay(e,t,i=Gi,n=0,o=!0){if(!B.enabled)return;const r=Si.getLine(n),a=r.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),bt.set(t.x,t.y,t.z).multiplyScalar(999999999),a.setXYZ(1,e.x+bt.x,e.y+bt.y,e.z+bt.z),a.needsUpdate=!0,r.material.color.set(i),r.material.depthTest=o,r.material.depthWrite=!1}static DrawDirection(e,t,i=Gi,n=0,o=!0,r=1){if(!B.enabled)return;const a=Si.getLine(n),l=a.geometry.getAttribute("position");l.setXYZ(0,e.x,e.y,e.z),t.w!==void 0?(bt.set(0,0,-r),Ay.set(t.x,t.y,t.z,t.w),bt.applyQuaternion(Ay)):(bt.set(t.x,t.y,t.z),bt.multiplyScalar(r)),l.setXYZ(1,e.x+bt.x,e.y+bt.y,e.z+bt.z),l.needsUpdate=!0,a.material.color.set(i),a.material.depthTest=o,a.material.depthWrite=!1}static DrawLine(e,t,i=Gi,n=0,o=!0){if(!B.enabled)return;const r=Si.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=o,r.material.depthWrite=!1,r.material.fog=!1}static DrawCircle(e,t,i,n=Gi,o=0,r=!0){if(!B.enabled)return;const a=Si.getCircle(o);a.position.set(e.x,e.y,e.z),a.scale.set(i,i,i),a.quaternion.setFromUnitVectors(this._up,bt.set(t.x,t.y,t.z).normalize()),a.material.color.set(n),a.material.depthTest=r,a.material.depthWrite=!1,a.material.fog=!1}static DrawWireSphere(e,t,i=Gi,n=0,o=!0){if(!B.enabled)return;const r=Si.getSphere(t,n,!0);Wo(r,e.x,e.y,e.z),r.material.color.set(i),r.material.depthTest=o,r.material.depthWrite=!1,r.material.fog=!1}static DrawSphere(e,t,i=Gi,n=0,o=!0){if(!B.enabled)return;const r=Si.getSphere(t,n,!1);Wo(r,e.x,e.y,e.z),r.material.color.set(i),r.material.depthTest=o,r.material.depthWrite=!1}static DrawWireBox(e,t,i=Gi,n=0,o=!0,r=void 0){if(!B.enabled)return;const a=Si.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=o,a.material.wireframe=!0,a.material.depthWrite=!1,a.material.fog=!1}static DrawWireBox3(e,t=Gi,i=0,n=!0){if(!B.enabled)return;const o=Si.getBox(i);o.position.copy(e.getCenter(bt)),o.scale.copy(e.getSize(bt)),o.material.color.set(t),o.material.depthTest=n,o.material.wireframe=!0,o.material.depthWrite=!1,o.material.fog=!1}static _up=new c.Vector3(0,1,0);static DrawArrow(e,t,i=Gi,n=0,o=!0,r=!1){if(!B.enabled)return;const a=Si.getArrowHead(n);a.position.set(t.x,t.y,t.z),a.quaternion.setFromUnitVectors(this._up.set(0,1,0),bt.set(t.x,t.y,t.z).sub(Ty.set(e.x,e.y,e.z)).normalize());const h=bt.set(t.x,t.y,t.z).sub(Ty.set(e.x,e.y,e.z)).length()*.1;a.scale.set(h,h,h),a.material.color.set(i),a.material.depthTest=o,a.material.wireframe=r,this.DrawLine(e,t,i,n,o)}static DrawWireMesh(e){const t=Si.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??Gi),t.material.depthTest=e.depthTest??!0,t.material.wireframe=!0}}const WS=new c.BoxGeometry(1,1,1);function ym(s=null){const e=new c.Color(s??14540253),t=new c.EdgesGeometry(WS);return new c.LineSegments(t,new c.LineBasicMaterial({color:e}))}const cp=Symbol("GizmoCache");class Si{static familyName="needle-gizmos";static ensureFont(){let e=J.__webpack_exports__default.FontLibrary.getFontFamily(this.familyName);e||(e=J.__webpack_exports__default.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",()=>{J.__webpack_exports__default.update()}))}static getTextLabel(e,t,i,n,o){this.ensureFont();let r=this.textLabelCache.pop(),a=1;o&&typeof o=="string"&&o?.length>=8&&o.startsWith("#")?(a=parseInt(o.substring(7),16)/255,o=o.substring(0,7),$S&&console.log(o,a)):typeof o=="object"&&o.a!==void 0&&(a=o.a);const l={boxSizing:"border-box",fontFamily:this.familyName,width:"auto",fontSize:i,color:n,lineHeight:1,backgroundColor:o??void 0,backgroundOpacity:a,textContent:t,borderRadius:.5*i,padding:.8*i,whiteSpace:"pre",offset:.05*i};if(r)r.set(l);else{r=new J.__webpack_exports__Text(l);const h=this,d=r;d.setText=function(u){this.set({textContent:u}),h.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(F.Current,r,e,this.textLabelCache),r}static getBox(e){let t=this.boxesCache.pop();if(!t){const i=new c.BoxGeometry(1,1,1);t=new c.Mesh(i)}return this.registerTimedObject(F.Current,t,e,this.boxesCache),t}static getLine(e){let t=this.linesCache.pop();if(!t){t=new c.Line;let i=t.geometry.getAttribute("position");i||(i=new c.BufferAttribute(new Float32Array(6),3),t.geometry.setAttribute("position",i))}return t.frustumCulled=!1,this.registerTimedObject(F.Current,t,e,this.linesCache),t}static getCircle(e){let t=this.circlesCache.pop();if(!t){t=new c.Line;let i=t.geometry.getAttribute("position");if(!i){i=new c.BufferAttribute(new Float32Array(of*3),3),t.geometry.setAttribute("position",i);const n=V(0,1,0),o=V(0,0,1),r=V(o);r.cross(n).normalize();const a=V(r),l=Math.PI*2/(of-1);for(let h=0;h<of+1;h++){const d=l*h;n.copy(a).multiplyScalar(Math.cos(d)*1),r.copy(o).multiplyScalar(Math.sin(d)*1);const u=n.add(r);i.setXYZ(h,u.x,u.y,u.z)}}}return t.frustumCulled=!1,this.registerTimedObject(F.Current,t,e,this.circlesCache),t}static getSphere(e,t,i){let n=this.spheresCache.pop();return n||(n=new c.Mesh(new c.SphereGeometry(1,8,8))),n.scale.set(e,e,e),n.material.wireframe=i,this.registerTimedObject(F.Current,n,t,this.spheresCache),n}static getArrowHead(e){let t=this.arrowHeadsCache.pop();return t||(t=new c.Mesh(new c.CylinderGeometry(0,.5,1,8))),this.registerTimedObject(F.Current,t,e,this.arrowHeadsCache),t}static getMesh(e){let t=this.mesh.pop();return t||(t=new c.Mesh,t.material=new c.MeshBasicMaterial),this.registerTimedObject(F.Current,t,e,this.mesh),t}static linesCache=[];static circlesCache=[];static spheresCache=[];static boxesCache=[];static arrowHeadsCache=[];static mesh=[];static textLabelCache=[];static registerTimedObject(e,t,i,n){if(!e){console.error("No Needle Engine context available. Did you call a Gizmos function in global scope?");return}const o=this.contextBeforeRenderCallbacks.get(e),r=this.contextPostRenderCallbacks.get(e);if(o){if(e.pre_render_callbacks[e.pre_render_callbacks.length-1]!==o){const a=e.pre_render_callbacks.indexOf(o);a>=0&&e.pre_render_callbacks.splice(a,1),e.pre_render_callbacks.push(o)}}else{const a=()=>{this.onBeforeRender(e,this.timedObjectsBuffer)};this.contextBeforeRenderCallbacks.set(e,a),e.pre_render_callbacks.push(a)}if(r){if(e.post_render_callbacks[e.post_render_callbacks.length-1]!==r){const a=e.post_render_callbacks.indexOf(r);a>=0&&e.post_render_callbacks.splice(a,1),e.post_render_callbacks.push(r)}}else{const a=()=>{this.onPostRender(e,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(e,a),e.post_render_callbacks.push(a)}t.traverse(a=>{a.layers.disableAll(),a.layers.enable(2)}),t.renderOrder=999999,t[cp]=n,t.castShadow=!1,t.receiveShadow=!1,t.isGizmo=!0,this.timedObjectsBuffer.push(t),this.timesBuffer.push(F.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,J.__webpack_exports__default.update());for(let i=0;i<t.length;i++){const n=t[i];if(e.mainCamera&&n instanceof J.__webpack_exports__default.MeshUIBaseElement){if(Ho(n))continue;const o=e.isInVR,r=!1,a=!o;cc(n,e.mainCamera,r,a)}}}static onPostRender(e,t,i){const n=e.time.realtimeSinceStartup;for(let o=t.length-1;o>=0;o--){const r=t[o];n>=i[o]-1e-6&&(t.splice(o,1),i.splice(o,1),r.removeFromParent(),Ho(r)!=!0&&r[cp].push(r))}}}const Dt=w("debugphysics"),Ly=new c.Layers;class io{static AllLayers=4294967295;ray;cam;screenPoint;raycaster;results;targets;recursive=!0;minDistance;maxDistance;lineThreshold;layerMask;ignore;testObject;useAcceleratedRaycast;allowSlowRaycastFallback=!0;screenPointFromOffset(e,t){this.screenPoint===void 0&&(this.screenPoint=new c.Vector2),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setLayer(e){Ly.set(e),this.layerMask=Ly}setMask(e){this.layerMask||(this.layerMask=new c.Layers);const t=this.layerMask;t?t.mask=e:this.layerMask=e}}class _m{distance;point;object;constructor(e,t,i){this.object=e,this.distance=t,this.point=i}}class da{static _raycasting=0;static get raycasting(){return this._raycasting>0}raycastPhysicsFast(e,t=void 0,i=1/0,n=!0){return this.context.physics.engine?.raycast(e,t,{maxDistance:i,solid:n})??null}raycastPhysicsFastAndGetNormal(e,t=void 0,i=1/0,n=!0){return this.context.physics.engine?.raycastAndGetNormal(e,t,{maxDistance:i,solid:n})??null}sphereOverlapPhysics(e,t){return this.context.physics.engine?.sphereOverlap(e,t)??null}context;engine;constructor(e){this.context=e}raycaster=new c.Raycaster;defaultRaycastOptions=new io;targetBuffer=new Array(1);defaultThresholds={Mesh:{},Line:{threshold:-1},LOD:{},Points:{threshold:0},Sprite:{}};sphereResults=new Array;sphereMask=new c.Layers;sphere=new c.Sphere;sphereOverlap(e,t,i=!0,n=!1,o=null){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;const r=this.sphereMask;r.enableAll(),r.disable(2);for(const a of this.context.scene.children)this.intersectSphere(a,e,t,r,this.sphereResults,i,n,o);return this.sphereResults.sort((a,l)=>a.distance-l.distance)}raycastFromRay(e,t=null){const i=t??this.defaultRaycastOptions;i.ray=e;const n=this.raycast(i);return i===this.defaultRaycastOptions&&(i.ray=void 0),n}raycast(e=null){Dt&&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 Dt&&console.error("Can not perform raycast - no main camera found"),this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),this.defaultRaycastOptions.results??[];const l=this.context.xrCamera;this.context.isInXR&&l instanceof c.ArrayCamera&&l.cameras.length>0?i.setFromCamera(t,l.cameras[0]):i.setFromCamera(t,a)}let n=e.targets;n||(n=this.targetBuffer,n.length=1,n[0]=this.context.scene);let o=e.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),o||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),o=this.defaultRaycastOptions.results),e.layerMask!==void 0?e.layerMask instanceof c.Layers?i.layers.mask=e.layerMask.mask:i.layers.mask=e.layerMask:(i.layers.enableAll(),i.layers.disable(2)),Dt&&console.time("raycast"),o.length=0,da._raycasting++,this.intersect(this.raycaster,n,o,e),o.sort((a,l)=>a.distance-l.distance);const r=e.ignore;return r!==void 0&&r.length>0&&(o=o.filter(a=>!r.includes(a.object))),da._raycasting--,Dt&&(console.timeEnd("raycast"),console.warn("#"+this.context.time.frame+", hits:",o?.length?[...o]:"nothing"),performance.mark("raycast.end"),performance.measure("raycast","raycast.start","raycast.end")),o}intersect(e,t,i,n){for(const o of t){if(!o||o.visible===!1||B.isGizmo(o)||n.lineThreshold!==void 0&&n.lineThreshold<0&&o instanceof c.Line)continue;let r=!0;const a=o,l=a.geometry;if(n.testObject){const h=n.testObject?.(o);if(h===!1)continue;h==="continue in children"&&(r=!1)}if(r&&(l&&Dy(l)||(r=!1)),r){const h=ne.getRaycastMesh(o);h&&(a.geometry=h);const d=i.length;let u=!0;if(n.precise===!1&&(u=!1),u||=l.getAttribute("position")?.array?.length<64,a instanceof q.GroundedSkybox&&(u=!1),!u&&HS(a,e,i)||(n.useAcceleratedRaycast!==!1?pd.runMeshBVHRaycast(e,a,i,this.context,n):e.intersectObject(a,!1,i)),Dt&&i.length!=d){const p=i[i.length-1],m=h?8969557:7798784;B.DrawWireSphere(p.point,.1,m,1,!1),B.DrawWireMesh({mesh:o,depthTest:!1,duration:.2,color:m})}a.geometry=l}n.recursive!==!1&&this.intersect(e,o.children,i,n)}return i}tempBoundingBox=new c.Box3;intersectSphere(e,t,i,n,o,r,a,l){let h=e&&e.isMesh&&e.layers.test(n)&&!B.isGizmo(e);h&&=e.visible,h&&=!(e instanceof c.Line),h&&=!(e instanceof q.GroundedSkybox);const d=e,u=d.geometry;if(h&&l){const p=l(e);if(p===!1)return;p==="continue in children"&&(h=!1)}if(u&&Dy(u)||(h=!1),h){if(a){const p=this.sphere;p.center.copy(t),p.radius=i;const m=o.length;if(pd.runMeshBVHRaycast(this.sphere,d,o,this.context,{}),m!=o.length&&!r)return}else if(u.boundingBox||u.computeBoundingBox(),u.boundingBox){d.matrixWorldNeedsUpdate&&d.updateWorldMatrix(!1,!1);const p=this.tempBoundingBox.copy(u.boundingBox).applyMatrix4(d.matrixWorld),m=this.sphere;if(m.center.copy(t),m.radius=i,m.intersectsBox(p)){const y=X(e),b=y.distanceTo(m.center),g=new _m(e,b,y);if(o.push(g),!r)return}}}if(e.children)for(const p of e.children){const m=o.length;if(this.intersectSphere(p,t,i,n,o,r,a,l),m!=o.length&&!r)return}}}function Dy(s){return!(s.index&&s.index.array.length<3)}const _o=new c.Sphere,mh=new c.Plane,GS=new c.Matrix3;function HS(s,e,t){const i=s._computeIntersections;if(!i)return!1;let n=s["_computeIntersections:Needle"];return n||(n=s["_computeIntersections:Needle"]=function(o,r,a){const l=this,h=l.geometry.boundingSphere;if(h){if(l instanceof q.GroundedSkybox){mh.setFromNormalAndCoplanarPoint(V(0,1,0),V(0,-l.position.y,0)),mh.applyMatrix4(l.matrixWorld,GS);const u=o.ray.intersectPlane(mh,V());if(u){_o.copy(h),_o.applyMatrix4(l.matrixWorld);const m=V(u).sub(o.ray.origin).length(),y=_o.radius*.5;m<y&&r.push({distance:m,point:u,object:l,normal:mh.normal.clone()})}return}_o.copy(h),_o.applyMatrix4(l.matrixWorld);const d=o.ray.intersectSphere(_o,V());if(d){const u=V(d).sub(o.ray.origin),p=u.length();if(p>_o.radius){const m=u.clone().normalize();r.push({distance:p,point:d,object:l,normal:m})}}}}),s._computeIntersections=n,e.intersectObject(s,!1,t),s._computeIntersections=i,!0}var pd;(s=>{function e(v,_,x,T,O){if(!_.geometry||!_.geometry.hasAttribute("position"))return!1;const M=_.geometry;if(_?.isSkinnedMesh){const E=_,j=E.bvhNeedsUpdate;if(!E.staticGenerator)a(),o&&(E.staticGenerator=new o(_),E.staticGenerator.applyWorldTransforms=!1,E.staticGeometry=E.staticGenerator.generate(),M.boundsTree=r?.call(E.staticGeometry),E.staticGeometryLastUpdate=performance.now()+Math.random()*200,E.bvhNeedsUpdate=!0);else if(M.boundsTree&&(E.autoUpdateMeshBvhInterval!==void 0&&E.autoUpdateMeshBvhInterval>=0||j===!0)){const L=performance.now(),z=L-E.staticGeometryLastUpdate,$=E.autoUpdateMeshBvhInterval??100;(j||z>$)&&(Dt&&console.warn(`Physics: updating skinned mesh bvh for ${_.name} after ${z.toFixed(2)}ms`),E.bvhNeedsUpdate=!1,E.staticGeometryLastUpdate=L,E.staticGenerator?.generate(E.staticGeometry),M.boundsTree.refit())}}else if(!M.boundsTree){h||g();let E=!0;if((T.xr||M[m]===!1||M.getAttribute("position")?.isInterleavedBufferAttribute||M.index&&M.index?.isInterleavedBufferAttribute)&&(E=!1),E&&u){if(M[p]===void 0){let j=null;if(b.length>0){const L=b.shift();L&&!L.running&&(j=L)}if(!j&&y.length<3&&(j=new u,y.push(j)),j!=null&&!j.running){const L=_.name;Dt&&console.log("<<<< worker start",L,j),M[p]="queued",performance.mark("bvh.create.start");const z=M.clone();try{j.generate(z).then($=>{M[p]="done",M.boundsTree=$}).catch($=>{M[p]="failed - "+$?.message,M[m]=!1,Dt&&console.error("Failed to generate mesh bvh on worker",$)}).finally(()=>{Dt&&console.log(">>>>> worker done",L,{hasBoundsTre:M.boundsTree!=null}),b.push(j),z.dispose(),performance.mark("bvh.create.end"),performance.measure("bvh.create (worker)","bvh.create.start","bvh.create.end")})}catch($){console.error("Failed to generate mesh bvh on worker",$)}}else Dt&&console.warn("No worker available")}}else(!d||!E)&&(a(),n&&(performance.mark("bvh.create.start"),M.boundsTree=new n(M),performance.mark("bvh.create.end"),performance.measure("bvh.create","bvh.create.start","bvh.create.end")))}if(v instanceof c.Raycaster){const E=v,j=_.raycast;if(M.boundsTree)a(),i&&(_.acceleratedRaycast||(_.acceleratedRaycast=i.bind(_),Dt&&console.debug(`Physics: bind acceleratedRaycast fn to "${_.name}"`)),_.raycast=_.acceleratedRaycast);else if(Dt&&console.warn("No bounds tree found for mesh",_.name,{workerTask:M[p],hasAcceleratedRaycast:i!=null}),O.allowSlowRaycastFallback===!1)return Dt&&console.warn("Skipping raycast because no bounds tree is available and allowSlowRaycastFallback is false"),!1;const L=E.firstHitOnly;return E.firstHitOnly=!1,E.intersectObject(_,!1,x),E.firstHitOnly=L,_.raycast=j,!0}else if(v instanceof c.Sphere){const E=M.boundsTree;if(E){const j=v;if(l.copy(_.matrixWorld).invert(),j.applyMatrix4(l),E.intersectsSphere(j)){const z=X(_),$=z.distanceTo(j.center),R=new _m(_,$,z);x.push(R)}}return!0}return!1}s.runMeshBVHRaycast=e;let t=!1,i=null,n=null,o=null,r=null;function a(){t||(t=!0,Promise.resolve().then(()=>require("./vendor-BtJpSuCj.umd.cjs")).then(v=>v.index$1).then(v=>{i=v.acceleratedRaycast,n=v.MeshBVH,o=v.StaticGeometryGenerator,r=v.computeBoundsTree}).catch(v=>{(Dt||A())&&console.error("Failed to load BVH library...",v.message)}))}const l=new c.Matrix4;let h=!1,d=!1,u=null;const p=Symbol("Needle:MeshBVH-Worker"),m=Symbol("Needle:MeshBVH-CanUseWorker"),y=[],b=[];function g(){h=!0,d=!0,Promise.resolve().then(()=>RR).then(v=>{u=v.GenerateMeshBVHWorker}).catch(v=>{(Dt||A())&&console.warn("Failed to setup mesh bvh worker")}).finally(()=>{d=!1})}})(pd||(pd={}));const Iy=Symbol("gltf-loader-internal-usage-tracker"),qS=w("debugusers");class ea{get name(){return"NEEDLE_internal_usage_tracker"}static isLoading(e){return ea._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(){ea._loadingProcesses++;const e=this,t=this._getDependency;return this.parser.getDependency=function(i,n){const o=t.call(this,i,n);return o.then(r=>(r&&(e._loadedObjects.add(r),r[Iy]=e._loadingId),r)),o},null}afterRoot(e){ea._loadingProcesses--,this.parser.getDependency=this._getDependency;for(const t of this._loadedObjects)delete t[Iy],t instanceof c.Object3D&&(t.parent||t instanceof c.Mesh&&setTimeout(()=>{qS&&console.warn("> GLTF LOADER: Mesh not used in scene!",t),t.material=null,t.geometry=null},1e3));return null}}class Kb{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 Hd=w("trackresources");function Zb(){return Hd==="dispose"}let nr=!0;Hd===0&&(nr=!1);function XS(s){nr=s}function Jb(){return nr}const ev=Symbol("disposable");function tv(s,e){s&&(s[ev]=e,Io&&console.warn("Set disposable",e,s))}const iv=Symbol("disposed");function QS(s){return s[iv]===!0}function _e(s){if(s){if(s[ev]===!1){Io&&console.warn("Object is marked as not disposable",s);return}if(typeof s=="object"&&(s[iv]=!0),s instanceof c.Scene)_e(s.environment),_e(s.background),_e(s.customDepthMaterial),_e(s.customDistanceMaterial);else if(s instanceof c.SkinnedMesh)_e(s.geometry),_e(s.material),_e(s.skeleton),_e(s.bindMatrix),_e(s.bindMatrixInverse),_e(s.customDepthMaterial),_e(s.customDistanceMaterial),s.visible=!1;else if(s instanceof c.Mesh)_e(s.geometry),_e(s.material),_e(s.customDepthMaterial),_e(s.customDistanceMaterial),s.visible=!1;else if(s instanceof c.Object3D)s.visible=!1;else if(s instanceof c.BufferGeometry){kr(s);for(const e of Object.keys(s.attributes)){const t=s.attributes[e];_e(t)}}else if(s instanceof c.BufferAttribute||s instanceof c.InterleavedBufferAttribute)Io&&console.warn("BufferAttribute dispose not supported",s.count);else if(s instanceof Array)for(const e of s)e instanceof c.Material&&_e(e);else if(s instanceof c.Material){kr(s);for(const t of Object.keys(s)){const i=s[t];i instanceof c.Texture&&_e(i)}const e=s.uniforms;if(e)for(const t of Object.keys(e)){const i=e[t];i instanceof c.Texture?_e(i):i instanceof c.Uniform$1&&_e(i.value)}}else s instanceof c.Texture?(kr(s),kr(s.source),s.source?.data instanceof ImageBitmap&&kr(s.source.data)):s instanceof c.Skeleton?(kr(s.boneTexture),s.boneTexture=null):s instanceof c.Bone||!(s instanceof c.Object3D)&&Io&&console.warn("Unknown object type",s)}}function kr(s){s&&((Io||Zb()||Hd)&&console.warn("🧨 FREE",s),s instanceof ImageBitmap||"dispose"in s&&typeof s.dispose=="function"&&s.dispose())}function YS(s){}const KS=new Set;function bm(s,e,t=null,i){if(i||(i=KS,i.clear()),!s)return i;const n=s[Hl];if(n)for(const o of n)i.has(o)||t?.call(null,o)!==!1&&(i.add(o),e&&bm(o,!0,t,i));return i}function ZS(s){return s[pl]}const Io=w("debugresourceusers")||w("debugmemory"),Hl=Symbol("needle-resource-users"),pl=Symbol("needle-resource-users-count");function Mt(s,e){$d(s,e,function(t,i){nr&&!da.raycasting&&(md(Hl,this,t,!1),md(Hl,this,i,!0))})}nr&&(Mt(c.Mesh.prototype,"material"),Mt(c.Mesh.prototype,"geometry"),Mt(c.Material.prototype,"map"),Mt(c.Material.prototype,"bumpMap"),Mt(c.Material.prototype,"alphaMap"),Mt(c.Material.prototype,"normalMap"),Mt(c.Material.prototype,"displacementMap"),Mt(c.Material.prototype,"roughnessMap"),Mt(c.Material.prototype,"metalnessMap"),Mt(c.Material.prototype,"emissiveMap"),Mt(c.Material.prototype,"specularMap"),Mt(c.Material.prototype,"envMap"),Mt(c.Material.prototype,"lightMap"),Mt(c.Material.prototype,"aoMap"),Mt(c.Material.prototype,"gradientMap"));function JS(s){if(nr===!1)return;const e=s[Hl];if(e)for(const t of e)md(Hl,t,s,!1)}nr&&$d(c.Material.prototype,"dispose",function(){JS(this)});let hp=0;function md(s,e,t,i){if(hp>0)return;if(Array.isArray(t)){for(const o of t)md(s,e,o,i);return}if(!t)return;let n=t[s];if(n||(n=new Set),i){if(e&&!n.has(e)){n.add(e);let o=t[pl]||0;o+=1,t[pl]=o,Io&&console.warn(`🟢 Added user of "${t.type}"`,e,t,o,"users:",n)}}else if(e&&n.has(e)){n.delete(e);let o=t[pl]||0;o>0&&(o-=1,t[pl]=o),Io&&console.warn(`🔴 Removed user of "${t.type}"`,e,t,o,"users:",n),o<=0&&(ea.isLoading(t)||(Hd&&console.warn(`🔴 Removed all user of "${t.type}"`,t),Zb()&&_e(t)))}t[s]=n}try{$d(c.WebGLRenderer.prototype,"render",function(){hp++},function(){hp--})}catch(s){console.warn("Could not wrap WebGLRenderer.render",s)}const jy=w("debugcomponentevents");class qd{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),jy&&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(jy&&console.log("Dispatching event "+e,i),!!i)for(const n of i)n(t)}}const ql=Symbol("NEEDLE_NEED_UPDATE_INSTANCE"),nv=Symbol("isUsingInstancing"),sv=Symbol("instancingRenderer"),ml=Symbol("instancingAutoUpdateBounds");class Li{static isUsingInstancing(e){return e[nv]===!0}static getRenderer(e){return e[sv]||null}setAutoUpdateBounds(e,t){const i=Li.getRenderer(e);i&&(i[ml]=t)}static markDirty(e,t=!0){if(e&&(this.isUsingInstancing(e)&&(e[ql]=!0,e.matrixWorldNeedsUpdate=!0),t))for(const i of e.children)Li.markDirty(i,!0)}}exports.NEEDLE_ENGINE_FEATURE_FLAGS=void 0;(s=>{s.experimentalSmartHierarchyUpdate=!1})(exports.NEEDLE_ENGINE_FEATURE_FLAGS||(exports.NEEDLE_ENGINE_FEATURE_FLAGS={}));function ta(s,e){try{e||s()}catch(t){return console.error(t),!1}return!0}const dp=w("debugnewscripts"),eC=w("debughierarchy"),ve=[];function tC(){return ve.length>0}function gd(s){if(dp&&console.log("Register new components",s.new_scripts.length,[...s.new_scripts],s.alias?"element: "+s.alias:s.hash,s),s.new_scripts_pre_setup_callbacks.length>0){for(const e of s.new_scripts_pre_setup_callbacks)e&&e();s.new_scripts_pre_setup_callbacks.length=0}if(!(s.new_scripts.length<=0)){ve.length=0,s.new_scripts.length>0&&ve.push(...s.new_scripts),s.new_scripts.length=0;for(let e=0;e<ve.length;e++)try{const t=ve[e];if(t.isComponent!==!0){(A()||dp)&&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),ve.splice(e,1),e--;continue}if(t.destroyed)continue;if(!t.gameObject){console.warn(`Component can not be initialized: no GameObject assigned.
|
|
@@ -187,7 +187,7 @@ Please use the component type instead. This may keep working in local developmen
|
|
|
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))),Wy()&&console.log("[onGetComponent] FIND",e),e==null))return null;for(let i=0;i<s.userData.components.length;i++){const n=s.userData.components[i];let o=Object.getPrototypeOf(n);for(;o;){if(o===e.prototype)if(Wy()&&console.log("[onGetComponent] MATCH BY PROTOYPE",o),t)t.push(n);else return n;o=Object.getPrototypeOf(o)}}return t||null}function sr(s,e){const t=Ov(s,e);return t?Array.isArray(t)?t[0]:t:null}function mc(s,e,t,i=!0){return t||(t=[]),i&&(t.length=0),Ov(s,e,t),t}function gc(s,e,t){if(t===!1&&s[as]===!1)return null;const i=sr(s,e);if(t===!1&&i?.enabled===!1)return null;if(i)return i;for(let n=0;n<s?.children?.length;n++){const o=gc(s.children[n],e);if(o)return o}return null}function va(s,e,t,i=!0){t||(t=[]),i&&(t.length=0),mc(s,e,t,!1);for(let n=0;n<s?.children?.length;n++)va(s.children[n],e,t,!1);return t}function Xl(s,e){if(!s)return null;if(Array.isArray(s)){for(let i=0;i<s.length;i++){const n=RC(s[i]),o=Xl(n,e);if(o)return o}return null}const t=sr(s,e);return t||(s.parent?Xl(s.parent,e):null)}function Xd(s,e,t,i=!0){return t||(t=[]),i&&(t.length=0),s?(mc(s,e,t,!1),s.parent?Xd(s.parent,e,t,!1):t):t}function yc(s,e=void 0,t=!0){if(!s)return null;if(!e&&(e=F.Current,!e))return console.error("Can not search object without any needle context or scene!!!"),null;let i=e;if(i.isScene||(i=e?.scene),!i)return null;const n=gc(i,s,t);return n||null}function Mv(s,e,t=void 0){if(!s)return e??[];if(e||(e=[]),e.length=0,!t&&(t=F.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&&va(i,s,e,!1),e}function Qd(s){s&&s.isObject3D===!0&&xv(s,c.Object3D)}if(exports.NEEDLE_ENGINE_FEATURE_FLAGS.experimentalSmartHierarchyUpdate){const s=c.Object3D.prototype.add;c.Object3D.prototype.add=function(...i){return af(),s.apply(this,i)};const e=c.Object3D.prototype.attach;c.Object3D.prototype.attach=function(...i){return af(),e.apply(this,i)};const t=c.Object3D.prototype.remove;c.Object3D.prototype.remove=function(...i){return af(),t.apply(this,i)}}c.Object3D.prototype.SetActive=function(s){this.visible=s};c.Object3D.prototype.setActive=function(s){this.visible=s};c.Object3D.prototype.destroy=function(){ui(this)};c.Object3D.prototype.addComponent=function(s,e){return Zi(this,s,e)};c.Object3D.prototype.addNewComponent=function(s,e){return Zi(this,s,e)};c.Object3D.prototype.removeComponent=function(s){return Om(this,s)};c.Object3D.prototype.getOrAddComponent=function(s,e){return pc(this,s,e)};c.Object3D.prototype.getComponent=function(s){return sr(this,s)};c.Object3D.prototype.getComponents=function(s,e){return mc(this,s,e)};c.Object3D.prototype.getComponentInChildren=function(s){return gc(this,s)};c.Object3D.prototype.getComponentsInChildren=function(s,e){return va(this,s,e)};c.Object3D.prototype.getComponentInParent=function(s){return Xl(this,s)};c.Object3D.prototype.getComponentsInParent=function(s,e){return Xd(this,s,e)};Object.getOwnPropertyDescriptor(c.Object3D.prototype,"activeSelf")||Object.defineProperty(c.Object3D.prototype,"activeSelf",{get:function(){return wa(this)},set:function(s){Ll(this,s)}});Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldPosition")||Object.defineProperty(c.Object3D.prototype,"worldPosition",{get:function(){return this instanceof q.TransformControlsGizmo?X(this.object):X(this)},set:function(s){ot(this,s)}});Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldQuaternion")||Object.defineProperty(c.Object3D.prototype,"worldQuaternion",{get:function(){return this instanceof q.TransformControlsGizmo?ue(this.object):ue(this)},set:function(s){Ji(this,s)}});Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldRotation")||Object.defineProperty(c.Object3D.prototype,"worldRotation",{get:function(){return Nd(this)},set:function(s){Cb(this,s)}});Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldScale")||Object.defineProperty(c.Object3D.prototype,"worldScale",{get:function(){return Ie(this)},set:function(s){aa(this,s)}});const TC=new c.Matrix4,AC=new c.Vector3(0,0,0),LC=new c.Vector3(0,1,0);Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldForward")||Object.defineProperty(c.Object3D.prototype,"worldForward",{get:function(){return V().set(0,0,1).applyQuaternion(ue(this))},set:function(s){const e=Gt().setFromRotationMatrix(TC.lookAt(AC.set(0,0,0),s,LC.set(0,1,0)));this.worldQuaternion=e}});Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldRight")||Object.defineProperty(c.Object3D.prototype,"worldRight",{get:function(){return V().set(1,0,0).applyQuaternion(ue(this))}});Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldUp")||Object.defineProperty(c.Object3D.prototype,"worldUp",{get:function(){return V().set(0,1,0).applyQuaternion(ue(this))}});Sv(c.Object3D);class Z extends c.Color{alpha=1;get isRGBAColor(){return!0}set a(e){this.alpha=e}get a(){return this.alpha}constructor(e,t,i,n){super(),typeof e=="number"&&typeof t=="number"&&typeof i=="number"?(this.set(e,t,i),this.alpha=typeof n=="number"?n:1):e!==void 0&&(this.set(e),this.alpha=1)}clone(){const e=super.clone();return e.alpha=this.alpha,e}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,"alpha"in e&&typeof e.alpha=="number"?this.alpha=e.alpha:typeof e.a=="number"&&(this.alpha=e.a),this}lerp(e,t){const i=e;return i.alpha!=null&&(this.alpha=D.lerp(this.alpha,i.alpha,t)),super.lerp(e,t)}lerpColors(e,t,i){const n=e,o=t;return n.alpha!=null&&o.alpha!=null&&(this.alpha=D.lerp(n.alpha,o.alpha,i)),super.lerpColors(e,t,i)}multiply(e){const t=e;return t.alpha!=null&&(this.alpha=this.alpha*t.alpha),super.multiply(e)}fromArray(e,t=0){return this.alpha=e[t+3],super.fromArray(e,t)}static fromColorRepresentation(e){if(typeof e=="string"){if(e.trim()==="transparent")return new Z(0,0,0,0);if(e.startsWith("#")&&e.length===9){const t=parseInt(e.slice(1,9),16),i=t>>24&255,n=t>>16&255,o=t>>8&255,r=t>>0&255;return new Z(i/255,n/255,o/255,r/255)}else if(e.startsWith("#")){const t=parseInt(e.slice(1),16),i=t>>16&255,n=t>>8&255,o=t>>0&255;return new Z(i/255,n/255,o/255,1)}else if(e.startsWith("rgba")){const t=e.slice(5,-1).split(",").map(Number);return new Z(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 Z(t[0]/255,t[1]/255,t[2]/255,1)}}else if(Array.isArray(e)){if(e.length===4)return new Z(e[0],e[1],e[2],e[3]);if(e.length===3)return new Z(e[0],e[1],e[2],1);console.error("Invalid color array length. Expected 3 or 4, got "+e.length)}return new Z(e)}}const Xh=w("debuggetcomponent"),Bo=w("debuginstantiate");class on{idProvider;parent;keepWorldPosition;position;rotation;scale;visible;context;components;clone(){const e=new on;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 wa(s){return s.visible}function Ll(s,e){return typeof e=="number"&&(e=e>.5),s.visible=e,s.visible}function kv(s){return s[as]||Yd(s)}function Ev(s,e){s[nv]=e}function Yd(s){return Li.isUsingInstancing(s)}function Mm(s,e){return ra(s,e,!0,!0)}const Rv=Symbol("isDestroyed");function Ho(s){return s[Rv]}function Tv(s,e){s[Rv]=e}const _p=Symbol("isDontDestroy");function Fr(s,e=!0){s[_p]=e}const Qh=[],Yh=[];function ui(s,e=!0,t=!1){Qh.length=0,Yh.length=0,bp(s,e,!0);for(const i of Qh)i.gameObject=null,i.context=null;for(const i of Yh)Tv(i,!0),t&&_e(i);Yh.length=0,Qh.length=0}function bp(s,e=!0,t=!0){if(s==null)return;const i=s;if(i.isComponent){if(i[_p])return;Qh.push(i);const r=i.gameObject;i.__internalDisable(),i.__internalDestroy(),i.gameObject=r;return}if(s[_p])return;const n=s;Xh&&console.log(n),Yh.push(n);const o=n.userData?.components;if(o!=null&&Array.isArray(o)){let r=o.length;for(let a=0;a<o.length;a++){const l=o[a];bp(l,e,!1),o.length<r&&(r=o.length,a--)}}if(e&&n.children)for(const r of n.children)bp(r,e,!1);t&&n.removeFromParent()}function qo(s,e,t=!0){return Av(s,e,t)}function*Kd(s,e,t=!1,i=999,n=0){if(s?.userData.components&&!(n>i)){for(const o of s.userData.components)e&&o?.isComponent===!0&&o instanceof e?yield o:yield o;if(t===!0)for(const o of s.children)yield*Kd(o,e,!0,i,n+1)}}function Av(s,e,t,i=0){if(s){if(s.isObject3D,i>1e3){console.warn("Failed to iterate components: too many levels");return}if(s.userData?.components)for(let n=0;n<s.userData.components.length;n++){const o=s.userData.components[n];if(o?.isComponent===!0){const r=e(o);if(r!==void 0)return r}}if(t&&s.children){const n=i+1;for(let o=0;o<s.children.length;o++){const r=s.children[o];if(!r)continue;const a=Av(r,e,t,n);if(a!==void 0)return a}}}}function Xo(s,e){if("isAssetReference"in s)return s.instantiate(e??void 0);let t=null;e!=null&&(e.x!==void 0?(t=new on,t.position=e):t=e);let i=F.Current;t?.context&&(i=t.context),Xh&&i.alias&&console.log("context",i.alias),t&&!t.idProvider&&(t.idProvider=new mt(Date.now()));const n=[],o={},r={},a=Lv(i,s,t,n,o,r);a&&(jC(a,o),IC(r,o)),Xh&&(dd(s,!0),dd(a,!0));const l={};if(t?.components!==!1){for(const h in n){const d=n[h],u=d.guid;t&&t.idProvider&&(d.guid=t.idProvider.generateUUID(),l[u]=d.guid,Xh&&console.log(d.name,d.guid)),Jd(d,i),d.__internalNewInstanceCreated&&d.__internalNewInstanceCreated()}for(const h in n){const d=n[h];d.resolveGuids&&d.resolveGuids(l),d.enabled!==!1&&(d.enabled=!0)}gd(i)}return a}function Lv(s,e,t,i,n,o){if(!e||e[ri])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},Bo&&console.log("ADD",e,l),e.type==="SkinnedMesh"&&(o[e.uuid]={original:e,clone:l}),t?.visible!==void 0&&(l.visible=t.visible),t?.idProvider){l.uuid=t.idProvider.generateUUID();const d=l;d&&(d.guid=l.uuid)}e.animations&&e.animations.length>0&&(l.animations=[...e.animations]);const h=e.parent;if(h&&h.add(l),t?.position)if(Array.isArray(t.position)){const d=new c.Vector3;d.fromArray(t.position),l.worldPosition=d}else l.worldPosition=t.position;else l.position.copy(e.position);if(t?.rotation){if(t.rotation instanceof c.Quaternion)l.worldQuaternion=t.rotation;else if(t.rotation instanceof c.Euler)l.worldQuaternion=Gt().setFromEuler(t.rotation);else if(Array.isArray(t.rotation)){const d=new c.Euler;d.fromArray(t.rotation),l.worldQuaternion=Gt().setFromEuler(d)}}else l.quaternion.copy(e.quaternion);if(t?.scale)if(Array.isArray(t.scale)){const d=new c.Vector3;d.fromArray(t.scale),t.scale=d}else l.scale.copy(t.scale);else l.scale.copy(e.scale);if(t?.parent&&t.parent!=="scene"){let d=null;if(typeof t.parent=="string"?d=ra(t.parent,s.scene,!0):d=t.parent,d){const u=t.keepWorldPosition===!0?d.attach:d.add;u?u.call(d,l):console.error("Invalid parent object",d,"received when instantiating:",e)}else console.warn("could not find parent:",t.parent)}for(const[d,u]of Object.entries(e.userData))d!=="components"&&(l.userData[d]=u);if(e.userData?.components){const d=e.userData.components,u=[];l.userData.components=u;for(let p=0;p<d.length;p++){const m=d[p],y=new m.constructor;DC(m,y),m[Rl]!==void 0&&(y[Rl]=m[Rl]),u.push(y),y.gameObject=l,i.push(y),n[m.guid]={original:m,clone:y},qd.dispatchComponentLifecycleEvent("component-added",y)}}t&&(t.position=void 0,t.rotation=void 0,t.scale=void 0,t.parent=void 0,t.visible=void 0);for(const d in e.children){const u=e.children[d],p=Lv(s,u,t,i,n,o);p&&(n[p.uuid]={original:u,clone:p},l.add(p))}return l}function DC(s,e,t){ua(e,s,void 0,{})}function IC(s,e){for(const t in s){const i=s[t],n=i.original,o=n.skeleton,r=i.clone;if(!o){console.warn("Skinned mesh has no skeleton?",i);continue}const a=o.bones,l=r.skeleton.clone();r.skeleton=l,r.bindMatrix.clone().copy(n.bindMatrix),r.bindMatrixInverse.copy(n.bindMatrixInverse);const h=[];l.bones=h;for(let d=0;d<a.length;d++){const u=a[d],m=e[u.uuid].clone;h.push(m)}}for(const t in s){const i=s[t].clone;i.skeleton.update(),i.bind(i.skeleton,i.bindMatrix),i.updateMatrixWorld(!0)}}function jC(s,e){for(const t in e){const n=e[t].clone;if(n?.isObject3D&&n?.userData?.components)for(let o=0;o<n.userData.components.length;o++){const r=n.userData.components[o],a=Object.entries(r);for(const[l,h]of a)if(Array.isArray(h)){const d=[];r[l]=d;for(let u=0;u<h.length;u++){const p=h[u];if(typeof p!="object"){d.push(p);continue}const m=Hy(r,l,p,e);m!==void 0?(Bo&&console.log("Found new instance for",l,p,"->",m),d.push(m)):(Bo&&console.warn("Could not find new instance for",l,p),d.push(p))}}else if(typeof h=="object"){const d=Hy(r,l,h,e);d!==void 0?r[l]=d:Bo&&console.warn("Could not find new instance for",l,h)}}}}function Hy(s,e,t,i){if(t!=null)if(t.isComponent===!0){const n=t.gameObject;if(n){const o=n.uuid,r=i[o]?.clone;if(!r){Bo&&console.log("reference did not change",e,s,t);return}const a=n.userData.components.indexOf(t);if(a>=0&&r.isObject3D)return Bo&&console.log(e,o),r.userData.components[a];console.warn("could not find component",e,t)}}else if(t.isObject3D===!0){if(e==="gameObject")return;const n=t;if(n){const o=n.uuid,r=i[o]?.clone;if(r)return Bo&&console.log(e,"old",t,"new",r),r}}else{if(t.isVector4||t.isVector3||t.isVector2||t.isQuaternion||t.isEuler)return t.clone();if(t.isColor===!0)return t.clone();if(t.isEventList===!0)return t.__internalOnInstantiate(i)}}exports.BlobStorage=void 0;(s=>{s.baseUrl="https://networking.needle.tools";function i(d){return se.md5(new Uint8Array(d))}s.hashMD5=i;function n(d){const u=se.md5(new Uint8Array(d),{encoding:"binary",asBytes:!0});return btoa(String.fromCharCode(...u))}s.hashMD5_Base64=n;function o(d){const u=new Uint8Array(d);return crypto.subtle.digest("SHA-256",u).then(m=>btoa(String.fromCharCode(...new Uint8Array(m))))}s.hashSha256=o;function r(d){const u=d.filesize/1024/1024;return Rn()?u<50:u<5}s.canUpload=r;async function a(d,u){const p=s.baseUrl;if(p){if(!d.name)return console.error("Upload: file name is missing"),null}else return console.error("Blob storage base url is not set"),null;let m=null;d instanceof File?m=await d.arrayBuffer():m=d.data;const y=m.byteLength,_=y/1024/1024;if(_>50)return u?.silent!==!0&&he(`File (${_.toFixed(1)}MB) is too large for uploading (see console for details)`),console.warn(`Your file is too large for uploading (${_.toFixed(1)}MB). Max allowed size is 50MB`),null;if(!Rn()&&_>5)return u?.silent!==!0&&he('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 (${_.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(y<1)return console.warn(`Your file is too small for uploading (${_.toFixed(1)}MB). Min size is 1 byte`),null;const g=n(m),v={filename:d.name,"Content-Md5":g,"Content-Type":d.type||"application/octet-stream",FileSize:y.toString(),"Content-Disposition":`attachment; filename="${d.name}"`,"x-amz-server-side-encryption":"AES256"},b=await fetch(p+"/api/needle/blob",{method:"POST",headers:v,signal:u?.abort}).then(x=>x.json()).catch(x=>(console.error(x),null));if(b==null)return console.warn("Upload failed..."),null;if("error"in b)return console.error(b.error),null;if("upload"in b&&b.upload){let x=function(M){return u?.onProgress?.call(null,{progress01:0,state:"inprogress"}),fetch(M,{method:"PUT",headers:v,body:m,signal:u?.abort}).then(j=>(u?.onProgress?.call(null,{progress01:1,state:"finished"}),j)).catch(j=>j)};console.debug("Uploading file",b.upload);let T=!1,O=null;for(let M=0;M<3;M++)try{if(T)break;if(u?.abort?.aborted)return console.debug("Aborted upload"),null;const E=await x(b.upload);E instanceof Error?(O=E,await Ln(1e3*M)):E.ok&&(console.debug("File uploaded successfully"),T=!0)}catch(E){console.error(E)}if(!T)return console.error(O?.message||"Failed to upload file"),null}if("download"in b){const x=p+b.download;return console.debug("File found in blob storage",x),{key:b.key,success:!0,download_url:x}}return null}s.upload=a;function l(d){return`${s.baseUrl}/api/needle/blob/${d}`}s.getBlobUrlForKey=l;async function h(d,u){const p=new c.FileLoader;p.setResponseType("arraybuffer");const m=await p.loadAsync(d,y=>{u&&u.call(null,y)});return m instanceof ArrayBuffer?new Uint8Array(m):(console.error("Download failed, no arraybuffer returned"),null)}s.download=h})(exports.BlobStorage||(exports.BlobStorage={}));const Ps=w("debugaddressables");class Dv{_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 hf=Symbol("assetReference");class Y{static getOrCreateFromUrl(e,t){if(!t&&(t=F.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 o=new Y(e,t.hash);return i.registerAssetReference(o),o}static getOrCreate(e,t,i){if(typeof e=="string"){if(!i&&(i=F.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=Js(e,t);Ps&&console.log("GetOrCreate Addressable from",e,t,"FinalPath=",n);const o=i.addressables,r=o.findAssetReference(n);if(r)return r;const a=new Y(n,i.hash);return o.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 c.Object3D&&(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;pv(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||Ho(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&&ui(this.asset.scene,!0,!0),ui(this.asset,!0,!0)),this.asset=null,this._rawBinary=void 0,this._glbRoot=null,this._loadingPromise=null,F.Current&&F.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 exports.BlobStorage.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=F.Current;if(this._rawBinary){if(!(this._rawBinary instanceof ArrayBuffer))return console.error("[AssetReference] Failed loading – Invalid data. Must be of type ArrayBuffer. "+typeof this._rawBinary),null;this._loadingPromise=en().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=en().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[hf]=this,this._glbRoot&&(this._glbRoot[hf]=this),this.asset&&(this.asset[hf]=this),gd(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=F.Current,o=new on;if(e instanceof c.Object3D?o.parent=e:e&&(Object.assign(o,e),o.cloneAssign(e)),o.parent===void 0&&(o.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=Y.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,Y.currentlyInstantiating.set(this.url,r),t){o.context=n;const a=this.asset;a.guid=this.url;const l=xm(a,o,void 0,i);if(l)return l}else{const a=Xo(this.asset,o);if(a)return a}}finally{n.post_render_callbacks.push(()=>{r===void 0||r<0?r=0:r-=1,Y.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 BC extends Ui{constructor(){super([Y],"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?Y.getOrCreate(t.gltfId,e,t.context):(console.error("Missing source id"),null):(console.error("Missing context"),null);if(e instanceof c.Object3D){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,o=i.guid??i.uuid,r=n.addressables.findAssetReference(o);if(r)return r;const a=new Y(o,void 0,i);return n.addressables.registerAssetReference(a),a}return null}}new BC;const FC=Promise.resolve(null);class Fo{static imageReferences=new Map;static getOrCreate(e){let t=Fo.imageReferences.get(e);return t||(t=new Fo(e),Fo.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 c.TextureLoader),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"),FC)}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 Iv extends Ui{constructor(){super([Fo],"ImageReferenceSerializer")}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"){const i=Js(t.gltfId,e);return Fo.getOrCreate(i)}}}new Iv;class Uo{static cache=new Map;static getOrCreate(e){let t=Uo.cache.get(e);return t||(t=new Uo(e),Uo.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 jv extends Ui{constructor(){super([Uo],"FileReferenceSerializer")}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"){const i=Js(t.gltfId,e);return Uo.getOrCreate(i)}}}new jv;class UC{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 fa{static tryGetActionsFromMixer(e){const t=e._actions;return t||null}static tryGetAnimationClipsFromObjectHierarchy(e,t){if(t||(t=new Array),e)e.animations&&t.push(...e.animations);else return t;if(e.children)for(const i of e.children)this.tryGetAnimationClipsFromObjectHierarchy(i,t);return t}static autoplayAnimations(e){if(!e||!e.animations)return console.debug("No animations found in file"),null;const t="scene"in e?e.scene:e,i=new Array;for(let o=0;o<e.animations.length;o++){const r=e.animations[o];if(!r.tracks||r.tracks.length<=0){console.warn("Animation has no tracks");continue}for(const a in r.tracks){const l=r.tracks[a],h=c.PropertyBinding.parseTrackName(l.name);let d=c.PropertyBinding.findNode(t,h.nodeName);if(!d){const p=l.__objectName??l.name.substring(0,l.name.indexOf("."));if(d=t.getObjectByProperty("uuid",p),!d)continue}let u=n(d)||n(t);if(!u){const p=P.get("Animation");if(u=t.addComponent(p),!u){console.error("Failed creating Animation component: No 'Animation' component found in TypeStore");break}}i.push(u),u.addClip&&u.addClip(r)}}return i;function n(o){if(!o)return null;const r=o.userData?.components;if(r&&r.length>0)for(let a=0;a<r.length;a++){const l=r[a];if(l.isAnimationComponent===!0)return l}return n(o.parent)}}}function*km(s,e=null){const t=e?e.time:F.Current.time,i=t.time;for(;t.time-i<s;)yield}function*zC(s){for(let e=0;e<s;e++)yield}function*Bv(s){let e=!0;for(s.then(()=>e=!1),s.catch(()=>e=!1);e;)yield}const qy="NEEDLE_lightmaps",Xa=w("debuglightmapsextension")||w("debuglightmaps");var _n=(s=>(s[s.Lightmap=0]="Lightmap",s[s.Skybox=1]="Skybox",s[s.Reflection=2]="Reflection",s))(_n||{});class NC{get name(){return qy}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[qy];if(i){const n=i.textures;return n?.length?(Xa&&console.log(i),new Promise(async(o,r)=>{const a=[];for(const h of n)if(h.pointer){Xa&&console.log(h);let d=null;if(h.pointer.startsWith("/textures/")||h.pointer.startsWith("textures/"))Xa&&console.log("Load texture from gltf",h.pointer),d=Cm(this.parser,h.pointer).then(u=>this.resolveTexture(h,u));else if(typeof h.pointer=="string"){Xa&&console.log("Load texture from path",h.pointer);const u=Js(this.source,h.pointer);let p;u.endsWith(".exr")?p=new q.EXRLoader(this.parser.options.manager):u.endsWith(".hdr")?p=new q.RGBELoader(this.parser.options.manager):p=new c.TextureLoader(this.parser.options.manager),d=p.loadAsync(u,void 0).then(m=>this.resolveTexture(h,m))}else h.pointer;d&&a.push(d)}const l=await Kp(a);l?.anyFailed&&A()&&console.error("Failed to load lightmap extension",l),o()})):null}}return null}resolveTexture(e,t){const i=t;Xa&&console.log("Lightmap loaded:",i),i?.isTexture&&(this.registry?(i.colorSpace=c.LinearSRGBColorSpace,this.registry.registerTexture(this.source,e.type,i,e.index)):console.log(_n[e.type],e.pointer,i))}}const Er=!!w("debuglightmaps");class VC{_context;_lightmaps=new Map;clear(){this._lightmaps.clear()}constructor(e){this._context=e}registerTexture(e,t,i,n){Er&&console.log("Registering ",_n[t]+' "'+e+'"',i),this._lightmaps.has(e)||this._lightmaps.set(e,new Map);const o=this._lightmaps.get(e),r=o?.get(t)??[];r.length<n&&(r.length=n+1),tv(i,!1),r[n]=i,o?.set(t,r)}tryGetLightmap(e,t=0){return this.tryGet(e,_n.Lightmap,t)}tryGetSkybox(e){return Er&&console.log("[Get Skybox]",e,this._lightmaps),this.tryGet(e,_n.Skybox,0)}tryGetReflection(e){return Er&&console.log("[Get Reflection]",e,this._lightmaps),this.tryGet(e,_n.Reflection,0)}tryGet(e,t,i){if(!e)return Er&&console.warn("Missing source id"),null;const n=this._lightmaps.get(e);if(!n)return Er&&console.warn(`[Lighting] No ${_n[t]} texture entry for`,e),null;const o=n.get(t);return o===void 0?(Er&&console.warn(`[Lighting] No ${_n[t]} texture for`,e,"index",i),null):!o?.length||o.length<=i?null:o[i]}}c.ShaderChunk.lights_fragment_maps=c.ShaderChunk.lights_fragment_maps.replace("vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );",`
|
|
190
|
+
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis`,e))),Wy()&&console.log("[onGetComponent] FIND",e),e==null))return null;for(let i=0;i<s.userData.components.length;i++){const n=s.userData.components[i];let o=Object.getPrototypeOf(n);for(;o;){if(o===e.prototype)if(Wy()&&console.log("[onGetComponent] MATCH BY PROTOYPE",o),t)t.push(n);else return n;o=Object.getPrototypeOf(o)}}return t||null}function sr(s,e){const t=Ov(s,e);return t?Array.isArray(t)?t[0]:t:null}function mc(s,e,t,i=!0){return t||(t=[]),i&&(t.length=0),Ov(s,e,t),t}function gc(s,e,t){if(t===!1&&s[as]===!1)return null;const i=sr(s,e);if(t===!1&&i?.enabled===!1)return null;if(i)return i;for(let n=0;n<s?.children?.length;n++){const o=gc(s.children[n],e);if(o)return o}return null}function va(s,e,t,i=!0){t||(t=[]),i&&(t.length=0),mc(s,e,t,!1);for(let n=0;n<s?.children?.length;n++)va(s.children[n],e,t,!1);return t}function Xl(s,e){if(!s)return null;if(Array.isArray(s)){for(let i=0;i<s.length;i++){const n=RC(s[i]),o=Xl(n,e);if(o)return o}return null}const t=sr(s,e);return t||(s.parent?Xl(s.parent,e):null)}function Xd(s,e,t,i=!0){return t||(t=[]),i&&(t.length=0),s?(mc(s,e,t,!1),s.parent?Xd(s.parent,e,t,!1):t):t}function yc(s,e=void 0,t=!0){if(!s)return null;if(!e&&(e=F.Current,!e))return console.error("Can not search object without any needle context or scene!!!"),null;let i=e;if(i.isScene||(i=e?.scene),!i)return null;const n=gc(i,s,t);return n||null}function Mv(s,e,t=void 0){if(!s)return e??[];if(e||(e=[]),e.length=0,!t&&(t=F.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&&va(i,s,e,!1),e}function Qd(s){s&&s.isObject3D===!0&&xv(s,c.Object3D)}if(exports.NEEDLE_ENGINE_FEATURE_FLAGS.experimentalSmartHierarchyUpdate){const s=c.Object3D.prototype.add;c.Object3D.prototype.add=function(...i){return af(),s.apply(this,i)};const e=c.Object3D.prototype.attach;c.Object3D.prototype.attach=function(...i){return af(),e.apply(this,i)};const t=c.Object3D.prototype.remove;c.Object3D.prototype.remove=function(...i){return af(),t.apply(this,i)}}c.Object3D.prototype.SetActive=function(s){this.visible=s};c.Object3D.prototype.setActive=function(s){this.visible=s};c.Object3D.prototype.destroy=function(){ui(this)};c.Object3D.prototype.addComponent=function(s,e){return Zi(this,s,e)};c.Object3D.prototype.addNewComponent=function(s,e){return Zi(this,s,e)};c.Object3D.prototype.removeComponent=function(s){return Om(this,s)};c.Object3D.prototype.getOrAddComponent=function(s,e){return pc(this,s,e)};c.Object3D.prototype.getComponent=function(s){return sr(this,s)};c.Object3D.prototype.getComponents=function(s,e){return mc(this,s,e)};c.Object3D.prototype.getComponentInChildren=function(s){return gc(this,s)};c.Object3D.prototype.getComponentsInChildren=function(s,e){return va(this,s,e)};c.Object3D.prototype.getComponentInParent=function(s){return Xl(this,s)};c.Object3D.prototype.getComponentsInParent=function(s,e){return Xd(this,s,e)};Object.getOwnPropertyDescriptor(c.Object3D.prototype,"activeSelf")||Object.defineProperty(c.Object3D.prototype,"activeSelf",{get:function(){return wa(this)},set:function(s){Ll(this,s)}});Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldPosition")||Object.defineProperty(c.Object3D.prototype,"worldPosition",{get:function(){return this instanceof q.TransformControlsGizmo?X(this.object):X(this)},set:function(s){ot(this,s)}});Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldQuaternion")||Object.defineProperty(c.Object3D.prototype,"worldQuaternion",{get:function(){return this instanceof q.TransformControlsGizmo?ue(this.object):ue(this)},set:function(s){Ji(this,s)}});Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldRotation")||Object.defineProperty(c.Object3D.prototype,"worldRotation",{get:function(){return Nd(this)},set:function(s){Cb(this,s)}});Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldScale")||Object.defineProperty(c.Object3D.prototype,"worldScale",{get:function(){return Ie(this)},set:function(s){aa(this,s)}});const TC=new c.Matrix4,AC=new c.Vector3(0,0,0),LC=new c.Vector3(0,1,0);Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldForward")||Object.defineProperty(c.Object3D.prototype,"worldForward",{get:function(){return V().set(0,0,1).applyQuaternion(ue(this))},set:function(s){const e=Gt().setFromRotationMatrix(TC.lookAt(AC.set(0,0,0),s,LC.set(0,1,0)));this.worldQuaternion=e}});Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldRight")||Object.defineProperty(c.Object3D.prototype,"worldRight",{get:function(){return V().set(1,0,0).applyQuaternion(ue(this))}});Object.getOwnPropertyDescriptor(c.Object3D.prototype,"worldUp")||Object.defineProperty(c.Object3D.prototype,"worldUp",{get:function(){return V().set(0,1,0).applyQuaternion(ue(this))}});Sv(c.Object3D);class Z extends c.Color{alpha=1;get isRGBAColor(){return!0}set a(e){this.alpha=e}get a(){return this.alpha}constructor(e,t,i,n){super(),typeof e=="number"&&typeof t=="number"&&typeof i=="number"?(this.set(e,t,i),this.alpha=typeof n=="number"?n:1):e!==void 0&&(this.set(e),this.alpha=1)}clone(){const e=super.clone();return e.alpha=this.alpha,e}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,"alpha"in e&&typeof e.alpha=="number"?this.alpha=e.alpha:typeof e.a=="number"&&(this.alpha=e.a),this}lerp(e,t){const i=e;return i.alpha!=null&&(this.alpha=D.lerp(this.alpha,i.alpha,t)),super.lerp(e,t)}lerpColors(e,t,i){const n=e,o=t;return n.alpha!=null&&o.alpha!=null&&(this.alpha=D.lerp(n.alpha,o.alpha,i)),super.lerpColors(e,t,i)}multiply(e){const t=e;return t.alpha!=null&&(this.alpha=this.alpha*t.alpha),super.multiply(e)}fromArray(e,t=0){return this.alpha=e[t+3],super.fromArray(e,t)}static fromColorRepresentation(e){if(typeof e=="string"){if(e.trim()==="transparent")return new Z(0,0,0,0);if(e.startsWith("#")&&e.length===9){const t=parseInt(e.slice(1,9),16),i=t>>24&255,n=t>>16&255,o=t>>8&255,r=t>>0&255;return new Z(i/255,n/255,o/255,r/255)}else if(e.startsWith("#")){const t=parseInt(e.slice(1),16),i=t>>16&255,n=t>>8&255,o=t>>0&255;return new Z(i/255,n/255,o/255,1)}else if(e.startsWith("rgba")){const t=e.slice(5,-1).split(",").map(Number);return new Z(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 Z(t[0]/255,t[1]/255,t[2]/255,1)}}else if(Array.isArray(e)){if(e.length===4)return new Z(e[0],e[1],e[2],e[3]);if(e.length===3)return new Z(e[0],e[1],e[2],1);console.error("Invalid color array length. Expected 3 or 4, got "+e.length)}return new Z(e)}}const Xh=w("debuggetcomponent"),Bo=w("debuginstantiate");class on{idProvider;parent;keepWorldPosition;position;rotation;scale;visible;context;components;clone(){const e=new on;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 wa(s){return s.visible}function Ll(s,e){return typeof e=="number"&&(e=e>.5),s.visible=e,s.visible}function kv(s){return s[as]||Yd(s)}function Ev(s,e){s[nv]=e}function Yd(s){return Li.isUsingInstancing(s)}function Mm(s,e){return ra(s,e,!0,!0)}const Rv=Symbol("isDestroyed");function Ho(s){return s[Rv]}function Tv(s,e){s[Rv]=e}const _p=Symbol("isDontDestroy");function Fr(s,e=!0){s[_p]=e}const Qh=[],Yh=[];function ui(s,e=!0,t=!1){Qh.length=0,Yh.length=0,bp(s,e,!0);for(const i of Qh)i.gameObject=null,i.context=null;for(const i of Yh)Tv(i,!0),t&&_e(i);Yh.length=0,Qh.length=0}function bp(s,e=!0,t=!0){if(s==null)return;const i=s;if(i.isComponent){if(i[_p])return;Qh.push(i);const r=i.gameObject;i.__internalDisable(),i.__internalDestroy(),i.gameObject=r;return}if(s[_p])return;const n=s;Xh&&console.log(n),Yh.push(n);const o=n.userData?.components;if(o!=null&&Array.isArray(o)){let r=o.length;for(let a=0;a<o.length;a++){const l=o[a];bp(l,e,!1),o.length<r&&(r=o.length,a--)}}if(e&&n.children)for(const r of n.children)bp(r,e,!1);t&&n.removeFromParent()}function qo(s,e,t=!0){return Av(s,e,t)}function*Kd(s,e,t=!1,i=999,n=0){if(s?.userData.components&&!(n>i)){for(const o of s.userData.components)e&&o?.isComponent===!0&&o instanceof e?yield o:yield o;if(t===!0)for(const o of s.children)yield*Kd(o,e,!0,i,n+1)}}function Av(s,e,t,i=0){if(s){if(s.isObject3D,i>1e3){console.warn("Failed to iterate components: too many levels");return}if(s.userData?.components)for(let n=0;n<s.userData.components.length;n++){const o=s.userData.components[n];if(o?.isComponent===!0){const r=e(o);if(r!==void 0)return r}}if(t&&s.children){const n=i+1;for(let o=0;o<s.children.length;o++){const r=s.children[o];if(!r)continue;const a=Av(r,e,t,n);if(a!==void 0)return a}}}}function Xo(s,e){if("isAssetReference"in s)return s.instantiate(e??void 0);let t=null;e!=null&&(e.x!==void 0?(t=new on,t.position=e):t=e);let i=F.Current;t?.context&&(i=t.context),Xh&&i.alias&&console.log("context",i.alias),t&&!t.idProvider&&(t.idProvider=new mt(Date.now()));const n=[],o={},r={},a=Lv(i,s,t,n,o,r);a&&(jC(a,o),IC(r,o)),Xh&&(dd(s,!0),dd(a,!0));const l={};if(t?.components!==!1){for(const h in n){const d=n[h],u=d.guid;t&&t.idProvider&&(d.guid=t.idProvider.generateUUID(),l[u]=d.guid,Xh&&console.log(d.name,d.guid)),Jd(d,i),d.__internalNewInstanceCreated&&d.__internalNewInstanceCreated()}for(const h in n){const d=n[h];d.resolveGuids&&d.resolveGuids(l),d.enabled!==!1&&(d.enabled=!0)}gd(i)}return a}function Lv(s,e,t,i,n,o){if(!e||e[ri])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},Bo&&console.log("ADD",e,l),e.type==="SkinnedMesh"&&(o[e.uuid]={original:e,clone:l}),t?.visible!==void 0&&(l.visible=t.visible),t?.idProvider){l.uuid=t.idProvider.generateUUID();const d=l;d&&(d.guid=l.uuid)}e.animations&&e.animations.length>0&&(l.animations=[...e.animations]);const h=e.parent;if(h&&h.add(l),t?.position)if(Array.isArray(t.position)){const d=new c.Vector3;d.fromArray(t.position),l.worldPosition=d}else l.worldPosition=t.position;else l.position.copy(e.position);if(t?.rotation){if(t.rotation instanceof c.Quaternion)l.worldQuaternion=t.rotation;else if(t.rotation instanceof c.Euler)l.worldQuaternion=Gt().setFromEuler(t.rotation);else if(Array.isArray(t.rotation)){const d=new c.Euler;d.fromArray(t.rotation),l.worldQuaternion=Gt().setFromEuler(d)}}else l.quaternion.copy(e.quaternion);if(t?.scale)if(Array.isArray(t.scale)){const d=new c.Vector3;d.fromArray(t.scale),t.scale=d}else l.scale.copy(t.scale);else l.scale.copy(e.scale);if(t?.parent&&t.parent!=="scene"){let d=null;if(typeof t.parent=="string"?d=ra(t.parent,s.scene,!0):d=t.parent,d){const u=t.keepWorldPosition===!0?d.attach:d.add;u?u.call(d,l):console.error("Invalid parent object",d,"received when instantiating:",e)}else console.warn("could not find parent:",t.parent)}for(const[d,u]of Object.entries(e.userData))d!=="components"&&(l.userData[d]=u);if(e.userData?.components){const d=e.userData.components,u=[];l.userData.components=u;for(let p=0;p<d.length;p++){const m=d[p],y=new m.constructor;DC(m,y),m[Rl]!==void 0&&(y[Rl]=m[Rl]),u.push(y),y.gameObject=l,i.push(y),n[m.guid]={original:m,clone:y},qd.dispatchComponentLifecycleEvent("component-added",y)}}t&&(t.position=void 0,t.rotation=void 0,t.scale=void 0,t.parent=void 0,t.visible=void 0);for(const d in e.children){const u=e.children[d],p=Lv(s,u,t,i,n,o);p&&(n[p.uuid]={original:u,clone:p},l.add(p))}return l}function DC(s,e,t){ua(e,s,void 0,{})}function IC(s,e){for(const t in s){const i=s[t],n=i.original,o=n.skeleton,r=i.clone;if(!o){console.warn("Skinned mesh has no skeleton?",i);continue}const a=o.bones,l=r.skeleton.clone();r.skeleton=l,r.bindMatrix.clone().copy(n.bindMatrix),r.bindMatrixInverse.copy(n.bindMatrixInverse);const h=[];l.bones=h;for(let d=0;d<a.length;d++){const u=a[d],m=e[u.uuid].clone;h.push(m)}}for(const t in s){const i=s[t].clone;i.skeleton.update(),i.bind(i.skeleton,i.bindMatrix),i.updateMatrixWorld(!0)}}function jC(s,e){for(const t in e){const n=e[t].clone;if(n?.isObject3D&&n?.userData?.components)for(let o=0;o<n.userData.components.length;o++){const r=n.userData.components[o],a=Object.entries(r);for(const[l,h]of a)if(Array.isArray(h)){const d=[];r[l]=d;for(let u=0;u<h.length;u++){const p=h[u];if(typeof p!="object"){d.push(p);continue}const m=Hy(r,l,p,e);m!==void 0?(Bo&&console.log("Found new instance for",l,p,"->",m),d.push(m)):(Bo&&console.warn("Could not find new instance for",l,p),d.push(p))}}else if(typeof h=="object"){const d=Hy(r,l,h,e);d!==void 0?r[l]=d:Bo&&console.warn("Could not find new instance for",l,h)}}}}function Hy(s,e,t,i){if(t!=null)if(t.isComponent===!0){const n=t.gameObject;if(n){const o=n.uuid,r=i[o]?.clone;if(!r){Bo&&console.log("reference did not change",e,s,t);return}const a=n.userData.components.indexOf(t);if(a>=0&&r.isObject3D)return Bo&&console.log(e,o),r.userData.components[a];console.warn("could not find component",e,t)}}else if(t.isObject3D===!0){if(e==="gameObject")return;const n=t;if(n){const o=n.uuid,r=i[o]?.clone;if(r)return Bo&&console.log(e,"old",t,"new",r),r}}else{if(t.isVector4||t.isVector3||t.isVector2||t.isQuaternion||t.isEuler)return t.clone();if(t.isColor===!0)return t.clone();if(t.isEventList===!0)return t.__internalOnInstantiate(i)}}exports.BlobStorage=void 0;(s=>{s.baseUrl="https://networking.needle.tools";function i(d){return se.md5(new Uint8Array(d))}s.hashMD5=i;function n(d){const u=se.md5(new Uint8Array(d),{encoding:"binary",asBytes:!0});return btoa(String.fromCharCode(...u))}s.hashMD5_Base64=n;function o(d){const u=new Uint8Array(d);return crypto.subtle.digest("SHA-256",u).then(m=>btoa(String.fromCharCode(...new Uint8Array(m))))}s.hashSha256=o;function r(d){const u=d.filesize/1024/1024;return Rn()?u<50:u<5}s.canUpload=r;async function a(d,u){const p=s.baseUrl;if(p){if(!d.name)return console.error("Upload: file name is missing"),null}else return console.error("Blob storage base url is not set"),null;let m=null;d instanceof File?m=await d.arrayBuffer():m=d.data;const y=m.byteLength,b=y/1024/1024;if(b>50)return u?.silent!==!0&&he(`File (${b.toFixed(1)}MB) is too large for uploading (see console for details)`),console.warn(`Your file is too large for uploading (${b.toFixed(1)}MB). Max allowed size is 50MB`),null;if(!Rn()&&b>5)return u?.silent!==!0&&he('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 (${b.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(y<1)return console.warn(`Your file is too small for uploading (${b.toFixed(1)}MB). Min size is 1 byte`),null;const g=n(m),v={filename:d.name,"Content-Md5":g,"Content-Type":d.type||"application/octet-stream",FileSize:y.toString(),"Content-Disposition":`attachment; filename="${d.name}"`,"x-amz-server-side-encryption":"AES256"},_=await fetch(p+"/api/needle/blob",{method:"POST",headers:v,signal:u?.abort}).then(x=>x.json()).catch(x=>(console.error(x),null));if(_==null)return console.warn("Upload failed..."),null;if("error"in _)return console.error(_.error),null;if("upload"in _&&_.upload){let x=function(M){return u?.onProgress?.call(null,{progress01:0,state:"inprogress"}),fetch(M,{method:"PUT",headers:v,body:m,signal:u?.abort}).then(j=>(u?.onProgress?.call(null,{progress01:1,state:"finished"}),j)).catch(j=>j)};console.debug("Uploading file",_.upload);let T=!1,O=null;for(let M=0;M<3;M++)try{if(T)break;if(u?.abort?.aborted)return console.debug("Aborted upload"),null;const E=await x(_.upload);E instanceof Error?(O=E,await Ln(1e3*M)):E.ok&&(console.debug("File uploaded successfully"),T=!0)}catch(E){console.error(E)}if(!T)return console.error(O?.message||"Failed to upload file"),null}if("download"in _){const x=p+_.download;return console.debug("File found in blob storage",x),{key:_.key,success:!0,download_url:x}}return null}s.upload=a;function l(d){return`${s.baseUrl}/api/needle/blob/${d}`}s.getBlobUrlForKey=l;async function h(d,u){const p=new c.FileLoader;p.setResponseType("arraybuffer");const m=await p.loadAsync(d,y=>{u&&u.call(null,y)});return m instanceof ArrayBuffer?new Uint8Array(m):(console.error("Download failed, no arraybuffer returned"),null)}s.download=h})(exports.BlobStorage||(exports.BlobStorage={}));const Ps=w("debugaddressables");class Dv{_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 hf=Symbol("assetReference");class Y{static getOrCreateFromUrl(e,t){if(!t&&(t=F.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 o=new Y(e,t.hash);return i.registerAssetReference(o),o}static getOrCreate(e,t,i){if(typeof e=="string"){if(!i&&(i=F.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=Js(e,t);Ps&&console.log("GetOrCreate Addressable from",e,t,"FinalPath=",n);const o=i.addressables,r=o.findAssetReference(n);if(r)return r;const a=new Y(n,i.hash);return o.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 c.Object3D&&(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;pv(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||Ho(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&&ui(this.asset.scene,!0,!0),ui(this.asset,!0,!0)),this.asset=null,this._rawBinary=void 0,this._glbRoot=null,this._loadingPromise=null,F.Current&&F.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 exports.BlobStorage.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=F.Current;if(this._rawBinary){if(!(this._rawBinary instanceof ArrayBuffer))return console.error("[AssetReference] Failed loading – Invalid data. Must be of type ArrayBuffer. "+typeof this._rawBinary),null;this._loadingPromise=en().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=en().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[hf]=this,this._glbRoot&&(this._glbRoot[hf]=this),this.asset&&(this.asset[hf]=this),gd(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=F.Current,o=new on;if(e instanceof c.Object3D?o.parent=e:e&&(Object.assign(o,e),o.cloneAssign(e)),o.parent===void 0&&(o.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=Y.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,Y.currentlyInstantiating.set(this.url,r),t){o.context=n;const a=this.asset;a.guid=this.url;const l=xm(a,o,void 0,i);if(l)return l}else{const a=Xo(this.asset,o);if(a)return a}}finally{n.post_render_callbacks.push(()=>{r===void 0||r<0?r=0:r-=1,Y.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 BC extends Ui{constructor(){super([Y],"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?Y.getOrCreate(t.gltfId,e,t.context):(console.error("Missing source id"),null):(console.error("Missing context"),null);if(e instanceof c.Object3D){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,o=i.guid??i.uuid,r=n.addressables.findAssetReference(o);if(r)return r;const a=new Y(o,void 0,i);return n.addressables.registerAssetReference(a),a}return null}}new BC;const FC=Promise.resolve(null);class Fo{static imageReferences=new Map;static getOrCreate(e){let t=Fo.imageReferences.get(e);return t||(t=new Fo(e),Fo.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 c.TextureLoader),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"),FC)}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 Iv extends Ui{constructor(){super([Fo],"ImageReferenceSerializer")}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"){const i=Js(t.gltfId,e);return Fo.getOrCreate(i)}}}new Iv;class Uo{static cache=new Map;static getOrCreate(e){let t=Uo.cache.get(e);return t||(t=new Uo(e),Uo.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 jv extends Ui{constructor(){super([Uo],"FileReferenceSerializer")}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"){const i=Js(t.gltfId,e);return Uo.getOrCreate(i)}}}new jv;class UC{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 fa{static tryGetActionsFromMixer(e){const t=e._actions;return t||null}static tryGetAnimationClipsFromObjectHierarchy(e,t){if(t||(t=new Array),e)e.animations&&t.push(...e.animations);else return t;if(e.children)for(const i of e.children)this.tryGetAnimationClipsFromObjectHierarchy(i,t);return t}static autoplayAnimations(e){if(!e||!e.animations)return console.debug("No animations found in file"),null;const t="scene"in e?e.scene:e,i=new Array;for(let o=0;o<e.animations.length;o++){const r=e.animations[o];if(!r.tracks||r.tracks.length<=0){console.warn("Animation has no tracks");continue}for(const a in r.tracks){const l=r.tracks[a],h=c.PropertyBinding.parseTrackName(l.name);let d=c.PropertyBinding.findNode(t,h.nodeName);if(!d){const p=l.__objectName??l.name.substring(0,l.name.indexOf("."));if(d=t.getObjectByProperty("uuid",p),!d)continue}let u=n(d)||n(t);if(!u){const p=P.get("Animation");if(u=t.addComponent(p),!u){console.error("Failed creating Animation component: No 'Animation' component found in TypeStore");break}}i.push(u),u.addClip&&u.addClip(r)}}return i;function n(o){if(!o)return null;const r=o.userData?.components;if(r&&r.length>0)for(let a=0;a<r.length;a++){const l=r[a];if(l.isAnimationComponent===!0)return l}return n(o.parent)}}}function*km(s,e=null){const t=e?e.time:F.Current.time,i=t.time;for(;t.time-i<s;)yield}function*zC(s){for(let e=0;e<s;e++)yield}function*Bv(s){let e=!0;for(s.then(()=>e=!1),s.catch(()=>e=!1);e;)yield}const qy="NEEDLE_lightmaps",Xa=w("debuglightmapsextension")||w("debuglightmaps");var _n=(s=>(s[s.Lightmap=0]="Lightmap",s[s.Skybox=1]="Skybox",s[s.Reflection=2]="Reflection",s))(_n||{});class NC{get name(){return qy}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[qy];if(i){const n=i.textures;return n?.length?(Xa&&console.log(i),new Promise(async(o,r)=>{const a=[];for(const h of n)if(h.pointer){Xa&&console.log(h);let d=null;if(h.pointer.startsWith("/textures/")||h.pointer.startsWith("textures/"))Xa&&console.log("Load texture from gltf",h.pointer),d=Cm(this.parser,h.pointer).then(u=>this.resolveTexture(h,u));else if(typeof h.pointer=="string"){Xa&&console.log("Load texture from path",h.pointer);const u=Js(this.source,h.pointer);let p;u.endsWith(".exr")?p=new q.EXRLoader(this.parser.options.manager):u.endsWith(".hdr")?p=new q.RGBELoader(this.parser.options.manager):p=new c.TextureLoader(this.parser.options.manager),d=p.loadAsync(u,void 0).then(m=>this.resolveTexture(h,m))}else h.pointer;d&&a.push(d)}const l=await Kp(a);l?.anyFailed&&A()&&console.error("Failed to load lightmap extension",l),o()})):null}}return null}resolveTexture(e,t){const i=t;Xa&&console.log("Lightmap loaded:",i),i?.isTexture&&(this.registry?(i.colorSpace=c.LinearSRGBColorSpace,this.registry.registerTexture(this.source,e.type,i,e.index)):console.log(_n[e.type],e.pointer,i))}}const Er=!!w("debuglightmaps");class VC{_context;_lightmaps=new Map;clear(){this._lightmaps.clear()}constructor(e){this._context=e}registerTexture(e,t,i,n){Er&&console.log("Registering ",_n[t]+' "'+e+'"',i),this._lightmaps.has(e)||this._lightmaps.set(e,new Map);const o=this._lightmaps.get(e),r=o?.get(t)??[];r.length<n&&(r.length=n+1),tv(i,!1),r[n]=i,o?.set(t,r)}tryGetLightmap(e,t=0){return this.tryGet(e,_n.Lightmap,t)}tryGetSkybox(e){return Er&&console.log("[Get Skybox]",e,this._lightmaps),this.tryGet(e,_n.Skybox,0)}tryGetReflection(e){return Er&&console.log("[Get Reflection]",e,this._lightmaps),this.tryGet(e,_n.Reflection,0)}tryGet(e,t,i){if(!e)return Er&&console.warn("Missing source id"),null;const n=this._lightmaps.get(e);if(!n)return Er&&console.warn(`[Lighting] No ${_n[t]} texture entry for`,e),null;const o=n.get(t);return o===void 0?(Er&&console.warn(`[Lighting] No ${_n[t]} texture for`,e,"index",i),null):!o?.length||o.length<=i?null:o[i]}}c.ShaderChunk.lights_fragment_maps=c.ShaderChunk.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`);c.UniformsLib.lightmap.lightmapScaleOffset={value:new c.Vector4(1,1,0,0)};const df=w("debugprogressive"),gh=new c.Box3,yh=new c.Sphere;class $C{static GLTF_PROGRESSIVE_LODSMANAGER_TYPE=ne.LODsManager;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(),ne.LODsManager.removePlugin(this),ne.LODsManager.addPlugin(this),ne.LODsManager.debugDrawLine=B.DrawLine,this._lodsManager=ne.LODsManager.get(e,{engine:"needle-engine"}),this.applySettings(),this._lodsManager.enable()}disable(){this._lodsManager?.disable(),ne.LODsManager.removePlugin(this)}onAfterUpdatedLOD(e,t,i,n,o){df&&this.onRenderDebug(i,n,o)}onRenderDebug(e,t,i){if(!t.geometry||!ne.NEEDLE_progressive.hasLODLevelAvailable(t.geometry)&&!ne.NEEDLE_progressive.hasLODLevelAvailable(t.material))return;const n=ne.LODsManager.getObjectLODState(t);if(!n)return;let o=i.mesh_lod;const r=i.mesh_lod!=n.lastLodLevel_Mesh||i.texture_lod!=n.lastLodLevel_Texture;if(df&&t.geometry.boundingSphere){const a=t.geometry.boundingSphere;yh.copy(a),yh.applyMatrix4(t.matrixWorld);const l=yh.center,h=yh.radius,d=["#76c43e","#bcc43e","#c4ac3e","#c4673e","#ff3e3e"];if(r)B.DrawWireSphere(l,h,d[o],.1);else{const u=t.geometry.index?.count??0,p=ne.NEEDLE_progressive.getMeshLODExtension(t.geometry)?.lods;o=p?Math.min(p?.length-1,o):0;let m="";if(p&&n.lastScreenCoverage>0)for(let g=0;g<p.length;g++){const v=p[g].density,
|
|
214
|
-
TEX `+i.texture_lod;if(df=="density"&&(
|
|
213
|
+
#endif`);c.UniformsLib.lightmap.lightmapScaleOffset={value:new c.Vector4(1,1,0,0)};const df=w("debugprogressive"),gh=new c.Box3,yh=new c.Sphere;class $C{static GLTF_PROGRESSIVE_LODSMANAGER_TYPE=ne.LODsManager;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(),ne.LODsManager.removePlugin(this),ne.LODsManager.addPlugin(this),ne.LODsManager.debugDrawLine=B.DrawLine,this._lodsManager=ne.LODsManager.get(e,{engine:"needle-engine"}),this.applySettings(),this._lodsManager.enable()}disable(){this._lodsManager?.disable(),ne.LODsManager.removePlugin(this)}onAfterUpdatedLOD(e,t,i,n,o){df&&this.onRenderDebug(i,n,o)}onRenderDebug(e,t,i){if(!t.geometry||!ne.NEEDLE_progressive.hasLODLevelAvailable(t.geometry)&&!ne.NEEDLE_progressive.hasLODLevelAvailable(t.material))return;const n=ne.LODsManager.getObjectLODState(t);if(!n)return;let o=i.mesh_lod;const r=i.mesh_lod!=n.lastLodLevel_Mesh||i.texture_lod!=n.lastLodLevel_Texture;if(df&&t.geometry.boundingSphere){const a=t.geometry.boundingSphere;yh.copy(a),yh.applyMatrix4(t.matrixWorld);const l=yh.center,h=yh.radius,d=["#76c43e","#bcc43e","#c4ac3e","#c4673e","#ff3e3e"];if(r)B.DrawWireSphere(l,h,d[o],.1);else{const u=t.geometry.index?.count??0,p=ne.NEEDLE_progressive.getMeshLODExtension(t.geometry)?.lods;o=p?Math.min(p?.length-1,o):0;let m="";if(p&&n.lastScreenCoverage>0)for(let g=0;g<p.length;g++){const v=p[g].density,_=g==p.length-1;m+=v.toFixed(0)+">"+(v/n.lastScreenCoverage).toFixed(0)+(_?"":",")}const y=p?p[o]?.density:-1;let b="LOD "+i.mesh_lod+`
|
|
214
|
+
TEX `+i.texture_lod;if(df=="density"&&(b+=`
|
|
215
215
|
`+u+` tris
|
|
216
216
|
`+(y/n.lastScreenCoverage).toFixed(0)+` dens
|
|
217
217
|
`+(n.lastScreenCoverage*100).toFixed(1)+`% cov
|
|
218
218
|
`+(n.lastCentrality*100).toFixed(1)+`% centr
|
|
219
|
-
`+(gh.min.x.toFixed(2)+"-"+gh.max.x.toFixed(2)+"x"+gh.min.y.toFixed(2)+"-"+gh.max.y.toFixed(2))+" scr"),n.lastScreenCoverage>.1){const g=e,v=g.worldForward,
|
|
219
|
+
`+(gh.min.x.toFixed(2)+"-"+gh.max.x.toFixed(2)+"x"+gh.min.y.toFixed(2)+"-"+gh.max.y.toFixed(2))+" scr"),n.lastScreenCoverage>.1){const g=e,v=g.worldForward,_=g.worldPosition,T=V(v).multiplyScalar(h*.7).add(l),O=T.distanceTo(_),M=d[Math.min(d.length-1,Math.max(0,o))]+"88",E=this.context.domHeight>0?screen.height/this.context.domHeight:1,j=e.isPerspectiveCamera?Math.tan(e.fov*Math.PI/180/2):1;B.DrawLabel(T,b,O*.012*E*j,void 0,16777215,M)}}}}}const WC=w("debugplayerview");var $s=(s=>(s.Browser="browser",s.Headset="headset",s.Handheld="handheld",s))($s||{});class Fv{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 Uv{context;playerViews=new Map;constructor(e){this.context=e}setPlayerView(e,t,i){let n=this.playerViews.get(e);n||(n=new Fv(e,this.context),this.playerViews.set(e,n)),n.viewDevice=i,n.currentObject=t,n.removed=!1}getPlayerView(e){if(!e)return;if(!this.context.connection.userIsInRoom(e)){this.playerViews.delete(e);return}return this.playerViews.get(e)}removePlayerView(e,t){const i=this.playerViews.get(e);i?.viewDevice===t&&(WC&&console.log("REMOVE",e),i.removed=!0,this.playerViews.delete(e))}}new c.FileLoader;const _c=new Uint8Array(4);_c[0]=255;_c[1]=255;_c[2]=255;_c[3]=255;const GC=new c.DataTexture(_c,1,1,c.RGBAFormat);function Em(s,e=1){const t="alpha"in s,i=e*e,n=new Uint8Array(4*i),o=Math.floor(s.r*255),r=Math.floor(s.g*255),a=Math.floor(s.b*255);for(let h=0;h<i;h++){const d=h*4;n[d+0]=o,n[d+1]=r,n[d+2]=a,t?n[d+3]=Math.floor(s.alpha*255):n[d+3]=255}const l=new c.DataTexture(n,e,e);return l.needsUpdate=!0,l}function HC(s,e,t,i=1,n=3){const r=i*n,a=[s,e,t],l=a.length,h=new Uint8Array(4*l*r),d=new c.Color;for(let p=0;p<n;p++){const m=Math.floor(p/n*l),y=D.clamp(m+1,0,l-1),b=a[m],g=a[y],v=p/n*l%1;d.lerpColors(b,g,v);const _=Math.floor(d.r*255),x=Math.floor(d.g*255),T=Math.floor(d.b*255);for(let O=0;O<i;O++){const M=(p*i+O)*4;h[M+0]=_,h[M+1]=x,h[M+2]=T,h[M+3]=255}}const u=new c.DataTexture(h,i,n);return u.needsUpdate=!0,u}function vd(s,e){const t=s.elements;e||(e=[]),e.length=0;for(let i=0;i<16;i+=4){const n=t[i],o=t[i+1],r=t[i+2],a=t[i+3],l=new c.Vector4(n,o,r,a);e.push(l)}return e}const uf=[],Xy=[];function qC(s,e){if(uf.length===0)for(let t=0;t<27;t++)uf.push(0);e||(e=uf);for(let t=0;t<27;t++)Xy[t]=e[t];e=Xy,s.unity_SHAr={value:new c.Vector4(e[9],e[3],e[6],e[0])},s.unity_SHBr={value:new c.Vector4(e[12],e[15],e[18],e[21])},s.unity_SHAg={value:new c.Vector4(e[10],e[4],e[7],e[1])},s.unity_SHBg={value:new c.Vector4(e[13],e[16],e[19],e[22])},s.unity_SHAb={value:new c.Vector4(e[11],e[5],e[8],e[2])},s.unity_SHBb={value:new c.Vector4(e[14],e[17],e[20],e[23])},s.unity_SHC={value:new c.Vector4(e[24],e[25],e[26],1)}}class XC{vertexShader;fragmentShader;technique;constructor(e,t,i){this.vertexShader=e,this.fragmentShader=t,this.technique=i}}async function QC(s,e){if(!s)return console.error("Can not find technique: no shader data"),null;const t=s.programs[e],i=t.vertexShader,n=t.fragmentShader;if(i!==void 0&&n!==void 0){const o=s.shaders[i],r=s.shaders[n];if(o.uri&&r.uri||o.code&&r.code){if(!o.code&&o.uri&&await Qy(o),!r.code&&r.uri&&await Qy(r),!o.code||!r.code)return null;const a=s.techniques[e];return new XC(o.code,r.code,a)}}return console.error("Shader technique not found",e),null}async function Qy(s){const e=s.uri;if(e)if(e.endsWith(".glsl")){const i=await new c.FileLoader().loadAsync(e);s.code=i.toString()}else s.code=YC(s.uri)}function YC(s){return decodeURIComponent(Array.prototype.map.call(atob(s),function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)}).join(""))}const Hi=w("debugenvlight");var ia=(s=>(s[s.Skybox=0]="Skybox",s[s.Trilight=1]="Trilight",s[s.Flat=3]="Flat",s[s.Custom=4]="Custom",s))(ia||{}),wd=(s=>(s[s.Skybox=0]="Skybox",s[s.Custom=1]="Custom",s))(wd||{});class zv{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 c.Vector4;get timeVec4(){return this._timevec4}get environmentIntensity(){if(!this._sceneLightSettings||!this._currentLightSettingsId)return 1;const e=this._sceneLightSettings.get(this._currentLightSettingsId);return e?e.ambientIntensity:1}get sceneLightSettings(){return this._sceneLightSettings?.values()}enable(e){e instanceof Y&&(e=e.url);const t=this._sceneLightSettings?.get(e);return t?(Hi&&console.log("Enable scene light settings",e,t),e!==this._currentLightSettingsId&&this._currentLightSettingsId&&this.disable(this._currentLightSettingsId),this._currentLightSettingsId=e,t.enabled=!0,!0):(Hi&&console.warn("No light settings found for",e),!1)}disable(e){if(e instanceof Y&&(e=e.url),e==null)return!1;const t=this._sceneLightSettings?.get(e);return t?(Hi&&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}Hi&&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}Hi&&console.log("Unregister "+e?.sourceId+" lighting",e),this._sceneLightSettings&&this._sceneLightSettings.delete(t)}internalRegisterReflection(e,t){Hi&&console.log("Register reflection",e,t);const i=new Nv(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(Hi&&console.log("Enable reflection",e,t?ia[t.ambientMode]:"Unknown ambient mode",t),t?.ambientMode){case 0:case 4:const i=this.internalGetReflection(e);if(i&&i.Source){Hi&&console.log("Setting environment reflection",i);const n=this.context.scene,o=i.Source;o.mapping=c.EquirectangularReflectionMapping,n.environment=o;return}else Hi&&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=HC(i[0],i[1],i[2],64,64);n.colorSpace=c.SRGBColorSpace,n.mapping=c.EquirectangularReflectionMapping,this.context.scene.environment=n}else console.error("Missing ambient trilight",t.sourceId);return;case 3:if(t.ambientLight){const i=Em(t.ambientLight,64);i.colorSpace=c.SRGBColorSpace,i.mapping=c.EquirectangularReflectionMapping,this.context.scene.environment=i}else console.error("Missing ambientlight",t.sourceId);return;default:return}}internalDisableReflection(e){if(e&&e!==this.__currentReflectionId){Hi&&console.log("Not disabling reflection for",e,"because it is not the current light settings id",this.__currentReflectionId);return}Hi&&console.log("Disable reflection",e);const t=this.context.scene;t.environment=null}_lighting={}}class Nv{get Source(){return this._source}_source;constructor(e,t,i=1){this._source=t,t.mapping=c.EquirectangularReflectionMapping}}const Yy=w("timescale");let vp=1;typeof Yy=="number"&&(vp=Yy);class Vv{get time(){return this._time}set time(e){this._time=e}_time=0;get deltaTime(){return this._deltaTime}set deltaTime(e){this._deltaTime=e}_deltaTime=0;get deltaTimeUnscaled(){return this._deltaTimeUnscaled}_deltaTimeUnscaled=0;timeScale=1;get frame(){return this._frame}set frame(e){this._frame=e}_frame=0;get frameCount(){return this.frame}get realtimeSinceStartup(){return this.clock.elapsedTime}get fps(){return 1/this.deltaTime}get smoothedFps(){return this._smoothedFps}get smoothedDeltaTime(){return 1/this._smoothedFps}clock=new c.Clock;_smoothedFps=0;_smoothedDeltaTime=0;_fpsSamples=[];_fpsSampleIndex=0;constructor(){typeof vp=="number"&&(this.timeScale=vp)}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 Ky=!1;function $v(s){Ky||(Ky=!0,KC(),ZC())}$v();function KC(){const s=`
|
|
220
220
|
float startCompression = 0.8;
|
|
221
221
|
float desaturation = 0.5;
|
|
222
222
|
// Patched tonemapping function
|
|
@@ -862,7 +862,7 @@ 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
|
-
`,n=`Needle Engine — No license active, commercial use is not allowed. Visit https://needle.tools/pricing for more information and licensing options! v${Ki}`;F.Current?.xr?console.log(n):console.log("%c "+n,t)}async function f1(s){if(window.crossOriginIsolated)return;if(kn==="pro"){const t=s?.domElement?.getAttribute("no-telemetry");if(t===""||t==="true"||t==="1"){ai&&console.debug("Telemetry is disabled");return}ai&&console.debug("Telemetry attribute: "+t)}try{const t="https://needle-engine-analytics-v2-r26roub2hq-lz.a.run.app";if(t){const i=window.location.href.split("?")[0];let n="api/v2/new/request";t.endsWith("/")||(n="/"+n);const o=kn,r=`${t}${n}`;ai&&console.debug("Sending beacon");const a={license:o,url:i,hostname:window.location.hostname,pathname:window.location.pathname,version:Ki,generator:Vd,build_time:am,public_key:Gr},l=navigator.sendBeacon?.(r,JSON.stringify(a));ai&&console.debug("Sent beacon: "+l)}}catch(t){ai&&console.log("Failed to send non-commercial usage message to analytics backend",t)}}function Yv(s,e){return hs(s,re.ContextCreated,e),()=>to(s,re.ContextCreated)}function p1(s,e){return hs(s,re.ContextClearing,e),()=>to(s,re.ContextClearing)}function m1(s,e){return hs(s,re.ContextDestroying,e),()=>to(s,re.ContextDestroying)}function eu(s,e){return hs(s,pe.Start,e),()=>to(s,pe.Start)}function Kv(s,e){return hs(s,pe.Update,e),()=>to(s,pe.Update)}function g1(s,e){return hs(s,pe.OnBeforeRender,e),()=>to(s,pe.OnBeforeRender)}function y1(s,e){return hs(s,pe.OnAfterRender,e),()=>to(s,pe.OnAfterRender)}const _1=w("debugdecoders");let mf=null;function Zv(){if(!mf){const s=ne.createLoaders(null);mf={dracoLoader:s.dracoLoader,ktx2Loader:s.ktx2Loader,meshoptDecoder:s.meshoptDecoder}}return mf}function t_(s){s!==void 0&&typeof s=="string"&&ne.setDracoDecoderLocation(s)}function i_(s){if(s!==void 0&&typeof s=="string"&&s!=="js"){const e=Zv();_1&&console.log("Setting draco decoder type to",s),e.dracoLoader.setDecoderConfig({type:s})}}function n_(s){s!==void 0&&typeof s=="string"&&ne.setKTX2TranscoderLocation(s)}function Tm(s,e){const t=Zv();return e.renderer?t.ktx2Loader.detectSupport(e.renderer):console.warn("No renderer provided to detect ktx2 support - loading KTX2 textures will probably fail"),ne.addDracoAndKTX2Loaders(s),s.dracoLoader||s.setDRACOLoader(t.dracoLoader),s.ktx2Loader||s.setKTX2Loader(t.ktx2Loader),s.meshoptDecoder||s.setMeshoptDecoder(t.meshoptDecoder),ne.configureLoader(s,{progressive:!0}),s}const $e=function(s){return f(s)},f=function(s){if(s===void 0&&(s=null),!Array.isArray(s))s=s_(s);else for(let e=0;e<s.length;e++){const t=s[e];s[e]=s_(t)}return function(e,t){if(!e){const n=typeof t=="string"?t:t.name;console.warn(`@serializable without a target at '${n}'.`);return}typeof t!="string"&&(t=t.name),Object.getOwnPropertyDescriptor(e,"$serializedTypes")||(e.$serializedTypes={});const i=e.$serializedTypes=e.$serializedTypes||{};i[t]=s}};function s_(s){switch(s?.prototype?.constructor?.name){case"Number":case"String":case"Boolean":return null}return s}const Ws=w("debughotreload");let Ql=!1;const Il=new Map;function b1(){return Ql}function Op(){return globalThis.NEEDLE_HOT_RELOAD_ENABLED===!0}function Jv(s){if(Ql){Ws&&console.warn("[Needle Engine] Hot reloading is in progress, not registering instance",s);return}Ws&&console.log("[Needle Engine] Registering hot reload instance",s);const t=s.constructor.name;Il.has(t)?Il.get(t)?.push(s):Il.set(t,[s])}function e0(s){if(Ql){Ws&&console.warn("[Needle Engine] Hot reloading is in progress, not unregistering instance",s);return}Ws&&console.log("[Needle Engine] Unregistering hot reload instance",s);const t=s.constructor.name,i=Il.get(t);if(!i)return;const n=i.indexOf(s);n!==-1&&i.splice(n,1)}let o_=!1;function v1(){if(Ws||o_)return;o_=!0;const s=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}}s.apply(console,e)}}function w1(s){Ws&&console.log("[HMR] Apply changes",s,Object.keys(s)),v1();for(const e of Object.keys(s))try{Ql=!0;const t=P.get(e);if(!t){Ws&&console.log("[HMR] Type not found: "+e);continue}const i=s[e],n=Il.get(i.name);let o="[Needle Engine] Updating type: "+e;const r=n?.length??-1;r>0?o+=" x"+r:o+=" (No instances registered)",console.log(o);const a=Object.getOwnPropertyNames(t.prototype),l=Object.getOwnPropertyDescriptors(i.prototype);for(const h in l)l[h].writable&&(t.prototype[h]=s[e].prototype[h]);for(const h of a)l[h]||delete t.prototype[h];if(n){const h=new i,d=Object.getOwnPropertyDescriptors(h);for(const u of n){const p=u,m=p.isComponent===!0,y=m?p.activeAndEnabled:!0,_=m?p.context:void 0;try{if(m&&_&&Jn(p,_),m&&y&&(p.enabled=!1),u.onBeforeHotReloadFields&&u.onBeforeHotReloadFields()===!1)continue;for(const g in d)if(d[g].writable){if(u[g]===void 0)u[g]=h[g];else if(typeof u[g]=="function"&&!u[g].prototype){const b=u[g],x=b.name,T="bound ";if(x===T)continue;const O=b.name.substring(T.length),M=i.prototype[O];M&&(u[g]=M.bind(u))}}u.onAfterHotReloadFields&&u.onAfterHotReloadFields()}finally{m&&_&&vm(p,_),m&&y&&(p.enabled=!0)}}}}catch(t){if(Ws)console.error(t);else return!1}finally{Ql=!1,Eo(ci.Log,"Script changes applied (HMR)")}return!0}class S extends c.Object3D{guid;static isDestroyed(e){return Ho(e)}static setActive(e,t,i=!0){e&&(Ll(e,t),Gh(e),t&&i&&ov(F.Current,e))}static isActiveSelf(e){return wa(e)}static isActiveInHierarchy(e){return kv(e)}static markAsInstancedRendered(e,t){Ev(e,t)}static isUsingInstancing(e){return Yd(e)}static foreachComponent(e,t,i=!0){return qo(e,t,i)}static instantiateSynced(e,t){return e?xm(e,t):null}static instantiate(e,t=null){return"isAssetReference"in e,Xo(e,t)}static destroySynced(e,t,i=!0){if(!e)return;const n=e;t=t??F.Current,uc(n,t.connection,i)}static destroy(e,t=!0){return ui(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=F.Current),t.add(e),Ll(e,!0),Gh(e),i?S.foreachComponent(e,n=>{vm(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),Ll(e,!1),Gh(e),S.foreachComponent(e,t=>{iC(t)},!0))}static invokeOnChildren(e,t,...i){this.invoke(e,t,!0,i)}static invoke(e,t,i=!1,...n){e&&this.foreachComponent(e,o=>{const r=o[t];r&&typeof r=="function"&&r?.call(o,...n)},i)}static addNewComponent(e,t,i,n=!0){return Zi(e,t,i,{callAwake:n})}static addComponent(e,t,i,n){return Zi(e,t,i,n)}static moveComponent(e,t){return Zi(e,t)}static removeComponent(e){return Om(e.gameObject,e),e}static getOrAddComponent(e,t){return pc(e,t)}static getComponent(e,t){return e===null?null:sr(e,t)}static getComponents(e,t,i=null){return e===null?i??[]:mc(e,t,i)}static findByGuid(e,t){return Mm(e,t)}static findObjectOfType(e,t,i=!0){return yc(e,t??F.Current,i)}static findObjectsOfType(e,t){const i=[];return Mv(e,i,t),i}static getComponentInChildren(e,t){return gc(e,t)}static getComponentsInChildren(e,t,i=null){return va(e,t,i??void 0)}static getComponentInParent(e,t){return Xl(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 k{get isComponent(){return!0}__context;get context(){return this.__context??F.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[as];return e===void 0?!0:e}set __isActiveInHierarchy(e){this.gameObject&&(this.gameObject[as]=e)}gameObject;guid="invalid";sourceId;awake(){}onEnable(){}onDisable(){}onDestroy(){this.__destroyed=!0}startCoroutine(e,t=pe.Update){return this.context.registerCoroutineUpdate(this,e,t)}stopCoroutine(e,t=pe.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),Op()&&Jv(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?(A()&&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}))),Pv(this),Op()&&e0(this))}get enabled(){return typeof this.__isEnabled=="boolean"?this.__isEnabled:!0}set enabled(e){if(this.__destroyed){A()&&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 X(this.gameObject)}set worldPosition(e){ot(this.gameObject,e)}setWorldPosition(e,t,i){Wo(this.gameObject,e,t,i)}get worldQuaternion(){return ue(this.gameObject)}set worldQuaternion(e){Ji(this.gameObject,e)}setWorldQuaternion(e,t,i,n){tm(this.gameObject,e,t,i,n)}get worldEuler(){return im(this.gameObject)}set worldEuler(e){nm(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){hc(this.gameObject,e,t,i,n)}static _forward=new c.Vector3;get forward(){return k._forward.set(0,0,-1).applyQuaternion(this.worldQuaternion)}static _right=new c.Vector3;get right(){return k._right.set(1,0,0).applyQuaternion(this.worldQuaternion)}static _up=new c.Vector3;get up(){return k._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 x1=Object.freeze(Object.defineProperty({__proto__:null,Behaviour:k,Component:k,GameObject:S},Symbol.toStringTag,{value:"Module"}));var S1=Object.defineProperty,t0=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&S1(e,t,n),n};class vc extends k{from;to;width=0;centered=!0;_centerPos;awake(){this._centerPos=new c.Vector3}update(){if(!this.from||!this.to)return;const e=X(this.from).clone(),t=X(this.to).clone(),i=e.distanceTo(t);this._centerPos.copy(e),this._centerPos.add(t),this._centerPos.multiplyScalar(.5),ot(this.gameObject,this.centered?this._centerPos:e),this.gameObject.lookAt(X(this.to).clone()),this.gameObject.scale.set(this.width,this.width,i)}}t0([f(S)],vc.prototype,"from");t0([f(S)],vc.prototype,"to");var C1=Object.defineProperty,P1=Object.getOwnPropertyDescriptor,or=(s,e,t,i)=>{for(var n=i>1?void 0:i?P1(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&C1(e,t,n),n};const Os=w("debuganimation");let i0=class{x;y};class Ft extends k{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){Os&&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,Os&&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){Os&&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){Os&&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(Os&&console.log("PLAY",e),this.ensureMixer(),!this.mixer){Os&&console.warn("Missing mixer",this);return}e===void 0&&(e=0);let i=e;if(typeof e=="number"){if(e>=this.animations.length){Os&&console.log("No animation at index",e);return}i=this.animations[e]}else typeof e=="string"&&(i=this.animations.find(o=>o.name===e));if(!i){console.error("Could not find clip",e);return}t||(t={});for(const o of this.actions)if(o.getClip()===i)return this.internalOnPlay(o,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(r=>r===e);if(i===e&&i.isRunning()&&i.time<i.getClip().duration){const r=this.tryFindHandle(e);if(i.paused&&(i.paused=!1),r)return r.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 r of this.actions)r!=i&&(t.fadeDuration?r.fadeOut(t.fadeDuration):r.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 r=e.getClip();e.time=D.lerp(t.minMaxOffsetNormalized.x,t.minMaxOffsetNormalized.y,Math.random())*r.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?c.LoopRepeat:c.LoopOnce:e.loop=c.LoopOnce,t?.clampWhenFinished&&(e.clampWhenFinished=!0),e.paused=!1,e.play(),Os&&console.log("PLAY",e.getClip().name,e);const o=new O1(e,this.mixer,t,r=>{this._handles.splice(this._handles.indexOf(o),1)});return this._handles.push(o),o.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 c.AnimationMixer(this.gameObject),this.gameObject[e]=this.mixer)}this.context.animations.registerAnimationMixer(this.mixer)}}or([f()],Ft.prototype,"playAutomatically",2);or([f()],Ft.prototype,"randomStartTime",2);or([f(i0)],Ft.prototype,"minMaxSpeed",2);or([f(i0)],Ft.prototype,"minMaxOffsetNormalized",2);or([f()],Ft.prototype,"loop",2);or([f()],Ft.prototype,"clampWhenFinished",2);or([f(c.AnimationClip)],Ft.prototype,"clips",1);class O1{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 Kh=Symbol("objectIsAnimatedData");function r_(s,e,t){if(!s)return;if(s[Kh]===void 0){if(!t)return;s[Kh]=new Set}const i=s[Kh];t?i.add(e):i.has(e)&&i.delete(e)}function M1(s){if(!s)return!1;const e=s[Kh];return e!==void 0&&e.size>0}class k1{_context;get context(){return this._context??F.Current}get isStateMachineBehaviour(){return!0}}class gl{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 n0(s,e){return{name:"Empty",isLooping:!1,guid:e?.generateUUID()??c.MathUtils.generateUUID(),index:-1,clip:new c.AnimationClip(s,0,[])}}var Bs=(s=>(s[s.If=1]="If",s[s.IfNot=2]="IfNot",s[s.Greater=3]="Greater",s[s.Less=4]="Less",s[s.Equals=6]="Equals",s[s.NotEqual=7]="NotEqual",s))(Bs||{}),Am=(s=>(s[s.Float=1]="Float",s[s.Int=3]="Int",s[s.Bool=4]="Bool",s[s.Trigger=9]="Trigger",s))(Am||{});const qe=w("debuganimatorcontroller"),vh=w("debugrootmotion");class Di{static createFromClips(e,t={looping:!1,autoTransition:!0,transitionDuration:0}){const i=[];for(let r=0;r<e.length;r++){const a=e[r],l=[];if(t.autoTransition!==!1){const d=t.transitionDuration??0,u=d/a.duration;let p=r;(t.autoTransition===void 0||t.autoTransition===!0)&&(p=(r+1)%e.length),l.push({exitTime:1-u,offset:0,duration:d,hasExitTime:!0,destinationState:p,conditions:[]})}const h={name:a.name,hash:r,motion:{name:a.name,clip:a,isLooping:t?.looping??!1},transitions:l,behaviours:[]};i.push(h)}const n={name:"AnimatorController",guid:new mt(Date.now()).generateUUID(),parameters:[],layers:[{name:"Base Layer",stateMachine:{defaultState:0,states:i}}]};return new Di(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 r=this.model.layers[t].stateMachine;for(const a of r.states)if(a.name===e||a.hash===e){qe&&console.log("transition to ",a),this.transitionTo(a,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(o=>o[i]===e);return n.forEach(o=>o.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){qe&&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 gl(this._activeState,i,t,this._speed)}get currentAction(){if(!this._activeState)return null;const e=this._activeState.motion.action;return e||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 c.AnimationMixer(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;qe&&console.warn("AnimatorController clone()",this.model);const e=ac(this.model,(i,n,o)=>o==null?!0:!(o.type==="Object3D"||o.isObject3D===!0||Pb(o)||o.tracks!==void 0||o instanceof Di));return console.assert(e!==this.model),new Di(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,qe&&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 o=n.action;o.weight=e,o.getEffectiveWeight()<=0&&!o.isRunning()&&(qe&&console.debug("REMOVE",i.name,o.getEffectiveWeight(),o.isRunning(),o.isScheduled()),this._activeStates.splice(t,1),t--)}}}setStartTransition(){this.model.layers.length>1&&(qe||A())&&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&&(qe&&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 o of t.transitions){if(!o.hasExitTime&&o.conditions.length<=0)continue;let r=!0;for(const a of o.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 h=o.exitTime;i.timeScale<0&&(h=1-h);let d=!1;if(o.hasExitTime?i.timeScale>0?d=l>=o.exitTime:i.timeScale<0&&(d=1-l>=o.exitTime):d=!0,d){for(const u of o.conditions){const p=this.model.parameters.find(m=>m.name===u.parameter);p?.type===Am.Trigger&&p.value&&(p.value=!1)}if(i.clampWhenFinished=!0,qe){const u=this.getState(o.destinationState,0);console.log(`Transition to ${o.destinationState} / ${u?.name}`,o,`
|
|
865
|
+
`,n=`Needle Engine — No license active, commercial use is not allowed. Visit https://needle.tools/pricing for more information and licensing options! v${Ki}`;F.Current?.xr?console.log(n):console.log("%c "+n,t)}async function f1(s){if(window.crossOriginIsolated)return;if(kn==="pro"){const t=s?.domElement?.getAttribute("no-telemetry");if(t===""||t==="true"||t==="1"){ai&&console.debug("Telemetry is disabled");return}ai&&console.debug("Telemetry attribute: "+t)}try{const t="https://needle-engine-analytics-v2-r26roub2hq-lz.a.run.app";if(t){const i=window.location.href.split("?")[0];let n="api/v2/new/request";t.endsWith("/")||(n="/"+n);const o=kn,r=`${t}${n}`;ai&&console.debug("Sending beacon");const a={license:o,url:i,hostname:window.location.hostname,pathname:window.location.pathname,version:Ki,generator:Vd,build_time:am,public_key:Gr},l=navigator.sendBeacon?.(r,JSON.stringify(a));ai&&console.debug("Sent beacon: "+l)}}catch(t){ai&&console.log("Failed to send non-commercial usage message to analytics backend",t)}}function Yv(s,e){return hs(s,re.ContextCreated,e),()=>to(s,re.ContextCreated)}function p1(s,e){return hs(s,re.ContextClearing,e),()=>to(s,re.ContextClearing)}function m1(s,e){return hs(s,re.ContextDestroying,e),()=>to(s,re.ContextDestroying)}function eu(s,e){return hs(s,pe.Start,e),()=>to(s,pe.Start)}function Kv(s,e){return hs(s,pe.Update,e),()=>to(s,pe.Update)}function g1(s,e){return hs(s,pe.OnBeforeRender,e),()=>to(s,pe.OnBeforeRender)}function y1(s,e){return hs(s,pe.OnAfterRender,e),()=>to(s,pe.OnAfterRender)}const _1=w("debugdecoders");let mf=null;function Zv(){if(!mf){const s=ne.createLoaders(null);mf={dracoLoader:s.dracoLoader,ktx2Loader:s.ktx2Loader,meshoptDecoder:s.meshoptDecoder}}return mf}function t_(s){s!==void 0&&typeof s=="string"&&ne.setDracoDecoderLocation(s)}function i_(s){if(s!==void 0&&typeof s=="string"&&s!=="js"){const e=Zv();_1&&console.log("Setting draco decoder type to",s),e.dracoLoader.setDecoderConfig({type:s})}}function n_(s){s!==void 0&&typeof s=="string"&&ne.setKTX2TranscoderLocation(s)}function Tm(s,e){const t=Zv();return e.renderer?t.ktx2Loader.detectSupport(e.renderer):console.warn("No renderer provided to detect ktx2 support - loading KTX2 textures will probably fail"),ne.addDracoAndKTX2Loaders(s),s.dracoLoader||s.setDRACOLoader(t.dracoLoader),s.ktx2Loader||s.setKTX2Loader(t.ktx2Loader),s.meshoptDecoder||s.setMeshoptDecoder(t.meshoptDecoder),ne.configureLoader(s,{progressive:!0}),s}const $e=function(s){return f(s)},f=function(s){if(s===void 0&&(s=null),!Array.isArray(s))s=s_(s);else for(let e=0;e<s.length;e++){const t=s[e];s[e]=s_(t)}return function(e,t){if(!e){const n=typeof t=="string"?t:t.name;console.warn(`@serializable without a target at '${n}'.`);return}typeof t!="string"&&(t=t.name),Object.getOwnPropertyDescriptor(e,"$serializedTypes")||(e.$serializedTypes={});const i=e.$serializedTypes=e.$serializedTypes||{};i[t]=s}};function s_(s){switch(s?.prototype?.constructor?.name){case"Number":case"String":case"Boolean":return null}return s}const Ws=w("debughotreload");let Ql=!1;const Il=new Map;function b1(){return Ql}function Op(){return globalThis.NEEDLE_HOT_RELOAD_ENABLED===!0}function Jv(s){if(Ql){Ws&&console.warn("[Needle Engine] Hot reloading is in progress, not registering instance",s);return}Ws&&console.log("[Needle Engine] Registering hot reload instance",s);const t=s.constructor.name;Il.has(t)?Il.get(t)?.push(s):Il.set(t,[s])}function e0(s){if(Ql){Ws&&console.warn("[Needle Engine] Hot reloading is in progress, not unregistering instance",s);return}Ws&&console.log("[Needle Engine] Unregistering hot reload instance",s);const t=s.constructor.name,i=Il.get(t);if(!i)return;const n=i.indexOf(s);n!==-1&&i.splice(n,1)}let o_=!1;function v1(){if(Ws||o_)return;o_=!0;const s=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}}s.apply(console,e)}}function w1(s){Ws&&console.log("[HMR] Apply changes",s,Object.keys(s)),v1();for(const e of Object.keys(s))try{Ql=!0;const t=P.get(e);if(!t){Ws&&console.log("[HMR] Type not found: "+e);continue}const i=s[e],n=Il.get(i.name);let o="[Needle Engine] Updating type: "+e;const r=n?.length??-1;r>0?o+=" x"+r:o+=" (No instances registered)",console.log(o);const a=Object.getOwnPropertyNames(t.prototype),l=Object.getOwnPropertyDescriptors(i.prototype);for(const h in l)l[h].writable&&(t.prototype[h]=s[e].prototype[h]);for(const h of a)l[h]||delete t.prototype[h];if(n){const h=new i,d=Object.getOwnPropertyDescriptors(h);for(const u of n){const p=u,m=p.isComponent===!0,y=m?p.activeAndEnabled:!0,b=m?p.context:void 0;try{if(m&&b&&Jn(p,b),m&&y&&(p.enabled=!1),u.onBeforeHotReloadFields&&u.onBeforeHotReloadFields()===!1)continue;for(const g in d)if(d[g].writable){if(u[g]===void 0)u[g]=h[g];else if(typeof u[g]=="function"&&!u[g].prototype){const _=u[g],x=_.name,T="bound ";if(x===T)continue;const O=_.name.substring(T.length),M=i.prototype[O];M&&(u[g]=M.bind(u))}}u.onAfterHotReloadFields&&u.onAfterHotReloadFields()}finally{m&&b&&vm(p,b),m&&y&&(p.enabled=!0)}}}}catch(t){if(Ws)console.error(t);else return!1}finally{Ql=!1,Eo(ci.Log,"Script changes applied (HMR)")}return!0}class S extends c.Object3D{guid;static isDestroyed(e){return Ho(e)}static setActive(e,t,i=!0){e&&(Ll(e,t),Gh(e),t&&i&&ov(F.Current,e))}static isActiveSelf(e){return wa(e)}static isActiveInHierarchy(e){return kv(e)}static markAsInstancedRendered(e,t){Ev(e,t)}static isUsingInstancing(e){return Yd(e)}static foreachComponent(e,t,i=!0){return qo(e,t,i)}static instantiateSynced(e,t){return e?xm(e,t):null}static instantiate(e,t=null){return"isAssetReference"in e,Xo(e,t)}static destroySynced(e,t,i=!0){if(!e)return;const n=e;t=t??F.Current,uc(n,t.connection,i)}static destroy(e,t=!0){return ui(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=F.Current),t.add(e),Ll(e,!0),Gh(e),i?S.foreachComponent(e,n=>{vm(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),Ll(e,!1),Gh(e),S.foreachComponent(e,t=>{iC(t)},!0))}static invokeOnChildren(e,t,...i){this.invoke(e,t,!0,i)}static invoke(e,t,i=!1,...n){e&&this.foreachComponent(e,o=>{const r=o[t];r&&typeof r=="function"&&r?.call(o,...n)},i)}static addNewComponent(e,t,i,n=!0){return Zi(e,t,i,{callAwake:n})}static addComponent(e,t,i,n){return Zi(e,t,i,n)}static moveComponent(e,t){return Zi(e,t)}static removeComponent(e){return Om(e.gameObject,e),e}static getOrAddComponent(e,t){return pc(e,t)}static getComponent(e,t){return e===null?null:sr(e,t)}static getComponents(e,t,i=null){return e===null?i??[]:mc(e,t,i)}static findByGuid(e,t){return Mm(e,t)}static findObjectOfType(e,t,i=!0){return yc(e,t??F.Current,i)}static findObjectsOfType(e,t){const i=[];return Mv(e,i,t),i}static getComponentInChildren(e,t){return gc(e,t)}static getComponentsInChildren(e,t,i=null){return va(e,t,i??void 0)}static getComponentInParent(e,t){return Xl(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 k{get isComponent(){return!0}__context;get context(){return this.__context??F.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[as];return e===void 0?!0:e}set __isActiveInHierarchy(e){this.gameObject&&(this.gameObject[as]=e)}gameObject;guid="invalid";sourceId;awake(){}onEnable(){}onDisable(){}onDestroy(){this.__destroyed=!0}startCoroutine(e,t=pe.Update){return this.context.registerCoroutineUpdate(this,e,t)}stopCoroutine(e,t=pe.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),Op()&&Jv(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?(A()&&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}))),Pv(this),Op()&&e0(this))}get enabled(){return typeof this.__isEnabled=="boolean"?this.__isEnabled:!0}set enabled(e){if(this.__destroyed){A()&&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 X(this.gameObject)}set worldPosition(e){ot(this.gameObject,e)}setWorldPosition(e,t,i){Wo(this.gameObject,e,t,i)}get worldQuaternion(){return ue(this.gameObject)}set worldQuaternion(e){Ji(this.gameObject,e)}setWorldQuaternion(e,t,i,n){tm(this.gameObject,e,t,i,n)}get worldEuler(){return im(this.gameObject)}set worldEuler(e){nm(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){hc(this.gameObject,e,t,i,n)}static _forward=new c.Vector3;get forward(){return k._forward.set(0,0,-1).applyQuaternion(this.worldQuaternion)}static _right=new c.Vector3;get right(){return k._right.set(1,0,0).applyQuaternion(this.worldQuaternion)}static _up=new c.Vector3;get up(){return k._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 x1=Object.freeze(Object.defineProperty({__proto__:null,Behaviour:k,Component:k,GameObject:S},Symbol.toStringTag,{value:"Module"}));var S1=Object.defineProperty,t0=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&S1(e,t,n),n};class vc extends k{from;to;width=0;centered=!0;_centerPos;awake(){this._centerPos=new c.Vector3}update(){if(!this.from||!this.to)return;const e=X(this.from).clone(),t=X(this.to).clone(),i=e.distanceTo(t);this._centerPos.copy(e),this._centerPos.add(t),this._centerPos.multiplyScalar(.5),ot(this.gameObject,this.centered?this._centerPos:e),this.gameObject.lookAt(X(this.to).clone()),this.gameObject.scale.set(this.width,this.width,i)}}t0([f(S)],vc.prototype,"from");t0([f(S)],vc.prototype,"to");var C1=Object.defineProperty,P1=Object.getOwnPropertyDescriptor,or=(s,e,t,i)=>{for(var n=i>1?void 0:i?P1(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&C1(e,t,n),n};const Os=w("debuganimation");let i0=class{x;y};class Ft extends k{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){Os&&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,Os&&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){Os&&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){Os&&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(Os&&console.log("PLAY",e),this.ensureMixer(),!this.mixer){Os&&console.warn("Missing mixer",this);return}e===void 0&&(e=0);let i=e;if(typeof e=="number"){if(e>=this.animations.length){Os&&console.log("No animation at index",e);return}i=this.animations[e]}else typeof e=="string"&&(i=this.animations.find(o=>o.name===e));if(!i){console.error("Could not find clip",e);return}t||(t={});for(const o of this.actions)if(o.getClip()===i)return this.internalOnPlay(o,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(r=>r===e);if(i===e&&i.isRunning()&&i.time<i.getClip().duration){const r=this.tryFindHandle(e);if(i.paused&&(i.paused=!1),r)return r.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 r of this.actions)r!=i&&(t.fadeDuration?r.fadeOut(t.fadeDuration):r.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 r=e.getClip();e.time=D.lerp(t.minMaxOffsetNormalized.x,t.minMaxOffsetNormalized.y,Math.random())*r.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?c.LoopRepeat:c.LoopOnce:e.loop=c.LoopOnce,t?.clampWhenFinished&&(e.clampWhenFinished=!0),e.paused=!1,e.play(),Os&&console.log("PLAY",e.getClip().name,e);const o=new O1(e,this.mixer,t,r=>{this._handles.splice(this._handles.indexOf(o),1)});return this._handles.push(o),o.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 c.AnimationMixer(this.gameObject),this.gameObject[e]=this.mixer)}this.context.animations.registerAnimationMixer(this.mixer)}}or([f()],Ft.prototype,"playAutomatically",2);or([f()],Ft.prototype,"randomStartTime",2);or([f(i0)],Ft.prototype,"minMaxSpeed",2);or([f(i0)],Ft.prototype,"minMaxOffsetNormalized",2);or([f()],Ft.prototype,"loop",2);or([f()],Ft.prototype,"clampWhenFinished",2);or([f(c.AnimationClip)],Ft.prototype,"clips",1);class O1{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 Kh=Symbol("objectIsAnimatedData");function r_(s,e,t){if(!s)return;if(s[Kh]===void 0){if(!t)return;s[Kh]=new Set}const i=s[Kh];t?i.add(e):i.has(e)&&i.delete(e)}function M1(s){if(!s)return!1;const e=s[Kh];return e!==void 0&&e.size>0}class k1{_context;get context(){return this._context??F.Current}get isStateMachineBehaviour(){return!0}}class gl{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 n0(s,e){return{name:"Empty",isLooping:!1,guid:e?.generateUUID()??c.MathUtils.generateUUID(),index:-1,clip:new c.AnimationClip(s,0,[])}}var Bs=(s=>(s[s.If=1]="If",s[s.IfNot=2]="IfNot",s[s.Greater=3]="Greater",s[s.Less=4]="Less",s[s.Equals=6]="Equals",s[s.NotEqual=7]="NotEqual",s))(Bs||{}),Am=(s=>(s[s.Float=1]="Float",s[s.Int=3]="Int",s[s.Bool=4]="Bool",s[s.Trigger=9]="Trigger",s))(Am||{});const qe=w("debuganimatorcontroller"),vh=w("debugrootmotion");class Di{static createFromClips(e,t={looping:!1,autoTransition:!0,transitionDuration:0}){const i=[];for(let r=0;r<e.length;r++){const a=e[r],l=[];if(t.autoTransition!==!1){const d=t.transitionDuration??0,u=d/a.duration;let p=r;(t.autoTransition===void 0||t.autoTransition===!0)&&(p=(r+1)%e.length),l.push({exitTime:1-u,offset:0,duration:d,hasExitTime:!0,destinationState:p,conditions:[]})}const h={name:a.name,hash:r,motion:{name:a.name,clip:a,isLooping:t?.looping??!1},transitions:l,behaviours:[]};i.push(h)}const n={name:"AnimatorController",guid:new mt(Date.now()).generateUUID(),parameters:[],layers:[{name:"Base Layer",stateMachine:{defaultState:0,states:i}}]};return new Di(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 r=this.model.layers[t].stateMachine;for(const a of r.states)if(a.name===e||a.hash===e){qe&&console.log("transition to ",a),this.transitionTo(a,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(o=>o[i]===e);return n.forEach(o=>o.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){qe&&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 gl(this._activeState,i,t,this._speed)}get currentAction(){if(!this._activeState)return null;const e=this._activeState.motion.action;return e||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 c.AnimationMixer(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;qe&&console.warn("AnimatorController clone()",this.model);const e=ac(this.model,(i,n,o)=>o==null?!0:!(o.type==="Object3D"||o.isObject3D===!0||Pb(o)||o.tracks!==void 0||o instanceof Di));return console.assert(e!==this.model),new Di(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,qe&&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 o=n.action;o.weight=e,o.getEffectiveWeight()<=0&&!o.isRunning()&&(qe&&console.debug("REMOVE",i.name,o.getEffectiveWeight(),o.isRunning(),o.isScheduled()),this._activeStates.splice(t,1),t--)}}}setStartTransition(){this.model.layers.length>1&&(qe||A())&&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&&(qe&&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 o of t.transitions){if(!o.hasExitTime&&o.conditions.length<=0)continue;let r=!0;for(const a of o.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 h=o.exitTime;i.timeScale<0&&(h=1-h);let d=!1;if(o.hasExitTime?i.timeScale>0?d=l>=o.exitTime:i.timeScale<0&&(d=1-l>=o.exitTime):d=!0,d){for(const u of o.conditions){const p=this.model.parameters.find(m=>m.name===u.parameter);p?.type===Am.Trigger&&p.value&&(p.value=!1)}if(i.clampWhenFinished=!0,qe){const u=this.getState(o.destinationState,0);console.log(`Transition to ${o.destinationState} / ${u?.name}`,o,`
|
|
866
866
|
Timescale: `+i.timeScale,`
|
|
867
867
|
Normalized time: `+l.toFixed(3),`
|
|
868
868
|
Exit Time: `+h,o.hasExitTime)}this.transitionTo(o.destinationState,o.duration,o.offset);return}}else{this.transitionTo(o.destinationState,o.duration,o.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 o=i?.getClip().duration,r=i.time/o,a=new gl(this._activeState,r,o,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&&(qe&&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 c.AnimationClip))return;const o=this._activeState===e;if(o){const d=e.motion;if(!d.action_loopback&&d.clip){const u=this.rootMotionHandler?this.animator.gameObject.matrix.clone():null;this._mixer.uncacheAction(d.clip,this.animator.gameObject),u&&u.decompose(this.animator.gameObject.position,this.animator.gameObject.quaternion,this.animator.gameObject.scale),d.action_loopback=this.createAction(d.clip)}}if(this._activeState?.behaviours&&this._activeState.motion.action){const d=this._activeState?.motion.clip.duration,u=this._activeState.motion.action.time/d,p=new gl(this._activeState,u,d,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;o&&(e.motion.action=e.motion.action_loopback,e.motion.action_loopback=r);const a=this._activeState;this._activeState=e;const l=e.motion?.action,h=e.motion.clip;if(h?.duration<=0&&h.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 u=this.getFloat(e.cycleOffsetParameter);typeof u=="number"?(u<0&&(u+=1),i+=u,i%=1):qe&&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 d=e.motion.clip.duration;if(l.time=o?0:i*d,l.timeScale<0&&(l.time=d-l.time),l.clampWhenFinished=!0,l.setLoop(c.LoopOnce,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 u=new gl(e,i,d,this._speed);for(const p of this._activeState.behaviours)p.instance?.onStateEnter?.call(p.instance,this.animator,u,n)}}else qe&&(e.__warned_no_motion||(e.__warned_no_motion=!0,console.warn("No action",e.motion,this)));qe&&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 E1(this));const i=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,i,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 Bs.If:return t.value===!0;case Bs.IfNot:return t.value===!1;case Bs.Greater:return t.value>e.threshold;case Bs.Less:return t.value<e.threshold;case Bs.Equals:return t.value===e.threshold;case Bs.NotEqual:return t.value!==e.threshold}return!1}createActions(e){qe&&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 o=i.states[n];o.transitions||(o.transitions=[]);for(const r of o.transitions)r.conditions||(r.conditions=[]);if(o.motion||(qe&&console.warn("No motion",o),o.motion=n0(o.name)),this.animator&&o.motion.clips){const r=o.motion.clips?.find(a=>a.node.name===this.animator?.gameObject?.name);r?o.motion.clip=r.clip:(qe||A())&&console.warn('Could not find clip for animator "'+this.animator?.gameObject?.name+'"',o.motion.clips.map(a=>a.node.name))}if(!o.motion.clip){qe&&console.warn("No clip assigned to state",o);const r=new c.AnimationClip(void 0,void 0,[]);o.motion.clip=r}if(o.motion?.clip){const r=o.motion.clip;if(r instanceof c.AnimationClip){const a=this.createAction(r);o.motion.action=a}else(qe||A())&&console.warn("No valid animationclip assigned",o)}if(o.behaviours&&Array.isArray(o.behaviours))for(const r of o.behaviours){if(!r?.typeName)continue;const a=P.get(r.typeName);if(a){const l=new a;l.isStateMachineBehaviour&&(l._context=this.context??void 0,ua(l,r.properties),r.instance=l),qe&&console.log("Created animator controller behaviour",o.name,r.typeName,r.properties,l)}else(qe||A())&&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 a_{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=o=>{if(!this.originalEvaluate)return;const r=this.originalEvaluate(o);return t(o,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 Ye{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 c.Vector3;rotationChange=new c.Quaternion;constructor(e,t,i,n,o){if(this.context=e,this.root=t,this.clip=i,Ye.firstKeyframeRotation[this.cacheId]||(Ye.firstKeyframeRotation[this.cacheId]=new c.Quaternion),o){const r=o.values;Ye.firstKeyframeRotation[this.cacheId].set(r[0],r[1],r[2],r[3])}Ye.spaceRotation[this.cacheId]||(Ye.spaceRotation[this.cacheId]=new c.Quaternion),Ye.effectiveSpaceRotation[this.cacheId]||(Ye.effectiveSpaceRotation[this.cacheId]=new c.Quaternion),Ye.clipOffsetRotation[this.cacheId]=new c.Quaternion,o&&Ye.clipOffsetRotation[this.cacheId].set(o.values[0],o.values[1],o.values[2],o.values[3]).invert(),this.handlePosition(i,n),this.handleRotation(i,o)}onStart(e){if(e.getClip()!==this.clip)return;Ye.lastObjRotation[this.cacheId]||(Ye.lastObjRotation[this.cacheId]=this.root.quaternion.clone());const t=Ye.lastObjRotation[this.cacheId];if(Ye.spaceRotation[this.cacheId].copy(t),vh){const i=new c.Euler().setFromQuaternion(t);console.log("START",this.clip.name,D.toDegrees(i.y),this.root.position.z)}}getClipRotationOffset(){return Ye.clipOffsetRotation[this.cacheId]}_prevTime=0;handlePosition(e,t){if(t){const i=this.root;vh&&i.add(new c.AxesHelper),Ye.lastObjPosition[this.cacheId]||(Ye.lastObjPosition[this.cacheId]=this.root.position.clone());const n=new c.Vector3,o=new c.Vector3;this.positionWrapper=new a_(t,(r,a)=>{const l=this.action.getEffectiveWeight();return vh&&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(o),n.multiplyScalar(l),n.applyQuaternion(this.getClipRotationOffset()),n.applyQuaternion(i.quaternion),this.positionChange.copy(n)),o.fromArray(a),this._prevTime=r,a[0]=0,a[1]=0,a[2]=0,a})}}static identityQuaternion=new c.Quaternion;handleRotation(e,t){if(t){if(vh){const r=t.values,a=new c.Euler().setFromQuaternion(new c.Quaternion(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,h=new c.Quaternion().set(r[l],r[l+1],r[l+2],r[l+3]),d=new c.Euler().setFromQuaternion(h);console.log(e.name,t.name,"LAST ROTATION IN TRACK",D.toDegrees(d.y))}let i=0;const n=new c.Quaternion,o=new c.Quaternion;this.rotationWrapper=new a_(t,(r,a)=>(r>i&&(o.set(a[0],a[1],a[2],a[3]),n.invert(),o.multiply(n),this.rotationChange.copy(o)),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(Ye.identityQuaternion,1-e),!0)}}class E1{controller;handler=[];root;basePosition=new c.Vector3;baseQuaternion=new c.Quaternion;baseRotation=new c.Euler;constructor(e){this.controller=e}createClip(e,t,i){this.root=t,t&&"name"in t&&t.name;const n=this.findRootTrack(i,".position"),o=this.findRootTrack(i,".quaternion"),r=new Ye(this.controller.context,t,i,n,o);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 c.Vector3;summedRotation=new c.Quaternion;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 R1 extends Ui{onSerialize(e,t){}onDeserialize(e,t){if(t.type===Di&&e?.__type==="AnimatorController")return new Di(e)}}new R1(Di);var T1=Object.defineProperty,A1=Object.getOwnPropertyDescriptor,tu=(s,e,t,i)=>{for(var n=i>1?void 0:i?A1(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&T1(e,t,n),n};const Pi=w("debuganimator");class rt extends k{get isAnimationComponent(){return!0}applyRootMotion=!1;hasRootMotion=!1;keepAnimatorControllerStateOnDisable=!1;set runtimeAnimatorController(e){this._animatorController&&this._animatorController.model===e||(e?e instanceof Di?(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 Di(e.model)),this._animatorController=e,this._animatorController.bind(this)):(Pi&&console.log("Assign animator controller",e,this),this._animatorController=new Di(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){Pi&&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 Pi&&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),Pi&&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 Pi&&console.log("getFloat",e,t),t}SetInteger(e,t){this.setInteger(e,t)}setInteger(e,t){this.runtimeAnimatorController?.getInteger(e)!==t&&(this._parametersAreDirty=!0),Pi&&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 Pi&&console.log("getInteger",e,t),t}SetTrigger(e){this.setTrigger(e)}setTrigger(e){this._parametersAreDirty=!0,Pi&&console.log("setTrigger",e),this.runtimeAnimatorController?.setTrigger(e)}ResetTrigger(e){this.resetTrigger(e)}resetTrigger(e){this._parametersAreDirty=!0,Pi&&console.log("resetTrigger",e),this.runtimeAnimatorController?.resetTrigger(e)}GetTrigger(e){this.getTrigger(e)}getTrigger(e){const t=this.runtimeAnimatorController?.getTrigger(e);return Pi&&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&&(Pi&&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(){Pi&&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,!M1(this.gameObject)&&this._animatorController&&this._animatorController.update(1)}}tu([f()],rt.prototype,"applyRootMotion",2);tu([f()],rt.prototype,"hasRootMotion",2);tu([f()],rt.prototype,"keepAnimatorControllerStateOnDisable",2);tu([f()],rt.prototype,"runtimeAnimatorController",1);const l_=Symbol("previous-visibility");class Sn extends c.WebGLRenderTarget{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 c.WebGLRenderer){this.onBeforeRender();const o=i.getRenderTarget(),r=i.xr.enabled;i.xr.enabled=!1,i.setRenderTarget(this),i.clear(!0,!0,!0),i.render(e,t),i.setRenderTarget(o),i.xr.enabled=r,this.onAfterRender()}}static _userSet=new Set;onBeforeRender(){Sn._userSet.clear();const e=bm(this.texture,!0,null,Sn._userSet);for(const t of e)t instanceof c.Mesh&&(t[l_]=t.visible,t.visible=!1)}onAfterRender(){for(const e of Sn._userSet)e instanceof c.Mesh&&(e.visible=e[l_]);Sn._userSet.clear()}}var L1=Object.defineProperty,D1=Object.getOwnPropertyDescriptor,wc=(s,e,t,i)=>{for(var n=i>1?void 0:i?D1(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&L1(e,t,n),n};const wh=w("debuggroundprojection");class In extends k{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 rs(this.context.scene,"background"),this._watcher.subscribeWrite(e=>{wh&&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 lc(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 c.Texture&&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 c.Texture)){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){wh&&console.log("Create/Update Ground Projection",e.name),this._projection?.removeFromParent();try{this._projection=new q.GroundedSkybox(e,this._height,this._radius,64)}catch(o){console.error("Error creating three GroundProjection",o);return}this._projection.position.y=this._height-i,this._projection.name="GroundProjection",sm(this._projection,!1)}else t=!1;if(this._projection.parent||this.gameObject.add(this._projection),this.autoFit&&t){this._projection.updateWorldMatrix(!0,!0);const o=Bt(this.context.scene.children,[this._projection]),r=o.min.y;if(r<1/0){const a=V();a.x=o.min.x+(o.max.x-o.min.x)*.5;const l=Ie(this.gameObject).x;a.y=r+this._height*l-i,a.z=o.min.z+(o.max.z-o.min.z)*.5,ot(this._projection,a)}wh&&B.DrawWireBox3(o,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,wh&&console.log("Update Blurriness",t),this._blurrynessShader??=new c.ShaderMaterial({name:"GroundProjectionBlurriness",uniforms:{map:{value:e},blurriness:{value:t},blending:{value:0},alphaFactor:{value:1}},vertexShader:I1,fragmentShader:j1}),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=Xs.copyTexture(e,this._blurrynessShader),this._projection.material.depthTest=!0,this._projection.material.depthWrite=!1}}wc([f()],In.prototype,"applyOnAwake",2);wc([f()],In.prototype,"autoFit",2);wc([f()],In.prototype,"radius",1);wc([f()],In.prototype,"height",1);wc([f()],In.prototype,"arBlending",1);const I1=`
|
|
@@ -946,7 +946,7 @@ ${t.path}! : AssetReference;
|
|
|
946
946
|
Could not find method ${r.method} on object ${l.name}. Please rename ${r.method} to ${p}?
|
|
947
947
|
`,l[p],`
|
|
948
948
|
in script: `,l),he("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 p=!1,m=l;for(;m;){const y=Object.getOwnPropertyDescriptor(m,r.method);if(y&&(y.writable===!0||y.set)){p=!0;break}m=Object.getPrototypeOf(m)}!p&&(A()||st)&&d()}}if(l){let d=r.argument;if(d!==void 0?d=a(d):r.arguments!==void 0&&(d=r.arguments.map(a)),!l[r.method])console.warn(`EventList method not found: "${r.method}" on ${l?.name}`);else{d!==void 0&&!Array.isArray(d)&&(d=[d]);const p=new is(l,r.method,d,r.enabled);i.push(p)}}else A()&&console.warn(`[Dev] EventList: Could not find event listener in scene (${t.object?.name})`,r)}const n=new oe(i);st&&console.log(n);const o=t.target;return o!==void 0&&t.path!==void 0&&n.setEventTarget(t.path,o),n}}}const K1=new Y1,Pd=new WeakMap,Z1=c.Texture.prototype.clone;c.Texture.prototype.clone=function(){const s=Z1.call(this);return Pd.has(s)||Pd.set(s,this),s};class a0 extends Ui{constructor(){super([Sn,c.WebGLRenderTarget])}onSerialize(e,t){}onDeserialize(e,t){if(e instanceof c.Texture&&t.type===Sn){let i=e;Pd.has(i)&&(i=Pd.get(i)),i.isRenderTargetTexture=!0,i.flipY=!0,i.offset.y=1,i.repeat.y=-1,i.needsUpdate=!0,i.mipmaps=[],i instanceof c.CompressedTexture&&(i.isCompressedTexture=!1,i.format=c.RGBAFormat);const n=new Sn(i.image.width,i.image.height,{colorSpace:c.LinearSRGBColorSpace});return n.texture=i,n}}}new a0;class l0 extends Ui{constructor(){super([URL])}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"&&e.length>0)return Js(t.gltfId,e)}}new l0;var J1=Object.defineProperty,eP=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&J1(e,t,n),n};class ma extends k{awake(){jt.createIfNoneExists(this.context)}onEnable(){jt.get(this.context)?.register(this)}onDisable(){jt.get(this.context)?.unregister(this)}}class fi extends ma{targets=null;raycastHits=[];ignoreSkinnedMeshes=!1;start(){this.targets=[this.gameObject]}performRaycast(e=null){if(!this.targets)return null;e??=new io,e.targets=this.targets,e.results=this.raycastHits,e.useAcceleratedRaycast=!0;const t=e.testObject;this.ignoreSkinnedMeshes&&(e.testObject=n=>n instanceof c.SkinnedMesh?"continue in children":t?t(n):!0);const i=this.context.physics.raycast(e);return e.testObject=t,i}}eP([f()],fi.prototype,"ignoreSkinnedMeshes");class su extends fi{constructor(){super(),this.ignoreSkinnedMeshes=!0}}class Qo extends ma{static allow=!0;performRaycast(e){if(!H.active||!Qo.allow||!e?.ray)return null;const t=e.ray.origin;return this.context.physics.sphereOverlap(t,.015,!1,!0)}}class Dm{static getObject(e){const t=e[ri];return t&&(t.isComponent===!0?e=t.gameObject:e=t),e}static isInteractable(e,t){if(t&&(t.canvasGroup=void 0,t.graphic=void 0),e==null||!e.visible||(e=this.getObject(e),!e.visible))return!1;const i=this.tryFindCanvasGroup(e);if(i?.isCanvasGroup===!0&&(t&&(t.canvasGroup=i),i.blocksRaycasts===!1||i.interactable===!1))return!1;const n=qo(e,o=>{if(o.isGraphic===!0)return o},!1);return t&&n?.isGraphic===!0&&(t.graphic=n),!(n?.raycastTarget===!1||n?.layer===2)}static tryFindCanvasGroup(e){if(!e)return null;const t=qo(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 Im(s){const e=s[ri];return e||(s.parent?Im(s.parent):null)}function tP(s){return s.isUI===!0||typeof s[ri]=="object"}function Od(s,e){if(!s)return;const t=s.material;if(t?.isMaterial===!0){const i=s.parent;i&&i.isText,t.side=e.doubleSided??!0?c.DoubleSide:c.FrontSide,t.shadowSide=e.doubleSided?c.DoubleSide:c.FrontSide,s.castShadow=e.castShadows?e.castShadows:!1,s.receiveShadow=e.receiveShadows?e.receiveShadows:!1}for(const i of s.children)Od(i,e)}function Ur(s,e,t){s[e]===void 0&&console.warn("Field",e,"is undefined on",s);const i=Proxy.revocable(s[e],{set(r,a,l,h){const d=r[a],u=Reflect.set(r,a,l,h);return t(l,d),u}}),n=i.revoke,o=s[e];return i.revoke=()=>{s[e]=o,n()},s[e]=i.proxy,i}const c_=Symbol("Scheduled action");function iP(s,e,t=pe.OnBeforeRender){let i=s[c_];i||(i=s[c_]={});const n=e.name;i[t]||(i[t]={});const o=i[t];if(o[n])return;function*a(){e?.call(s),o[n]=null}const l=s.startCoroutine(a(),t);o[n]=l}const Ds=w("debugeventsystem");var kp=(s=>(s.BeforeHandleInput="BeforeHandleInput",s.AfterHandleInput="AfterHandleInput",s))(kp||{});Yv(s=>{jt.createIfNoneExists(s)});class jt extends k{static ensureUpdateMeshUI(e,t,i=!1){Qa.update(e,t,i)}static markUIDirty(e){Qa.markDirty()}static createIfNoneExists(e){e.scene.getComponent(jt)||e.scene.addComponent(jt)}static get(e){return this.createIfNoneExists(e),e.scene.getComponent(jt)}static get instance(){return this.get(F.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(ma)||this.context.scene.addComponent(fi)}onEnable(){this.context.input.addEventListener(we.PointerDown,this.onPointerEvent),this.context.input.addEventListener(we.PointerUp,this.onPointerEvent),this.context.input.addEventListener(we.PointerMove,this.onPointerEvent)}onDisable(){this.context.input.removeEventListener(we.PointerDown,this.onPointerEvent),this.context.input.removeEventListener(we.PointerUp,this.onPointerEvent),this.context.input.removeEventListener(we.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 xc(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==we.PointerDown,t.isUp=e.type==we.PointerUp,t.isPressed=this.context.input.getPointerPressed(e.pointerId);const i=new io;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(Ds&&(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})}Ds&&t.isClick&&Se("EventSystem: "+t.pointerId+" - "+this.context.time.frame+" - Up:"+t.isUp+", Down:"+t.isDown);const o={sender:this,args:t,hasActiveUI:this.currentActiveMeshUIComponents.length>0};this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:o})),this.handleIntersections(n,t),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:o}))};_sortedHits=[];_testObjectsCache=new Map;_currentlyActiveRaycaster=null;_currentPointerEventName=null;shouldRaycastObject=e=>{const t=e&&"getComponent"in e?e.getComponent(ma):null;if(t&&t!=this._currentlyActiveRaycaster)return!1;let i=null;if(tP(e)&&(i=e[ri]?.gameObject),this._testObjectsCache.has(e)||i&&this._testObjectsCache.has(i))return this._testObjectsCache.get(e)===!1?"continue in children":!0;{let o=Cd(e,this._currentPointerEventName);if(!o&&i&&(o=Cd(i,this._currentPointerEventName)),o){this._testObjectsCache.set(e,!0);for(const r of e.children)this.shouldRaycastObject_AddToYesCache(r);return!0}return this._testObjectsCache.set(e,!1),"continue in children"}};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&&Ds&&console.log("not allowed",e),!1;if(t.pointerId===void 0)return Ds&&console.error("Event without pointer can't be handled",t),!1;t.object=e;const i=e.parent,n=t.isClick??!1;let o=null;if(i&&i.isUI){const d=(t.isPressed||t.isClick)??!1;if(i[ri]){const u=i[ri].gameObject;if(u){if(!Dm.isInteractable(u,this.out))return!1;o=this.out.canvasGroup??null,this.handleMeshUIIntersection(e,d),e=u}}}n&&Ds&&console.log(this.context.time.frame,e);const r=this.hoveredByID.get(t.pointerId),a=r?.obj;a!==e&&a&&this.propagatePointerExit(a,r.data,e);const h=this.hoveredByID.get(t.pointerId);if(h?(h.obj=e,h.data=t):this.hoveredByID.set(t.pointerId,{obj:e,data:t}),t.isDown){const d=this.pressedByID.get(t.pointerId);d?(d.obj=e,d.data=t):this.pressedByID.set(t.pointerId,{obj:e,data:t,handlers:new Set})}return(o===null||o.interactable)&&this.handleMainInteraction(e,t,a??null),!0}propagate(e,t){for(;e;)S.foreachComponent(e,i=>{t(i)},!1),e=e.parent}handleMainInteraction(e,t,i){const n=this.pressedByID.get(t.pointerId),o=i!==e;let r=!0;switch(t.event.pointerType){case"mouse":case"touch":const a=this.context.input.getPointerPositionLastFrame(t.pointerId),l=this.context.input.getPointerPosition(t.pointerId);r=a&&!D.approximately(a,l);break}this.propagate(e,a=>{const l=a;l.interactable!==!1&&(!l.activeAndEnabled||!l.enabled||(l.onPointerEnter&&o&&this.handlePointerEnter(l,t),t.isDown&&l.onPointerDown&&(l.onPointerDown(t),n?.handlers.add(l),this.handlePointerCapture(t,l)),l.onPointerMove&&(r&&l.onPointerMove(t),this.handlePointerCapture(t,l)),t.isUp&&(l.onPointerUp&&(this.invokeOnPointerUp(t,l),n?.handlers.delete(l)),l.onPointerExit&&t.event?.pointerType===Gd.Touch&&(this.handlePointerExit(l,t),this.hoveredByID.delete(t.pointerId))),t.isClick&&l.onPointerClick&&l.onPointerClick(t)))}),t.isUp&&(n?.handlers.forEach(a=>{this.invokeOnPointerUp(t,a)}),this.pressedByID.delete(t.pointerId))}propagatePointerExit(e,t,i){this.propagate(e,n=>{if(!n.gameObject||n.destroyed)return;const o=n;if(o.onPointerExit||o.onPointerEnter){if(i&&this.isChild(i,n.gameObject))return;this.handlePointerExit(o,t)}})}invokeOnPointerUp(e,t){t.onPointerUp?.call(t,e),this.releasePointerCapture(e,t)}handlePointerEnter(e,t){e.onPointerEnter&&this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!0)&&e.onPointerEnter(t),this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!1)}handlePointerExit(e,t){e.onPointerExit&&this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!0)&&e.onPointerExit(t),this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!1)}updatePointerState(e,t,i,n){let o=e[i];if(n)return o&&o.includes(t)?!1:(o=o||[],o.push(t),e[i]=o,!0);{if(!o||!o.includes(t))return!1;const r=o.indexOf(t);return r!==-1&&o.splice(r,1),!0}}_capturedPointer={};handlePointerCapture(e,t){if(e.z__pointer_ctured){e.z__pointer_ctured=!1;const i=e.pointerId;if(t.onPointerMove){const n=this._capturedPointer[i]||[];n.push(t),this._capturedPointer[i]=n}else A()&&!t.z__warned_no_pointermove&&(t.z__warned_no_pointermove=!0,console.warn("PointerCapture was requested but the component doesn't implement onPointerMove. It will not receive any pointer events"))}else e.z__pointer_cture_rleased&&(e.z__pointer_cture_rleased=!1,this.releasePointerCapture(e,t))}releasePointerCapture(e,t){const i=e.pointerId;if(this._capturedPointer[i]){const n=this._capturedPointer[i].indexOf(t);n!==-1&&(this._capturedPointer[i].splice(n,1),Ds&&console.log("released pointer capture",i,t,this._capturedPointer))}}invokePointerCapture(e){if(e.event.type===we.PointerMove){const t=e.pointerId,i=this._capturedPointer[t];if(i){Ds&&console.log("Captured",t,i);for(let n=0;n<i.length;n++){const o=i[n];if(o.destroyed){i.splice(n,1),n--;continue}o.onPointerMove?.call(o,e)}}}}pointerEnterSymbol=Symbol("pointerEnter");pointerExitSymbol=Symbol("pointerExit");isChild(e,t){return!e||!t?!1:e===t?!0:e.parent?this.isChild(e.parent,t):!1}handleMeshUiObjectWithoutShadowDom(e,t){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,t)}currentActiveMeshUIComponents=[];handleMeshUIIntersection(e,t){const i=Qa.updateState(e,t);return i&&this.currentActiveMeshUIComponents.push(i),i!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&Qa.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){const t=this.currentActiveMeshUIComponents[e];Qa.resetState(t)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?S.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}}class Qa{static lastSelected=null;static lastUpdateFrame=[];static needsUpdate=!1;static markDirty(){this.needsUpdate=!0}static update(e,t,i=!1){if(i){e.update();return}const n=t.time.frameCount;for(const o of this.lastUpdateFrame)if(o.context===t){if(n===o.frame)return;o.frame=n;let r=this.needsUpdate||n<1;o.nextUpdate<=n&&(r=!0),r&&(Ds&&console.log("Update threemeshui"),this.needsUpdate=!1,o.nextUpdate=n+60,e.update());return}this.lastUpdateFrame=[{context:t,frame:n,nextUpdate:n+60}],e.update(),this.needsUpdate=!1}static updateState(e,t){let i=null;if(e&&(i=this.findBlockOrTextInParent(e),i&&i!==this.lastSelected)){if(i.interactable===!1)return null;this.needsUpdate=!0}return i}static resetLastSelected(){const e=this.lastSelected;e&&(this.lastSelected=null,this.resetState(e))}static resetState(e){e&&(this.needsUpdate=!0)}static findBlockOrTextInParent(e){return e?e.isBlock||e.isText?e:this.findBlockOrTextInParent(e.parent):null}}var nP=Object.defineProperty,Ce=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&nP(e,t,n),n};const kt=w("debugorbit"),gf=w("freecam"),Ya=w("debugcamerafit"),xh=w("smoothcam"),sP={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let yf;class Kl extends CustomEvent{constructor(e,t){super("target-reached",{detail:{controls:e,type:t}})}}class de extends k{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 c.Vector3;_lookTargetEndPosition=new c.Vector3;_lookTargetLerp01=0;_lookTargetLerpDuration=0;_cameraLerpActive=!1;_cameraStartPosition=new c.Vector3;_cameraEndPosition=new c.Vector3;_cameraLerp01=0;_cameraLerpDuration=0;_fovLerpActive=!1;_fovLerpStartValue=0;_fovLerpEndValue=0;_fovLerp01=0;_fovLerpDuration=0;_inputs=0;_enableTime=0;_startedListeningToKeyEvents=!1;_eventSystem;_afterHandleInputFn;_camera=null;_syncedTransform;_didSetTarget=0;awake(){kt&&console.debug("OrbitControls",this),this._didSetTarget=0,this._startedListeningToKeyEvents=!1}start(){this._eventSystem=jt.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(kp.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){this._controls?.dispose(),this._eventSystem?.removeEventListener(kp.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._didSetTarget=0,this._enableTime=this.context.time.time;const e=S.getComponent(this.gameObject,qt);this._camera=e;let t=e?.threeCamera;if(!t&&this.gameObject instanceof c.PerspectiveCamera&&(t=this.gameObject),t&&np(t,this,!0),!this._controls&&t instanceof c.Object3D){this._cameraObject=t;const i=this.targetElement??this.context.renderer.domElement,n=t?.quaternion.clone();this._controls=new q.OrbitControls(t,i),t?.quaternion.copy(n),yf===void 0&&(yf={...this._controls.keys});const o=X(t),r=this.gameObject.worldForward,l=o.clone().sub(r.multiplyScalar(2.5));this._controls.target.copy(l)}if(this._controls)if(gf&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,exports.DeviceUtilities.isMobileDevice()&&(this.doubleClickToFocus=!0)),this._controls.addEventListener("start",this.onControlsChangeStarted),this._controls.addEventListener("endMovement",this.onControlsChangeEnded),!this._startedListeningToKeyEvents&&this.enableKeys)this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(this.context.domElement);else try{this._controls.stopListenToKeyEvents()}catch{}this._syncedTransform=S.getComponent(this.gameObject,nn)??void 0,this.context.pre_render_callbacks.push(this.__onPreRender),this._activePointerEvents=[],this.context.input.addEventListener("pointerdown",this._onPointerDown,{queue:Ht.Early}),this.context.input.addEventListener("pointerdown",this._onPointerDownLate,{queue:Ht.Late}),this.context.input.addEventListener("pointerup",this._onPointerUp,{queue:Ht.Early}),this.context.input.addEventListener("pointerup",this._onPointerUpLate,{queue:Ht.Late})}onDisable(){if(this._camera?.threeCamera&&np(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}kt&&console.log(this.clickBackgroundToFitScene,e.intersections.length,this._clickOnBackgroundCount)}};_onPointerUpLate=e=>{this.doubleClickToFocus&&e.isDoubleClick&&!e.used&&this.setTargetFromRaycast()};updateTargetNow(e){const t=new c.Ray(this._cameraObject?.worldPosition,this._cameraObject?.worldForward.multiplyScalar(-1)),i=this.context.physics.raycastFromRay(t,e),n=i.length>0?i[0]:void 0;n&&n.distance>this.minZoom&&n.distance<this.maxZoom?(kt&&B.DrawWireSphere(n.point,.1,16711680,2),this._controls?.target.copy(i[0].point)):kt&&console.log("OrbitControls: No hit found when updating target",{hits:[...i]})}_orbitStartAngle=0;_zoomStartDistance=0;onControlsChangeStarted=()=>{kt&&console.debug("OrbitControls: Change started"),this._controls&&(this._orbitStartAngle=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle(),this._zoomStartDistance=this._controls.getDistance()),this._syncedTransform&&this._syncedTransform.requestOwnership()};onControlsChangeEnded=()=>{if(kt&&console.debug("OrbitControls: Change ended",{autoTarget:this.autoTarget}),this._controls&&this.autoTarget){const t=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle()-this._orbitStartAngle;Math.abs(t)<.01?(kt&&console.debug("OrbitControls: Update target",{deltaAngle:t}),this.updateTargetNow({allowSlowRaycastFallback:!1})):kt&&console.debug("OrbitControls: No target update",{deltaAngle:t})}};_shouldDisable=!1;afterHandleInput(e){e.detail.args.pointerId===0&&(e.detail.args.isDown?this._controls&&this._eventSystem&&(this._shouldDisable=this._eventSystem.hasActiveUI):(!e.detail.args.isPressed||e.detail.args.isUp)&&(this._shouldDisable=!1))}onPausedChanged(e){this._controls&&e&&(this._controls.enabled=!1)}onBeforeRender(){if(!this._controls)return;if(this._cameraObject!==this.context.mainCamera){this._controls.enabled=!1;return}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 t=S.getComponent(this.gameObject,qt);if(t&&!this.setLookTargetFromConstraint()){this.debugLog&&console.log("NO TARGET");const i=X(t.threeCamera),n=Math.max(.01,i.length()),o=new c.Vector3(0,0,-n).applyMatrix4(t.threeCamera.matrixWorld);kt&&B.DrawLine(i,o,5592575,10),this.setLookTargetPosition(o,!0)}if(!this.setLookTargetFromConstraint()){const i=new io;i.screenPoint=new c.Vector2(0,0),i.lineThreshold=.1;const n=this.context.physics.raycast(i);n.length>0&&this.setLookTargetPosition(n[0].point,!0),Ya&&console.log("OrbitControls hits",...n)}}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 Kl(this,"camera"));else{const t=D.easeInOutCubic(this._cameraLerp01);this._cameraObject.position.lerpVectors(this._cameraStartPosition,this._cameraEndPosition,t)}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 Kl(this,"lookat"));else{const t=D.easeInOutCubic(this._lookTargetLerp01);this.lerpLookTarget(this._lookTargetStartPosition,this._lookTargetEndPosition,t)}if(this._fovLerpActive&&this._cameraObject){const t=this._cameraObject;if(this._fovLerp01+=this.context.time.deltaTime/this._fovLerpDuration,this._fovLerp01>=1)t.fov=this._fovLerpEndValue,this._fovLerpActive=!1;else{const i=D.easeInOutCubic(this._fovLerp01);t.fov=D.lerp(this._fovLerpStartValue,this._fovLerpEndValue,i)}t.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(t=>t.used),this._controls.keys=this.enableKeys?yf:sP,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,gf||(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 xh=="number"||xh===!0){this._controls.enableDamping=!0;const t=typeof xh=="number"?xh:.99;this._controls.dampingFactor=Math.max(.001,1-Math.min(1,t))}this.allowInterrupt||(this._lookTargetLerpActive&&(this._controls.enablePan=!1),this._cameraLerpActive&&(this._controls.enableRotate=!1,this._controls.autoRotate=!1),(this._lookTargetLerpActive||this._cameraLerpActive)&&(this._controls.enableZoom=!1)),this.context.isInXR||(!gf&&this.lookAtConstraint?.locked&&!this._lookTargetLerpActive&&this.setLookTargetFromConstraint(0,this.lookAtConstraint01),this._controls.update(this.context.time.deltaTime),kt&&B.DrawWireSphere(this._controls.target,.1,65280))}}__onPreRender=()=>{const e=this.context.pre_render_callbacks.indexOf(this.__onPreRender);e>=0&&this.context.pre_render_callbacks.splice(e,1),this.autoFit&&(this.autoFit=!1,this.fitCamera({centerCamera:"y",immediate:!0,objects:this.scene.children}))};setCameraAndLookTarget(e,t=!1){if(!e)return(A()||kt)&&console.warn("[OrbitControls] setCameraAndLookTarget target is null"),!1;if(!(e instanceof c.Object3D)&&!(e instanceof qt))return(A()||kt)&&console.warn("[OrbitControls] setCameraAndLookTarget target is not an Object3D or Camera"),!1;e instanceof qt&&(e=e.gameObject);const i=e.worldPosition,n=e.worldForward;e instanceof c.Camera&&(kt&&console.debug("[OrbitControls] setCameraAndLookTarget flip forward direction for camera"),n.multiplyScalar(-1));const o=new c.Ray(i,n);return kt&&B.DrawRay(o.origin,o.direction,16711680,10),this.setTargetFromRaycast(o,t)||this.setLookTargetPosition(o.at(2,V()),t),this.setCameraTargetPosition(i,t),!0}setCameraTargetPosition(e,t=!1){e&&(e instanceof c.Object3D&&(e=X(e)),this._cameraEndPosition||(this._cameraEndPosition=new c.Vector3),this._cameraEndPosition.copy(e),t===!0?(this._cameraLerpActive=!1,this._cameraObject&&this._cameraObject.position.copy(this._cameraEndPosition)):this._cameraObject&&(this._cameraLerpActive=!0,this._cameraLerp01=0,this._cameraStartPosition.copy(this._cameraObject?.position),typeof t=="number"?this._cameraLerpDuration=t:this._cameraLerpDuration=this.targetLerpDuration))}get cameraLerpActive(){return this._cameraLerpActive}stopCameraLerp(){this._cameraLerpActive=!1}setFieldOfView(e,t=!1){if(!this._controls||typeof e!="number")return;const i=this._camera?.threeCamera;i&&(t===!0?i.fov=e:(this._fovLerpActive=!0,this._fovLerp01=0,this._fovLerpStartValue=i.fov,this._fovLerpEndValue=e,typeof t=="number"?this._fovLerpDuration=t:this._fovLerpDuration=this.targetLerpDuration))}setLookTargetPosition(e=null,t=!1){this._controls&&e&&(e instanceof c.Object3D&&(e=X(e)),this._lookTargetEndPosition.copy(e),this._didSetTarget++,kt&&(console.warn("OrbitControls: setLookTargetPosition",e,t),B.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&&S.isActiveInHierarchy(n.object)){const o=Im(n.object);if(o&&o.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 c.Object3D)&&!Array.isArray(e)&&(t=e,i=t.objects),i&&!Array.isArray(i)&&(i=[i]),(!Array.isArray(i)||i&&i.length<=0)&&(i=this.context.scene.children),!Array.isArray(i)||i.length<=0){console.warn("No objects to fit camera to...");return}const n=this._cameraObject,o=this._controls;if(!n||!o){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:h=1.1,fov:d=n?.fov}=t,u=new c.Vector3,p=new c.Vector3,m=Bt(i,void 0,this._camera?.threeCamera?.layers),y=m.clone();m.getCenter(p);const _=new c.Vector3;if(m.getSize(_),n.updateMatrixWorld(),m.applyMatrix4(n.matrixWorldInverse),m.getSize(u),m.setFromCenterAndSize(p,u),Number.isNaN(u.x)||Number.isNaN(u.y)||Number.isNaN(u.z)){console.warn("Camera fit size resultet in NaN",n,m,[...i]);return}if(u.length()<=1e-10){Ya&&console.warn("Camera fit size is zero",m,[...i]);return}const g=d,v=2*Math.atan(Math.tan(g*Math.PI/360/2)*n.aspect)/Math.PI*360,b=u.y/(2*Math.atan(Math.PI*g/360)),x=u.x/(2*Math.atan(Math.PI*v/360)),T=h*Math.max(b,x)+u.z/2;Ya&&console.log("Fit camera to objects",{fitHeightDistance:b,fitWidthDistance:x,distance:T,verticalFov:g,horizontalFov:v}),this.maxZoom=T*10,this.minZoom=T*.01;const O=.05,M=p.clone();if(M.y-=u.y*O,t.targetOffset&&(t.targetOffset.x!==void 0&&(M.x+=t.targetOffset.x),t.targetOffset.y!==void 0&&(M.y+=t.targetOffset.y),t.targetOffset.z!==void 0&&(M.z+=t.targetOffset.z)),t.relativeTargetOffset&&(t.relativeTargetOffset.x!==void 0&&(M.x+=t.relativeTargetOffset.x*u.x),t.relativeTargetOffset.y!==void 0&&(M.y+=t.relativeTargetOffset.y*u.y),t.relativeTargetOffset.z!==void 0&&(M.z+=t.relativeTargetOffset.z*u.z)),this.setLookTargetPosition(M,r),this.setFieldOfView(t.fov,r),l==null||l=="auto"){const z=S.findObjectOfType(In),$=z?z.radius:0,R=Math.max(_.x,_.y,_.z,$);n.near=T/100,n.far=R+T*10,n.updateProjectionMatrix(),z&&(this.maxZoom=Math.max(Math.min(this.maxZoom,$*.5),T))}const E=o.getDistance();E<this.minZoom&&(this.minZoom=E*.9),E>this.maxZoom&&(this.maxZoom=E*1.1);const j=p.clone();t.fitDirection?j.sub(new c.Vector3().copy(t.fitDirection).multiplyScalar(1e6)):j.sub(n.worldPosition),a==="y"&&(j.y=0),j.normalize(),j.multiplyScalar(T),a==="y"&&(j.y+=-O*4*T);let L=p.clone().sub(j);t.cameraOffset&&(t.cameraOffset.x!==void 0&&(L.x+=t.cameraOffset.x),t.cameraOffset.y!==void 0&&(L.y+=t.cameraOffset.y),t.cameraOffset.z!==void 0&&(L.z+=t.cameraOffset.z)),t.relativeCameraOffset&&(t.relativeCameraOffset.x!==void 0&&(L.x+=t.relativeCameraOffset.x*u.x),t.relativeCameraOffset.y!==void 0&&(L.y+=t.relativeCameraOffset.y*u.y),t.relativeCameraOffset.z!==void 0&&(L.z+=t.relativeCameraOffset.z*u.z)),n.parent&&(L=n.parent.worldToLocal(L)),this.setCameraTargetPosition(L,r),(Ya||t.debug)&&(B.DrawWireBox3(m,16777011,10),B.DrawWireBox3(y,65280,10),!this._haveAttachedKeyboardEvents&&Ya&&(this._haveAttachedKeyboardEvents=!0,document.body.addEventListener("keydown",z=>{if(z.code==="KeyF"){let $;this._cameraObject instanceof c.PerspectiveCamera&&($=Math.random()*Math.random()*170+10),this.fitCamera({objects:i,fitOffset:h,immediate:!1,fov:$})}z.code==="KeyV"&&this._cameraObject instanceof c.PerspectiveCamera&&(this._cameraObject.fov=60)}))),this.onBeforeRender()}_haveAttachedKeyboardEvents=!1}Ce([f()],de.prototype,"autoTarget");Ce([f()],de.prototype,"autoFit");Ce([f()],de.prototype,"enableRotate");Ce([f()],de.prototype,"autoRotate");Ce([f()],de.prototype,"autoRotateSpeed");Ce([f()],de.prototype,"minAzimuthAngle");Ce([f()],de.prototype,"maxAzimuthAngle");Ce([f()],de.prototype,"minPolarAngle");Ce([f()],de.prototype,"maxPolarAngle");Ce([f()],de.prototype,"enableKeys");Ce([f()],de.prototype,"enableDamping");Ce([f()],de.prototype,"dampingFactor");Ce([f()],de.prototype,"enableZoom");Ce([f()],de.prototype,"minZoom");Ce([f()],de.prototype,"maxZoom");Ce([f()],de.prototype,"zoomSpeed");Ce([f()],de.prototype,"enablePan");Ce([f(rr)],de.prototype,"lookAtConstraint");Ce([f()],de.prototype,"lookAtConstraint01");Ce([f()],de.prototype,"allowInterrupt");Ce([f()],de.prototype,"middleClickToFocus");Ce([f()],de.prototype,"doubleClickToFocus");Ce([f()],de.prototype,"clickBackgroundToFitScene");Ce([f()],de.prototype,"targetLerpDuration");var oP=Object.defineProperty,rP=Object.getOwnPropertyDescriptor,Ut=(s,e,t,i)=>{for(var n=i>1?void 0:i?rP(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&oP(e,t,n),n},No=(s=>(s[s.None=0]="None",s[s.Skybox=1]="Skybox",s[s.SolidColor=2]="SolidColor",s[s.Uninitialized=4]="Uninitialized",s))(No||{});const Is=w("debugcam"),h_=w("debugscreenpointtoray"),xt=class yl extends k{get isCamera(){return!0}get aspect(){return this._cam instanceof c.PerspectiveCamera?this._cam.aspect:this.context.domWidth/this.context.domHeight}set aspect(e){this._cam instanceof c.PerspectiveCamera&&this._cam.aspect!==e&&(this._cam.aspect=e,this._cam.updateProjectionMatrix())}get fieldOfView(){return this._cam instanceof c.PerspectiveCamera?this._cam.fov:this._fov}set fieldOfView(e){const t=this.fieldOfView!=e;if(this._fov=e,t&&this._cam&&this._cam instanceof c.PerspectiveCamera){if(this._fov===void 0){console.warn("Can not set undefined fov on PerspectiveCamera");return}this._cam.fov=this._fov,this._cam.updateProjectionMatrix()}}get nearClipPlane(){return this._nearClipPlane}set nearClipPlane(e){const t=this._nearClipPlane!=e;this._nearClipPlane=e,this._cam&&(t||this._cam.near!=e)&&(this._cam.near=e,this._cam.updateProjectionMatrix())}_nearClipPlane=.1;get farClipPlane(){return this._farClipPlane}set farClipPlane(e){const t=this._farClipPlane!=e;this._farClipPlane=e,this._cam&&(t||this._cam.far!=e)&&(this._cam.far=e,this._cam.updateProjectionMatrix())}_farClipPlane=1e3;applyClippingPlane(){this._cam&&(this._cam.near=this._nearClipPlane,this._cam.far=this._farClipPlane,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(e){if(typeof e=="string")switch(e){case"skybox":e=1;break;case"solidcolor":e=2;break;default:e=0;break}e!==this._clearFlags&&(this._clearFlags=e,this.applyClearFlagsIfIsActiveCamera())}orthographic=!1;orthographicSize=5;ARBackgroundAlpha=0;set cullingMask(e){this._cullingMask=e,this._cam&&(this._cam.layers.mask=e)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}_cullingMask=4294967295;set cullingLayer(e){this.cullingMask=(1<<e|0)>>>0}set backgroundBlurriness(e){e!==this._backgroundBlurriness&&(e===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(e,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}_backgroundBlurriness=void 0;set backgroundIntensity(e){e!==this._backgroundIntensity&&(e===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(e,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}_backgroundIntensity=void 0;set backgroundRotation(e){e!==this._backgroundRotation&&(e===void 0?this._backgroundRotation=void 0:this._backgroundRotation=e,this.applyClearFlagsIfIsActiveCamera())}get backgroundRotation(){return this._backgroundRotation}_backgroundRotation=void 0;set environmentIntensity(e){this._environmentIntensity=e}get environmentIntensity(){return this._environmentIntensity}_environmentIntensity=void 0;get backgroundColor(){return this._backgroundColor??null}set backgroundColor(e){e&&(this._backgroundColor||(this._backgroundColor=new Z(1,1,1,1)),this._backgroundColor.copy(e),(!("alpha"in e)||e.alpha===void 0)&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera())}set targetTexture(e){this._targetTexture=e}get targetTexture(){return this._targetTexture}_targetTexture=null;_backgroundColor;_fov;_cam=null;_clearFlags=2;_skybox;get cam(){return this.threeCamera}get threeCamera(){return this.activeAndEnabled&&this.buildCamera(),this._cam}static _origin=new c.Vector3;static _direction=new c.Vector3;screenPointToRay(e,t,i){const n=this.threeCamera,o=yl._origin;o.set(e,t,-1),this.context.input.convertScreenspaceToRaycastSpace(o),h_&&console.log("screenPointToRay",e.toFixed(2),t.toFixed(2),"now:",o.x.toFixed(2),o.y.toFixed(2),"isInXR:"+this.context.isInXR),o.z=-1,o.unproject(n);const r=yl._direction.set(o.x,o.y,o.z),a=X(n);return r.sub(a),r.normalize(),i?(i.set(a,r),i):new c.Ray(a.clone(),r.clone())}_frustum;getFrustum(){return this._frustum||(this._frustum=new c.Frustum,this.updateFrustum()),this._frustum}updateFrustum(){this._frustum||(this._frustum=new c.Frustum),this._frustum.setFromProjectionMatrix(this.getProjectionScreenMatrix(this._projScreenMatrix,!0),this.context.renderer.coordinateSystem)}getProjectionScreenMatrix(e,t){return t&&this._projScreenMatrix.multiplyMatrices(this.threeCamera.projectionMatrix,this.threeCamera.matrixWorldInverse),e===this._projScreenMatrix?e:e.copy(this._projScreenMatrix)}_projScreenMatrix=new c.Matrix4;awake(){h_&&window.addEventListener("pointerdown",e=>{const t=e.clientX,i=e.clientY;console.log("touch",t.toFixed(2),i.toFixed(2));const n=this.screenPointToRay(t,i),o="#"+Math.floor(Math.random()*16777215).toString(16);B.DrawRay(n.origin,n.direction,o,10)})}onEnable(){Is&&console.log(`Camera enabled: "${this.name}". ClearFlags=${No[this._clearFlags]}`,this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),lP(this)),this.applyClearFlagsIfIsActiveCamera({applySkybox:!0})}onDisable(){this.context.removeCamera(this)}onLeaveXR(e){this.fieldOfView=this._fov}onBeforeRender(){if(this._cam&&(this._frustum&&this.updateFrustum(),this._clearFlags===2&&this.applyClearFlagsIfIsActiveCamera(),this._targetTexture)){this.context.isManagedExternally&&(this._warnedAboutExternalRenderer||(this._warnedAboutExternalRenderer=!0,console.warn("Rendering with external renderer is not supported yet. This may not work or throw errors. Please remove the the target texture from your camera: "+this.name,this.targetTexture))),this.context.composer;const e=this.context.renderer;if(e){const t=this.context.mainCameraComponent;this.applyClearFlags(),this._targetTexture.render(this.context.scene,this._cam,e),t?.applyClearFlags()}}}buildCamera(){if(this._cam)return;const e=this.gameObject.isCamera;let t=null;if(e?(t=this.gameObject,t?.layers.enableAll(),t instanceof c.PerspectiveCamera&&(this._fov=t.fov)):t=this.gameObject.children[0],t&&t.isCamera)t instanceof c.PerspectiveCamera&&(this._fov&&(t.fov=this._fov),t.near=this._nearClipPlane,t.far=this._farClipPlane,t.updateProjectionMatrix());else if(!this.orthographic)t=new c.PerspectiveCamera(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),this.fieldOfView&&(t.fov=this.fieldOfView),this.gameObject.add(t);else{const i=this.orthographicSize*100;t=new c.OrthographicCamera(window.innerWidth/-i,window.innerWidth/i,window.innerHeight/i,window.innerHeight/-i,this._nearClipPlane,this._farClipPlane),this.gameObject.add(t)}this._cam=t,this._cam.layers.mask=this._cullingMask,this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(e){this.context.mainCameraComponent===this&&this.applyClearFlags(e)}applyClearFlags(e){if(!this._cam){Is&&console.log("Camera does not exist (apply clear flags)");return}if(this.fieldOfView=this.fieldOfView,Is){const i=`[Camera] Apply ClearFlags: ${No[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(yl.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:Is&&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:Is&&console.warn(`Camera "${this.name}" has no background intensity`);break;case 2:if(this._backgroundColor&&!t){let i=this._backgroundColor.alpha;yl.backgroundShouldBeTransparent(this.context)&&(i=this.ARBackgroundAlpha??0),this.context.scene.background=null,this.context.xr?.isVR?this.context.renderer.setClearColor(xb(this._backgroundColor).convertLinearToSRGB()):this.context.renderer.setClearColor(this._backgroundColor,i)}else this._backgroundColor||Is&&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 aP(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;Is&&Se("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}};Ut([f()],xt.prototype,"aspect",1);Ut([f()],xt.prototype,"fieldOfView",1);Ut([f()],xt.prototype,"nearClipPlane",1);Ut([f()],xt.prototype,"farClipPlane",1);Ut([f()],xt.prototype,"clearFlags",1);Ut([f()],xt.prototype,"orthographic",2);Ut([f()],xt.prototype,"orthographicSize",2);Ut([f()],xt.prototype,"ARBackgroundAlpha",2);Ut([f()],xt.prototype,"cullingMask",1);Ut([f()],xt.prototype,"backgroundBlurriness",1);Ut([f()],xt.prototype,"backgroundIntensity",1);Ut([f(c.Euler)],xt.prototype,"backgroundRotation",1);Ut([f()],xt.prototype,"environmentIntensity",1);Ut([f(Z)],xt.prototype,"backgroundColor",1);Ut([f(Sn)],xt.prototype,"targetTexture",1);let qt=xt;class aP{_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");Is&&console.debug(`[Camera] Apply Skybox ${this._skybox?.name} ${e} - "${this._camera.name}"`),e?.length||(this._skybox.mapping=c.EquirectangularReflectionMapping,this.context.scene.background=this._skybox)}}}function lP(s){w("freecam")&&s.context.mainCameraComponent===s&&S.getOrAddComponent(s.gameObject,de)}class ns extends k{get listener(){return this._listener==null&&(this._listener=new c.AudioListener),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||S.getComponentInParent(this.gameObject,qt);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 cP=Object.defineProperty,hP=Object.getOwnPropertyDescriptor,rn=(s,e,t,i)=>{for(var n=i>1?void 0:i?hP(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&cP(e,t,n),n};const ht=w("debugaudio"),zi=class js extends k{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&&(ht&&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&&js.userInteractionRegistered){let e=this.gameObject.getComponent(ns)??this.context.mainCamera.getComponent(ns)??yc(ns,this.context,!1);!e&&this.context.mainCamera&&(e=this.context.mainCamera.addComponent(ns)),e?.listener?(this.sound=new c.PositionalAudio(e.listener),this.gameObject?.add(this.sound)):ht&&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(){ht&&console.log("[AudioSource]",this),this.audioLoader=new c.AudioLoader,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),js.userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():js.registerWaitForAllowAudio(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.onNewClip(this.clip)}),globalThis.addEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.addEventListener(ap.MuteChanged,this.onApplicationMuteChanged)}onDisable(){globalThis.removeEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.removeEventListener(ap.MuteChanged,this.onApplicationMuteChanged),this.pause()}onVisibilityChanged=()=>{switch(document.visibilityState){case"hidden":(this.playInBackground===!1||exports.DeviceUtilities.isMobileDevice())&&(this.wasPlaying=this.isPlaying,this.isPlaying&&this.pause());break;case"visible":ht&&console.log("visible",this.enabled,this.playOnAwake,!this.isPlaying,js.userInteractionRegistered,this.wasPlaying),this.enabled&&this.playOnAwake&&!this.isPlaying&&js.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){ht&&console.warn("AudioSource destroyed, not creating audio",this.name);return}ht&&console.log("AudioBuffer finished loading",e);const t=this.Sound;if(!t){ht&&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&&js.userInteractionRegistered,this.applySpatialDistanceSettings(),t.isPlaying&&t.stop(),js.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(ht&&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?ht&&!this.helper&&(this.helper=new q.PositionalAudioHelper(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(ht&&console.log(e),e.endsWith(".mp3")||e.endsWith(".wav")){if(this.audioLoader||(this.audioLoader=new c.AudioLoader),this.shouldPlay=!0,this._lastClipStartedLoading===e){ht&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=e,ht&&console.log("load audio",e);const t=await this.audioLoader.loadAsync(e).catch(console.error);if(this.destroyed)return;this._lastClipStartedLoading===e&&(this._lastClipStartedLoading=null),t&&this.createAudio(t)}else console.warn("Unsupported audio clip type",e);else this.shouldPlay=!0,this.createAudio()}play(e=void 0){!e&&this.clip&&(e=this.clip),e!==void 0&&typeof e!="string"&&!(e instanceof MediaStream)&&(A()&&console.warn("Called play on AudioSource with unknown argument type:",e+`
|
|
949
|
+
Could not find method ${r.method} on object ${l.name}`,l,typeof l[r.method])};if(typeof l[r.method]!="function"){let p=!1,m=l;for(;m;){const y=Object.getOwnPropertyDescriptor(m,r.method);if(y&&(y.writable===!0||y.set)){p=!0;break}m=Object.getPrototypeOf(m)}!p&&(A()||st)&&d()}}if(l){let d=r.argument;if(d!==void 0?d=a(d):r.arguments!==void 0&&(d=r.arguments.map(a)),!l[r.method])console.warn(`EventList method not found: "${r.method}" on ${l?.name}`);else{d!==void 0&&!Array.isArray(d)&&(d=[d]);const p=new is(l,r.method,d,r.enabled);i.push(p)}}else A()&&console.warn(`[Dev] EventList: Could not find event listener in scene (${t.object?.name})`,r)}const n=new oe(i);st&&console.log(n);const o=t.target;return o!==void 0&&t.path!==void 0&&n.setEventTarget(t.path,o),n}}}const K1=new Y1,Pd=new WeakMap,Z1=c.Texture.prototype.clone;c.Texture.prototype.clone=function(){const s=Z1.call(this);return Pd.has(s)||Pd.set(s,this),s};class a0 extends Ui{constructor(){super([Sn,c.WebGLRenderTarget])}onSerialize(e,t){}onDeserialize(e,t){if(e instanceof c.Texture&&t.type===Sn){let i=e;Pd.has(i)&&(i=Pd.get(i)),i.isRenderTargetTexture=!0,i.flipY=!0,i.offset.y=1,i.repeat.y=-1,i.needsUpdate=!0,i.mipmaps=[],i instanceof c.CompressedTexture&&(i.isCompressedTexture=!1,i.format=c.RGBAFormat);const n=new Sn(i.image.width,i.image.height,{colorSpace:c.LinearSRGBColorSpace});return n.texture=i,n}}}new a0;class l0 extends Ui{constructor(){super([URL])}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"&&e.length>0)return Js(t.gltfId,e)}}new l0;var J1=Object.defineProperty,eP=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&J1(e,t,n),n};class ma extends k{awake(){jt.createIfNoneExists(this.context)}onEnable(){jt.get(this.context)?.register(this)}onDisable(){jt.get(this.context)?.unregister(this)}}class fi extends ma{targets=null;raycastHits=[];ignoreSkinnedMeshes=!1;start(){this.targets=[this.gameObject]}performRaycast(e=null){if(!this.targets)return null;e??=new io,e.targets=this.targets,e.results=this.raycastHits,e.useAcceleratedRaycast=!0;const t=e.testObject;this.ignoreSkinnedMeshes&&(e.testObject=n=>n instanceof c.SkinnedMesh?"continue in children":t?t(n):!0);const i=this.context.physics.raycast(e);return e.testObject=t,i}}eP([f()],fi.prototype,"ignoreSkinnedMeshes");class su extends fi{constructor(){super(),this.ignoreSkinnedMeshes=!0}}class Qo extends ma{static allow=!0;performRaycast(e){if(!H.active||!Qo.allow||!e?.ray)return null;const t=e.ray.origin;return this.context.physics.sphereOverlap(t,.015,!1,!0)}}class Dm{static getObject(e){const t=e[ri];return t&&(t.isComponent===!0?e=t.gameObject:e=t),e}static isInteractable(e,t){if(t&&(t.canvasGroup=void 0,t.graphic=void 0),e==null||!e.visible||(e=this.getObject(e),!e.visible))return!1;const i=this.tryFindCanvasGroup(e);if(i?.isCanvasGroup===!0&&(t&&(t.canvasGroup=i),i.blocksRaycasts===!1||i.interactable===!1))return!1;const n=qo(e,o=>{if(o.isGraphic===!0)return o},!1);return t&&n?.isGraphic===!0&&(t.graphic=n),!(n?.raycastTarget===!1||n?.layer===2)}static tryFindCanvasGroup(e){if(!e)return null;const t=qo(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 Im(s){const e=s[ri];return e||(s.parent?Im(s.parent):null)}function tP(s){return s.isUI===!0||typeof s[ri]=="object"}function Od(s,e){if(!s)return;const t=s.material;if(t?.isMaterial===!0){const i=s.parent;i&&i.isText,t.side=e.doubleSided??!0?c.DoubleSide:c.FrontSide,t.shadowSide=e.doubleSided?c.DoubleSide:c.FrontSide,s.castShadow=e.castShadows?e.castShadows:!1,s.receiveShadow=e.receiveShadows?e.receiveShadows:!1}for(const i of s.children)Od(i,e)}function Ur(s,e,t){s[e]===void 0&&console.warn("Field",e,"is undefined on",s);const i=Proxy.revocable(s[e],{set(r,a,l,h){const d=r[a],u=Reflect.set(r,a,l,h);return t(l,d),u}}),n=i.revoke,o=s[e];return i.revoke=()=>{s[e]=o,n()},s[e]=i.proxy,i}const c_=Symbol("Scheduled action");function iP(s,e,t=pe.OnBeforeRender){let i=s[c_];i||(i=s[c_]={});const n=e.name;i[t]||(i[t]={});const o=i[t];if(o[n])return;function*a(){e?.call(s),o[n]=null}const l=s.startCoroutine(a(),t);o[n]=l}const Ds=w("debugeventsystem");var kp=(s=>(s.BeforeHandleInput="BeforeHandleInput",s.AfterHandleInput="AfterHandleInput",s))(kp||{});Yv(s=>{jt.createIfNoneExists(s)});class jt extends k{static ensureUpdateMeshUI(e,t,i=!1){Qa.update(e,t,i)}static markUIDirty(e){Qa.markDirty()}static createIfNoneExists(e){e.scene.getComponent(jt)||e.scene.addComponent(jt)}static get(e){return this.createIfNoneExists(e),e.scene.getComponent(jt)}static get instance(){return this.get(F.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(ma)||this.context.scene.addComponent(fi)}onEnable(){this.context.input.addEventListener(we.PointerDown,this.onPointerEvent),this.context.input.addEventListener(we.PointerUp,this.onPointerEvent),this.context.input.addEventListener(we.PointerMove,this.onPointerEvent)}onDisable(){this.context.input.removeEventListener(we.PointerDown,this.onPointerEvent),this.context.input.removeEventListener(we.PointerUp,this.onPointerEvent),this.context.input.removeEventListener(we.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 xc(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==we.PointerDown,t.isUp=e.type==we.PointerUp,t.isPressed=this.context.input.getPointerPressed(e.pointerId);const i=new io;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(Ds&&(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})}Ds&&t.isClick&&Se("EventSystem: "+t.pointerId+" - "+this.context.time.frame+" - Up:"+t.isUp+", Down:"+t.isDown);const o={sender:this,args:t,hasActiveUI:this.currentActiveMeshUIComponents.length>0};this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:o})),this.handleIntersections(n,t),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:o}))};_sortedHits=[];_testObjectsCache=new Map;_currentlyActiveRaycaster=null;_currentPointerEventName=null;shouldRaycastObject=e=>{const t=e&&"getComponent"in e?e.getComponent(ma):null;if(t&&t!=this._currentlyActiveRaycaster)return!1;let i=null;if(tP(e)&&(i=e[ri]?.gameObject),this._testObjectsCache.has(e)||i&&this._testObjectsCache.has(i))return this._testObjectsCache.get(e)===!1?"continue in children":!0;{let o=Cd(e,this._currentPointerEventName);if(!o&&i&&(o=Cd(i,this._currentPointerEventName)),o){this._testObjectsCache.set(e,!0);for(const r of e.children)this.shouldRaycastObject_AddToYesCache(r);return!0}return this._testObjectsCache.set(e,!1),"continue in children"}};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&&Ds&&console.log("not allowed",e),!1;if(t.pointerId===void 0)return Ds&&console.error("Event without pointer can't be handled",t),!1;t.object=e;const i=e.parent,n=t.isClick??!1;let o=null;if(i&&i.isUI){const d=(t.isPressed||t.isClick)??!1;if(i[ri]){const u=i[ri].gameObject;if(u){if(!Dm.isInteractable(u,this.out))return!1;o=this.out.canvasGroup??null,this.handleMeshUIIntersection(e,d),e=u}}}n&&Ds&&console.log(this.context.time.frame,e);const r=this.hoveredByID.get(t.pointerId),a=r?.obj;a!==e&&a&&this.propagatePointerExit(a,r.data,e);const h=this.hoveredByID.get(t.pointerId);if(h?(h.obj=e,h.data=t):this.hoveredByID.set(t.pointerId,{obj:e,data:t}),t.isDown){const d=this.pressedByID.get(t.pointerId);d?(d.obj=e,d.data=t):this.pressedByID.set(t.pointerId,{obj:e,data:t,handlers:new Set})}return(o===null||o.interactable)&&this.handleMainInteraction(e,t,a??null),!0}propagate(e,t){for(;e;)S.foreachComponent(e,i=>{t(i)},!1),e=e.parent}handleMainInteraction(e,t,i){const n=this.pressedByID.get(t.pointerId),o=i!==e;let r=!0;switch(t.event.pointerType){case"mouse":case"touch":const a=this.context.input.getPointerPositionLastFrame(t.pointerId),l=this.context.input.getPointerPosition(t.pointerId);r=a&&!D.approximately(a,l);break}this.propagate(e,a=>{const l=a;l.interactable!==!1&&(!l.activeAndEnabled||!l.enabled||(l.onPointerEnter&&o&&this.handlePointerEnter(l,t),t.isDown&&l.onPointerDown&&(l.onPointerDown(t),n?.handlers.add(l),this.handlePointerCapture(t,l)),l.onPointerMove&&(r&&l.onPointerMove(t),this.handlePointerCapture(t,l)),t.isUp&&(l.onPointerUp&&(this.invokeOnPointerUp(t,l),n?.handlers.delete(l)),l.onPointerExit&&t.event?.pointerType===Gd.Touch&&(this.handlePointerExit(l,t),this.hoveredByID.delete(t.pointerId))),t.isClick&&l.onPointerClick&&l.onPointerClick(t)))}),t.isUp&&(n?.handlers.forEach(a=>{this.invokeOnPointerUp(t,a)}),this.pressedByID.delete(t.pointerId))}propagatePointerExit(e,t,i){this.propagate(e,n=>{if(!n.gameObject||n.destroyed)return;const o=n;if(o.onPointerExit||o.onPointerEnter){if(i&&this.isChild(i,n.gameObject))return;this.handlePointerExit(o,t)}})}invokeOnPointerUp(e,t){t.onPointerUp?.call(t,e),this.releasePointerCapture(e,t)}handlePointerEnter(e,t){e.onPointerEnter&&this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!0)&&e.onPointerEnter(t),this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!1)}handlePointerExit(e,t){e.onPointerExit&&this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!0)&&e.onPointerExit(t),this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!1)}updatePointerState(e,t,i,n){let o=e[i];if(n)return o&&o.includes(t)?!1:(o=o||[],o.push(t),e[i]=o,!0);{if(!o||!o.includes(t))return!1;const r=o.indexOf(t);return r!==-1&&o.splice(r,1),!0}}_capturedPointer={};handlePointerCapture(e,t){if(e.z__pointer_ctured){e.z__pointer_ctured=!1;const i=e.pointerId;if(t.onPointerMove){const n=this._capturedPointer[i]||[];n.push(t),this._capturedPointer[i]=n}else A()&&!t.z__warned_no_pointermove&&(t.z__warned_no_pointermove=!0,console.warn("PointerCapture was requested but the component doesn't implement onPointerMove. It will not receive any pointer events"))}else e.z__pointer_cture_rleased&&(e.z__pointer_cture_rleased=!1,this.releasePointerCapture(e,t))}releasePointerCapture(e,t){const i=e.pointerId;if(this._capturedPointer[i]){const n=this._capturedPointer[i].indexOf(t);n!==-1&&(this._capturedPointer[i].splice(n,1),Ds&&console.log("released pointer capture",i,t,this._capturedPointer))}}invokePointerCapture(e){if(e.event.type===we.PointerMove){const t=e.pointerId,i=this._capturedPointer[t];if(i){Ds&&console.log("Captured",t,i);for(let n=0;n<i.length;n++){const o=i[n];if(o.destroyed){i.splice(n,1),n--;continue}o.onPointerMove?.call(o,e)}}}}pointerEnterSymbol=Symbol("pointerEnter");pointerExitSymbol=Symbol("pointerExit");isChild(e,t){return!e||!t?!1:e===t?!0:e.parent?this.isChild(e.parent,t):!1}handleMeshUiObjectWithoutShadowDom(e,t){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,t)}currentActiveMeshUIComponents=[];handleMeshUIIntersection(e,t){const i=Qa.updateState(e,t);return i&&this.currentActiveMeshUIComponents.push(i),i!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&Qa.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){const t=this.currentActiveMeshUIComponents[e];Qa.resetState(t)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?S.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}}class Qa{static lastSelected=null;static lastUpdateFrame=[];static needsUpdate=!1;static markDirty(){this.needsUpdate=!0}static update(e,t,i=!1){if(i){e.update();return}const n=t.time.frameCount;for(const o of this.lastUpdateFrame)if(o.context===t){if(n===o.frame)return;o.frame=n;let r=this.needsUpdate||n<1;o.nextUpdate<=n&&(r=!0),r&&(Ds&&console.log("Update threemeshui"),this.needsUpdate=!1,o.nextUpdate=n+60,e.update());return}this.lastUpdateFrame=[{context:t,frame:n,nextUpdate:n+60}],e.update(),this.needsUpdate=!1}static updateState(e,t){let i=null;if(e&&(i=this.findBlockOrTextInParent(e),i&&i!==this.lastSelected)){if(i.interactable===!1)return null;this.needsUpdate=!0}return i}static resetLastSelected(){const e=this.lastSelected;e&&(this.lastSelected=null,this.resetState(e))}static resetState(e){e&&(this.needsUpdate=!0)}static findBlockOrTextInParent(e){return e?e.isBlock||e.isText?e:this.findBlockOrTextInParent(e.parent):null}}var nP=Object.defineProperty,Ce=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&nP(e,t,n),n};const kt=w("debugorbit"),gf=w("freecam"),Ya=w("debugcamerafit"),xh=w("smoothcam"),sP={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let yf;class Kl extends CustomEvent{constructor(e,t){super("target-reached",{detail:{controls:e,type:t}})}}class de extends k{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 c.Vector3;_lookTargetEndPosition=new c.Vector3;_lookTargetLerp01=0;_lookTargetLerpDuration=0;_cameraLerpActive=!1;_cameraStartPosition=new c.Vector3;_cameraEndPosition=new c.Vector3;_cameraLerp01=0;_cameraLerpDuration=0;_fovLerpActive=!1;_fovLerpStartValue=0;_fovLerpEndValue=0;_fovLerp01=0;_fovLerpDuration=0;_inputs=0;_enableTime=0;_startedListeningToKeyEvents=!1;_eventSystem;_afterHandleInputFn;_camera=null;_syncedTransform;_didSetTarget=0;awake(){kt&&console.debug("OrbitControls",this),this._didSetTarget=0,this._startedListeningToKeyEvents=!1}start(){this._eventSystem=jt.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(kp.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){this._controls?.dispose(),this._eventSystem?.removeEventListener(kp.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._didSetTarget=0,this._enableTime=this.context.time.time;const e=S.getComponent(this.gameObject,qt);this._camera=e;let t=e?.threeCamera;if(!t&&this.gameObject instanceof c.PerspectiveCamera&&(t=this.gameObject),t&&np(t,this,!0),!this._controls&&t instanceof c.Object3D){this._cameraObject=t;const i=this.targetElement??this.context.renderer.domElement,n=t?.quaternion.clone();this._controls=new q.OrbitControls(t,i),t?.quaternion.copy(n),yf===void 0&&(yf={...this._controls.keys});const o=X(t),r=this.gameObject.worldForward,l=o.clone().sub(r.multiplyScalar(2.5));this._controls.target.copy(l)}if(this._controls)if(gf&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,exports.DeviceUtilities.isMobileDevice()&&(this.doubleClickToFocus=!0)),this._controls.addEventListener("start",this.onControlsChangeStarted),this._controls.addEventListener("endMovement",this.onControlsChangeEnded),!this._startedListeningToKeyEvents&&this.enableKeys)this._startedListeningToKeyEvents=!0,this._controls.listenToKeyEvents(this.context.domElement);else try{this._controls.stopListenToKeyEvents()}catch{}this._syncedTransform=S.getComponent(this.gameObject,nn)??void 0,this.context.pre_render_callbacks.push(this.__onPreRender),this._activePointerEvents=[],this.context.input.addEventListener("pointerdown",this._onPointerDown,{queue:Ht.Early}),this.context.input.addEventListener("pointerdown",this._onPointerDownLate,{queue:Ht.Late}),this.context.input.addEventListener("pointerup",this._onPointerUp,{queue:Ht.Early}),this.context.input.addEventListener("pointerup",this._onPointerUpLate,{queue:Ht.Late})}onDisable(){if(this._camera?.threeCamera&&np(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}kt&&console.log(this.clickBackgroundToFitScene,e.intersections.length,this._clickOnBackgroundCount)}};_onPointerUpLate=e=>{this.doubleClickToFocus&&e.isDoubleClick&&!e.used&&this.setTargetFromRaycast()};updateTargetNow(e){const t=new c.Ray(this._cameraObject?.worldPosition,this._cameraObject?.worldForward.multiplyScalar(-1)),i=this.context.physics.raycastFromRay(t,e),n=i.length>0?i[0]:void 0;n&&n.distance>this.minZoom&&n.distance<this.maxZoom?(kt&&B.DrawWireSphere(n.point,.1,16711680,2),this._controls?.target.copy(i[0].point)):kt&&console.log("OrbitControls: No hit found when updating target",{hits:[...i]})}_orbitStartAngle=0;_zoomStartDistance=0;onControlsChangeStarted=()=>{kt&&console.debug("OrbitControls: Change started"),this._controls&&(this._orbitStartAngle=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle(),this._zoomStartDistance=this._controls.getDistance()),this._syncedTransform&&this._syncedTransform.requestOwnership()};onControlsChangeEnded=()=>{if(kt&&console.debug("OrbitControls: Change ended",{autoTarget:this.autoTarget}),this._controls&&this.autoTarget){const t=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle()-this._orbitStartAngle;Math.abs(t)<.01?(kt&&console.debug("OrbitControls: Update target",{deltaAngle:t}),this.updateTargetNow({allowSlowRaycastFallback:!1})):kt&&console.debug("OrbitControls: No target update",{deltaAngle:t})}};_shouldDisable=!1;afterHandleInput(e){e.detail.args.pointerId===0&&(e.detail.args.isDown?this._controls&&this._eventSystem&&(this._shouldDisable=this._eventSystem.hasActiveUI):(!e.detail.args.isPressed||e.detail.args.isUp)&&(this._shouldDisable=!1))}onPausedChanged(e){this._controls&&e&&(this._controls.enabled=!1)}onBeforeRender(){if(!this._controls)return;if(this._cameraObject!==this.context.mainCamera){this._controls.enabled=!1;return}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 t=S.getComponent(this.gameObject,qt);if(t&&!this.setLookTargetFromConstraint()){this.debugLog&&console.log("NO TARGET");const i=X(t.threeCamera),n=Math.max(.01,i.length()),o=new c.Vector3(0,0,-n).applyMatrix4(t.threeCamera.matrixWorld);kt&&B.DrawLine(i,o,5592575,10),this.setLookTargetPosition(o,!0)}if(!this.setLookTargetFromConstraint()){const i=new io;i.screenPoint=new c.Vector2(0,0),i.lineThreshold=.1;const n=this.context.physics.raycast(i);n.length>0&&this.setLookTargetPosition(n[0].point,!0),Ya&&console.log("OrbitControls hits",...n)}}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 Kl(this,"camera"));else{const t=D.easeInOutCubic(this._cameraLerp01);this._cameraObject.position.lerpVectors(this._cameraStartPosition,this._cameraEndPosition,t)}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 Kl(this,"lookat"));else{const t=D.easeInOutCubic(this._lookTargetLerp01);this.lerpLookTarget(this._lookTargetStartPosition,this._lookTargetEndPosition,t)}if(this._fovLerpActive&&this._cameraObject){const t=this._cameraObject;if(this._fovLerp01+=this.context.time.deltaTime/this._fovLerpDuration,this._fovLerp01>=1)t.fov=this._fovLerpEndValue,this._fovLerpActive=!1;else{const i=D.easeInOutCubic(this._fovLerp01);t.fov=D.lerp(this._fovLerpStartValue,this._fovLerpEndValue,i)}t.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(t=>t.used),this._controls.keys=this.enableKeys?yf:sP,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,gf||(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 xh=="number"||xh===!0){this._controls.enableDamping=!0;const t=typeof xh=="number"?xh:.99;this._controls.dampingFactor=Math.max(.001,1-Math.min(1,t))}this.allowInterrupt||(this._lookTargetLerpActive&&(this._controls.enablePan=!1),this._cameraLerpActive&&(this._controls.enableRotate=!1,this._controls.autoRotate=!1),(this._lookTargetLerpActive||this._cameraLerpActive)&&(this._controls.enableZoom=!1)),this.context.isInXR||(!gf&&this.lookAtConstraint?.locked&&!this._lookTargetLerpActive&&this.setLookTargetFromConstraint(0,this.lookAtConstraint01),this._controls.update(this.context.time.deltaTime),kt&&B.DrawWireSphere(this._controls.target,.1,65280))}}__onPreRender=()=>{const e=this.context.pre_render_callbacks.indexOf(this.__onPreRender);e>=0&&this.context.pre_render_callbacks.splice(e,1),this.autoFit&&(this.autoFit=!1,this.fitCamera({centerCamera:"y",immediate:!0,objects:this.scene.children}))};setCameraAndLookTarget(e,t=!1){if(!e)return(A()||kt)&&console.warn("[OrbitControls] setCameraAndLookTarget target is null"),!1;if(!(e instanceof c.Object3D)&&!(e instanceof qt))return(A()||kt)&&console.warn("[OrbitControls] setCameraAndLookTarget target is not an Object3D or Camera"),!1;e instanceof qt&&(e=e.gameObject);const i=e.worldPosition,n=e.worldForward;e instanceof c.Camera&&(kt&&console.debug("[OrbitControls] setCameraAndLookTarget flip forward direction for camera"),n.multiplyScalar(-1));const o=new c.Ray(i,n);return kt&&B.DrawRay(o.origin,o.direction,16711680,10),this.setTargetFromRaycast(o,t)||this.setLookTargetPosition(o.at(2,V()),t),this.setCameraTargetPosition(i,t),!0}setCameraTargetPosition(e,t=!1){e&&(e instanceof c.Object3D&&(e=X(e)),this._cameraEndPosition||(this._cameraEndPosition=new c.Vector3),this._cameraEndPosition.copy(e),t===!0?(this._cameraLerpActive=!1,this._cameraObject&&this._cameraObject.position.copy(this._cameraEndPosition)):this._cameraObject&&(this._cameraLerpActive=!0,this._cameraLerp01=0,this._cameraStartPosition.copy(this._cameraObject?.position),typeof t=="number"?this._cameraLerpDuration=t:this._cameraLerpDuration=this.targetLerpDuration))}get cameraLerpActive(){return this._cameraLerpActive}stopCameraLerp(){this._cameraLerpActive=!1}setFieldOfView(e,t=!1){if(!this._controls||typeof e!="number")return;const i=this._camera?.threeCamera;i&&(t===!0?i.fov=e:(this._fovLerpActive=!0,this._fovLerp01=0,this._fovLerpStartValue=i.fov,this._fovLerpEndValue=e,typeof t=="number"?this._fovLerpDuration=t:this._fovLerpDuration=this.targetLerpDuration))}setLookTargetPosition(e=null,t=!1){this._controls&&e&&(e instanceof c.Object3D&&(e=X(e)),this._lookTargetEndPosition.copy(e),this._didSetTarget++,kt&&(console.warn("OrbitControls: setLookTargetPosition",e,t),B.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&&S.isActiveInHierarchy(n.object)){const o=Im(n.object);if(o&&o.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 c.Object3D)&&!Array.isArray(e)&&(t=e,i=t.objects),i&&!Array.isArray(i)&&(i=[i]),(!Array.isArray(i)||i&&i.length<=0)&&(i=this.context.scene.children),!Array.isArray(i)||i.length<=0){console.warn("No objects to fit camera to...");return}const n=this._cameraObject,o=this._controls;if(!n||!o){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:h=1.1,fov:d=n?.fov}=t,u=new c.Vector3,p=new c.Vector3,m=Bt(i,void 0,this._camera?.threeCamera?.layers),y=m.clone();m.getCenter(p);const b=new c.Vector3;if(m.getSize(b),n.updateMatrixWorld(),m.applyMatrix4(n.matrixWorldInverse),m.getSize(u),m.setFromCenterAndSize(p,u),Number.isNaN(u.x)||Number.isNaN(u.y)||Number.isNaN(u.z)){console.warn("Camera fit size resultet in NaN",n,m,[...i]);return}if(u.length()<=1e-10){Ya&&console.warn("Camera fit size is zero",m,[...i]);return}const g=d,v=2*Math.atan(Math.tan(g*Math.PI/360/2)*n.aspect)/Math.PI*360,_=u.y/(2*Math.atan(Math.PI*g/360)),x=u.x/(2*Math.atan(Math.PI*v/360)),T=h*Math.max(_,x)+u.z/2;Ya&&console.log("Fit camera to objects",{fitHeightDistance:_,fitWidthDistance:x,distance:T,verticalFov:g,horizontalFov:v}),this.maxZoom=T*10,this.minZoom=T*.01;const O=.05,M=p.clone();if(M.y-=u.y*O,t.targetOffset&&(t.targetOffset.x!==void 0&&(M.x+=t.targetOffset.x),t.targetOffset.y!==void 0&&(M.y+=t.targetOffset.y),t.targetOffset.z!==void 0&&(M.z+=t.targetOffset.z)),t.relativeTargetOffset&&(t.relativeTargetOffset.x!==void 0&&(M.x+=t.relativeTargetOffset.x*u.x),t.relativeTargetOffset.y!==void 0&&(M.y+=t.relativeTargetOffset.y*u.y),t.relativeTargetOffset.z!==void 0&&(M.z+=t.relativeTargetOffset.z*u.z)),this.setLookTargetPosition(M,r),this.setFieldOfView(t.fov,r),l==null||l=="auto"){const z=S.findObjectOfType(In),$=z?z.radius:0,R=Math.max(b.x,b.y,b.z,$);n.near=T/100,n.far=R+T*10,n.updateProjectionMatrix(),z&&(this.maxZoom=Math.max(Math.min(this.maxZoom,$*.5),T))}const E=o.getDistance();E<this.minZoom&&(this.minZoom=E*.9),E>this.maxZoom&&(this.maxZoom=E*1.1);const j=p.clone();t.fitDirection?j.sub(new c.Vector3().copy(t.fitDirection).multiplyScalar(1e6)):j.sub(n.worldPosition),a==="y"&&(j.y=0),j.normalize(),j.multiplyScalar(T),a==="y"&&(j.y+=-O*4*T);let L=p.clone().sub(j);t.cameraOffset&&(t.cameraOffset.x!==void 0&&(L.x+=t.cameraOffset.x),t.cameraOffset.y!==void 0&&(L.y+=t.cameraOffset.y),t.cameraOffset.z!==void 0&&(L.z+=t.cameraOffset.z)),t.relativeCameraOffset&&(t.relativeCameraOffset.x!==void 0&&(L.x+=t.relativeCameraOffset.x*u.x),t.relativeCameraOffset.y!==void 0&&(L.y+=t.relativeCameraOffset.y*u.y),t.relativeCameraOffset.z!==void 0&&(L.z+=t.relativeCameraOffset.z*u.z)),n.parent&&(L=n.parent.worldToLocal(L)),this.setCameraTargetPosition(L,r),(Ya||t.debug)&&(B.DrawWireBox3(m,16777011,10),B.DrawWireBox3(y,65280,10),!this._haveAttachedKeyboardEvents&&Ya&&(this._haveAttachedKeyboardEvents=!0,document.body.addEventListener("keydown",z=>{if(z.code==="KeyF"){let $;this._cameraObject instanceof c.PerspectiveCamera&&($=Math.random()*Math.random()*170+10),this.fitCamera({objects:i,fitOffset:h,immediate:!1,fov:$})}z.code==="KeyV"&&this._cameraObject instanceof c.PerspectiveCamera&&(this._cameraObject.fov=60)}))),this.onBeforeRender()}_haveAttachedKeyboardEvents=!1}Ce([f()],de.prototype,"autoTarget");Ce([f()],de.prototype,"autoFit");Ce([f()],de.prototype,"enableRotate");Ce([f()],de.prototype,"autoRotate");Ce([f()],de.prototype,"autoRotateSpeed");Ce([f()],de.prototype,"minAzimuthAngle");Ce([f()],de.prototype,"maxAzimuthAngle");Ce([f()],de.prototype,"minPolarAngle");Ce([f()],de.prototype,"maxPolarAngle");Ce([f()],de.prototype,"enableKeys");Ce([f()],de.prototype,"enableDamping");Ce([f()],de.prototype,"dampingFactor");Ce([f()],de.prototype,"enableZoom");Ce([f()],de.prototype,"minZoom");Ce([f()],de.prototype,"maxZoom");Ce([f()],de.prototype,"zoomSpeed");Ce([f()],de.prototype,"enablePan");Ce([f(rr)],de.prototype,"lookAtConstraint");Ce([f()],de.prototype,"lookAtConstraint01");Ce([f()],de.prototype,"allowInterrupt");Ce([f()],de.prototype,"middleClickToFocus");Ce([f()],de.prototype,"doubleClickToFocus");Ce([f()],de.prototype,"clickBackgroundToFitScene");Ce([f()],de.prototype,"targetLerpDuration");var oP=Object.defineProperty,rP=Object.getOwnPropertyDescriptor,Ut=(s,e,t,i)=>{for(var n=i>1?void 0:i?rP(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&oP(e,t,n),n},No=(s=>(s[s.None=0]="None",s[s.Skybox=1]="Skybox",s[s.SolidColor=2]="SolidColor",s[s.Uninitialized=4]="Uninitialized",s))(No||{});const Is=w("debugcam"),h_=w("debugscreenpointtoray"),xt=class yl extends k{get isCamera(){return!0}get aspect(){return this._cam instanceof c.PerspectiveCamera?this._cam.aspect:this.context.domWidth/this.context.domHeight}set aspect(e){this._cam instanceof c.PerspectiveCamera&&this._cam.aspect!==e&&(this._cam.aspect=e,this._cam.updateProjectionMatrix())}get fieldOfView(){return this._cam instanceof c.PerspectiveCamera?this._cam.fov:this._fov}set fieldOfView(e){const t=this.fieldOfView!=e;if(this._fov=e,t&&this._cam&&this._cam instanceof c.PerspectiveCamera){if(this._fov===void 0){console.warn("Can not set undefined fov on PerspectiveCamera");return}this._cam.fov=this._fov,this._cam.updateProjectionMatrix()}}get nearClipPlane(){return this._nearClipPlane}set nearClipPlane(e){const t=this._nearClipPlane!=e;this._nearClipPlane=e,this._cam&&(t||this._cam.near!=e)&&(this._cam.near=e,this._cam.updateProjectionMatrix())}_nearClipPlane=.1;get farClipPlane(){return this._farClipPlane}set farClipPlane(e){const t=this._farClipPlane!=e;this._farClipPlane=e,this._cam&&(t||this._cam.far!=e)&&(this._cam.far=e,this._cam.updateProjectionMatrix())}_farClipPlane=1e3;applyClippingPlane(){this._cam&&(this._cam.near=this._nearClipPlane,this._cam.far=this._farClipPlane,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(e){if(typeof e=="string")switch(e){case"skybox":e=1;break;case"solidcolor":e=2;break;default:e=0;break}e!==this._clearFlags&&(this._clearFlags=e,this.applyClearFlagsIfIsActiveCamera())}orthographic=!1;orthographicSize=5;ARBackgroundAlpha=0;set cullingMask(e){this._cullingMask=e,this._cam&&(this._cam.layers.mask=e)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}_cullingMask=4294967295;set cullingLayer(e){this.cullingMask=(1<<e|0)>>>0}set backgroundBlurriness(e){e!==this._backgroundBlurriness&&(e===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(e,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}_backgroundBlurriness=void 0;set backgroundIntensity(e){e!==this._backgroundIntensity&&(e===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(e,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}_backgroundIntensity=void 0;set backgroundRotation(e){e!==this._backgroundRotation&&(e===void 0?this._backgroundRotation=void 0:this._backgroundRotation=e,this.applyClearFlagsIfIsActiveCamera())}get backgroundRotation(){return this._backgroundRotation}_backgroundRotation=void 0;set environmentIntensity(e){this._environmentIntensity=e}get environmentIntensity(){return this._environmentIntensity}_environmentIntensity=void 0;get backgroundColor(){return this._backgroundColor??null}set backgroundColor(e){e&&(this._backgroundColor||(this._backgroundColor=new Z(1,1,1,1)),this._backgroundColor.copy(e),(!("alpha"in e)||e.alpha===void 0)&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera())}set targetTexture(e){this._targetTexture=e}get targetTexture(){return this._targetTexture}_targetTexture=null;_backgroundColor;_fov;_cam=null;_clearFlags=2;_skybox;get cam(){return this.threeCamera}get threeCamera(){return this.activeAndEnabled&&this.buildCamera(),this._cam}static _origin=new c.Vector3;static _direction=new c.Vector3;screenPointToRay(e,t,i){const n=this.threeCamera,o=yl._origin;o.set(e,t,-1),this.context.input.convertScreenspaceToRaycastSpace(o),h_&&console.log("screenPointToRay",e.toFixed(2),t.toFixed(2),"now:",o.x.toFixed(2),o.y.toFixed(2),"isInXR:"+this.context.isInXR),o.z=-1,o.unproject(n);const r=yl._direction.set(o.x,o.y,o.z),a=X(n);return r.sub(a),r.normalize(),i?(i.set(a,r),i):new c.Ray(a.clone(),r.clone())}_frustum;getFrustum(){return this._frustum||(this._frustum=new c.Frustum,this.updateFrustum()),this._frustum}updateFrustum(){this._frustum||(this._frustum=new c.Frustum),this._frustum.setFromProjectionMatrix(this.getProjectionScreenMatrix(this._projScreenMatrix,!0),this.context.renderer.coordinateSystem)}getProjectionScreenMatrix(e,t){return t&&this._projScreenMatrix.multiplyMatrices(this.threeCamera.projectionMatrix,this.threeCamera.matrixWorldInverse),e===this._projScreenMatrix?e:e.copy(this._projScreenMatrix)}_projScreenMatrix=new c.Matrix4;awake(){h_&&window.addEventListener("pointerdown",e=>{const t=e.clientX,i=e.clientY;console.log("touch",t.toFixed(2),i.toFixed(2));const n=this.screenPointToRay(t,i),o="#"+Math.floor(Math.random()*16777215).toString(16);B.DrawRay(n.origin,n.direction,o,10)})}onEnable(){Is&&console.log(`Camera enabled: "${this.name}". ClearFlags=${No[this._clearFlags]}`,this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),lP(this)),this.applyClearFlagsIfIsActiveCamera({applySkybox:!0})}onDisable(){this.context.removeCamera(this)}onLeaveXR(e){this.fieldOfView=this._fov}onBeforeRender(){if(this._cam&&(this._frustum&&this.updateFrustum(),this._clearFlags===2&&this.applyClearFlagsIfIsActiveCamera(),this._targetTexture)){this.context.isManagedExternally&&(this._warnedAboutExternalRenderer||(this._warnedAboutExternalRenderer=!0,console.warn("Rendering with external renderer is not supported yet. This may not work or throw errors. Please remove the the target texture from your camera: "+this.name,this.targetTexture))),this.context.composer;const e=this.context.renderer;if(e){const t=this.context.mainCameraComponent;this.applyClearFlags(),this._targetTexture.render(this.context.scene,this._cam,e),t?.applyClearFlags()}}}buildCamera(){if(this._cam)return;const e=this.gameObject.isCamera;let t=null;if(e?(t=this.gameObject,t?.layers.enableAll(),t instanceof c.PerspectiveCamera&&(this._fov=t.fov)):t=this.gameObject.children[0],t&&t.isCamera)t instanceof c.PerspectiveCamera&&(this._fov&&(t.fov=this._fov),t.near=this._nearClipPlane,t.far=this._farClipPlane,t.updateProjectionMatrix());else if(!this.orthographic)t=new c.PerspectiveCamera(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),this.fieldOfView&&(t.fov=this.fieldOfView),this.gameObject.add(t);else{const i=this.orthographicSize*100;t=new c.OrthographicCamera(window.innerWidth/-i,window.innerWidth/i,window.innerHeight/i,window.innerHeight/-i,this._nearClipPlane,this._farClipPlane),this.gameObject.add(t)}this._cam=t,this._cam.layers.mask=this._cullingMask,this.tag=="MainCamera"&&this.context.setCurrentCamera(this)}applyClearFlagsIfIsActiveCamera(e){this.context.mainCameraComponent===this&&this.applyClearFlags(e)}applyClearFlags(e){if(!this._cam){Is&&console.log("Camera does not exist (apply clear flags)");return}if(this.fieldOfView=this.fieldOfView,Is){const i=`[Camera] Apply ClearFlags: ${No[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(yl.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:Is&&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:Is&&console.warn(`Camera "${this.name}" has no background intensity`);break;case 2:if(this._backgroundColor&&!t){let i=this._backgroundColor.alpha;yl.backgroundShouldBeTransparent(this.context)&&(i=this.ARBackgroundAlpha??0),this.context.scene.background=null,this.context.xr?.isVR?this.context.renderer.setClearColor(xb(this._backgroundColor).convertLinearToSRGB()):this.context.renderer.setClearColor(this._backgroundColor,i)}else this._backgroundColor||Is&&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 aP(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;Is&&Se("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}};Ut([f()],xt.prototype,"aspect",1);Ut([f()],xt.prototype,"fieldOfView",1);Ut([f()],xt.prototype,"nearClipPlane",1);Ut([f()],xt.prototype,"farClipPlane",1);Ut([f()],xt.prototype,"clearFlags",1);Ut([f()],xt.prototype,"orthographic",2);Ut([f()],xt.prototype,"orthographicSize",2);Ut([f()],xt.prototype,"ARBackgroundAlpha",2);Ut([f()],xt.prototype,"cullingMask",1);Ut([f()],xt.prototype,"backgroundBlurriness",1);Ut([f()],xt.prototype,"backgroundIntensity",1);Ut([f(c.Euler)],xt.prototype,"backgroundRotation",1);Ut([f()],xt.prototype,"environmentIntensity",1);Ut([f(Z)],xt.prototype,"backgroundColor",1);Ut([f(Sn)],xt.prototype,"targetTexture",1);let qt=xt;class aP{_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");Is&&console.debug(`[Camera] Apply Skybox ${this._skybox?.name} ${e} - "${this._camera.name}"`),e?.length||(this._skybox.mapping=c.EquirectangularReflectionMapping,this.context.scene.background=this._skybox)}}}function lP(s){w("freecam")&&s.context.mainCameraComponent===s&&S.getOrAddComponent(s.gameObject,de)}class ns extends k{get listener(){return this._listener==null&&(this._listener=new c.AudioListener),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||S.getComponentInParent(this.gameObject,qt);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 cP=Object.defineProperty,hP=Object.getOwnPropertyDescriptor,rn=(s,e,t,i)=>{for(var n=i>1?void 0:i?hP(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&cP(e,t,n),n};const ht=w("debugaudio"),zi=class js extends k{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&&(ht&&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&&js.userInteractionRegistered){let e=this.gameObject.getComponent(ns)??this.context.mainCamera.getComponent(ns)??yc(ns,this.context,!1);!e&&this.context.mainCamera&&(e=this.context.mainCamera.addComponent(ns)),e?.listener?(this.sound=new c.PositionalAudio(e.listener),this.gameObject?.add(this.sound)):ht&&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(){ht&&console.log("[AudioSource]",this),this.audioLoader=new c.AudioLoader,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),js.userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():js.registerWaitForAllowAudio(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.onNewClip(this.clip)}),globalThis.addEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.addEventListener(ap.MuteChanged,this.onApplicationMuteChanged)}onDisable(){globalThis.removeEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.removeEventListener(ap.MuteChanged,this.onApplicationMuteChanged),this.pause()}onVisibilityChanged=()=>{switch(document.visibilityState){case"hidden":(this.playInBackground===!1||exports.DeviceUtilities.isMobileDevice())&&(this.wasPlaying=this.isPlaying,this.isPlaying&&this.pause());break;case"visible":ht&&console.log("visible",this.enabled,this.playOnAwake,!this.isPlaying,js.userInteractionRegistered,this.wasPlaying),this.enabled&&this.playOnAwake&&!this.isPlaying&&js.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){ht&&console.warn("AudioSource destroyed, not creating audio",this.name);return}ht&&console.log("AudioBuffer finished loading",e);const t=this.Sound;if(!t){ht&&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&&js.userInteractionRegistered,this.applySpatialDistanceSettings(),t.isPlaying&&t.stop(),js.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(ht&&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?ht&&!this.helper&&(this.helper=new q.PositionalAudioHelper(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(ht&&console.log(e),e.endsWith(".mp3")||e.endsWith(".wav")){if(this.audioLoader||(this.audioLoader=new c.AudioLoader),this.shouldPlay=!0,this._lastClipStartedLoading===e){ht&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=e,ht&&console.log("load audio",e);const t=await this.audioLoader.loadAsync(e).catch(console.error);if(this.destroyed)return;this._lastClipStartedLoading===e&&(this._lastClipStartedLoading=null),t&&this.createAudio(t)}else console.warn("Unsupported audio clip type",e);else this.shouldPlay=!0,this.createAudio()}play(e=void 0){!e&&this.clip&&(e=this.clip),e!==void 0&&typeof e!="string"&&!(e instanceof MediaStream)&&(A()&&console.warn("Called play on AudioSource with unknown argument type:",e+`
|
|
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,ht&&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(){ht&&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(){ht&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.source&&(this._lastContextTime=this.sound?.context.currentTime,ht&&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,ht&&console.log("Audio clip ended",this.clip),this.dispatchEvent(new CustomEvent("ended",{detail:this})))}};rn([f(URL)],zi.prototype,"clip",2);rn([f()],zi.prototype,"playOnAwake",2);rn([f()],zi.prototype,"preload",2);rn([f()],zi.prototype,"playInBackground",2);rn([f()],zi.prototype,"loop",1);rn([f()],zi.prototype,"spatialBlend",1);rn([f()],zi.prototype,"minDistance",1);rn([f()],zi.prototype,"maxDistance",1);rn([f()],zi.prototype,"volume",1);rn([f()],zi.prototype,"pitch",1);rn([f()],zi.prototype,"rollOffMode",2);let pi=zi;const dP=w("debugavatar");class xe extends k{static getAvatar(e){return e>=0&&e<xe.instances.length?xe.instances[e]:null}static instances=[];static onAvatarMarkerCreated(e){return xe._onNewAvatarMarkerAdded.push(e),e}static onAvatarMarkerDestroyed(e){return xe._onAvatarMarkerDestroyed.push(e),e}static _onNewAvatarMarkerAdded=[];static _onAvatarMarkerDestroyed=[];connectionId;avatar;awake(){xe.instances.push(this),dP&&console.log(this);for(const e of xe._onNewAvatarMarkerAdded)e({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){xe.instances.splice(xe.instances.indexOf(this),1);for(const e of xe._onAvatarMarkerDestroyed)e({avatarMarker:this,gameObject:this.gameObject})}isLocalAvatar(){return this.connectionId===this.context.connection.connectionId}}class Vo{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??F.Current?.time.time;return}}}}class uP{guid;position=new c.Vector3}class Zl extends k{set controlledTarget(e){this.target=e;const t=P.get("MoveRandom");if(t&&this.target){const i=S.getComponent(this.target,t);i&&i.destroy()}}target=null;avatar=null;_model=null;_targetModel=new uP;_currentTargetObject=null;_lastUpdateTime=0;_lookDuration=0;_lastPoiChangedTime=0;awake(){if(this.avatar=S.getComponentInParent(this.gameObject,xe),this.avatar){const e=S.getComponentInParent(this.gameObject,xe);this._model=new mm(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&&ot(this.target,e.position)})}update(){if((!this.context.connection.isConnected||this._model?.hasOwnership)&&(Vo.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=Vo.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){const t=X(this._currentTargetObject);ot(this.target,t),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(t))}}selectTarget(){if(this.context.time.time-this._lastUpdateTime>this._lookDuration){this._lastUpdateTime=this.context.time.time,this._lookDuration=Math.random()*.5+.2;const t=Vo.Pois;if(t.length>0){const i=t[Math.floor(Math.random()*t.length)];if(i&&i.obj){if(i.avatar&&i.avatar===this.avatar)return;this._currentTargetObject=i.obj}}}}}function c0(s){const e=s;return!!(e.parser&&e.parser.json)}var ou=(s=>(s[s.None=0]="None",s[s.DontExport=1]="DontExport",s))(ou||{});function h0(s){return s&&s.isComponent}const fP=Symbol("object"),_f=new di(()=>new c.Vector3,20);class d0{_point;_normal;_tangentVelocity;distance;impulse;friction;get point(){return _f.get().set(this._point.x,this._point.y,this._point.z)}get normal(){return _f.get().set(this._normal.x,this._normal.y,this._normal.z)}get tangentVelocity(){return _f.get().set(this._tangentVelocity.x,this._tangentVelocity.y,this._tangentVelocity.z)}constructor(e,t,i,n,o,r){this._point=e,this.distance=t,this._normal=i,this.impulse=n,this.friction=o,this._tangentVelocity=r}}class u0{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 f0{object;collider;constructor(e,t){this.object=e,this.collider=t}}const Me=w("debugnetworkingstreams");var Cn=(s=>(s.Connected="peer-user-connected",s.StreamReceived="receive-stream",s.StreamEnded="call-ended",s.Disconnected="peer-user-disconnected",s.UserJoined="user-joined",s))(Cn||{});class jm{type="call-ended";userId;direction;constructor(e,t){this.userId=e,this.direction=t}}class p0{type="receive-stream";userId;stream;target;constructor(e,t,i){this.userId=e,this.stream=t,this.target=i}}class pP{guid;peerId;dontSave=!0;constructor(e,t){this.guid=e.id,this.peerId=t}}var m0=(s=>(s.Incoming="incoming",s.Outgoing="outgoing",s))(m0||{});class mP extends c.EventDispatcher{peerId;userId;direction;call;get stream(){return this._stream}_stream=null;_isDisposed=!1;close(){this._isDisposed||(this._isDisposed=!0,this.call.close(),Pn(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",o=>{if(Me&&console.log("Receive stream",`
|
|
951
951
|
Audio:`,o.getAudioTracks(),`
|
|
952
952
|
Video:`,o.getVideoTracks()),this._stream=o,i==="incoming"){const r=new p0(e,o,this);this.dispatchEvent(r)}}),t.on("close",()=>{this.dispatchEvent(new jm(e,i))})}}function d_(s){return s=s.replace("a=fmtp:111 minptime=10;useinbandfec=1","a=fmtp:111 ptime=5;useinbandfec=1;stereo=1;maxplaybackrate=48000;maxaveragebitrat=128000;sprop-stereo=1"),s}class ss extends c.EventDispatcher{static instances=new Map;static getOrCreate(e,t){if(ss.instances.has(t))return ss.instances.get(t);const i=new ss(e,t);return ss.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){Me?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:o=>d_(o)},n=this._peer?.call(e,t,i);if(n){const o=this.registerCall(n,"outgoing",t);return Me&&console.warn(`📞 CALL ${e}`,`
|
|
@@ -954,9 +954,9 @@ Outgoing:`,this._outgoingCalls,`
|
|
|
954
954
|
Incoming:`,this._incomingCalls),o}else Me&&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?Me&&console.warn("!!! Stream is still active, don't remove call",t.userId,"Your id: "+this.context.connection.connectionId):(Me&&console.warn("!!! Remove closed call",t.userId),i=!0)),this.context.connection.userIsInRoom(t.userId)===!1&&(Me&&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:Me&&console.warn("[PeerJs] getUserMedia is not writable")}catch(n){Me&&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(Q.JoinedRoom,this.onConnectRoomFn),this.subscribePeerEvents())}disable(){this._enabled&&(this._enabled=!1,this.context.connection.stopListen(Q.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=$b(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(Me&&console.log("PEER opened as",e),e===null){console.error("Peer connection failed",e);return}this.context.connection.send("peer-user-connected",new pP(this,e))};onPeerClose=()=>{Me&&console.log("PEER closed"),this.updateCalls()};onPeerDisconnected=()=>{Me&&console.log("PEER disconnected"),this.updateCalls()};onPeerError=e=>{Me&&console.error("PEER error",e)};onPeerReceivingCall=e=>{e.answer(void 0,{sdpTransform:t=>d_(t)}),this.registerCall(e,"incoming",null)};registerCall(e,t,i){const n=e.metadata;(!n||!n.userId)&&console.error("Missing call metadata",e);const o=n.userId;t==="incoming"&&Me?console.warn("← Receive call from",e.metadata,e.connectionId):Me&&console.warn("→ Make call to",e.metadata);const r=t==="incoming"?this._incomingCalls:this._outgoingCalls,a=new mP(o,e,t,i);return r.push(a),e.on("error",l=>{console.error("Call error",l)}),e.on("close",()=>{Me&&console.log("Call ended",e.metadata);const l=r.indexOf(a);l!==-1&&r.splice(l,1),a.close(),this.dispatchEvent(new jm(o,t))}),a.addEventListener("call-ended",l=>{this.dispatchEvent(l)}),t==="incoming"&&(a.addEventListener("receive-stream",l=>{this.dispatchEvent(l)}),e.on("stream",()=>{Me&&console.log("Received stream for call",e.metadata);let l=0;const h=setInterval(()=>{const d=l===0;!a.isOpen&&d&&(Me&&console.warn("Close call because stream is not active",e.metadata),l+=1,clearInterval(h),a.close())},2e3)})),a}}class Sc extends c.EventDispatcher{static create(e,t){const i=ss.getOrCreate(e.context,t||e.context.connection.connectionId||e.guid);return new Sc(e.context,i)}context;peer;_sendingStreams=new Map;debug=!1;constructor(e,t){if(super(),h0(e)){const i=e;e=i.context,t=ss.getOrCreate(i.context,i.guid)}else typeof t=="string"&&(t=ss.getOrCreate(e,t));if(e){if(!(e instanceof F))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,Me&&(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(Q.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(Q.UserJoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(Q.UserLeftRoom,this.onUserLeft),this.context.connection.beginListen(Q.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(Q.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(Q.UserJoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(Q.UserLeftRoom,this.onUserLeft),this.context.connection.stopListen(Q.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 Me&&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 o=this.peer.getPeerIdFromUserId(n);if(i.find(a=>a.peerId===o&&a.direction==="outgoing"&&!a.isClosed&&a.stream?.active))Me&&console.debug("Already have a call with user "+n+" / peer "+o);else{const a=this.peer.makeCall(o,t);a&&i.push(a)}}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)?Me&&(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}`)):(Me&&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 Pn(s){if(s&&s instanceof MediaStream)for(const e of s.getTracks())e.stop()}var gP=Object.defineProperty,Bm=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&gP(e,t,n),n};const yP="noVoip",_P=w("debugvoip");class no extends k{autoConnect=!0;runInBackground=!0;createMenuButton=!0;debug=!1;_net;_menubutton;awake(){_P&&(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=Sc.create(this)),this.debug&&(this._net.debug=!0),this._net.addEventListener(Cn.StreamReceived,this.onReceiveStream),this._net.addEventListener(Cn.StreamEnded,this.onStreamEnded),this._net.enable(),this.autoConnect&&this.context.connection.isConnected&&this.connect(),this.context.connection.beginListen(Q.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(Q.LeftRoom,this.onLeftRoom),this.onEnabledChanged(),this.updateButton(),window.addEventListener("visibilitychange",this.onVisibilityChanged)}onDisable(){this._net&&(this._net.stopSendingStream(this._outputStream),this._net.removeEventListener(Cn.StreamReceived,this.onReceiveStream),this._net.removeEventListener(Cn.StreamEnded,this.onStreamEnded),this._net?.disable()),this.context.connection.stopListen(Q.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(Q.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 exports.DeviceUtilities.microphonePermissionsGranted())return console.error("Cannot connect to voice chat - microphone permissions not granted"),this.updateButton(),!1}else return console.error("Cannot connect to voice chat - not connected to server"),this.updateButton(),!1;return this._allowSending=!0,this._net?.stopSendingStream(this._outputStream),Pn(this._outputStream),this._outputStream=await this.getAudioStream(e),this._outputStream?(this.debug&&console.log("VOIP: Got audio stream"),this._net?.startSendingStream(this._outputStream),this.updateButton(),!0):(this.updateButton(),await exports.DeviceUtilities.microphonePermissionsGranted()?console.error("VOIP: Could not get audio stream - please make sure to connect an audio device and grant microphone permissions"):dc("Microphone permissions not granted: Please grant microphone permissions to use voice chat"),(this.debug||A())&&console.log("VOIP: Failed to get audio stream"),!1)}disconnect(e){e?.remember&&(this._allowSending=!1),this._net?.stopSendingStream(this._outputStream),Pn(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(),exports.DeviceUtilities.microphonePermissionsGranted().then(e=>{e||he("<strong>Microphone permissions not granted</strong>. Please allow your browser to use the microphone to be able to talk. Click on the button on the left side of your browser's address bar to allow microphone permissions.")})})),this._menubutton){this.context.menu.appendChild(this._menubutton),this.activeAndEnabled?this._menubutton.style.display="":this._menubutton.style.display="none",this._menubutton.title=this.isSending?"Click to disable your microphone":"Click to enable your microphone";let e=(this.isSending,""),t=this.isSending?"mic":"mic_off";await exports.DeviceUtilities.microphonePermissionsGranted()||(e="No Permission",t="mic_off",this._menubutton.title="Microphone permissions not granted. Please allow your browser to use the microphone to be able to talk. This can usually be done in the addressbar of the webpage."),this._menubutton.innerText=e,this._menubutton.prepend(pt(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,A()&&he("VOIP: getFrequency is currently not supported"),console.warn("VOIP: getFrequency is currently not supported")),null}async getAudioStream(e){if(!navigator.mediaDevices.getUserMedia)return console.error("No getDisplayMedia support"),null;const t=async n=>await navigator.mediaDevices.getUserMedia({audio:n??!0,video:!1}).catch(o=>(console.warn("VOIP failed getting audio stream",o),null)),i=await t(e);if(!i)return null;if(exports.DeviceUtilities.isiOS()&&e?.deviceId===void 0){const o=(await navigator.mediaDevices.enumerateDevices()).find(r=>(r.kind==="audioinput"||r.kind==="audiooutput")&&!r.label.includes("iPhone"));if(o){const r=Object.assign({},e);return r.deviceId=o.deviceId,await t(r)}}return i}onJoinedRoom=async()=>{this.debug&&console.log("VOIP: Joined room"),await Ln(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())Pn(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(o=>{console.error("VOIP: Failed to play audio",o)})})};onStreamEnded=e=>{const t=this._incomingStreams.get(e.userId);Pn(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 t=!(document.visibilityState==="visible");this.setMuted(t);for(const i of this._incomingStreams){const n=i[1];n.muted=t}}}Bm([f()],no.prototype,"autoConnect");Bm([f()],no.prototype,"runInBackground");Bm([f()],no.prototype,"createMenuButton");var bP=Object.defineProperty,g0=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&bP(e,t,n),n};const vP=w("debugmouth");class Cc extends k{idle=[];talking=[];marker=null;voip=null;lastMouthChangeTime=0;mouthChangeLength=0;awake(){setTimeout(()=>{this.voip=S.findObjectOfType(no,this.context),this.marker||(this.marker=S.getComponentInParent(this.gameObject,xe))},3e3)}update(){if(!this.voip||this.context.time.frameCount%10!==0)return;let e=this.marker?.connectionId??null;if(!e){vP&&(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)}}}}g0([f(c.Object3D)],Cc.prototype,"idle");g0([f(c.Object3D)],Cc.prototype,"talking");class Fm extends k{voip=null;marker=null;_startPosition=null;awake(){this.voip=S.findObjectOfType(no,this.context),this.marker=S.getComponentInParent(this.gameObject,xe)}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 wP=Object.defineProperty,xP=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&wP(e,t,n),n};const zr=w("debugxrflags"),y0=w("disablexrflags");y0&&console.warn("XRFlags are disabled");var wn=(s=>(s[s.Never=0]="Never",s[s.Browser=1]="Browser",s[s.AR=2]="AR",s[s.VR=4]="VR",s[s.FirstPerson=8]="FirstPerson",s[s.ThirdPerson=16]="ThirdPerson",s[s.All=4294967295]="All",s))(wn||{});class It{static Global=new It;Mask=17;Has(e){return(this.Mask&e)!==0}Set(e){zr&&console.warn("Set XR flag state to",e),this.Mask=e,Ti.Apply()}Enable(e){this.Mask|=e,Ti.Apply()}Disable(e){this.Mask&=~e,Ti.Apply()}Toggle(e){this.Mask^=e,Ti.Apply()}EnableAll(){this.Mask=-1,Ti.Apply()}DisableAll(){this.Mask=0,Ti.Apply()}}const _0=class qn extends k{static registry=[];static Apply(){for(const e of this.registry)e.UpdateVisible(It.Global)}static firstApply;static buffer=new It;visibleIn;awake(){qn.registry.push(this)}onEnable(){qn.firstApply?this.UpdateVisible(It.Global):(qn.firstApply=!0,qn.Apply())}onDestroy(){const e=qn.registry.indexOf(this);e>=0&&qn.registry.splice(e,1)}get isOn(){return this.gameObject.visible}UpdateVisible(e=null){if(y0)return;let t;const i=e;if(i&&typeof i=="number"&&(console.assert(typeof i=="number","XRFlag.UpdateVisible: state must be a number",i),zr&&console.log(i),qn.buffer.Mask=i,e=qn.buffer),e instanceof It?(zr&&console.warn(this.name,"use passed in mask",e.Mask,this.visibleIn),t=e.Has(this.visibleIn)):(zr&&console.log(this.name,"use global mask"),It.Global.Has(this.visibleIn)),t!==void 0)if(t)zr&&console.log(this.name,"is visible",this.gameObject.uuid),S.setActive(this.gameObject,!0);else{if(zr&&console.log(this.name,"is not visible",this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}};xP([f()],_0.prototype,"visibleIn");let Ti=_0;var SP=Object.defineProperty,ru=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&SP(e,t,n),n};class ar extends k{eyes=[];lastBlinkTime=0;blinkLength=0;eyesOpen=!0;state=null;awake(){this.state=S.getComponentInParent(this.gameObject,Ti)}update(){if(!this.gameObject||!this.gameObject.visible||!this.eyes||!Array.isArray(this.eyes)||this.eyes.length===0)return;if(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 t of this.eyes)t&&(t.visible=this.eyesOpen)}}}ru([f(c.Object3D)],ar.prototype,"eyes");ru([f()],ar.prototype,"lastBlinkTime");ru([f()],ar.prototype,"blinkLength");ru([f()],ar.prototype,"eyesOpen");var CP=Object.defineProperty,Um=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&CP(e,t,n),n};const au=class b0 extends k{head=null;eyes=null;target=null;brain=null;awake(){this.brain||(this.brain=S.getComponentInParent(this.gameObject,Zl)),this.brain||(this.brain=S.addComponent(this.gameObject,Zl)),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}vec=new c.Vector3;static forward=new c.Vector3(0,0,1);currentTargetPoint=new c.Vector3;update(){const e=this.target;if(e&&this.head){const t=this.eyes;if(t){const i=X(e);this.currentTargetPoint.lerp(i,this.context.time.deltaTime/.1);const n=X(this.head),o=this.vec.copy(this.currentTargetPoint).sub(n).normalize();if(o.length()<.1)return;const r=b0.forward;if(r.set(0,0,1),r.applyQuaternion(ue(this.head)),r.dot(o)>.45)for(let l=0;l<t.length;l++)t[l].lookAt(this.currentTargetPoint)}}}};Um([f(c.Object3D)],au.prototype,"head");Um([f(c.Object3D)],au.prototype,"eyes");Um([f(c.Object3D)],au.prototype,"target");let zm=au;var PP=Object.defineProperty,Nm=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&PP(e,t,n),n};class xa extends k{length=1;depthTest=!0;isGizmo=!1;_axes=null;onEnable(){if(this.isGizmo&&!fc)return;this._axes||(this._axes=new c.AxesHelper(this.length)),this._axes.layers.disableAll(),this._axes.layers.set(this.layer),this.gameObject.add(this._axes);const e=this._axes.material;e&&e.depthTest!==void 0&&(e.depthTest=this.depthTest)}onDisable(){this._axes&&this.gameObject.remove(this._axes)}}Nm([f()],xa.prototype,"length");Nm([f()],xa.prototype,"depthTest");Nm([f()],xa.prototype,"isGizmo");class Vm extends k{from;to;hint;desiredDistance=1;onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;const e=X(this.to).clone(),t=X(this.from).clone(),i=e.distanceTo(t),n=e.clone();n.sub(t);const o=t.clone();o.add(e),o.multiplyScalar(.5);const r=X(this.hint).clone();r.sub(o);const a=new c.Vector3;a.crossVectors(r,n),a.crossVectors(n,a),a.normalize();const l=i*.5,h=Math.max(this.desiredDistance,l),d=Math.sqrt(h*h-l*l),u=a.clone();u.multiplyScalar(d),u.add(o),ot(this.gameObject,u);const p=o.clone();p.sub(a),this.gameObject.lookAt(p)}}const OP=w("gizmos"),MP=w("debugboxhelper");class nt extends k{box=null;static testBox=new c.Box3;_lastMatrixUpdateFrame=-1;static _position=new c.Vector3;static _size=new c.Vector3(.01,.01,.01);static _emptyObjectSize=new c.Vector3(.01,.01,.01);isInBox(e){if(!e)return;if(this.box||(this.box=new c.Box3),Bt([e],void 0,void 0,nt.testBox),nt.testBox.isEmpty()){const i=X(e,nt._position);nt.testBox.setFromCenterAndSize(i,nt._emptyObjectSize)}this.updateBox();const t=this.box?.intersectsBox(nt.testBox);return t&&MP&&B.DrawWireBox3(nt.testBox,16711680,5),t}intersects(e){return e?this.updateBox(!1).intersectsBox(e):!1}updateBox(e=!1){if(this.box||(this.box=new c.Box3),e||this.context.time.frameCount!=this._lastMatrixUpdateFrame){const t=this._lastMatrixUpdateFrame<0;this._lastMatrixUpdateFrame=this.context.time.frameCount;const i=t,n=X(this.gameObject,nt._position,i),o=Ie(this.gameObject,nt._size);this.box.setFromCenterAndSize(n,o)}return this.box}_helper=null;_color=null;awake(){this._helper=null,this._color=null,this.box=null}showHelper(e=null,t=!1){if(!(!OP&&!t)){if(this._helper){e&&this._color?.set(e),this.gameObject.add(this._helper);return}this._helper=ym(e),this.gameObject.add(this._helper)}}}var kP=Object.defineProperty,Yt=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&kP(e,t,n),n};class Kt extends k{get isCollider(){return!0}attachedRigidbody=null;isTrigger=!1;sharedMaterial;membership=[0];filter;awake(){super.awake(),this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Ne))}start(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Ne))}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Ne))}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)}}Yt([f(Ne)],Kt.prototype,"attachedRigidbody");Yt([f()],Kt.prototype,"isTrigger");Yt([f()],Kt.prototype,"sharedMaterial");Yt([f()],Kt.prototype,"membership");Yt([f()],Kt.prototype,"filter");class Sa extends Kt{radius=.5;center=new c.Vector3(0,0,0);onEnable(){super.onEnable(),this.context.physics.engine?.addSphereCollider(this),zd(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),Yp(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}}Yt([yt(),f()],Sa.prototype,"radius");Yt([f(c.Vector3)],Sa.prototype,"center");const $m=class v0 extends Kt{static add(e,t){const i=Zi(e,v0);return i.autoFit(),t?.rigidbody===!0&&Zi(e,Ne,{isKinematic:!1}),i}size=new c.Vector3(1,1,1);center=new c.Vector3(0,0,0);onEnable(){super.onEnable(),this.context.physics.engine?.addBoxCollider(this,this.size),zd(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),Yp(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}autoFit(e){const t=this.gameObject,i=t.position.clone(),n=t.quaternion.clone(),o=t.scale.clone(),r=t.parent;t.position.set(0,0,0),t.quaternion.set(0,0,0,1),t.scale.set(1,1,1),t.parent=null,t.updateMatrix();const a=Bt([t]);t.position.copy(i),t.quaternion.copy(n),t.scale.copy(o),t.parent=r,e?.debug===!0&&B.DrawWireBox3(a,16768256,20),this.size=a.getSize(new c.Vector3)||new c.Vector3(1,1,1),this.center=a.getCenter(new c.Vector3)||new c.Vector3(0,0,0),this.size.length()<=0&&this.size.set(.01,.01,.01)}};Yt([yt(),f(c.Vector3)],$m.prototype,"size");Yt([f(c.Vector3)],$m.prototype,"center");let lu=$m;class so extends Kt{sharedMesh;convex=!1;onEnable(){if(super.onEnable(),!this.context.physics.engine)return;this.sharedMesh?.isMesh||(this.gameObject instanceof c.Mesh||this.gameObject instanceof c.Group)&&(this.sharedMesh=this.gameObject);const e=0;if(this.sharedMesh?.isMesh)this.context.physics.engine.addMeshCollider(this,this.sharedMesh,this.convex),ne.NEEDLE_progressive.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 o=t.children[n];o.isMesh&&(this.context.physics.engine.addMeshCollider(this,o,this.convex),i.push(ne.NEEDLE_progressive.assignMeshLOD(o,e)))}Promise.all(i).then(n=>{if(n.some(r=>r)==!1)return;this.context.physics.engine?.removeBody(this);const o=new c.Mesh;for(const r of n)r&&this.activeAndEnabled&&(o.geometry=r,this.context.physics.engine?.addMeshCollider(this,o,this.convex))})}else(A()||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)}}}Yt([f(c.Mesh)],so.prototype,"sharedMesh");Yt([f()],so.prototype,"convex");class ls extends Kt{center=new c.Vector3(0,0,0);radius=.5;height=2;onEnable(){super.onEnable(),this.context.physics.engine?.addCapsuleCollider(this,this.height,this.radius)}}Yt([f(c.Vector3)],ls.prototype,"center");Yt([f()],ls.prototype,"radius");Yt([f()],ls.prototype,"height");var EP=Object.defineProperty,ds=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&EP(e,t,n),n};const u_=w("debugcharactercontroller");class lr extends k{center=new c.Vector3(0,0,0);radius=.5;height=2;_rigidbody=null;get rigidbody(){return this._rigidbody?this._rigidbody:(this._rigidbody=this.gameObject.getComponent(Ne),this._rigidbody||(this._rigidbody=this.gameObject.addComponent(Ne)),this.rigidbody)}_activeGroundCollisions;awake(){this._activeGroundCollisions=new Set}onEnable(){const e=this.rigidbody;let t=this.gameObject.getComponent(ls);t||(t=this.gameObject.addComponent(ls)),t.center.copy(this.center),t.radius=this.radius,t.height=this.height;const i=new c.Vector3(0,0,1),n=new c.Vector3(1,0,0),o=new c.Vector3(0,1,0),r=this.gameObject.getWorldDirection(new c.Vector3);r.y=0;const a=n.dot(r)<0?-1:1,l=i.angleTo(r)*a;this.gameObject.setRotationFromAxisAngle(o,l),e.lockRotationX=!0,e.lockRotationY=!0,e.lockRotationZ=!0}move(e){this.gameObject.position.add(e)}onCollisionEnter(e){(e.contacts.length==0||e.contacts.some(t=>t.normal.y>.2))&&(this._activeGroundCollisions.add(e),u_&&console.log(`Collision(${this._activeGroundCollisions.size}): ${e.contacts.map(t=>t.normal.y.toFixed(2)).join(", ")} - ${this.isGrounded}`))}onCollisionExit(e){this._activeGroundCollisions.delete(e),u_&&console.log(`Collision(${this._activeGroundCollisions.size}) - ${this.isGrounded}`)}get isGrounded(){return this._activeGroundCollisions.size>0}_contactVelocity=new c.Vector3;get contactVelocity(){this._contactVelocity.set(0,0,0);for(const e of this._activeGroundCollisions){const t=this.context.physics.engine?.getLinearVelocity(e.collider);t&&(this._contactVelocity.x+=t.x,this._contactVelocity.y+=t.y,this._contactVelocity.z+=t.z)}return this._contactVelocity}}ds([f(c.Vector3)],lr.prototype,"center");ds([f()],lr.prototype,"radius");ds([f()],lr.prototype,"height");class us extends k{controller;movementSpeed=2;rotationSpeed=2;jumpForce=1;doubleJumpForce=2;animator;lookForward=!0;awake(){this._currentRotation=new c.Quaternion}update(){const e=this.context.input;e.isKeyPressed("KeyW")?this.moveInput.y+=1:e.isKeyPressed("KeyS")&&(this.moveInput.y-=1),e.isKeyPressed("KeyD")?this.lookInput.x+=1:e.isKeyPressed("KeyA")&&(this.lookInput.x-=1),this.jumpInput||=e.isKeyDown("Space")}move(e){this.moveInput.add(e)}look(e){this.lookInput.add(e)}jump(){this.jumpInput=!0}lookInput=new c.Vector2(0,0);moveInput=new c.Vector2(0,0);jumpInput=!1;onBeforeRender(){this.handleInput(this.moveInput,this.lookInput,this.jumpInput),this.lookInput.set(0,0),this.moveInput.set(0,0),this.jumpInput=!1}_currentSpeed=new c.Vector3(0,0,0);_currentAngularSpeed=new c.Vector3(0,0,0);_temp=new c.Vector3(0,0,0);_jumpCount=0;_currentRotation;handleInput(e,t,i){if(this.controller?.isGrounded&&(this._jumpCount=0,this.doubleJumpForce>0&&this.animator?.setBool("doubleJump",!1)),this._currentSpeed.z+=e.y*this.movementSpeed*this.context.time.deltaTime,this.animator?.setBool("running",e.length()>.01),this.animator?.setBool("jumping",this.controller?.isGrounded===!0&&i),this._temp.copy(this._currentSpeed),this._temp.applyQuaternion(this.gameObject.quaternion),this.controller?this.controller.move(this._temp):this.gameObject.position.add(this._temp),this._currentAngularSpeed.y+=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 c.Vector3(0,0,1),n),this.gameObject.quaternion.slerp(this._currentRotation,this.context.time.deltaTime*10)}if(this.gameObject.rotateY(this._currentAngularSpeed.y),this._currentSpeed.multiplyScalar(1-this.context.time.deltaTime*10),this._currentAngularSpeed.y*=1-this.context.time.deltaTime*10,this.controller&&i&&this.jumpForce>0){let n=this.controller?.isGrounded;if(this.doubleJumpForce>0&&!this.controller?.isGrounded&&this._jumpCount===1&&(n=!0,this.animator?.setBool("doubleJump",!0)),n){this._jumpCount+=1;const o=this.controller.rigidbody,r=this._jumpCount===2?this.doubleJumpForce:this.jumpForce;o.applyImpulse(new c.Vector3(0,1,0).multiplyScalar(r))}}if(this.controller){const n=this.controller?.rigidbody.getVelocity().y;if(n<-1){this._raycastOptions.ray||(this._raycastOptions.ray=new c.Ray),this._raycastOptions.ray.origin.copy(X(this.gameObject)),this._raycastOptions.ray.direction.set(0,-1,0);const o=this.layer;this.gameObject.layers.disableAll(),this.gameObject.layers.set(2);const r=this.context.physics.raycast(this._raycastOptions);this.gameObject.layers.set(o),(r.length&&r[0].distance>2||n<-10)&&this.animator?.setBool("falling",!0)}else this.animator?.setBool("falling",!1)}}_raycastOptions=new io}ds([f(lr)],us.prototype,"controller");ds([f()],us.prototype,"movementSpeed");ds([f()],us.prototype,"rotationSpeed");ds([f()],us.prototype,"jumpForce");ds([f()],us.prototype,"doubleJumpForce");ds([f(rt)],us.prototype,"animator");var RP=Object.defineProperty,Ca=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&RP(e,t,n),n};const Ka=w("debugcontactshadows");eu(s=>{const e=s.domElement.getAttribute("contactshadows")||s.domElement.getAttribute("contact-shadows");if(e!=null&&e!="0"&&e!="false"){console.debug("Auto-creating ContactShadows because of `contactshadows` attribute");const t=Pc.auto(s),i=parseFloat(e);isNaN(i)||(t.opacity=i,t.darkness=i)}});const cr=class _l extends k{static _instances=new Map;static auto(e,t){if(e||(e=F.Current),!e)throw new Error("No context provided and no current context set.");let i=this._instances.get(e);if(!i||i.destroyed){const n=new c.Object3D;i=Zi(n,_l,{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 c.Object3D;shadowCamera;shadowGroup=new c.Group;renderTarget;renderTargetBlur;plane;occluderMesh;blurPlane;depthMaterial;horizontalBlurMaterial;verticalBlurMaterial;textureSize=512;fitShadows(e={}){Ka&&console.warn("Fitting shadows to scene"),cd(this.shadowsRoot,!1);const t=e.object||this.context.scene,i=Bt(t,[this.shadowsRoot]),n=Math.max(1,this.blur/32),o=i.max.x-i.min.x,r=i.max.z-i.min.z;i.expandByVector(new c.Vector3(n*o,0,n*r)),Ka&&B.DrawWireBox3(i,16776960,60),this.gameObject.parent&&i.applyMatrix4(this.gameObject.parent.matrixWorld.clone().invert());const a=i.min,l=Math.max(1e-5,(i.max.y-a.y)*.002);i.max.y+=l,this.shadowsRoot.position.set((a.x+i.max.x)/2,a.y-l,(a.z+i.max.z)/2),this.shadowsRoot.scale.set(i.max.x-a.x,i.max.y-a.y,i.max.z-a.z),e.positionOffset&&(e.positionOffset.x!==void 0&&(this.shadowsRoot.position.x+=e.positionOffset.x),e.positionOffset.y!==void 0&&(this.shadowsRoot.position.y+=e.positionOffset.y),e.positionOffset.z!==void 0&&(this.shadowsRoot.position.z+=e.positionOffset.z)),e.scaleFactor&&(e.scaleFactor.x!==void 0&&(this.shadowsRoot.scale.x*=e.scaleFactor.x),e.scaleFactor.y!==void 0&&(this.shadowsRoot.scale.y*=e.scaleFactor.y),e.scaleFactor.z!==void 0&&(this.shadowsRoot.scale.z*=e.scaleFactor.z)),this.applyMinSize(),this.shadowsRoot.matrixWorldNeedsUpdate=!0,Ka&&console.log("Fitted shadows to scene",this.shadowsRoot.scale.clone())}awake(){_l._instances.set(this.context,this),this.shadowsRoot.hideFlags=ou.DontExport,cd(this.shadowsRoot,!1)}start(){Ka&&console.log("Create ContactShadows on "+this.gameObject.name,this),this.gameObject.add(this.shadowsRoot),this.shadowsRoot.add(this.shadowGroup),this.renderTarget=new c.WebGLRenderTarget(this.textureSize,this.textureSize),this.renderTarget.texture.generateMipmaps=!1,this.renderTargetBlur=new c.WebGLRenderTarget(this.textureSize,this.textureSize),this.renderTargetBlur.texture.generateMipmaps=!1;const e=new c.PlaneGeometry(1,1).rotateX(Math.PI/2);this.gameObject instanceof c.Mesh&&(console.warn("ContactShadows can not be added to a Mesh. Please add it to a Group or an empty Object"),es(this.gameObject,!1));const t=new c.MeshBasicMaterial({map:this.renderTarget.texture,opacity:this.opacity,color:0,transparent:!0,depthWrite:!1,side:c.FrontSide});this.plane=new c.Mesh(e,t),this.plane.scale.y=-1,this.plane.layers.set(2),this.shadowsRoot.add(this.plane),this.plane&&(this.plane.renderOrder=1),this.occluderMesh=new c.Mesh(this.plane.geometry,new c.MeshBasicMaterial({depthWrite:!0,stencilWrite:!0,colorWrite:!1,side:c.BackSide})).translateY(-1e-4),this.occluderMesh.renderOrder=-100,this.occluderMesh.layers.set(2),this.shadowsRoot.add(this.occluderMesh),this.blurPlane=new c.Mesh(e),this.blurPlane.visible=!1,this.shadowGroup.add(this.blurPlane);const i=0,n=1;this.shadowCamera=new c.OrthographicCamera(-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 c.MeshDepthMaterial,this.depthMaterial.userData.darkness={value:this.darkness},this.depthMaterial.blending=c.CustomBlending,this.depthMaterial.blendEquation=c.MaxEquation,this.depthMaterial.onBeforeCompile=o=>{this.depthMaterial&&(o.uniforms.darkness=this.depthMaterial.userData.darkness,o.fragmentShader=`
|
|
955
955
|
uniform float darkness;
|
|
956
956
|
${o.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 c.ShaderMaterial(q.HorizontalBlurShader),this.horizontalBlurMaterial.depthTest=!1,this.verticalBlurMaterial=new c.ShaderMaterial(q.VerticalBlurShader),this.verticalBlurMaterial.depthTest=!1,this.shadowGroup.visible=!1,this.autoFit?this.fitShadows():this.applyMinSize()}onEnable(){this._needsUpdate=!0}onDestroy(){_l._instances.get(this.context)===this&&_l._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){Ka&&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 o=this.plane.visible;this.plane.visible=!1,this.gameObject instanceof c.Mesh&&es(this.gameObject,!1);const r=t.background;t.background=null,t.overrideMaterial=this.depthMaterial,this.backfaceShadows?this.depthMaterial.side=c.DoubleSide:this.depthMaterial.side=c.FrontSide;const a=i.getClearAlpha();i.setClearAlpha(0);const l=i.xr.enabled;i.xr.enabled=!1;const h=this.context.scene.matrixWorldAutoUpdate;this.context.scene.matrixWorldAutoUpdate=!1;const d=i.renderLists.get(t,0),u=d.transparent;f_.length=0,d.transparent=f_,bf.length=0;for(const m of d.opaque){if(!m.object.visible)continue;const y=m.material;let _=m.material.colorWrite==!1||y.wireframe===!0||Mb(m.object)===!1;!_&&m.material.isLineMaterial&&(_=!0),!_&&m.material.isPointsMaterial&&(_=!0),_&&(bf.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),d.transparent=u;for(const m of bf)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=o,i.setRenderTarget(n),i.setClearAlpha(a),t.background=r,i.xr.enabled=l,this.context.scene.matrixWorldAutoUpdate=h}blurShadow(e){if(!this.blurPlane||!this.shadowCamera||!this.renderTarget||!this.renderTargetBlur||!this.horizontalBlurMaterial||!this.verticalBlurMaterial)return;this.blurPlane.visible=!0;const t=this.shadowsRoot.worldScale,i=(t.x+t.z)/2,n=t.z/i,o=t.x/i;this.blurPlane.material=this.horizontalBlurMaterial,this.blurPlane.material.uniforms.tDiffuse.value=this.renderTarget.texture,this.horizontalBlurMaterial.uniforms.h.value=e*1/this.textureSize*n;const r=this.context.renderer,a=r.getRenderTarget();r.setRenderTarget(this.renderTargetBlur),r.render(this.blurPlane,this.shadowCamera),this.blurPlane.material=this.verticalBlurMaterial,this.blurPlane.material.uniforms.tDiffuse.value=this.renderTargetBlur.texture,this.verticalBlurMaterial.uniforms.v.value=e*1/this.textureSize*o,r.setRenderTarget(this.renderTarget),r.render(this.blurPlane,this.shadowCamera),this.blurPlane.visible=!1,r.setRenderTarget(a)}applyMinSize(){this.minSize&&this.shadowsRoot.scale.set(Math.max(this.minSize.x||0,this.shadowsRoot.scale.x),Math.max(this.minSize.y||0,this.shadowsRoot.scale.y),Math.max(this.minSize.z||0,this.shadowsRoot.scale.z))}};Ca([f()],cr.prototype,"autoFit");Ca([f()],cr.prototype,"darkness");Ca([f()],cr.prototype,"opacity");Ca([f()],cr.prototype,"blur");Ca([f()],cr.prototype,"occludeBelowGround");Ca([f()],cr.prototype,"backfaceShadows");let Pc=cr;const f_=[],bf=new Array,TP=w("logstats");class Wm extends k{onEnable(){console.log(this),TP&&this.startCoroutine(this.run(),pe.OnAfterRender)}*run(){for(;this.enabled;){const e=this.context.renderer.info;console.log(e.memory,e.render,e.programs),yield}}}class Oc extends k{isUsed=!0;usedBy=null}class Gm extends k{}const p_=w("debugdeletable");class Gs extends nt{static _instances=[];onEnable(){Gs._instances.push(this)}onDisable(){const e=Gs._instances.indexOf(this);e>=0&&Gs._instances.splice(e,1)}}class Hm extends k{update(){for(const e of Gs._instances){const t=this.gameObject;if(e.isInBox(t)===!0){const n=S.getComponentInParent(this.gameObject,Oc);if(n)p_&&console.warn("DeleteBox: Not deleting object with usage marker",this.guid,n);else{if(p_)try{if(e.box){const o=e.box,r=nt.testBox;B.DrawWireBox3(o,16711680,5),B.DrawWireBox3(r,255,5),console.log("DeleteBox: Destroying",this.gameObject,{deleteBoxArea:o,deletedObjectArea:r})}else console.log("DeleteBox: Destroying",this.gameObject)}catch{}uc(this.gameObject,this.context.connection)}}}}}var AP=Object.defineProperty,LP=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&AP(e,t,n),n};class cu extends k{visibleOn;onEnable(){this.apply()}apply(){this.test()||S.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:exports.DeviceUtilities.isMobileDevice()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}}LP([f()],cu.prototype,"visibleOn");var DP=Object.defineProperty,hr=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&DP(e,t,n),n};const On=w("debugdrag"),vf=[];var qm=(s=>(s[s.XZPlane=0]="XZPlane",s[s.Attached=1]="Attached",s[s.HitNormal=2]="HitNormal",s[s.DynamicViewAngle=3]="DynamicViewAngle",s[s.SnapToSurfaces=4]="SnapToSurfaces",s[s.None=5]="None",s))(qm||{});const oo=class Oi extends k{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=S.getComponentInChildren(e,Ne),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 c.Vector3;_marker=null;_isDragging=!1;_didDrag=!1;awake(){this._potentialDragStartEvt=null,this._dragHandlers=new Map,this._totalMovement=new c.Vector3,this._marker=null,this._isDragging=!1,this._didDrag=!1,this._dragHelper=null,this._draggingRigidbodies=[]}start(){this.gameObject.getComponentInParent(fi)||this.gameObject.addComponent(fi)}onEnable(){Oi._instances.push(this)}onDisable(){Oi._instances=Oi._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 n=S.getComponentInParent(e.object,Oi);!n||n!==this||(Oi.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"&&Oi.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)&&(Oi.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),Oi._active+=1;const n=new wf(this,this._targetObject);if(this._dragHandlers.set(e.event.space,n),n.onDragStart(e),this._dragHandlers.size===2){const o=this._dragHandlers.values(),r=o.next().value,a=o.next().value;if(r instanceof wf&&a instanceof wf){const l=new IP(this,this._targetObject,r,a);this._dragHandlers.set(this.gameObject,l),l.onDragStart(e)}else console.error("Attempting to construct a MultiTouchDragHandler with invalid DragPointerHandlers. This is likely a bug.",{a:r,b:a})}e.use()}}onPointerUp(e){if(On&&B.DrawLabel(e.point??this.gameObject.worldPosition,"POINTERUP:"+e.pointerId+", "+e.button,.03,3),!this.allowEdit(this.gameObject)||e.button!==0)return;this._potentialDragStartEvt=null;const t=this._dragHandlers.get(e.event.space),i=this._dragHandlers.get(this.gameObject);i&&(i.handlerA===t||i.handlerB===t)&&(this._dragHandlers.delete(this.gameObject),i.onDragEnd(e)),t&&(Oi._active>0&&(Oi._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=S.getComponentInParent(e.object,Oi);if(!t||t!==this&&t._isDragging)return;const i=this._targetObject||this.gameObject;if(!i)return;this._isDragging=!0;const n=S.getComponentInChildren(i,nn);On&&console.log("DRAG START",n,i),n&&(n.fastMode=!0,n?.requestOwnership()),this._marker=S.addComponent(i,Oc),this._draggingRigidbodies.length=0;const o=S.getComponentsInChildren(i,Ne);o&&this._draggingRigidbodies.push(...o)}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;Li.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=S.getComponentInChildren(e.object,nn);i&&(i.fastMode=!1)}if(this._marker&&this._marker.destroy(),!this._dragHelper)return;const t=this._dragHelper.selected;On&&console.log("DRAG END",t,t?.visible),this._dragHelper.setSelected(null,this.context)}};hr([f()],oo.prototype,"dragMode");hr([f()],oo.prototype,"snapGridResolution");hr([f()],oo.prototype,"keepRotation");hr([f()],oo.prototype,"xrDragMode");hr([f()],oo.prototype,"xrKeepRotation");hr([f()],oo.prototype,"xrDistanceDragFactor");hr([f()],oo.prototype,"showGizmo");let Ro=oo;class IP{handlerA;handlerB;context;settings;gameObject;_handlerAAttachmentPoint=new c.Vector3;_handlerBAttachmentPoint=new c.Vector3;_followObject;_manipulatorObject;_deviceMode;_followObjectStartWorldQuaternion=new c.Quaternion;constructor(e,t,i,n){this.context=e.context,this.settings=e,this.gameObject=t,this.handlerA=i,this.handlerB=n,this._followObject=new c.Object3D,this._manipulatorObject=new c.Object3D,this.context.scene.add(this._manipulatorObject);const o=H.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),o&&(o.worldToLocal(this._tempVec1),o.worldToLocal(this._tempVec2)),this._initialDistance=this._tempVec1.distanceTo(this._tempVec2),this._initialDistance<.02?(On&&console.log("Finding alternative drag attachment points since initial distance is too low: "+this._initialDistance.toFixed(2)),this.handlerA.followObject.parent.getWorldPosition(this._tempVec1),this.handlerB.followObject.parent.getWorldPosition(this._tempVec2),this._handlerAAttachmentPoint.copy(this._tempVec1),this._handlerBAttachmentPoint.copy(this._tempVec2),this.gameObject.worldToLocal(this._handlerAAttachmentPoint),this.gameObject.worldToLocal(this._handlerBAttachmentPoint),this._initialDistance=this._tempVec1.distanceTo(this._tempVec2),this._initialDistance<.001&&(console.warn("Not supported right now – controller drag points for multitouch are too close!"),this._initialDistance=1)):(this._handlerAAttachmentPoint.copy(this.handlerA.hitPointInLocalSpace),this._handlerBAttachmentPoint.copy(this.handlerB.hitPointInLocalSpace)),this._tempVec3.lerpVectors(this._tempVec1,this._tempVec2,.5),this._initialScale.copy(t.scale),On){this._followObject.add(new c.AxesHelper(2)),this._manipulatorObject.add(new c.AxesHelper(5));const r=a=>`${a.x.toFixed(2)}, ${a.y.toFixed(2)}, ${a.z.toFixed(2)}`;B.DrawLine(this._tempVec1,this._tempVec2,65535,0,!1),B.DrawLabel(this._tempVec3,"A:B "+this._initialDistance.toFixed(2)+`
|
|
957
|
+
`)},this.depthMaterial.depthTest=!1,this.depthMaterial.depthWrite=!1,this.horizontalBlurMaterial=new c.ShaderMaterial(q.HorizontalBlurShader),this.horizontalBlurMaterial.depthTest=!1,this.verticalBlurMaterial=new c.ShaderMaterial(q.VerticalBlurShader),this.verticalBlurMaterial.depthTest=!1,this.shadowGroup.visible=!1,this.autoFit?this.fitShadows():this.applyMinSize()}onEnable(){this._needsUpdate=!0}onDestroy(){_l._instances.get(this.context)===this&&_l._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){Ka&&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 o=this.plane.visible;this.plane.visible=!1,this.gameObject instanceof c.Mesh&&es(this.gameObject,!1);const r=t.background;t.background=null,t.overrideMaterial=this.depthMaterial,this.backfaceShadows?this.depthMaterial.side=c.DoubleSide:this.depthMaterial.side=c.FrontSide;const a=i.getClearAlpha();i.setClearAlpha(0);const l=i.xr.enabled;i.xr.enabled=!1;const h=this.context.scene.matrixWorldAutoUpdate;this.context.scene.matrixWorldAutoUpdate=!1;const d=i.renderLists.get(t,0),u=d.transparent;f_.length=0,d.transparent=f_,bf.length=0;for(const m of d.opaque){if(!m.object.visible)continue;const y=m.material;let b=m.material.colorWrite==!1||y.wireframe===!0||Mb(m.object)===!1;!b&&m.material.isLineMaterial&&(b=!0),!b&&m.material.isPointsMaterial&&(b=!0),b&&(bf.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),d.transparent=u;for(const m of bf)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=o,i.setRenderTarget(n),i.setClearAlpha(a),t.background=r,i.xr.enabled=l,this.context.scene.matrixWorldAutoUpdate=h}blurShadow(e){if(!this.blurPlane||!this.shadowCamera||!this.renderTarget||!this.renderTargetBlur||!this.horizontalBlurMaterial||!this.verticalBlurMaterial)return;this.blurPlane.visible=!0;const t=this.shadowsRoot.worldScale,i=(t.x+t.z)/2,n=t.z/i,o=t.x/i;this.blurPlane.material=this.horizontalBlurMaterial,this.blurPlane.material.uniforms.tDiffuse.value=this.renderTarget.texture,this.horizontalBlurMaterial.uniforms.h.value=e*1/this.textureSize*n;const r=this.context.renderer,a=r.getRenderTarget();r.setRenderTarget(this.renderTargetBlur),r.render(this.blurPlane,this.shadowCamera),this.blurPlane.material=this.verticalBlurMaterial,this.blurPlane.material.uniforms.tDiffuse.value=this.renderTargetBlur.texture,this.verticalBlurMaterial.uniforms.v.value=e*1/this.textureSize*o,r.setRenderTarget(this.renderTarget),r.render(this.blurPlane,this.shadowCamera),this.blurPlane.visible=!1,r.setRenderTarget(a)}applyMinSize(){this.minSize&&this.shadowsRoot.scale.set(Math.max(this.minSize.x||0,this.shadowsRoot.scale.x),Math.max(this.minSize.y||0,this.shadowsRoot.scale.y),Math.max(this.minSize.z||0,this.shadowsRoot.scale.z))}};Ca([f()],cr.prototype,"autoFit");Ca([f()],cr.prototype,"darkness");Ca([f()],cr.prototype,"opacity");Ca([f()],cr.prototype,"blur");Ca([f()],cr.prototype,"occludeBelowGround");Ca([f()],cr.prototype,"backfaceShadows");let Pc=cr;const f_=[],bf=new Array,TP=w("logstats");class Wm extends k{onEnable(){console.log(this),TP&&this.startCoroutine(this.run(),pe.OnAfterRender)}*run(){for(;this.enabled;){const e=this.context.renderer.info;console.log(e.memory,e.render,e.programs),yield}}}class Oc extends k{isUsed=!0;usedBy=null}class Gm extends k{}const p_=w("debugdeletable");class Gs extends nt{static _instances=[];onEnable(){Gs._instances.push(this)}onDisable(){const e=Gs._instances.indexOf(this);e>=0&&Gs._instances.splice(e,1)}}class Hm extends k{update(){for(const e of Gs._instances){const t=this.gameObject;if(e.isInBox(t)===!0){const n=S.getComponentInParent(this.gameObject,Oc);if(n)p_&&console.warn("DeleteBox: Not deleting object with usage marker",this.guid,n);else{if(p_)try{if(e.box){const o=e.box,r=nt.testBox;B.DrawWireBox3(o,16711680,5),B.DrawWireBox3(r,255,5),console.log("DeleteBox: Destroying",this.gameObject,{deleteBoxArea:o,deletedObjectArea:r})}else console.log("DeleteBox: Destroying",this.gameObject)}catch{}uc(this.gameObject,this.context.connection)}}}}}var AP=Object.defineProperty,LP=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&AP(e,t,n),n};class cu extends k{visibleOn;onEnable(){this.apply()}apply(){this.test()||S.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:exports.DeviceUtilities.isMobileDevice()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}}LP([f()],cu.prototype,"visibleOn");var DP=Object.defineProperty,hr=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&DP(e,t,n),n};const On=w("debugdrag"),vf=[];var qm=(s=>(s[s.XZPlane=0]="XZPlane",s[s.Attached=1]="Attached",s[s.HitNormal=2]="HitNormal",s[s.DynamicViewAngle=3]="DynamicViewAngle",s[s.SnapToSurfaces=4]="SnapToSurfaces",s[s.None=5]="None",s))(qm||{});const oo=class Oi extends k{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=S.getComponentInChildren(e,Ne),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 c.Vector3;_marker=null;_isDragging=!1;_didDrag=!1;awake(){this._potentialDragStartEvt=null,this._dragHandlers=new Map,this._totalMovement=new c.Vector3,this._marker=null,this._isDragging=!1,this._didDrag=!1,this._dragHelper=null,this._draggingRigidbodies=[]}start(){this.gameObject.getComponentInParent(fi)||this.gameObject.addComponent(fi)}onEnable(){Oi._instances.push(this)}onDisable(){Oi._instances=Oi._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 n=S.getComponentInParent(e.object,Oi);!n||n!==this||(Oi.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"&&Oi.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)&&(Oi.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),Oi._active+=1;const n=new wf(this,this._targetObject);if(this._dragHandlers.set(e.event.space,n),n.onDragStart(e),this._dragHandlers.size===2){const o=this._dragHandlers.values(),r=o.next().value,a=o.next().value;if(r instanceof wf&&a instanceof wf){const l=new IP(this,this._targetObject,r,a);this._dragHandlers.set(this.gameObject,l),l.onDragStart(e)}else console.error("Attempting to construct a MultiTouchDragHandler with invalid DragPointerHandlers. This is likely a bug.",{a:r,b:a})}e.use()}}onPointerUp(e){if(On&&B.DrawLabel(e.point??this.gameObject.worldPosition,"POINTERUP:"+e.pointerId+", "+e.button,.03,3),!this.allowEdit(this.gameObject)||e.button!==0)return;this._potentialDragStartEvt=null;const t=this._dragHandlers.get(e.event.space),i=this._dragHandlers.get(this.gameObject);i&&(i.handlerA===t||i.handlerB===t)&&(this._dragHandlers.delete(this.gameObject),i.onDragEnd(e)),t&&(Oi._active>0&&(Oi._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=S.getComponentInParent(e.object,Oi);if(!t||t!==this&&t._isDragging)return;const i=this._targetObject||this.gameObject;if(!i)return;this._isDragging=!0;const n=S.getComponentInChildren(i,nn);On&&console.log("DRAG START",n,i),n&&(n.fastMode=!0,n?.requestOwnership()),this._marker=S.addComponent(i,Oc),this._draggingRigidbodies.length=0;const o=S.getComponentsInChildren(i,Ne);o&&this._draggingRigidbodies.push(...o)}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;Li.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=S.getComponentInChildren(e.object,nn);i&&(i.fastMode=!1)}if(this._marker&&this._marker.destroy(),!this._dragHelper)return;const t=this._dragHelper.selected;On&&console.log("DRAG END",t,t?.visible),this._dragHelper.setSelected(null,this.context)}};hr([f()],oo.prototype,"dragMode");hr([f()],oo.prototype,"snapGridResolution");hr([f()],oo.prototype,"keepRotation");hr([f()],oo.prototype,"xrDragMode");hr([f()],oo.prototype,"xrKeepRotation");hr([f()],oo.prototype,"xrDistanceDragFactor");hr([f()],oo.prototype,"showGizmo");let Ro=oo;class IP{handlerA;handlerB;context;settings;gameObject;_handlerAAttachmentPoint=new c.Vector3;_handlerBAttachmentPoint=new c.Vector3;_followObject;_manipulatorObject;_deviceMode;_followObjectStartWorldQuaternion=new c.Quaternion;constructor(e,t,i,n){this.context=e.context,this.settings=e,this.gameObject=t,this.handlerA=i,this.handlerB=n,this._followObject=new c.Object3D,this._manipulatorObject=new c.Object3D,this.context.scene.add(this._manipulatorObject);const o=H.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),o&&(o.worldToLocal(this._tempVec1),o.worldToLocal(this._tempVec2)),this._initialDistance=this._tempVec1.distanceTo(this._tempVec2),this._initialDistance<.02?(On&&console.log("Finding alternative drag attachment points since initial distance is too low: "+this._initialDistance.toFixed(2)),this.handlerA.followObject.parent.getWorldPosition(this._tempVec1),this.handlerB.followObject.parent.getWorldPosition(this._tempVec2),this._handlerAAttachmentPoint.copy(this._tempVec1),this._handlerBAttachmentPoint.copy(this._tempVec2),this.gameObject.worldToLocal(this._handlerAAttachmentPoint),this.gameObject.worldToLocal(this._handlerBAttachmentPoint),this._initialDistance=this._tempVec1.distanceTo(this._tempVec2),this._initialDistance<.001&&(console.warn("Not supported right now – controller drag points for multitouch are too close!"),this._initialDistance=1)):(this._handlerAAttachmentPoint.copy(this.handlerA.hitPointInLocalSpace),this._handlerBAttachmentPoint.copy(this.handlerB.hitPointInLocalSpace)),this._tempVec3.lerpVectors(this._tempVec1,this._tempVec2,.5),this._initialScale.copy(t.scale),On){this._followObject.add(new c.AxesHelper(2)),this._manipulatorObject.add(new c.AxesHelper(5));const r=a=>`${a.x.toFixed(2)}, ${a.y.toFixed(2)}, ${a.z.toFixed(2)}`;B.DrawLine(this._tempVec1,this._tempVec2,65535,0,!1),B.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 c.Vector3;_manipulatorRotOffset=new c.Quaternion;_manipulatorScaleOffset=new c.Vector3;_tempVec1=new c.Vector3;_tempVec2=new c.Vector3;_tempVec3=new c.Vector3;tempLookMatrix=new c.Matrix4;_initialScale=new c.Vector3;_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),On&&(B.DrawLabel(this._tempVec3.clone().add(new c.Vector3(0,.2,0)),"A:B "+t.toFixed(2),.03),B.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 r=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer"?this.settings.xrKeepRotation:this.settings.keepRotation;if(this.settings.snapGridResolution>0){const u=this._followObject.worldPosition,p=this.settings.snapGridResolution;u.x=Math.round(u.x/p)*p,u.y=Math.round(u.y/p)*p,u.z=Math.round(u.z/p)*p,this._followObject.worldPosition=u,this._followObject.updateMatrix()}r&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion,this._followObject.updateMatrix());const a=D.clamp01(this.context.time.deltaTime*e*t),l=i.worldPosition;l.lerp(n.worldPosition,a),i.worldPosition=l;const h=i.worldQuaternion;h.slerp(n.worldQuaternion,a),i.worldQuaternion=h;const d=i.worldScale;d.lerp(n.worldScale,a),i.worldScale=d}setTargetObject(e){this.gameObject=e}}class wf{getTotalMovement(){return this._totalMovement}get followObject(){return this._followObject}get hitPointInLocalSpace(){return this._hitPointInLocalSpace}context;gameObject;settings;_lastRig=void 0;_followObject;_totalMovement=new c.Vector3;_totalMovementAlongRayDirection=0;_grabStartDistance=0;_deviceMode;_followObjectStartPosition=new c.Vector3;_followObjectStartQuaternion=new c.Quaternion;_followObjectStartWorldQuaternion=new c.Quaternion;_lastDragPosRigSpace;_tempVec=new c.Vector3;_tempMat=new c.Matrix4;_hitPointInLocalSpace=new c.Vector3;_hitNormalInLocalSpace=new c.Vector3;_bottomCenter=new c.Vector3;_backCenter=new c.Vector3;_backBottomCenter=new c.Vector3;_bounds=new c.Box3;_dragPlane=new c.Plane(new c.Vector3(0,1,0));_draggedOverObject=null;_draggedOverObjectLastSetUp=null;_draggedOverObjectLastNormal=new c.Vector3;_draggedOverObjectDuration=0;setTargetObject(e){this.gameObject=e}constructor(e,t){this.settings=e,this.context=e.context,this.gameObject=t,this._followObject=new c.Object3D}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 n=H.active?.rig?.gameObject?.worldScale.x||1;this._grabStartDistance/=n,this._totalMovementAlongRayDirection=0,this._lastDragPosRigSpace=void 0,On&&(B.DrawLine(t,e.worldPosition,65280,.5,!1),B.DrawLabel(e.worldPosition.add(new c.Vector3(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 _=e.event.space,g=_.worldPosition;this.gameObject.worldToLocal(g),this._hitPointInLocalSpace.copy(g);const v=_.worldUp;this._tempMat.copy(this.gameObject.matrixWorld).invert(),v.transformDirection(this._tempMat),this._hitNormalInLocalSpace.copy(v)}this.recenter(),this._totalMovement.set(0,0,0),this._deviceMode=e.mode;const i=this._followObject.parent.worldForward,o=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer"?this.settings.xrDragMode:this.settings.dragMode,r=this._hitPointInLocalSpace.clone();switch(this.gameObject.localToWorld(r),o){case 0:const _=new c.Vector3(0,1,0);this.gameObject.parent&&_.transformDirection(this.gameObject.parent.matrixWorld.clone().invert()),this._dragPlane.setFromNormalAndCoplanarPoint(_,r);break;case 2:const g=this._hitNormalInLocalSpace.clone();g.transformDirection(this.gameObject.matrixWorld),this._dragPlane.setFromNormalAndCoplanarPoint(g,r);break;case 1:this._dragPlane.setFromNormalAndCoplanarPoint(i,r);break;case 3:this.setPlaneViewAligned(r,!0);break;case 4:this.setPlaneViewAligned(r,!1);break}const a=this.gameObject.parent,l=this.gameObject.position.clone(),h=this.gameObject.quaternion.clone(),d=this.gameObject.scale.clone(),u=this.gameObject.matrixWorld.clone();a&&a.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 p=Bt([this.gameObject]);p.expandByPoint(this.gameObject.worldPosition);const m=new c.Vector3;p.getCenter(m);const y=new c.Vector3;p.getSize(y),this._bottomCenter.copy(m.clone().add(new c.Vector3(0,-y.y/2,0))),this._backCenter.copy(m.clone().add(new c.Vector3(0,0,y.z/2))),this._backBottomCenter.copy(m.clone().add(new c.Vector3(0,-y.y/2,y.z/2))),this._bounds.copy(p),a&&a.add(this.gameObject),this.gameObject.position.copy(l),this.gameObject.quaternion.copy(h),this.gameObject.scale.copy(d),this.gameObject.matrixWorld.copy(u),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=H.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),On){let o=t;i&&(o=o.clone(),o.transformDirection(i.matrixWorld)),B.DrawRay(o,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,o=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 h=10;a&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);let d=1,u=2;if(r&&this._grabStartDistance>.5){const b=1+this._totalMovementAlongRayDirection*(2*this.settings.xrDistanceDragFactor);d=Math.max(0,b),d=d*d*d}else this._grabStartDistance<=.5&&(u=3);this._followObject.position.copy(this._followObjectStartPosition),a||this._followObject.quaternion.copy(this._followObjectStartQuaternion),this._followObject.position.multiplyScalar(d),this._followObject.updateMatrix();const p=this._hasLastSurfaceHitPoint;this._hasLastSurfaceHitPoint=!1;const m=new c.Ray(n,o);if(l==4){const b=this.context.physics.raycastFromRay(m,{testObject:x=>x!==this.followObject&&x!==i&&x!==t});if(b.length>0){const x=b[0];if(this._draggedOverObject===x.object?this._draggedOverObjectDuration+=this.context.time.deltaTime:(this._draggedOverObject=x.object,this._draggedOverObjectDuration=0),x.face){this._hasLastSurfaceHitPoint=!0,this._lastSurfaceHitPoint.copy(x.point);const O=this._draggedOverObjectDuration>=.15,E=this._totalMovement.length()>=.001,j=V(x.normal||x.face.normal).applyQuaternion(x.object.worldQuaternion);if((O||E)&&(this._draggedOverObjectLastSetUp!==this._draggedOverObject||this._draggedOverObjectLastNormal.dot(j)<.999999||this.context.time.frame%60===0)){this._draggedOverObjectLastSetUp=this._draggedOverObject,this._draggedOverObjectLastNormal.copy(x.face.normal);const L=V(),z=V();this._bounds.getCenter(L),this._bounds.getSize(z),L.sub(z.multiplyScalar(.5).multiply(j)),this._hitPointInLocalSpace.copy(L),this._hitNormalInLocalSpace.copy(x.face.normal),this._bounds.getCenter(L),this._bounds.getSize(z),L.add(z.multiplyScalar(.5).multiply(x.face.normal));const $=V(this._hitPointInLocalSpace).add(L);this._followObject.localToWorld($);const R=x.point;this._dragPlane.setFromNormalAndCoplanarPoint(j,R)}else if(!(O||E))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 b=V(this._hitPointInLocalSpace);this._followObject.localToWorld(b),On&&B.DrawLine(b,this._tempVec,65535,0,!1),this._followObject.worldPosition=this._tempVec.multiplyScalar(2).sub(b),this._followObject.updateMatrix(),this._followObject.updateMatrix()}if(this.settings.snapGridResolution>0){const b=this._followObject.worldPosition,x=this.settings.snapGridResolution;b.x=Math.round(b.x/x)*x,b.y=Math.round(b.y/x)*x,b.z=Math.round(b.z/x)*x,this._followObject.worldPosition=b,this._followObject.updateMatrix()}a&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion,this._followObject.updateMatrix());const y=D.clamp01(this.context.time.deltaTime*h*u),_=D.clamp01(this.context.time.deltaTime*h*.5*u),g=t.worldPosition;g.lerp(this._followObject.worldPosition,y),t.worldPosition=g;const v=t.worldQuaternion;if(v.slerp(this._followObject.worldQuaternion,_),t.worldQuaternion=v,On){const b=this._hitPointInLocalSpace.clone();t.localToWorld(b),B.DrawSphere(b,.02,16711680);const x=this._hitNormalInLocalSpace.clone();x.applyQuaternion(v),B.DrawRay(b,x,16711680),B.DrawLabel(g.add(new c.Vector3(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 c.Vector3;_manipulatorRotOffset=new c.Quaternion;_manipulatorScaleOffset=new c.Vector3;_tempVec1=new c.Vector3;_tempVec2=new c.Vector3;_tempVec3=new c.Vector3;tempLookMatrix=new c.Matrix4;_initialScale=new c.Vector3;_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),On&&(B.DrawLabel(this._tempVec3.clone().add(new c.Vector3(0,.2,0)),"A:B "+t.toFixed(2),.03),B.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 r=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer"?this.settings.xrKeepRotation:this.settings.keepRotation;if(this.settings.snapGridResolution>0){const u=this._followObject.worldPosition,p=this.settings.snapGridResolution;u.x=Math.round(u.x/p)*p,u.y=Math.round(u.y/p)*p,u.z=Math.round(u.z/p)*p,this._followObject.worldPosition=u,this._followObject.updateMatrix()}r&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion,this._followObject.updateMatrix());const a=D.clamp01(this.context.time.deltaTime*e*t),l=i.worldPosition;l.lerp(n.worldPosition,a),i.worldPosition=l;const h=i.worldQuaternion;h.slerp(n.worldQuaternion,a),i.worldQuaternion=h;const d=i.worldScale;d.lerp(n.worldScale,a),i.worldScale=d}setTargetObject(e){this.gameObject=e}}class wf{getTotalMovement(){return this._totalMovement}get followObject(){return this._followObject}get hitPointInLocalSpace(){return this._hitPointInLocalSpace}context;gameObject;settings;_lastRig=void 0;_followObject;_totalMovement=new c.Vector3;_totalMovementAlongRayDirection=0;_grabStartDistance=0;_deviceMode;_followObjectStartPosition=new c.Vector3;_followObjectStartQuaternion=new c.Quaternion;_followObjectStartWorldQuaternion=new c.Quaternion;_lastDragPosRigSpace;_tempVec=new c.Vector3;_tempMat=new c.Matrix4;_hitPointInLocalSpace=new c.Vector3;_hitNormalInLocalSpace=new c.Vector3;_bottomCenter=new c.Vector3;_backCenter=new c.Vector3;_backBottomCenter=new c.Vector3;_bounds=new c.Box3;_dragPlane=new c.Plane(new c.Vector3(0,1,0));_draggedOverObject=null;_draggedOverObjectLastSetUp=null;_draggedOverObjectLastNormal=new c.Vector3;_draggedOverObjectDuration=0;setTargetObject(e){this.gameObject=e}constructor(e,t){this.settings=e,this.context=e.context,this.gameObject=t,this._followObject=new c.Object3D}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 n=H.active?.rig?.gameObject?.worldScale.x||1;this._grabStartDistance/=n,this._totalMovementAlongRayDirection=0,this._lastDragPosRigSpace=void 0,On&&(B.DrawLine(t,e.worldPosition,65280,.5,!1),B.DrawLabel(e.worldPosition.add(new c.Vector3(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 b=e.event.space,g=b.worldPosition;this.gameObject.worldToLocal(g),this._hitPointInLocalSpace.copy(g);const v=b.worldUp;this._tempMat.copy(this.gameObject.matrixWorld).invert(),v.transformDirection(this._tempMat),this._hitNormalInLocalSpace.copy(v)}this.recenter(),this._totalMovement.set(0,0,0),this._deviceMode=e.mode;const i=this._followObject.parent.worldForward,o=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer"?this.settings.xrDragMode:this.settings.dragMode,r=this._hitPointInLocalSpace.clone();switch(this.gameObject.localToWorld(r),o){case 0:const b=new c.Vector3(0,1,0);this.gameObject.parent&&b.transformDirection(this.gameObject.parent.matrixWorld.clone().invert()),this._dragPlane.setFromNormalAndCoplanarPoint(b,r);break;case 2:const g=this._hitNormalInLocalSpace.clone();g.transformDirection(this.gameObject.matrixWorld),this._dragPlane.setFromNormalAndCoplanarPoint(g,r);break;case 1:this._dragPlane.setFromNormalAndCoplanarPoint(i,r);break;case 3:this.setPlaneViewAligned(r,!0);break;case 4:this.setPlaneViewAligned(r,!1);break}const a=this.gameObject.parent,l=this.gameObject.position.clone(),h=this.gameObject.quaternion.clone(),d=this.gameObject.scale.clone(),u=this.gameObject.matrixWorld.clone();a&&a.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 p=Bt([this.gameObject]);p.expandByPoint(this.gameObject.worldPosition);const m=new c.Vector3;p.getCenter(m);const y=new c.Vector3;p.getSize(y),this._bottomCenter.copy(m.clone().add(new c.Vector3(0,-y.y/2,0))),this._backCenter.copy(m.clone().add(new c.Vector3(0,0,y.z/2))),this._backBottomCenter.copy(m.clone().add(new c.Vector3(0,-y.y/2,y.z/2))),this._bounds.copy(p),a&&a.add(this.gameObject),this.gameObject.position.copy(l),this.gameObject.quaternion.copy(h),this.gameObject.scale.copy(d),this.gameObject.matrixWorld.copy(u),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=H.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),On){let o=t;i&&(o=o.clone(),o.transformDirection(i.matrixWorld)),B.DrawRay(o,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,o=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 h=10;a&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);let d=1,u=2;if(r&&this._grabStartDistance>.5){const _=1+this._totalMovementAlongRayDirection*(2*this.settings.xrDistanceDragFactor);d=Math.max(0,_),d=d*d*d}else this._grabStartDistance<=.5&&(u=3);this._followObject.position.copy(this._followObjectStartPosition),a||this._followObject.quaternion.copy(this._followObjectStartQuaternion),this._followObject.position.multiplyScalar(d),this._followObject.updateMatrix();const p=this._hasLastSurfaceHitPoint;this._hasLastSurfaceHitPoint=!1;const m=new c.Ray(n,o);if(l==4){const _=this.context.physics.raycastFromRay(m,{testObject:x=>x!==this.followObject&&x!==i&&x!==t});if(_.length>0){const x=_[0];if(this._draggedOverObject===x.object?this._draggedOverObjectDuration+=this.context.time.deltaTime:(this._draggedOverObject=x.object,this._draggedOverObjectDuration=0),x.face){this._hasLastSurfaceHitPoint=!0,this._lastSurfaceHitPoint.copy(x.point);const O=this._draggedOverObjectDuration>=.15,E=this._totalMovement.length()>=.001,j=V(x.normal||x.face.normal).applyQuaternion(x.object.worldQuaternion);if((O||E)&&(this._draggedOverObjectLastSetUp!==this._draggedOverObject||this._draggedOverObjectLastNormal.dot(j)<.999999||this.context.time.frame%60===0)){this._draggedOverObjectLastSetUp=this._draggedOverObject,this._draggedOverObjectLastNormal.copy(x.face.normal);const L=V(),z=V();this._bounds.getCenter(L),this._bounds.getSize(z),L.sub(z.multiplyScalar(.5).multiply(j)),this._hitPointInLocalSpace.copy(L),this._hitNormalInLocalSpace.copy(x.face.normal),this._bounds.getCenter(L),this._bounds.getSize(z),L.add(z.multiplyScalar(.5).multiply(x.face.normal));const $=V(this._hitPointInLocalSpace).add(L);this._followObject.localToWorld($);const R=x.point;this._dragPlane.setFromNormalAndCoplanarPoint(j,R)}else if(!(O||E))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(_),On&&B.DrawLine(_,this._tempVec,65535,0,!1),this._followObject.worldPosition=this._tempVec.multiplyScalar(2).sub(_),this._followObject.updateMatrix(),this._followObject.updateMatrix()}if(this.settings.snapGridResolution>0){const _=this._followObject.worldPosition,x=this.settings.snapGridResolution;_.x=Math.round(_.x/x)*x,_.y=Math.round(_.y/x)*x,_.z=Math.round(_.z/x)*x,this._followObject.worldPosition=_,this._followObject.updateMatrix()}a&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion,this._followObject.updateMatrix());const y=D.clamp01(this.context.time.deltaTime*h*u),b=D.clamp01(this.context.time.deltaTime*h*.5*u),g=t.worldPosition;g.lerp(this._followObject.worldPosition,y),t.worldPosition=g;const v=t.worldQuaternion;if(v.slerp(this._followObject.worldQuaternion,b),t.worldQuaternion=v,On){const _=this._hitPointInLocalSpace.clone();t.localToWorld(_),B.DrawSphere(_,.02,16711680);const x=this._hitNormalInLocalSpace.clone();x.applyQuaternion(v),B.DrawRay(_,x,16711680),B.DrawLabel(g.add(new c.Vector3(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: "${o}"
|
|
975
|
-
Binary:`,i)}else console.debug("Could not determine file type from binary data");return"unknown"}var BP=Object.defineProperty,Pa=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&BP(e,t,n),n};const oi=w("debugdroplistener");class FP extends CustomEvent{constructor(e){super("object-added",{detail:e})}}const UP="blob";class fs extends k{dropArea;fitIntoVolume=!1;fitVolumeSize=new c.Vector3(1,1,1);placeAtHitPosition=!0;useNetworking=!1;onDropped=new oe;loadFromURL(e,t){return this.addFromUrl(e,{screenposition:new c.Vector2,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){oi&&console.debug("[DropListener] Ignoring networked event because networking is disabled",e);return}if(e.guid?.startsWith(this.guid)){const t=e.url;if(console.debug("[DropListener] Received networked event",e),t)if(Array.isArray(t))for(const i of t)this.addFromUrl(i,{screenposition:new c.Vector2,point:e.point,size:e.size},!0);else this.addFromUrl(t,{screenposition:new c.Vector2,point:e.point,size:e.size},!0)}};handlePaste=e=>{if(this.context.connection.allowEditing===!1||e.defaultPrevented)return;navigator.clipboard.readText().then(i=>{if(i&&(i.startsWith("http")||i.startsWith("https")||i.startsWith("blob"))){const o={screenposition:new c.Vector2(this.context.input.mousePosition.x,this.context.input.mousePosition.y)};this.testIfIsInDropArea(o)&&this.addFromUrl(i,o,!1)}}).catch(console.warn)};onDrag=e=>{this.context.connection.allowEditing!==!1&&e.preventDefault()};onDrop=async e=>{if(this.context.connection.allowEditing===!1||(oi&&console.log(e),!e?.dataTransfer)||e["droplistener:handled"])return;e.preventDefault();const t={screenposition:new c.Vector2(e.offsetX,e.offsetY)};if(this.dropArea&&this.testIfIsInDropArea(t)===!1)return;e["droplistener:handled"]=!0;const i=e.dataTransfer.items;if(!i)return;const n=[];for(const o in i){const r=i[o];if(r.kind==="file"){const a=r.getAsFile();if(!a)continue;n.push(a)}else r.kind==="string"&&r.type=="text/plain"&&r.getAsString(a=>{this.addFromUrl(a,t,!1)})}n.length>0&&await this.addFromFiles(n,t)};async addFromUrl(e,t,i){oi&&console.log("dropped url",e);try{if(e.startsWith("https://github.com/")){const r=e.split("/"),a=r[3],l=r[4],h=r[6],d=r.slice(7).join("/");e=`https://raw.githubusercontent.com/${a}/${l}/${h}/${d}`}else e.startsWith("https://polyhaven.com/a")&&(e=zP(e));if(!e)return null;const n=e.toLowerCase();if(n.endsWith(".hdr")||n.endsWith(".hdri")||n.endsWith(".exr")||n.endsWith(".png")||n.endsWith(".jpg")||n.endsWith(".jpeg"))return console.warn(`Fileformat is not supported: ${n}`),null;this.removePreviouslyAddedObjects();const o=await Md.loadFileFromURL(new URL(e),{guid:this.guid,context:this.context,parent:this.gameObject,point:t.point,size:t.size});if(o&&this._addedObjects.length<=0)return t.url=e,this.onObjectLoaded(o,t,i)}catch{console.warn("String is not a valid URL",e)}return null}_abort=null;async addFromFiles(e,t){if(oi&&console.log("Add files",e),!!Array.isArray(e)&&e.length){this.deleteDropEvent(),this.removePreviouslyAddedObjects(),Wl(UP,null),this._abort?.abort("New files dropped"),this._abort=new AbortController;for(const i of e){if(!i)continue;if(i.type.startsWith("image/")){oi&&console.warn("Ignoring dropped image file",i.name,i.type);continue}else if(i.name.endsWith(".bin")){oi&&console.warn("Ignoring dropped binary file",i.name,i.type);continue}console.debug("Load file "+i.name+" + "+i.type);const n=await Md.loadFile(i,this.context,{guid:this.guid});if(n){this.dispatchEvent(new CustomEvent("file-dropped",{detail:i})),t.file=i;const o=this.onObjectLoaded(n,t,!1);o&&this.context.connection.isConnected&&this.useNetworking&&(console.debug("Uploading dropped file to blob storage"),exports.BlobStorage.upload(i,{abort:this._abort?.signal}).then(r=>{r?.download_url&&this._addedObjects.includes(o)&&this.sendDropEvent(r.download_url,o,n.contentMD5)}).catch(console.warn));break}}}}_addedObjects=new Array;_addedModels=new Array;removePreviouslyAddedObjects(e=!0){if(e)for(const t of this._addedObjects)t.parent===this.gameObject&&ui(t,!0,!0);this._addedObjects.length=0,this._addedModels.length=0}onObjectLoaded(e,t,i){const{model:n,contentMD5:o}=e;if(oi&&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 c.Box3().setFromCenterAndSize(new c.Vector3(0,this.fitVolumeSize.y*.5,0).add(this.gameObject.worldPosition),this.fitVolumeSize);if(oi&&B.DrawWireBox3(a,255,5),this.fitIntoVolume&&kb(r,a,{position:!this.placeAtHitPosition}),this.placeAtHitPosition&&t&&t.screenposition){r.visible=!1;const h=this.context.physics.raycast({screenPoint:this.context.input.convertScreenspaceToRaycastSpace(t.screenposition.clone())});if(r.visible=!0,h&&h.length>0)for(const d of h){const u=d.point.clone();oi&&console.log("Place object at hit",d),Eb(r,u);break}}fa.autoplayAnimations(n);const l=new FP({sender:this,gltf:n,model:n,object:r,contentMD5:o,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,o),r}async sendDropEvent(e,t,i){if(!this.useNetworking){oi&&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=Bt([t]),o={name:t.name,guid:this.guid,url:e,point:t.worldPosition.clone(),size:n.getSize(new c.Vector3),contentMD5:i};this.context.connection.send("droplistener",o)}}deleteDropEvent(){this.context.connection.sendDeleteRemoteState(this.guid)}testIfIsInDropArea(e){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:n=>!this._addedObjects.includes(n)}).length)return A()&&console.log(`Dropped outside of drop area for DropListener "${this.name}".`),!1}return!0}}Pa([f(c.Object3D)],fs.prototype,"dropArea");Pa([f()],fs.prototype,"fitIntoVolume");Pa([f(c.Vector3)],fs.prototype,"fitVolumeSize");Pa([f()],fs.prototype,"placeAtHitPosition");Pa([f()],fs.prototype,"useNetworking");Pa([f(oe)],fs.prototype,"onDropped");function zP(s){if(!s.startsWith("https://polyhaven.com/"))return s;const e="https://dl.polyhaven.org/file/ph-assets/Models/gltf/4k/",n=new URL(s).pathname.split("/").pop(),o=`${e}${n}/${n}_4k.gltf`;return console.log("Resolved polyhaven asset url",s,"→",o),o}var Md;(s=>{async function e(i,n,o){const r=o.guid,a=new mt(r),l=new Blob([i],{type:i.type||S0(i.name)||void 0}),h=URL.createObjectURL(l),d=await en().loadSync(n,h,i.name,a).catch(u=>(console.error(`Failed to load file "${i.name}" (${i.type}):`,u),null));return URL.revokeObjectURL(h),d?new Promise((u,p)=>{const m=new FileReader;m.readAsArrayBuffer(i),m.onloadend=async y=>{const _=m.result,g=exports.BlobStorage.hashMD5(_);return u({model:d,contentMD5:g})}}):(console.warn(`Failed to load "${i.name}" (${i.type})`),null)}s.loadFile=e;async function t(i,n){return new Promise(async(o,r)=>{const a=new mt(n.guid),l=i.toString();oi&&B.DrawWireSphere(n.point,.1,16711680,3);const h=exports.PreviewHelper.addPreview({guid:n.guid,parent:n.parent,position:n?.point,size:n?.size}),d=await en().loadSync(n.context,l,l,a,u=>{h.onProgress(u.loaded/u.total)}).catch(console.warn);if(d){const u=await fetch(l).then(m=>m.arrayBuffer()),p=exports.BlobStorage.hashMD5(u);oi?setTimeout(()=>exports.PreviewHelper.removePreview(n.guid),3e3):exports.PreviewHelper.removePreview(n.guid),o({model:d,contentMD5:p})}else oi?setTimeout(()=>exports.PreviewHelper.removePreview(n.guid),3e3):exports.PreviewHelper.removePreview(n.guid),console.warn("Unsupported file type: "+i.toString())})}s.loadFileFromURL=t})(Md||(Md={}));var NP=Object.defineProperty,Xm=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&NP(e,t,n),n};const hu=class O0 extends k{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 mt(this.guid);this.object=S.instantiate(this.object,{idProvider:t,keepWorldPosition:!1}),S.getComponent(this.object,O0)?.destroy();let n=this.object.getComponentInChildren(Ro);n||(n=this.object.addComponent(Ro,{dragMode:qm.SnapToSurfaces}),n.guid=t.generateUUID());let o=S.getComponent(n.gameObject,nn);o||(o=n.gameObject.addComponent(nn),o.guid=t.generateUUID())}this.object.visible=!1;const e=this.gameObject.getComponent(Ro);e&&(e.enabled=!1),this._startPosition=this.object.position?.clone()??new c.Vector3(0,0,0),this._startQuaternion=this.object.quaternion?.clone()??new c.Quaternion(0,0,0,1)}this.gameObject.getComponentInParent(fi)||this.gameObject.addComponent(fi)}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=S.getComponent(t,Ro);i?(i.onPointerDown(e),this._forwardPointerEvents.set(e.event.space,i)):A()&&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 km(1)}handleDuplication(){if(!this.object||this.limitCount>0&&this._currentCount>=this.limitCount||this.object===this.gameObject)return null;if(S.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 on;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=S.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}};Xm([f(c.Object3D)],hu.prototype,"parent");Xm([f(c.Object3D)],hu.prototype,"object");Xm([f()],hu.prototype,"limitCount");let Qm=hu;var Xn=(s=>(s[s.PointerEnter=0]="PointerEnter",s[s.PointerExit=1]="PointerExit",s[s.PointerDown=2]="PointerDown",s[s.PointerUp=3]="PointerUp",s[s.PointerClick=4]="PointerClick",s[s.Drag=5]="Drag",s[s.Drop=6]="Drop",s[s.Scroll=7]="Scroll",s[s.UpdateSelected=8]="UpdateSelected",s[s.Select=9]="Select",s[s.Deselect=10]="Deselect",s[s.Move=11]="Move",s[s.InitializePotentialDrag=12]="InitializePotentialDrag",s[s.BeginDrag=13]="BeginDrag",s[s.EndDrag=14]="EndDrag",s[s.Submit=15]="Submit",s[s.Cancel=16]="Cancel",s))(Xn||{}),VP=Object.defineProperty,Ym=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&VP(e,t,n),n};class Km{eventID;callback=new oe}Ym([f()],Km.prototype,"eventID");Ym([f(oe)],Km.prototype,"callback");class du extends k{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(Xn.PointerClick)||this.hasTrigger(Xn.PointerDown)||this.hasTrigger(Xn.PointerUp)}onPointerClick(e){this.invoke(Xn.PointerClick)}onPointerEnter(e){this.shouldChangeCursor()&&this.context.input.setCursor("pointer"),this.invoke(Xn.PointerEnter)}onPointerExit(e){this.shouldChangeCursor()&&this.context.input.unsetCursor("pointer"),this.invoke(Xn.PointerExit)}onPointerDown(e){this.invoke(Xn.PointerDown)}onPointerUp(e){this.invoke(Xn.PointerUp)}}Ym([f(Km)],du.prototype,"triggers");class M0{writer;constructor(e){this.writer=e}writeNode(e){}}class $P extends M0{beforeWriteNode(e,t){B.isGizmo(e)&&(t.keep=!1)}}class k0 extends M0{beforeWriteTexture(e,t){e.isRenderTargetTexture&&(t.newTexture=Em(new Z(1,1,1,0)))}}function Ep(s){const e=ou.DontExport;return!(s.hideFlags&e)}const xf=w("debugexr");class WP{get name(){return"EXT_texture_exr"}parser;constructor(e){this.parser=e,xf&&console.log(e)}loadTexture(e){const t=this.name,i=this.parser,o=i.json.textures[e];if(xf&&console.log("EXT_texture_exr.loadTexture",e,o),!o.extensions||!o.extensions[t])return null;const r=o.extensions[t],a=new q.EXRLoader(i.options.manager);return xf&&console.log("EXT_texture_exr.loadTexture",r),i.loadTextureImage(e,r.source,a)}}typeof window<"u"&&window.addEventListener("unhandledrejection",s=>{});const Wn=st,Sh="$___Export_Components",GP="NEEDLE_components";class HP{[Po]}class qP{node;nodeIndex;nodeDef;constructor(e,t,i){this.node=e,this.nodeIndex=t,this.nodeDef=i}}class E0{get name(){return GP}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,o)=>{try{this.serializeUserData(n,o)&&(t.extensionsUsed[this.name]=!0),i(n,o)}finally{this.afterSerializeUserData(n,o)}}}return this})}beforeParse(){this.exportContext={},this.objectToNodeMap={}}serializeUserData(e,t){const i=e.userData?.components;return!i||i.length<=0?!1:(delete e.userData.components,e[Sh]=i,!0)}afterSerializeUserData(e,t){if(e.type==="Scene"&&Wn&&console.log("DONE",JSON.stringify(t)),e[Sh]===void 0)return;const i=e[Sh];delete e[Sh],i!==null&&(e.userData.components=i)}writeNode(e,t){const i=this.writer.json.nodes.length;Wn&&console.log(e.name,i,e.uuid);const n=new qP(e,i,t);this.exportContext[i]=n,this.objectToNodeMap[e.uuid]=i}afterParse(e){Wn&&console.log("AFTER",e);for(const t in this.exportContext){const i=this.exportContext[t],n=i.node,o=i.nodeDef,r=i.nodeIndex,a=n.userData?.components;if(!a||a.length<=0)continue;const l=new HP;o.extensions=o.extensions||{},o.extensions[this.name]=l,this.context.object=n,this.context.nodeId=r,this.context.objectToNode=this.objectToNodeMap;const h=[];for(const d of a){this.context.target=d;const u=en().writeBuiltinComponentData(d,this.context);u!==null&&h.push(u)}h.length>0&&(l[Po]=h,Wn&&console.log("DID WRITE",n,"nodeIndex",r,h))}}beforeRoot(){return Wn&&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];Wn&&console.log("After root",e,this.parser,i);const o=[];if(n===!0){const r=t.json.nodes;if(r){for(let a=0;a<r.length;a++){const l=await t.getDependency("node",a);this.nodeToObjectMap[a]=l}for(let a=0;a<r.length;a++){const l=r[a],h=a,d=l.extensions;if(!d)continue;const u=d[this.name];if(!u)continue;Wn&&console.log("NODE",l);const p=this.nodeToObjectMap[h];if(!p){console.error("Could not find object for node index: "+h,l,t);continue}Qd(p),o.push(this.createComponents(p,u))}}}await Promise.all(o);for(const r of t.associations.keys()){const a=t.associations.get(r);if(a?.materials!=null){const l="/materials/"+a.materials;mC(r,l)}}}async createComponents(e,t){if(!t)return;const i=t[Po];if(i){const n=new Array;Wn&&console.log(e.name,i);for(const o in i){const r=i[o];Wn&&console.log("Serialized data",JSON.parse(JSON.stringify(r))),r&&this.parser&&n.push(Cm(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[Po]=e.userData[Po]||[],e.userData[Po].push(r)}await Promise.all(n).catch(o=>{console.error("Error while loading components",o)})}}}const m_="NEEDLE_gameobject_data";class XP{get name(){return m_}parser;constructor(e){this.parser=e}afterRoot(e){const t=[];for(let i=0;i<this.parser.json.nodes?.length;i++){const n=this.parser.json.nodes[i];if(n&&n.extensions){const o=n.extensions[m_];if(o){const r=this.findAndApplyExtensionData(i,o);t.push(r)}}}return Promise.all(t).then(()=>null)}async findAndApplyExtensionData(e,t){const i=await this.parser.getDependency("node",e);i&&this.applyExtensionData(i,t)}applyExtensionData(e,t){t.layers===void 0&&(t.layers=0),e.userData.layer=t.layers,e.layers.disableAll(),e.layers.set(t.layers),e.userData.tag=t.tag??"none",e.hideFlags=0,e.userData.static=t.static??!1,e.visible=t.activeSelf??!0,e.guid=t.guid}}const g_="NEEDLE_lighting_settings",Nr=w("debugenvlight");class QP{get name(){return g_}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[g_];if(i){Nr&&console.log('Loaded "'+this.name+'", src: "'+this.sourceId+'"',i);let n;if(e.scene.children.length===1){const o=e.scene.children[0];n=S.addComponent(o,kd,{},{callAwake:!1})}else{const o=new c.Object3D;o.name="LightSettings "+this.sourceId,e.scene.add(o),n=S.addComponent(o,kd,{},{callAwake:!1})}n.sourceId=this.sourceId,n.ambientIntensity=i.ambientIntensity,n.ambientLight=new c.Color().fromArray(i.ambientLight),Array.isArray(i.ambientTrilight)&&(n.ambientTrilight=i.ambientTrilight.map(o=>new c.Color().fromArray(o))),n.ambientMode=i.ambientMode,n.environmentReflectionSource=i.environmentReflectionSource}}return null}}ae.registerCallback(re.ContextCreated,s=>{const e=s.context,t=S.findObjectOfType(kd,e);t?.sourceId&&(t.enabled=!0)});class kd extends k{ambientMode=ia.Skybox;ambientLight;ambientTrilight;ambientIntensity=1;environmentReflectionSource=wd.Skybox;_hasReflection=!1;_ambientLightObj;_hemisphereLightObj;awake(){if(this.sourceId){const t=this.environmentReflectionSource===wd.Skybox?_n.Skybox:_n.Reflection,i=this.context.lightmaps.tryGet(this.sourceId,t,0);this._hasReflection=i!=null,i&&this.context.sceneLighting.internalRegisterReflection(this.sourceId,i)}this.enabled=!1,this.context.sceneLighting.internalRegisterSceneLightSettings(this),Nr&&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(Nr&&console.warn("💡🟡 >>> Enable lighting",this.sourceId,this.enabled,this),this.ambientMode==ia.Flat){if(this.ambientLight&&!this._ambientLightObj){const e=this.calculateIntensityFactor(this.ambientLight);this._ambientLightObj=new c.AmbientLight(this.ambientLight,this.ambientIntensity*e),Nr&&console.log("Created ambient light",this.sourceId,this._ambientLightObj,this.ambientIntensity,e)}this._ambientLightObj&&this.gameObject.add(this._ambientLightObj)}else if(this.ambientMode===ia.Trilight){if(this.ambientTrilight){const e=this.ambientTrilight[0],t=this.ambientTrilight[this.ambientTrilight.length-1],i=this.calculateIntensityFactor(t);this._hemisphereLightObj=new c.HemisphereLight(t,e,this.ambientIntensity*i),this.gameObject.add(this._hemisphereLightObj),Nr&&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(){Nr&&console.warn("💡⚫ <<< Disable lighting:",this.sourceId,this),this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._hemisphereLightObj&&this._hemisphereLightObj.removeFromParent(),this.sourceId&&this.context.sceneLighting.internalDisableReflection(this.sourceId)}}const Sf=w("debugstencil");function YP(s,e){return(s&1<<e.layer)!=0}const KP=Symbol("stencils");class Us{get name(){return"NEEDLE_render_objects"}static stencils={};static applyStencil(e){if(!e)return;const t=e.sourceId;if(Sf&&console.log(t,Us.stencils),!t)return;const i=Us.stencils[t];if(i)for(let n=i.length-1;n>=0;n--){const o=i[n];if(YP(o.layer,e)){Sf&&console.log(o),setTimeout(()=>{Ii()&&Yd(e.gameObject)&&(he("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[KP]=!0,a.stencilWrite=!0,a.stencilWriteMask=255,a.stencilFuncMask=255,a.stencilRef=o.value,a.stencilFunc=o.compareFunc,a.stencilZPass=o.passOp,a.stencilFail=o.failOp,a.stencilZFail=o.zFailOp,e.sharedMaterials[r]=a)}e.gameObject.renderOrder=o.event*1e3+o.index*50;break}}}parser;source;constructor(e,t){this.parser=e,this.source=t}afterRoot(e){const t=this.parser.json.extensions;if(t){const i=t[JP];if(i){Sf&&console.log(i);const n=i.stencil;if(n&&Array.isArray(n))for(const o of n){const r={...o};r.compareFunc=ZP(r.compareFunc),r.passOp=Cf(r.passOp),r.failOp=Cf(r.failOp),r.zFailOp=Cf(r.zFailOp),Us.stencils[this.source]||(Us.stencils[this.source]=[]),Us.stencils[this.source].push(r)}}}return null}}function Cf(s){switch(s){case 0:return c.KeepStencilOp;case 1:return c.ZeroStencilOp;case 2:return c.ReplaceStencilOp;case 3:return c.IncrementStencilOp;case 4:return c.DecrementStencilOp;case 6:return c.IncrementWrapStencilOp;case 7:return c.DecrementWrapStencilOp;case 5:return c.InvertStencilOp}return 0}function ZP(s){switch(s){case 1:return c.NeverStencilFunc;case 2:return c.LessStencilFunc;case 3:return c.EqualStencilFunc;case 4:return c.LessEqualStencilFunc;case 5:return c.GreaterStencilFunc;case 6:return c.NotEqualStencilFunc;case 7:return c.GreaterEqualStencilFunc;case 8:return c.AlwaysStencilFunc}return c.NeverStencilFunc}const JP="NEEDLE_render_objects";var R0=(s=>(s[s.INT=5124]="INT",s[s.FLOAT=5126]="FLOAT",s[s.FLOAT_VEC2=35664]="FLOAT_VEC2",s[s.FLOAT_VEC3=35665]="FLOAT_VEC3",s[s.FLOAT_VEC4=35666]="FLOAT_VEC4",s[s.INT_VEC2=35667]="INT_VEC2",s[s.INT_VEC3=35668]="INT_VEC3",s[s.INT_VEC4=35669]="INT_VEC4",s[s.BOOL=35670]="BOOL",s[s.BOOL_VEC2=35671]="BOOL_VEC2",s[s.BOOL_VEC3=35672]="BOOL_VEC3",s[s.BOOL_VEC4=35673]="BOOL_VEC4",s[s.FLOAT_MAT2=35674]="FLOAT_MAT2",s[s.FLOAT_MAT3=35675]="FLOAT_MAT3",s[s.FLOAT_MAT4=35676]="FLOAT_MAT4",s[s.SAMPLER_2D=35678]="SAMPLER_2D",s[s.SAMPLER_3D=35680]="SAMPLER_3D",s[s.SAMPLER_CUBE=35681]="SAMPLER_CUBE",s[s.UNKNOWN=0]="UNKNOWN",s))(R0||{});const mn=w("debugcustomshader"),Rr="NEEDLE_techniques_webgl";class eO{objectToWorldMatrix=new c.Matrix4;worldToObjectMatrix=new c.Matrix4;objectToWorld=new Array;worldToObject=new Array;updateFrom(e){this.objectToWorldMatrix.copy(e.matrixWorld),vd(this.objectToWorldMatrix,this.objectToWorld),this.worldToObjectMatrix.copy(e.matrixWorld).invert(),vd(this.worldToObjectMatrix,this.worldToObject)}}class ye extends c.RawShaderMaterial{identifier;onBeforeRenderSceneCallback=this.onBeforeRenderScene.bind(this);clone(){const e=super.clone();return T0(e),e}constructor(e,...t){super(...t),this.identifier=e,mn&&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)&&F.Current.pre_render_callbacks.push(this.onBeforeRenderSceneCallback)}dispose(){super.dispose();const e=F.Current.pre_render_callbacks.indexOf(this.onBeforeRenderSceneCallback);e>=0&&F.Current.pre_render_callbacks.splice(e,1)}_sphericalHarmonicsName="unity_SpecCube0";_objToWorldName="hlslcc_mtx4x4unity_ObjectToWorld";_worldToObjectName="hlslcc_mtx4x4unity_WorldToObject";static viewProjection=new c.Matrix4;static _viewProjectionValues=[];_viewProjectionName="hlslcc_mtx4x4unity_MatrixVP";static viewMatrix=new c.Matrix4;static _viewMatrixValues=[];_viewMatrixName="hlslcc_mtx4x4unity_MatrixV";static _worldSpaceCameraPosName="_WorldSpaceCameraPos";static _worldSpaceCameraPos=new c.Vector3;static _mainLightColor=new c.Vector4;static _mainLightPosition=new c.Vector3;static _lightData=new c.Vector4;_rendererData=new eO;get depthTextureUniform(){if(this.uniforms)return this.uniforms._CameraDepthTexture}get opaqueTextureUniform(){if(this.uniforms)return this.uniforms._CameraOpaqueTexture}onBeforeRenderScene(){this.opaqueTextureUniform&&F.Current.setRequireColor(!0),this.depthTextureUniform&&F.Current.setRequireDepth(!0)}onBeforeRender(e,t,i,n,o,r){n.attributes.tangent||n.computeTangents(),this.onUpdateUniforms(i,o)}onUpdateUniforms(e,t){const i=F.Current;if(e&&(ye.viewProjection&&this.uniforms[this._viewProjectionName]&&(ye.viewProjection.copy(e.projectionMatrix).multiply(e.matrixWorldInverse),vd(ye.viewProjection,ye._viewProjectionValues)),ye.viewMatrix&&this.uniforms[this._viewMatrixName]&&(ye.viewMatrix.copy(e.matrixWorldInverse),vd(ye.viewMatrix,ye._viewMatrixValues)),this.uniforms[ye._worldSpaceCameraPosName]&&ye._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=X(n.gameObject,ye._mainLightPosition);this.uniforms._MainLightPosition={value:a.normalize()},ye._mainLightColor.set(n.color.r,n.color.g,n.color.b,0),this.uniforms._MainLightColor={value:ye._mainLightColor};const l=n.intensity;ye._lightData.z=l,this.uniforms.unity_LightData={value:ye._lightData}}if(e&&(ye.viewProjection&&this.uniforms[this._viewProjectionName]&&(this.uniforms[this._viewProjectionName].value=ye._viewProjectionValues),ye.viewMatrix&&this.uniforms[this._viewMatrixName]&&(this.uniforms[this._viewMatrixName].value=ye._viewMatrixValues),this.uniforms[ye._worldSpaceCameraPosName]&&(this.uniforms[ye._worldSpaceCameraPosName]={value:ye._worldSpaceCameraPos}),i.mainCameraComponent)){if(this.uniforms._ProjectionParams){const a=this.uniforms._ProjectionParams.value;a.x=1,a.y=i.mainCameraComponent.nearClipPlane,a.z=i.mainCameraComponent.farClipPlane,a.w=1/a.z,this.uniforms._ProjectionParams.value=a}if(this.uniforms._ZBufferParams){const a=this.uniforms._ZBufferParams.value,l=i.mainCameraComponent;a.x=1-l.farClipPlane/l.nearClipPlane,a.y=l.farClipPlane/l.nearClipPlane,a.z=a.x/l.farClipPlane,a.w=a.y/l.farClipPlane,this.uniforms._ZBufferParams.value=a}if(this.uniforms._ScreenParams){const a=this.uniforms._ScreenParams.value;a.x=i.domWidth,a.y=i.domHeight,a.z=1+1/a.x,a.w=1+1/a.y,this.uniforms._ScreenParams.value=a}if(this.uniforms._ScaledScreenParams){const a=this.uniforms._ScaledScreenParams.value;a.x=i.domWidth,a.y=i.domHeight,a.z=1+1/a.x,a.w=1+1/a.y,this.uniforms._ScaledScreenParams.value=a}}const o=this.depthTextureUniform;o&&(o.value=i.depthTexture);const r=this.opaqueTextureUniform;if(r&&(r.value=i.opaqueColorTexture),t){const a=this._rendererData;a.updateFrom(t),this.uniforms[this._worldToObjectName].value=a.worldToObject,this.uniforms[this._objToWorldName].value=a.objectToWorld}this.uniformsNeedUpdate=!0}}class tO{get name(){return Rr}parser;identifier;constructor(e,t){this.parser=e,this.identifier=t}loadMaterial(e){const t=this.parser.json.materials[e];if(!t)return mn&&console.log(e,this.parser.json.materials),null;if(!t.extensions||!t.extensions[Rr])return mn&&console.log(`Material ${e} does not use NEEDLE_techniques_webgl`),null;mn&&console.log(`Material ${e} uses NEEDLE_techniques_webgl`,t);const i=t.extensions[Rr].technique;if(i<0)return console.debug(`Material ${e} does not have a valid technique index`),null;const n=this.parser.json.extensions[Rr];if(!n)return mn?console.error("Missing shader data",this.parser.json.extensions):console.debug("Missing custom shader data in parser.json.extensions"),null;mn&&console.log(n);const o=n.techniques[i];return o?new Promise(async(r,a)=>{const l=await QC(n,o.program),h=l?.fragmentShader,d=l?.vertexShader;if(!h||!d)return a();mn&&console.log("loadMaterial",t,l);const u={},p=o.uniforms;(d.includes("_Time")||h.includes("_Time"))&&(u._Time={value:new c.Vector4(0,0,0,0)}),(d.includes("_SinTime")||h.includes("_SinTime"))&&(u._SinTime={value:new c.Vector4(0,0,0,0)}),(d.includes("_CosTime")||h.includes("_CosTime"))&&(u._CosTime={value:new c.Vector4(0,0,0,0)}),(d.includes("unity_DeltaTime")||h.includes("unity_DeltaTime"))&&(u.unity_DeltaTime={value:new c.Vector4(0,0,0,0)});for(const v in p){const b=v;switch(b){case"_TimeParameters":const x=new c.Vector4;u[b]={value:x};break;case"hlslcc_mtx4x4unity_MatrixV":case"hlslcc_mtx4x4unity_MatrixVP":u[b]={value:[]};break;case"_MainLightPosition":case"_MainLightColor":case"_WorldSpaceCameraPos":u[b]={value:[0,0,0,1]};break;case"unity_OrthoParams":break;case"unity_SpecCube0":u[b]={value:null};break;default:case"_ScreenParams":case"_ZBufferParams":case"_ProjectionParams":u[b]={value:[0,0,0,0]};break;case"_CameraOpaqueTexture":case"_CameraDepthTexture":u[b]={value:null};break}}let m=!1;if(t.extensions&&t.extensions[Rr]){const v=t.extensions[Rr];if(v.technique===i){mn&&console.log(t.name,"Material Properties",v);for(const b in v.values){const x=v.values[b];if(typeof x=="string"){if(x.startsWith("/textures/")){const T=x.substring(10),O=Number.parseInt(T);if(O>=0){const M=await this.parser.getDependency("texture",O);M instanceof c.Texture&&(M.colorSpace=c.LinearSRGBColorSpace,M.needsUpdate=!0),u[b]={value:M};continue}}switch(b){case"alphaMode":x==="BLEND"&&(m=!0);continue}}if(Array.isArray(x)&&x.length===4){u[b]={value:new c.Vector4(x[0],x[1],x[2],x[3])};continue}u[b]={value:x}}}}const y=new ye(this.identifier,{name:t.name??"",uniforms:u,vertexShader:d,fragmentShader:h,lights:!1});switch(y.glslVersion=c.GLSL3,y.vertexShader=y.vertexShader.replace("#version 300 es",""),y.fragmentShader=y.fragmentShader.replace("#version 300 es",""),u._Cull?.value){case 0:y.side=c.DoubleSide;break;case 1:y.side=c.BackSide;break;case 2:y.side=c.FrontSide;break;default:y.side=c.FrontSide;break}switch(u._ZTest?.value){case 3:y.depthTest=!0,y.depthFunc=c.EqualDepth;break;case 6:y.depthTest=!0,y.depthFunc=c.NotEqualDepth;break;case 2:y.depthTest=!0,y.depthFunc=c.LessDepth;break;case 4:y.depthTest=!0,y.depthFunc=c.LessEqualDepth;break;case 5:y.depthTest=!0,y.depthFunc=c.GreaterDepth;break;case 7:y.depthTest=!0,y.depthFunc=c.GreaterEqualDepth;break;case 8:y.depthTest=!1,y.depthFunc=c.AlwaysDepth;break}y.transparent=m,m&&(y.depthWrite=!1),qC(u),y.onUpdateUniforms();for(const v in p){const b=v,x=p[v].type;if(u[b]?.value===void 0)switch(x){case R0.SAMPLER_2D:u[b]={value:GC},console.warn("Missing/unassigned texture, fallback to white: "+b);break;default:b==="unity_OrthoParams"||console.warn("TODO: EXPECTED UNIFORM / fallback NOT SET: "+b,p[v]);break}}mn&&console.log(y.uuid,u),T0(y),r(y)}):null}}function T0(s){if(s.uniforms){mn&&console.log("Uniforms:",s.uniforms);for(const t in s.uniforms)switch(e(t,t),t){case"_Color":e("color",t);break}}function e(t,i){Object.getOwnPropertyDescriptor(s,t)||Object.defineProperty(s,t,{get:()=>s.uniforms[i].value,set:n=>{s.uniforms[i].value=n,s.needsUpdate=!0}})}}const iO=w("debugextensions");let Ed;const nO=Promise.resolve().then(()=>require("./vendor-BtJpSuCj.umd.cjs")).then(s=>s.index$2).then(async s=>(Ed=s.GLTFAnimationPointerExtension,Ed)).catch(s=>{console.warn("Failed to import GLTFLoaderAnimationPointer. Please use @needle-tools/three-animationpointer for full KHR_animation support",s)}),Yo=new Array;function sO(s){Yo.includes(s)||Yo.push(s)}function oO(s){const e=Yo.indexOf(s);e>=0&&Yo.splice(e,1)}function Zm(s){if(s instanceof q.GLTFLoader){const e=new E0;return s.register(t=>(e.parser=t,e)),e}return null}class rO{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 Rd(s,e,t){const i=t.indexOf("?");i>=0&&(t=t.substring(0,i)),s.register(n=>new XP(n)),s.register(n=>new yC(n)),s.register(n=>new NC(n,e.lightmaps,t)),s.register(n=>new QP(n,t,e)),s.register(n=>new tO(n,t)),s.register(n=>new Us(n,t)),s.register(n=>new ne.NEEDLE_progressive(n)),s.register(n=>new WP(n)),Jb()&&s.register(n=>new ea(n)),await nO.catch(n=>{}),s.register(n=>{if(Ed){const o=new Ed(n);return o.setAnimationPointerResolver.bind(o)(new rO),o}else return(iO||A())&&console.error("Missing KHR_animation_pointer extension..."),{name:"KHR_animation_pointer_NOT_AVAILABLE"}});for(const n of Yo)n.onImport&&n.onImport(s,t,e)}function Jm(s,e){for(const t of Yo)t.onExport&&t.onExport(s,e)}function A0(s,e,t){for(const i of Yo)i.onLoaded&&i.onLoaded(s,e,t)}class L0{constructor(e){this.writer=e,this.name="EXT_mesh_gpu_instancing"}writeNode(e,t){if(e.constructor.name!=="InstancedMesh")return;const i=this.writer,n=i.extensionsUsed,o={};t.extensions=t.extensions||{},t.extensions[this.name]=o;let r=new c.Matrix4;const a=new Array,l=new Array,h=new Array;for(let m=0;m<e.count;m++){e.getMatrixAt(m,r);let y=new c.Vector3,_=new c.Quaternion,g=new c.Vector3;r.decompose(y,_,g),a.push(y.x,y.y,y.z),l.push(_.x,_.y,_.z,_.w),h.push(g.x,g.y,g.z)}const d=new Float32Array(a),u=new Float32Array(l),p=new Float32Array(h);o.attributes={TRANSLATION:i.processAccessor(new c.BufferAttribute(d,3)),ROTATION:i.processAccessor(new c.BufferAttribute(u,4)),SCALE:i.processAccessor(new c.BufferAttribute(p,3))},n[this.name]=!0}}var aO=Object.defineProperty,D0=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&aO(e,t,n),n};const Za=w("debugreflectionprobe"),y_=w("noreflectionprobe"),Pf=Symbol("reflectionProbeKey"),__=Symbol("original material"),eg=class Qn extends k{static _probes=new Map;static isUsingReflectionProbe(e){return!!(e[Pf]||e[__]?.[Pf])}static get(e,t,i,n){if(!e||e.isObject3D!==!0||y_)return null;const o=Qn._probes.get(t);if(o){for(const r of o)if(r.__didAwake||r.__internalAwake(),r.activeAndEnabled){if(n){if(r.gameObject===n)return r}else if(r.isInBox(e))return Za&&console.log("Found reflection probe",e.name,r.name),r}}return Za&&console.debug("Did not find reflection probe",e.name,i,e),null}_texture;set texture(e){if(e&&!(e instanceof c.Texture)){console.error("ReflectionProbe.texture must be a Texture",e);return}this._texture=e,e&&(e.mapping=c.EquirectangularReflectionMapping,e.colorSpace=c.LinearSRGBColorSpace,e.needsUpdate=!0)}get texture(){return this._texture}center;size;_boxHelper;isInBox(e){return this._boxHelper?.isInBox(e)}constructor(){super(),Qn._probes.has(this.context)||Qn._probes.set(this.context,[]),Qn._probes.get(this.context)?.push(this)}awake(){this._boxHelper=this.gameObject.addComponent(nt),this._boxHelper.updateBox(!0),Za&&this._boxHelper.showHelper(5592320,!0),this._texture&&(this._texture.mapping=c.EquirectangularReflectionMapping,this._texture.colorSpace=c.LinearSRGBColorSpace,this._texture.needsUpdate=!0)}start(){!this._texture&&A()&&(console.warn(`[ReflectionProbe] Missing texture. Please assign a custom cubemap texture. To use reflection probes assign them to your renderer's "anchor" property.`),he("ReflectionProbe configuration hint: See browser console for details"))}onDestroy(){const e=Qn._probes.get(this.context);if(e){const t=e.indexOf(this);t>=0&&e.splice(t,1)}}static _rendererMaterialsCache=new Map;onSet(e){if(y_||!this.enabled||e.sharedMaterials?.length<=0||!this.texture)return;let t=Qn._rendererMaterialsCache.get(e);t||(t=[],Qn._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 c.MeshBasicMaterial)continue;let o=t[i];const r=n===o?.copy,a=!o||o.material.uuid!==n.uuid||o.copy.version!==n.version;if(!r&&a){if(Za){let d="";o?o.material!==n?d="reference changed; cached instance?: "+r:o.copy.version!==n.version&&(d="version changed"):d="not cached",console.warn("Cloning material",n.name,n.version,"Reason:",d,`
|
|
975
|
+
Binary:`,i)}else console.debug("Could not determine file type from binary data");return"unknown"}var BP=Object.defineProperty,Pa=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&BP(e,t,n),n};const oi=w("debugdroplistener");class FP extends CustomEvent{constructor(e){super("object-added",{detail:e})}}const UP="blob";class fs extends k{dropArea;fitIntoVolume=!1;fitVolumeSize=new c.Vector3(1,1,1);placeAtHitPosition=!0;useNetworking=!1;onDropped=new oe;loadFromURL(e,t){return this.addFromUrl(e,{screenposition:new c.Vector2,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){oi&&console.debug("[DropListener] Ignoring networked event because networking is disabled",e);return}if(e.guid?.startsWith(this.guid)){const t=e.url;if(console.debug("[DropListener] Received networked event",e),t)if(Array.isArray(t))for(const i of t)this.addFromUrl(i,{screenposition:new c.Vector2,point:e.point,size:e.size},!0);else this.addFromUrl(t,{screenposition:new c.Vector2,point:e.point,size:e.size},!0)}};handlePaste=e=>{if(this.context.connection.allowEditing===!1||e.defaultPrevented)return;navigator.clipboard.readText().then(i=>{if(i&&(i.startsWith("http")||i.startsWith("https")||i.startsWith("blob"))){const o={screenposition:new c.Vector2(this.context.input.mousePosition.x,this.context.input.mousePosition.y)};this.testIfIsInDropArea(o)&&this.addFromUrl(i,o,!1)}}).catch(console.warn)};onDrag=e=>{this.context.connection.allowEditing!==!1&&e.preventDefault()};onDrop=async e=>{if(this.context.connection.allowEditing===!1||(oi&&console.log(e),!e?.dataTransfer)||e["droplistener:handled"])return;e.preventDefault();const t={screenposition:new c.Vector2(e.offsetX,e.offsetY)};if(this.dropArea&&this.testIfIsInDropArea(t)===!1)return;e["droplistener:handled"]=!0;const i=e.dataTransfer.items;if(!i)return;const n=[];for(const o in i){const r=i[o];if(r.kind==="file"){const a=r.getAsFile();if(!a)continue;n.push(a)}else r.kind==="string"&&r.type=="text/plain"&&r.getAsString(a=>{this.addFromUrl(a,t,!1)})}n.length>0&&await this.addFromFiles(n,t)};async addFromUrl(e,t,i){oi&&console.log("dropped url",e);try{if(e.startsWith("https://github.com/")){const r=e.split("/"),a=r[3],l=r[4],h=r[6],d=r.slice(7).join("/");e=`https://raw.githubusercontent.com/${a}/${l}/${h}/${d}`}else e.startsWith("https://polyhaven.com/a")&&(e=zP(e));if(!e)return null;const n=e.toLowerCase();if(n.endsWith(".hdr")||n.endsWith(".hdri")||n.endsWith(".exr")||n.endsWith(".png")||n.endsWith(".jpg")||n.endsWith(".jpeg"))return console.warn(`Fileformat is not supported: ${n}`),null;this.removePreviouslyAddedObjects();const o=await Md.loadFileFromURL(new URL(e),{guid:this.guid,context:this.context,parent:this.gameObject,point:t.point,size:t.size});if(o&&this._addedObjects.length<=0)return t.url=e,this.onObjectLoaded(o,t,i)}catch{console.warn("String is not a valid URL",e)}return null}_abort=null;async addFromFiles(e,t){if(oi&&console.log("Add files",e),!!Array.isArray(e)&&e.length){this.deleteDropEvent(),this.removePreviouslyAddedObjects(),Wl(UP,null),this._abort?.abort("New files dropped"),this._abort=new AbortController;for(const i of e){if(!i)continue;if(i.type.startsWith("image/")){oi&&console.warn("Ignoring dropped image file",i.name,i.type);continue}else if(i.name.endsWith(".bin")){oi&&console.warn("Ignoring dropped binary file",i.name,i.type);continue}console.debug("Load file "+i.name+" + "+i.type);const n=await Md.loadFile(i,this.context,{guid:this.guid});if(n){this.dispatchEvent(new CustomEvent("file-dropped",{detail:i})),t.file=i;const o=this.onObjectLoaded(n,t,!1);o&&this.context.connection.isConnected&&this.useNetworking&&(console.debug("Uploading dropped file to blob storage"),exports.BlobStorage.upload(i,{abort:this._abort?.signal}).then(r=>{r?.download_url&&this._addedObjects.includes(o)&&this.sendDropEvent(r.download_url,o,n.contentMD5)}).catch(console.warn));break}}}}_addedObjects=new Array;_addedModels=new Array;removePreviouslyAddedObjects(e=!0){if(e)for(const t of this._addedObjects)t.parent===this.gameObject&&ui(t,!0,!0);this._addedObjects.length=0,this._addedModels.length=0}onObjectLoaded(e,t,i){const{model:n,contentMD5:o}=e;if(oi&&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 c.Box3().setFromCenterAndSize(new c.Vector3(0,this.fitVolumeSize.y*.5,0).add(this.gameObject.worldPosition),this.fitVolumeSize);if(oi&&B.DrawWireBox3(a,255,5),this.fitIntoVolume&&kb(r,a,{position:!this.placeAtHitPosition}),this.placeAtHitPosition&&t&&t.screenposition){r.visible=!1;const h=this.context.physics.raycast({screenPoint:this.context.input.convertScreenspaceToRaycastSpace(t.screenposition.clone())});if(r.visible=!0,h&&h.length>0)for(const d of h){const u=d.point.clone();oi&&console.log("Place object at hit",d),Eb(r,u);break}}fa.autoplayAnimations(n);const l=new FP({sender:this,gltf:n,model:n,object:r,contentMD5:o,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,o),r}async sendDropEvent(e,t,i){if(!this.useNetworking){oi&&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=Bt([t]),o={name:t.name,guid:this.guid,url:e,point:t.worldPosition.clone(),size:n.getSize(new c.Vector3),contentMD5:i};this.context.connection.send("droplistener",o)}}deleteDropEvent(){this.context.connection.sendDeleteRemoteState(this.guid)}testIfIsInDropArea(e){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:n=>!this._addedObjects.includes(n)}).length)return A()&&console.log(`Dropped outside of drop area for DropListener "${this.name}".`),!1}return!0}}Pa([f(c.Object3D)],fs.prototype,"dropArea");Pa([f()],fs.prototype,"fitIntoVolume");Pa([f(c.Vector3)],fs.prototype,"fitVolumeSize");Pa([f()],fs.prototype,"placeAtHitPosition");Pa([f()],fs.prototype,"useNetworking");Pa([f(oe)],fs.prototype,"onDropped");function zP(s){if(!s.startsWith("https://polyhaven.com/"))return s;const e="https://dl.polyhaven.org/file/ph-assets/Models/gltf/4k/",n=new URL(s).pathname.split("/").pop(),o=`${e}${n}/${n}_4k.gltf`;return console.log("Resolved polyhaven asset url",s,"→",o),o}var Md;(s=>{async function e(i,n,o){const r=o.guid,a=new mt(r),l=new Blob([i],{type:i.type||S0(i.name)||void 0}),h=URL.createObjectURL(l),d=await en().loadSync(n,h,i.name,a).catch(u=>(console.error(`Failed to load file "${i.name}" (${i.type}):`,u),null));return URL.revokeObjectURL(h),d?new Promise((u,p)=>{const m=new FileReader;m.readAsArrayBuffer(i),m.onloadend=async y=>{const b=m.result,g=exports.BlobStorage.hashMD5(b);return u({model:d,contentMD5:g})}}):(console.warn(`Failed to load "${i.name}" (${i.type})`),null)}s.loadFile=e;async function t(i,n){return new Promise(async(o,r)=>{const a=new mt(n.guid),l=i.toString();oi&&B.DrawWireSphere(n.point,.1,16711680,3);const h=exports.PreviewHelper.addPreview({guid:n.guid,parent:n.parent,position:n?.point,size:n?.size}),d=await en().loadSync(n.context,l,l,a,u=>{h.onProgress(u.loaded/u.total)}).catch(console.warn);if(d){const u=await fetch(l).then(m=>m.arrayBuffer()),p=exports.BlobStorage.hashMD5(u);oi?setTimeout(()=>exports.PreviewHelper.removePreview(n.guid),3e3):exports.PreviewHelper.removePreview(n.guid),o({model:d,contentMD5:p})}else oi?setTimeout(()=>exports.PreviewHelper.removePreview(n.guid),3e3):exports.PreviewHelper.removePreview(n.guid),console.warn("Unsupported file type: "+i.toString())})}s.loadFileFromURL=t})(Md||(Md={}));var NP=Object.defineProperty,Xm=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&NP(e,t,n),n};const hu=class O0 extends k{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 mt(this.guid);this.object=S.instantiate(this.object,{idProvider:t,keepWorldPosition:!1}),S.getComponent(this.object,O0)?.destroy();let n=this.object.getComponentInChildren(Ro);n||(n=this.object.addComponent(Ro,{dragMode:qm.SnapToSurfaces}),n.guid=t.generateUUID());let o=S.getComponent(n.gameObject,nn);o||(o=n.gameObject.addComponent(nn),o.guid=t.generateUUID())}this.object.visible=!1;const e=this.gameObject.getComponent(Ro);e&&(e.enabled=!1),this._startPosition=this.object.position?.clone()??new c.Vector3(0,0,0),this._startQuaternion=this.object.quaternion?.clone()??new c.Quaternion(0,0,0,1)}this.gameObject.getComponentInParent(fi)||this.gameObject.addComponent(fi)}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=S.getComponent(t,Ro);i?(i.onPointerDown(e),this._forwardPointerEvents.set(e.event.space,i)):A()&&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 km(1)}handleDuplication(){if(!this.object||this.limitCount>0&&this._currentCount>=this.limitCount||this.object===this.gameObject)return null;if(S.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 on;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=S.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}};Xm([f(c.Object3D)],hu.prototype,"parent");Xm([f(c.Object3D)],hu.prototype,"object");Xm([f()],hu.prototype,"limitCount");let Qm=hu;var Xn=(s=>(s[s.PointerEnter=0]="PointerEnter",s[s.PointerExit=1]="PointerExit",s[s.PointerDown=2]="PointerDown",s[s.PointerUp=3]="PointerUp",s[s.PointerClick=4]="PointerClick",s[s.Drag=5]="Drag",s[s.Drop=6]="Drop",s[s.Scroll=7]="Scroll",s[s.UpdateSelected=8]="UpdateSelected",s[s.Select=9]="Select",s[s.Deselect=10]="Deselect",s[s.Move=11]="Move",s[s.InitializePotentialDrag=12]="InitializePotentialDrag",s[s.BeginDrag=13]="BeginDrag",s[s.EndDrag=14]="EndDrag",s[s.Submit=15]="Submit",s[s.Cancel=16]="Cancel",s))(Xn||{}),VP=Object.defineProperty,Ym=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&VP(e,t,n),n};class Km{eventID;callback=new oe}Ym([f()],Km.prototype,"eventID");Ym([f(oe)],Km.prototype,"callback");class du extends k{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(Xn.PointerClick)||this.hasTrigger(Xn.PointerDown)||this.hasTrigger(Xn.PointerUp)}onPointerClick(e){this.invoke(Xn.PointerClick)}onPointerEnter(e){this.shouldChangeCursor()&&this.context.input.setCursor("pointer"),this.invoke(Xn.PointerEnter)}onPointerExit(e){this.shouldChangeCursor()&&this.context.input.unsetCursor("pointer"),this.invoke(Xn.PointerExit)}onPointerDown(e){this.invoke(Xn.PointerDown)}onPointerUp(e){this.invoke(Xn.PointerUp)}}Ym([f(Km)],du.prototype,"triggers");class M0{writer;constructor(e){this.writer=e}writeNode(e){}}class $P extends M0{beforeWriteNode(e,t){B.isGizmo(e)&&(t.keep=!1)}}class k0 extends M0{beforeWriteTexture(e,t){e.isRenderTargetTexture&&(t.newTexture=Em(new Z(1,1,1,0)))}}function Ep(s){const e=ou.DontExport;return!(s.hideFlags&e)}const xf=w("debugexr");class WP{get name(){return"EXT_texture_exr"}parser;constructor(e){this.parser=e,xf&&console.log(e)}loadTexture(e){const t=this.name,i=this.parser,o=i.json.textures[e];if(xf&&console.log("EXT_texture_exr.loadTexture",e,o),!o.extensions||!o.extensions[t])return null;const r=o.extensions[t],a=new q.EXRLoader(i.options.manager);return xf&&console.log("EXT_texture_exr.loadTexture",r),i.loadTextureImage(e,r.source,a)}}typeof window<"u"&&window.addEventListener("unhandledrejection",s=>{});const Wn=st,Sh="$___Export_Components",GP="NEEDLE_components";class HP{[Po]}class qP{node;nodeIndex;nodeDef;constructor(e,t,i){this.node=e,this.nodeIndex=t,this.nodeDef=i}}class E0{get name(){return GP}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,o)=>{try{this.serializeUserData(n,o)&&(t.extensionsUsed[this.name]=!0),i(n,o)}finally{this.afterSerializeUserData(n,o)}}}return this})}beforeParse(){this.exportContext={},this.objectToNodeMap={}}serializeUserData(e,t){const i=e.userData?.components;return!i||i.length<=0?!1:(delete e.userData.components,e[Sh]=i,!0)}afterSerializeUserData(e,t){if(e.type==="Scene"&&Wn&&console.log("DONE",JSON.stringify(t)),e[Sh]===void 0)return;const i=e[Sh];delete e[Sh],i!==null&&(e.userData.components=i)}writeNode(e,t){const i=this.writer.json.nodes.length;Wn&&console.log(e.name,i,e.uuid);const n=new qP(e,i,t);this.exportContext[i]=n,this.objectToNodeMap[e.uuid]=i}afterParse(e){Wn&&console.log("AFTER",e);for(const t in this.exportContext){const i=this.exportContext[t],n=i.node,o=i.nodeDef,r=i.nodeIndex,a=n.userData?.components;if(!a||a.length<=0)continue;const l=new HP;o.extensions=o.extensions||{},o.extensions[this.name]=l,this.context.object=n,this.context.nodeId=r,this.context.objectToNode=this.objectToNodeMap;const h=[];for(const d of a){this.context.target=d;const u=en().writeBuiltinComponentData(d,this.context);u!==null&&h.push(u)}h.length>0&&(l[Po]=h,Wn&&console.log("DID WRITE",n,"nodeIndex",r,h))}}beforeRoot(){return Wn&&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];Wn&&console.log("After root",e,this.parser,i);const o=[];if(n===!0){const r=t.json.nodes;if(r){for(let a=0;a<r.length;a++){const l=await t.getDependency("node",a);this.nodeToObjectMap[a]=l}for(let a=0;a<r.length;a++){const l=r[a],h=a,d=l.extensions;if(!d)continue;const u=d[this.name];if(!u)continue;Wn&&console.log("NODE",l);const p=this.nodeToObjectMap[h];if(!p){console.error("Could not find object for node index: "+h,l,t);continue}Qd(p),o.push(this.createComponents(p,u))}}}await Promise.all(o);for(const r of t.associations.keys()){const a=t.associations.get(r);if(a?.materials!=null){const l="/materials/"+a.materials;mC(r,l)}}}async createComponents(e,t){if(!t)return;const i=t[Po];if(i){const n=new Array;Wn&&console.log(e.name,i);for(const o in i){const r=i[o];Wn&&console.log("Serialized data",JSON.parse(JSON.stringify(r))),r&&this.parser&&n.push(Cm(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[Po]=e.userData[Po]||[],e.userData[Po].push(r)}await Promise.all(n).catch(o=>{console.error("Error while loading components",o)})}}}const m_="NEEDLE_gameobject_data";class XP{get name(){return m_}parser;constructor(e){this.parser=e}afterRoot(e){const t=[];for(let i=0;i<this.parser.json.nodes?.length;i++){const n=this.parser.json.nodes[i];if(n&&n.extensions){const o=n.extensions[m_];if(o){const r=this.findAndApplyExtensionData(i,o);t.push(r)}}}return Promise.all(t).then(()=>null)}async findAndApplyExtensionData(e,t){const i=await this.parser.getDependency("node",e);i&&this.applyExtensionData(i,t)}applyExtensionData(e,t){t.layers===void 0&&(t.layers=0),e.userData.layer=t.layers,e.layers.disableAll(),e.layers.set(t.layers),e.userData.tag=t.tag??"none",e.hideFlags=0,e.userData.static=t.static??!1,e.visible=t.activeSelf??!0,e.guid=t.guid}}const g_="NEEDLE_lighting_settings",Nr=w("debugenvlight");class QP{get name(){return g_}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[g_];if(i){Nr&&console.log('Loaded "'+this.name+'", src: "'+this.sourceId+'"',i);let n;if(e.scene.children.length===1){const o=e.scene.children[0];n=S.addComponent(o,kd,{},{callAwake:!1})}else{const o=new c.Object3D;o.name="LightSettings "+this.sourceId,e.scene.add(o),n=S.addComponent(o,kd,{},{callAwake:!1})}n.sourceId=this.sourceId,n.ambientIntensity=i.ambientIntensity,n.ambientLight=new c.Color().fromArray(i.ambientLight),Array.isArray(i.ambientTrilight)&&(n.ambientTrilight=i.ambientTrilight.map(o=>new c.Color().fromArray(o))),n.ambientMode=i.ambientMode,n.environmentReflectionSource=i.environmentReflectionSource}}return null}}ae.registerCallback(re.ContextCreated,s=>{const e=s.context,t=S.findObjectOfType(kd,e);t?.sourceId&&(t.enabled=!0)});class kd extends k{ambientMode=ia.Skybox;ambientLight;ambientTrilight;ambientIntensity=1;environmentReflectionSource=wd.Skybox;_hasReflection=!1;_ambientLightObj;_hemisphereLightObj;awake(){if(this.sourceId){const t=this.environmentReflectionSource===wd.Skybox?_n.Skybox:_n.Reflection,i=this.context.lightmaps.tryGet(this.sourceId,t,0);this._hasReflection=i!=null,i&&this.context.sceneLighting.internalRegisterReflection(this.sourceId,i)}this.enabled=!1,this.context.sceneLighting.internalRegisterSceneLightSettings(this),Nr&&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(Nr&&console.warn("💡🟡 >>> Enable lighting",this.sourceId,this.enabled,this),this.ambientMode==ia.Flat){if(this.ambientLight&&!this._ambientLightObj){const e=this.calculateIntensityFactor(this.ambientLight);this._ambientLightObj=new c.AmbientLight(this.ambientLight,this.ambientIntensity*e),Nr&&console.log("Created ambient light",this.sourceId,this._ambientLightObj,this.ambientIntensity,e)}this._ambientLightObj&&this.gameObject.add(this._ambientLightObj)}else if(this.ambientMode===ia.Trilight){if(this.ambientTrilight){const e=this.ambientTrilight[0],t=this.ambientTrilight[this.ambientTrilight.length-1],i=this.calculateIntensityFactor(t);this._hemisphereLightObj=new c.HemisphereLight(t,e,this.ambientIntensity*i),this.gameObject.add(this._hemisphereLightObj),Nr&&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(){Nr&&console.warn("💡⚫ <<< Disable lighting:",this.sourceId,this),this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._hemisphereLightObj&&this._hemisphereLightObj.removeFromParent(),this.sourceId&&this.context.sceneLighting.internalDisableReflection(this.sourceId)}}const Sf=w("debugstencil");function YP(s,e){return(s&1<<e.layer)!=0}const KP=Symbol("stencils");class Us{get name(){return"NEEDLE_render_objects"}static stencils={};static applyStencil(e){if(!e)return;const t=e.sourceId;if(Sf&&console.log(t,Us.stencils),!t)return;const i=Us.stencils[t];if(i)for(let n=i.length-1;n>=0;n--){const o=i[n];if(YP(o.layer,e)){Sf&&console.log(o),setTimeout(()=>{Ii()&&Yd(e.gameObject)&&(he("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[KP]=!0,a.stencilWrite=!0,a.stencilWriteMask=255,a.stencilFuncMask=255,a.stencilRef=o.value,a.stencilFunc=o.compareFunc,a.stencilZPass=o.passOp,a.stencilFail=o.failOp,a.stencilZFail=o.zFailOp,e.sharedMaterials[r]=a)}e.gameObject.renderOrder=o.event*1e3+o.index*50;break}}}parser;source;constructor(e,t){this.parser=e,this.source=t}afterRoot(e){const t=this.parser.json.extensions;if(t){const i=t[JP];if(i){Sf&&console.log(i);const n=i.stencil;if(n&&Array.isArray(n))for(const o of n){const r={...o};r.compareFunc=ZP(r.compareFunc),r.passOp=Cf(r.passOp),r.failOp=Cf(r.failOp),r.zFailOp=Cf(r.zFailOp),Us.stencils[this.source]||(Us.stencils[this.source]=[]),Us.stencils[this.source].push(r)}}}return null}}function Cf(s){switch(s){case 0:return c.KeepStencilOp;case 1:return c.ZeroStencilOp;case 2:return c.ReplaceStencilOp;case 3:return c.IncrementStencilOp;case 4:return c.DecrementStencilOp;case 6:return c.IncrementWrapStencilOp;case 7:return c.DecrementWrapStencilOp;case 5:return c.InvertStencilOp}return 0}function ZP(s){switch(s){case 1:return c.NeverStencilFunc;case 2:return c.LessStencilFunc;case 3:return c.EqualStencilFunc;case 4:return c.LessEqualStencilFunc;case 5:return c.GreaterStencilFunc;case 6:return c.NotEqualStencilFunc;case 7:return c.GreaterEqualStencilFunc;case 8:return c.AlwaysStencilFunc}return c.NeverStencilFunc}const JP="NEEDLE_render_objects";var R0=(s=>(s[s.INT=5124]="INT",s[s.FLOAT=5126]="FLOAT",s[s.FLOAT_VEC2=35664]="FLOAT_VEC2",s[s.FLOAT_VEC3=35665]="FLOAT_VEC3",s[s.FLOAT_VEC4=35666]="FLOAT_VEC4",s[s.INT_VEC2=35667]="INT_VEC2",s[s.INT_VEC3=35668]="INT_VEC3",s[s.INT_VEC4=35669]="INT_VEC4",s[s.BOOL=35670]="BOOL",s[s.BOOL_VEC2=35671]="BOOL_VEC2",s[s.BOOL_VEC3=35672]="BOOL_VEC3",s[s.BOOL_VEC4=35673]="BOOL_VEC4",s[s.FLOAT_MAT2=35674]="FLOAT_MAT2",s[s.FLOAT_MAT3=35675]="FLOAT_MAT3",s[s.FLOAT_MAT4=35676]="FLOAT_MAT4",s[s.SAMPLER_2D=35678]="SAMPLER_2D",s[s.SAMPLER_3D=35680]="SAMPLER_3D",s[s.SAMPLER_CUBE=35681]="SAMPLER_CUBE",s[s.UNKNOWN=0]="UNKNOWN",s))(R0||{});const mn=w("debugcustomshader"),Rr="NEEDLE_techniques_webgl";class eO{objectToWorldMatrix=new c.Matrix4;worldToObjectMatrix=new c.Matrix4;objectToWorld=new Array;worldToObject=new Array;updateFrom(e){this.objectToWorldMatrix.copy(e.matrixWorld),vd(this.objectToWorldMatrix,this.objectToWorld),this.worldToObjectMatrix.copy(e.matrixWorld).invert(),vd(this.worldToObjectMatrix,this.worldToObject)}}class ye extends c.RawShaderMaterial{identifier;onBeforeRenderSceneCallback=this.onBeforeRenderScene.bind(this);clone(){const e=super.clone();return T0(e),e}constructor(e,...t){super(...t),this.identifier=e,mn&&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)&&F.Current.pre_render_callbacks.push(this.onBeforeRenderSceneCallback)}dispose(){super.dispose();const e=F.Current.pre_render_callbacks.indexOf(this.onBeforeRenderSceneCallback);e>=0&&F.Current.pre_render_callbacks.splice(e,1)}_sphericalHarmonicsName="unity_SpecCube0";_objToWorldName="hlslcc_mtx4x4unity_ObjectToWorld";_worldToObjectName="hlslcc_mtx4x4unity_WorldToObject";static viewProjection=new c.Matrix4;static _viewProjectionValues=[];_viewProjectionName="hlslcc_mtx4x4unity_MatrixVP";static viewMatrix=new c.Matrix4;static _viewMatrixValues=[];_viewMatrixName="hlslcc_mtx4x4unity_MatrixV";static _worldSpaceCameraPosName="_WorldSpaceCameraPos";static _worldSpaceCameraPos=new c.Vector3;static _mainLightColor=new c.Vector4;static _mainLightPosition=new c.Vector3;static _lightData=new c.Vector4;_rendererData=new eO;get depthTextureUniform(){if(this.uniforms)return this.uniforms._CameraDepthTexture}get opaqueTextureUniform(){if(this.uniforms)return this.uniforms._CameraOpaqueTexture}onBeforeRenderScene(){this.opaqueTextureUniform&&F.Current.setRequireColor(!0),this.depthTextureUniform&&F.Current.setRequireDepth(!0)}onBeforeRender(e,t,i,n,o,r){n.attributes.tangent||n.computeTangents(),this.onUpdateUniforms(i,o)}onUpdateUniforms(e,t){const i=F.Current;if(e&&(ye.viewProjection&&this.uniforms[this._viewProjectionName]&&(ye.viewProjection.copy(e.projectionMatrix).multiply(e.matrixWorldInverse),vd(ye.viewProjection,ye._viewProjectionValues)),ye.viewMatrix&&this.uniforms[this._viewMatrixName]&&(ye.viewMatrix.copy(e.matrixWorldInverse),vd(ye.viewMatrix,ye._viewMatrixValues)),this.uniforms[ye._worldSpaceCameraPosName]&&ye._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=X(n.gameObject,ye._mainLightPosition);this.uniforms._MainLightPosition={value:a.normalize()},ye._mainLightColor.set(n.color.r,n.color.g,n.color.b,0),this.uniforms._MainLightColor={value:ye._mainLightColor};const l=n.intensity;ye._lightData.z=l,this.uniforms.unity_LightData={value:ye._lightData}}if(e&&(ye.viewProjection&&this.uniforms[this._viewProjectionName]&&(this.uniforms[this._viewProjectionName].value=ye._viewProjectionValues),ye.viewMatrix&&this.uniforms[this._viewMatrixName]&&(this.uniforms[this._viewMatrixName].value=ye._viewMatrixValues),this.uniforms[ye._worldSpaceCameraPosName]&&(this.uniforms[ye._worldSpaceCameraPosName]={value:ye._worldSpaceCameraPos}),i.mainCameraComponent)){if(this.uniforms._ProjectionParams){const a=this.uniforms._ProjectionParams.value;a.x=1,a.y=i.mainCameraComponent.nearClipPlane,a.z=i.mainCameraComponent.farClipPlane,a.w=1/a.z,this.uniforms._ProjectionParams.value=a}if(this.uniforms._ZBufferParams){const a=this.uniforms._ZBufferParams.value,l=i.mainCameraComponent;a.x=1-l.farClipPlane/l.nearClipPlane,a.y=l.farClipPlane/l.nearClipPlane,a.z=a.x/l.farClipPlane,a.w=a.y/l.farClipPlane,this.uniforms._ZBufferParams.value=a}if(this.uniforms._ScreenParams){const a=this.uniforms._ScreenParams.value;a.x=i.domWidth,a.y=i.domHeight,a.z=1+1/a.x,a.w=1+1/a.y,this.uniforms._ScreenParams.value=a}if(this.uniforms._ScaledScreenParams){const a=this.uniforms._ScaledScreenParams.value;a.x=i.domWidth,a.y=i.domHeight,a.z=1+1/a.x,a.w=1+1/a.y,this.uniforms._ScaledScreenParams.value=a}}const o=this.depthTextureUniform;o&&(o.value=i.depthTexture);const r=this.opaqueTextureUniform;if(r&&(r.value=i.opaqueColorTexture),t){const a=this._rendererData;a.updateFrom(t),this.uniforms[this._worldToObjectName].value=a.worldToObject,this.uniforms[this._objToWorldName].value=a.objectToWorld}this.uniformsNeedUpdate=!0}}class tO{get name(){return Rr}parser;identifier;constructor(e,t){this.parser=e,this.identifier=t}loadMaterial(e){const t=this.parser.json.materials[e];if(!t)return mn&&console.log(e,this.parser.json.materials),null;if(!t.extensions||!t.extensions[Rr])return mn&&console.log(`Material ${e} does not use NEEDLE_techniques_webgl`),null;mn&&console.log(`Material ${e} uses NEEDLE_techniques_webgl`,t);const i=t.extensions[Rr].technique;if(i<0)return console.debug(`Material ${e} does not have a valid technique index`),null;const n=this.parser.json.extensions[Rr];if(!n)return mn?console.error("Missing shader data",this.parser.json.extensions):console.debug("Missing custom shader data in parser.json.extensions"),null;mn&&console.log(n);const o=n.techniques[i];return o?new Promise(async(r,a)=>{const l=await QC(n,o.program),h=l?.fragmentShader,d=l?.vertexShader;if(!h||!d)return a();mn&&console.log("loadMaterial",t,l);const u={},p=o.uniforms;(d.includes("_Time")||h.includes("_Time"))&&(u._Time={value:new c.Vector4(0,0,0,0)}),(d.includes("_SinTime")||h.includes("_SinTime"))&&(u._SinTime={value:new c.Vector4(0,0,0,0)}),(d.includes("_CosTime")||h.includes("_CosTime"))&&(u._CosTime={value:new c.Vector4(0,0,0,0)}),(d.includes("unity_DeltaTime")||h.includes("unity_DeltaTime"))&&(u.unity_DeltaTime={value:new c.Vector4(0,0,0,0)});for(const v in p){const _=v;switch(_){case"_TimeParameters":const x=new c.Vector4;u[_]={value:x};break;case"hlslcc_mtx4x4unity_MatrixV":case"hlslcc_mtx4x4unity_MatrixVP":u[_]={value:[]};break;case"_MainLightPosition":case"_MainLightColor":case"_WorldSpaceCameraPos":u[_]={value:[0,0,0,1]};break;case"unity_OrthoParams":break;case"unity_SpecCube0":u[_]={value:null};break;default:case"_ScreenParams":case"_ZBufferParams":case"_ProjectionParams":u[_]={value:[0,0,0,0]};break;case"_CameraOpaqueTexture":case"_CameraDepthTexture":u[_]={value:null};break}}let m=!1;if(t.extensions&&t.extensions[Rr]){const v=t.extensions[Rr];if(v.technique===i){mn&&console.log(t.name,"Material Properties",v);for(const _ in v.values){const x=v.values[_];if(typeof x=="string"){if(x.startsWith("/textures/")){const T=x.substring(10),O=Number.parseInt(T);if(O>=0){const M=await this.parser.getDependency("texture",O);M instanceof c.Texture&&(M.colorSpace=c.LinearSRGBColorSpace,M.needsUpdate=!0),u[_]={value:M};continue}}switch(_){case"alphaMode":x==="BLEND"&&(m=!0);continue}}if(Array.isArray(x)&&x.length===4){u[_]={value:new c.Vector4(x[0],x[1],x[2],x[3])};continue}u[_]={value:x}}}}const y=new ye(this.identifier,{name:t.name??"",uniforms:u,vertexShader:d,fragmentShader:h,lights:!1});switch(y.glslVersion=c.GLSL3,y.vertexShader=y.vertexShader.replace("#version 300 es",""),y.fragmentShader=y.fragmentShader.replace("#version 300 es",""),u._Cull?.value){case 0:y.side=c.DoubleSide;break;case 1:y.side=c.BackSide;break;case 2:y.side=c.FrontSide;break;default:y.side=c.FrontSide;break}switch(u._ZTest?.value){case 3:y.depthTest=!0,y.depthFunc=c.EqualDepth;break;case 6:y.depthTest=!0,y.depthFunc=c.NotEqualDepth;break;case 2:y.depthTest=!0,y.depthFunc=c.LessDepth;break;case 4:y.depthTest=!0,y.depthFunc=c.LessEqualDepth;break;case 5:y.depthTest=!0,y.depthFunc=c.GreaterDepth;break;case 7:y.depthTest=!0,y.depthFunc=c.GreaterEqualDepth;break;case 8:y.depthTest=!1,y.depthFunc=c.AlwaysDepth;break}y.transparent=m,m&&(y.depthWrite=!1),qC(u),y.onUpdateUniforms();for(const v in p){const _=v,x=p[v].type;if(u[_]?.value===void 0)switch(x){case R0.SAMPLER_2D:u[_]={value:GC},console.warn("Missing/unassigned texture, fallback to white: "+_);break;default:_==="unity_OrthoParams"||console.warn("TODO: EXPECTED UNIFORM / fallback NOT SET: "+_,p[v]);break}}mn&&console.log(y.uuid,u),T0(y),r(y)}):null}}function T0(s){if(s.uniforms){mn&&console.log("Uniforms:",s.uniforms);for(const t in s.uniforms)switch(e(t,t),t){case"_Color":e("color",t);break}}function e(t,i){Object.getOwnPropertyDescriptor(s,t)||Object.defineProperty(s,t,{get:()=>s.uniforms[i].value,set:n=>{s.uniforms[i].value=n,s.needsUpdate=!0}})}}const iO=w("debugextensions");let Ed;const nO=Promise.resolve().then(()=>require("./vendor-BtJpSuCj.umd.cjs")).then(s=>s.index$2).then(async s=>(Ed=s.GLTFAnimationPointerExtension,Ed)).catch(s=>{console.warn("Failed to import GLTFLoaderAnimationPointer. Please use @needle-tools/three-animationpointer for full KHR_animation support",s)}),Yo=new Array;function sO(s){Yo.includes(s)||Yo.push(s)}function oO(s){const e=Yo.indexOf(s);e>=0&&Yo.splice(e,1)}function Zm(s){if(s instanceof q.GLTFLoader){const e=new E0;return s.register(t=>(e.parser=t,e)),e}return null}class rO{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 Rd(s,e,t){const i=t.indexOf("?");i>=0&&(t=t.substring(0,i)),s.register(n=>new XP(n)),s.register(n=>new yC(n)),s.register(n=>new NC(n,e.lightmaps,t)),s.register(n=>new QP(n,t,e)),s.register(n=>new tO(n,t)),s.register(n=>new Us(n,t)),s.register(n=>new ne.NEEDLE_progressive(n)),s.register(n=>new WP(n)),Jb()&&s.register(n=>new ea(n)),await nO.catch(n=>{}),s.register(n=>{if(Ed){const o=new Ed(n);return o.setAnimationPointerResolver.bind(o)(new rO),o}else return(iO||A())&&console.error("Missing KHR_animation_pointer extension..."),{name:"KHR_animation_pointer_NOT_AVAILABLE"}});for(const n of Yo)n.onImport&&n.onImport(s,t,e)}function Jm(s,e){for(const t of Yo)t.onExport&&t.onExport(s,e)}function A0(s,e,t){for(const i of Yo)i.onLoaded&&i.onLoaded(s,e,t)}class L0{constructor(e){this.writer=e,this.name="EXT_mesh_gpu_instancing"}writeNode(e,t){if(e.constructor.name!=="InstancedMesh")return;const i=this.writer,n=i.extensionsUsed,o={};t.extensions=t.extensions||{},t.extensions[this.name]=o;let r=new c.Matrix4;const a=new Array,l=new Array,h=new Array;for(let m=0;m<e.count;m++){e.getMatrixAt(m,r);let y=new c.Vector3,b=new c.Quaternion,g=new c.Vector3;r.decompose(y,b,g),a.push(y.x,y.y,y.z),l.push(b.x,b.y,b.z,b.w),h.push(g.x,g.y,g.z)}const d=new Float32Array(a),u=new Float32Array(l),p=new Float32Array(h);o.attributes={TRANSLATION:i.processAccessor(new c.BufferAttribute(d,3)),ROTATION:i.processAccessor(new c.BufferAttribute(u,4)),SCALE:i.processAccessor(new c.BufferAttribute(p,3))},n[this.name]=!0}}var aO=Object.defineProperty,D0=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&aO(e,t,n),n};const Za=w("debugreflectionprobe"),y_=w("noreflectionprobe"),Pf=Symbol("reflectionProbeKey"),__=Symbol("original material"),eg=class Qn extends k{static _probes=new Map;static isUsingReflectionProbe(e){return!!(e[Pf]||e[__]?.[Pf])}static get(e,t,i,n){if(!e||e.isObject3D!==!0||y_)return null;const o=Qn._probes.get(t);if(o){for(const r of o)if(r.__didAwake||r.__internalAwake(),r.activeAndEnabled){if(n){if(r.gameObject===n)return r}else if(r.isInBox(e))return Za&&console.log("Found reflection probe",e.name,r.name),r}}return Za&&console.debug("Did not find reflection probe",e.name,i,e),null}_texture;set texture(e){if(e&&!(e instanceof c.Texture)){console.error("ReflectionProbe.texture must be a Texture",e);return}this._texture=e,e&&(e.mapping=c.EquirectangularReflectionMapping,e.colorSpace=c.LinearSRGBColorSpace,e.needsUpdate=!0)}get texture(){return this._texture}center;size;_boxHelper;isInBox(e){return this._boxHelper?.isInBox(e)}constructor(){super(),Qn._probes.has(this.context)||Qn._probes.set(this.context,[]),Qn._probes.get(this.context)?.push(this)}awake(){this._boxHelper=this.gameObject.addComponent(nt),this._boxHelper.updateBox(!0),Za&&this._boxHelper.showHelper(5592320,!0),this._texture&&(this._texture.mapping=c.EquirectangularReflectionMapping,this._texture.colorSpace=c.LinearSRGBColorSpace,this._texture.needsUpdate=!0)}start(){!this._texture&&A()&&(console.warn(`[ReflectionProbe] Missing texture. Please assign a custom cubemap texture. To use reflection probes assign them to your renderer's "anchor" property.`),he("ReflectionProbe configuration hint: See browser console for details"))}onDestroy(){const e=Qn._probes.get(this.context);if(e){const t=e.indexOf(this);t>=0&&e.splice(t,1)}}static _rendererMaterialsCache=new Map;onSet(e){if(y_||!this.enabled||e.sharedMaterials?.length<=0||!this.texture)return;let t=Qn._rendererMaterialsCache.get(e);t||(t=[],Qn._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 c.MeshBasicMaterial)continue;let o=t[i];const r=n===o?.copy,a=!o||o.material.uuid!==n.uuid||o.copy.version!==n.version;if(!r&&a){if(Za){let d="";o?o.material!==n?d="reference changed; cached instance?: "+r:o.copy.version!==n.version&&(d="version changed"):d="not cached",console.warn("Cloning material",n.name,n.version,"Reason:",d,`
|
|
977
977
|
`,n.uuid,`
|
|
978
978
|
`,o?.copy.uuid,`
|
|
979
979
|
`,e.name)}const h=n.clone();h.version=n.version,o?(o.copy=h,o.material=n):(o={material:n,copy:h},t.push(o)),h[Pf]=this,h[__]=n,Za&&console.log("Set reflection",e.name,e.guid)}o&&o.copy&&(o.copy.onBeforeCompile=n.onBeforeCompile);const l=o?.copy;l.envMap=this.texture,e.sharedMaterials[i]=l}}onUnset(e){const t=Qn._rendererMaterialsCache.get(e);if(t)for(let i=0;i<t.length;i++){const n=t[i];e.sharedMaterials[i]=n.material}}};D0([f(c.Vector3)],eg.prototype,"center");D0([f(c.Vector3)],eg.prototype,"size");let Jl=eg;const Nt=w("debuginstancing");class Ko{static instance=new Ko;static getStartInstanceCount=e=>4;objs=[];setup(e,t,i,n,o,r=0){e.applySettings(t);const a=this.tryCreateOrAddInstance(t,i,o);if(a){n===null&&(n=[]),n.push(a),ne.NEEDLE_progressive.assignTextureLOD(a.renderer.material,0);for(let l=0;l<e.sharedMeshes.length;l++){const h=e.sharedMeshes[l],d=h.geometry;ne.NEEDLE_progressive.assignMeshLOD(h,0).then(u=>{u&&e.activeAndEnabled&&d!=u&&a.setGeometry(u)})}}else if(r<=0&&t.type!=="Mesh"){const l=r+1;for(const h of t.children)n=this.setup(e,h,i,n,o,l)}return r===0&&o.useMatrixWorldAutoUpdate&&n&&n.length>=0&&this.autoUpdateInstanceMatrix(t),n}tryCreateOrAddInstance(e,t,i){if(e.type==="Mesh"){const n=i.foundMeshes;if(i.foundMeshes+=1,!i.rend.enableInstancing)return null;if(i.rend.enableInstancing!==!0){if(n>=i.rend.enableInstancing.length)return Nt&&console.error("Something is wrong with instance setup",e,i.rend.enableInstancing,n),null;if(!i.rend.enableInstancing[n])return null}const o=e,r=o.material;for(const u of this.objs){if(!u.canAdd(o.geometry,r))continue;return u.addInstance(o)}let a=Ko.getStartInstanceCount(e);(!a||a<0)&&(a=4);let l=e.name;l?.length||(l=lb());const h=new lO(l,o.geometry,r,a,t);return this.objs.push(h),h.addInstance(o)}return null}autoUpdateInstanceMatrix(e){const t=e.matrixWorld.multiplyMatrices.bind(e.matrixWorld),i=e.matrixWorld.clone(),n=(o,r)=>{const a=t(o,r);return(e[ql]||i.equals(a)===!1)&&(i.copy(a),e[ql]=!0),a};e.matrixWorld.multiplyMatrices=n}}class $o{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[sv]=t,this.meshInformation=Mo(e.geometry),$o.all.push(this)}updateMeshInformation(){const e=Mo(this.object.geometry),t=this.meshInformation.vertexCount,i=this.meshInformation.indexCount;return Object.assign(this.meshInformation,e),t!==this.meshInformation.vertexCount||i!==this.meshInformation.indexCount}updateInstanceMatrix(e=!1,t=!0){this.__instanceIndex<0||(t&&this.object.updateWorldMatrix(!0,e),this.renderer.updateInstance(this.object.matrixWorld,this.__instanceIndex))}setMatrix(e){this.__instanceIndex<0||this.renderer.updateInstance(e,this.__instanceIndex)}setGeometry(e){if(this.__geometryIndex<0)return!1;const t=this;if(this.vertexCount>this.__reservedVertexRange)return i(`Instancing: Can not update geometry (${this.name}), reserved vertex range is too small: ${this.__reservedVertexRange.toLocaleString()} < ${this.vertexCount.toLocaleString()} vertices for ${this.name}`);if(this.indexCount>this.__reservedIndexRange)return i(`Instancing: Can not update geometry (${this.name}), reserved index range is too small: ${this.__reservedIndexRange.toLocaleString()} < ${this.indexCount.toLocaleString()} indices for ${this.name}`);return this.renderer.updateGeometry(e,this.__geometryIndex);function i(n){return t.updateMeshInformation()&&(t.renderer.remove(t,!0),t.renderer.add(t))?!0:((A()||Nt)&&console.error(n),!1)}}add(){this.__instanceIndex>=0||(this.renderer.add(this),S.markAsInstancedRendered(this.object,!0))}remove(e){if(!(this.__instanceIndex<0)&&(this.renderer.remove(this,e),S.markAsInstancedRendered(this.object,!1),e)){const t=$o.all.indexOf(this);t>=0&&$o.all.splice(t,1)}}}class lO{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(),Nt&&this._batchedMesh.boundingSphere){const i=this._batchedMesh.boundingSphere;B.DrawWireSphere(i.center,i.radius,65280)}}_context;_batchedMesh;_handles=[];_geometryIds=new Map;_maxInstanceCount;_currentInstanceCount=0;_currentVertexCount=0;_currentIndexCount=0;_maxVertexCount;_maxIndexCount;static nullMatrix=new c.Matrix4;canAdd(e,t){return this._maxVertexCount>1e7||t!==this.material||!this.validateGeometry(e)?!1:!!(!this.mustGrow(e)||this.allowResize)}_needUpdateBounds=!1;_debugMaterial=null;constructor(e,t,i,n,o){this.name=e,this.geometry=t,this.material=i,this._context=o,this._maxInstanceCount=Math.max(2,n),Nt&&(this._debugMaterial=b_());const r=this.tryEstimateVertexCountSize(this._maxInstanceCount,[t],n);this._maxVertexCount=r.vertexCount,this._maxIndexCount=r.indexCount,this._batchedMesh=new c.BatchedMesh(this._maxInstanceCount,this._maxVertexCount,this._maxIndexCount,this._debugMaterial??this.material),this._batchedMesh[ml]=!0,this._batchedMesh.visible=!0,this._context.scene.add(this._batchedMesh),i instanceof c.RawShaderMaterial&&(i.defines.USE_INSTANCING=!0,i.needsUpdate=!0),o.pre_render_callbacks.push(this.onBeforeRender),o.post_render_callbacks.push(this.onAfterRender),Nt&&console.log(`Instanced renderer created with ${this._maxInstanceCount} instances, ${this._maxVertexCount} max vertices and ${this._maxIndexCount} max indices for "${e}"`)}dispose(){Nt&&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 $o(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()):Tr&&console.log("Use debuglightmap
|
|
|
1023
1023
|
gl_FragColor = lightMapTexel;
|
|
1024
1024
|
gl_FragColor.a = 1.;
|
|
1025
1025
|
}
|
|
1026
|
-
`,defines:{USE_LIGHTMAP:""}})}}var cO=Object.defineProperty,ps=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&cO(e,t,n),n};const Vr=w("debugrenderer"),v_=w("debugskinnedmesh"),w_=w("noinstancing"),hO=w("wireframe");class I0{path=null;asset=null;default}class dO{_renderer;_targets=[];_indexMapMaxIndex;_indexMap;_changed=!1;get changed(){return this._changed}set changed(e){e===!0&&Vr&&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),o=e.gameObject;if(this._targets=[],o)switch(o.type){case"Group":this._targets=[...o.children];break;case"SkinnedMesh":case"Mesh":this._targets.push(o);break}let r=!1,a,l=0;for(let h=0;h<this._targets.length;h++){const d=this._targets[h];if(!d)continue;const u=d.material;if(u){u.shadowSide=u.side;for(let p=0;p<t.length;p++){const m=t[p];if(!m){r=!0;continue}if(u.name===m.name){a===void 0&&(a=new Map),a.set(p,h),l=Math.max(l,p);break}}}}if(r){this._indexMapMaxIndex=l,this._indexMap=a;const h=`Renderer ${e.name} was initialized with missing materials - this may lead to unexpected behaviour when trying to access sharedMaterials by index.`;console.warn(h),Ii()&&he("Found renderer with missing materials: please check the console for details.")}return new Proxy(this,{get(h,d){if(typeof d=="string"){const u=parseInt(d);if(!isNaN(u))return n(u)}return h[d]},set(h,d,u){return typeof d=="string"&&i(u,Number.parseInt(d)),Reflect.set(h,d,u)?(u instanceof c.Material&&(h.changed=!0),!0):!1}})}get length(){return this._indexMapMaxIndex!==void 0?this._indexMapMaxIndex+1:this._targets.length}*[Symbol.iterator](){for(let e=0;e<this.length;e++)yield this.getMaterial(e)}resolveIndex(e){const t=this._indexMap;return t&&t.has(e)?t.get(e):e}setMaterial(e,t){if(t=this.resolveIndex(t),t<0||t>=this._targets.length)return;const i=this._targets[t];!i||i.material===void 0||(i.material=e,this.changed=!0)}getMaterial(e){if(e=this.resolveIndex(e),e<0)return null;const t=this._targets;if(e>=t.length)return null;const i=t[e];return i?i.material:null}}const jn=class td extends k{static setInstanced(e,t){const i=pc(e,td);return i.setInstancingEnabled(t),i}static isInstanced(e){const t=sr(e,td);return t?t.isInstancingActive:Li.isUsingInstancing(e)}static setVisible(e,t){es(e,t)}receiveShadows=!1;shadowCastingMode=0;lightmapIndex=-1;lightmapScaleOffset=new c.Vector4(1,1,0,0);enableInstancing=void 0;renderOrder=void 0;allowOcclusionWhenDynamic=!0;probeAnchor;reflectionProbeUsage=0;_lightmaps;get sharedMesh(){if(this.gameObject.type==="Mesh")return this.gameObject;if(this.gameObject.type==="SkinnesMesh")return this.gameObject;if(this.gameObject.type==="Group")return this.gameObject.children[0]}_sharedMeshes=[];get sharedMeshes(){if(this.destroyed||!this.gameObject)return this._sharedMeshes;if(this._sharedMeshes.length=0,this.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 c.Material?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 dO(this,this._originalMaterials)),this._sharedMaterials):null}static get shouldSuppressInstancing(){return w_}_lightmapTextureOverride=void 0;get lightmap(){return this._lightmaps?.length?this._lightmaps[0].lightmap:null}set lightmap(e){if(this._lightmapTextureOverride=e,e===void 0&&(e=this.context.lightmaps.tryGetLightmap(this.sourceId,this.lightmapIndex)),this._lightmaps?.length)for(const t of this._lightmaps)t.lightmap=e}get hasLightmap(){const e=this.lightmap;return e!=null}allowProgressiveLoading=!0;_firstFrame=-1;registering(){this.enabled||this.setVisibility(!1)}awake(){if(this._firstFrame=this.context.time.frame,Vr&&console.log("Renderer ",this.name,this),this.clearInstancingState(),this.probeAnchor&&Vr&&this.probeAnchor.add(new c.AxesHelper(.2)),this._reflectionProbe=null,this.isMultiMaterialObject(this.gameObject)){for(const e of this.gameObject.children)this.context.addBeforeRenderListener(e,this.onBeforeRenderThree),e.layers.mask=this.gameObject.layers.mask;if(this.renderOrder!==void 0){let e=0;for(let t=0;t<this.gameObject.children.length;t++){const i=this.gameObject.children[t];if(!(!this.isMeshOrSkinnedMesh(i)||S.getComponent(i,td))){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(),hO)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 o=new Td(this.gameObject,this.context);this._lightmaps.push(o)}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 o;i>=this._lightmaps.length?(o=new Td(n,this.context),this._lightmaps.push(o)):o=this._lightmaps[i],o.init(this.lightmapIndex,this.lightmapScaleOffset,t)}}}else Vr&&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=Ko.instance.setup(this,this.gameObject,this.context,null,{rend:this,foundMeshes:0,useMatrixWorldAutoUpdate:this.useInstanceMatrixWorldAutoUpdate()}),this._handles)return S.markAsInstancedRendered(this.gameObject,!0),!0}else if(this._handles!==null){for(const t of this._handles)t.updateInstanceMatrix(!0),t.add();return S.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&&!w_&&(this.setInstancingEnabled(!0),Li.markDirty(this.gameObject)),this.gameObject.frustumCulled=this.allowOcclusionWhenDynamic,this.isMultiMaterialObject(this.gameObject))for(let e=0;e<this.gameObject.children.length;e++){const t=this.gameObject.children[e];t.frustumCulled=this.allowOcclusionWhenDynamic}}onEnable(){this.sharedMeshes,this.setVisibility(!0),this._isInstancingEnabled||this.enableInstancing==!0||Array.isArray(this.enableInstancing)&&this.enableInstancing.some(t=>t)?this.__internalDidAwakeAndStart&&this.setInstancingEnabled(!0):this.enabled&&this.applyStencil(),this.updateReflectionProbe()}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()),Vr==this.name&&this.gameObject instanceof c.Mesh){this.gameObject.geometry.computeBoundingSphere();const e=V(this.gameObject.geometry.boundingSphere.center).applyMatrix4(this.gameObject.matrixWorld);B.DrawWireSphere(e,this.gameObject.geometry.boundingSphere.radius,56831)}if(this.isMultiMaterialObject(this.gameObject)&&this.gameObject.children?.length>0)for(const e of this.gameObject.children)this.applySettings(e);else this.applySettings(this.gameObject);if(this.sharedMaterials?.changed&&(this.sharedMaterials.changed=!1,this.applyLightmapping()),this._handles?.length&&this.gameObject[ql]===!0){this.gameObject[ql]=!1;for(let t=this._handles.length-1;t>=0;t--)this._handles[t].updateInstanceMatrix();this.gameObject.matrixWorldNeedsUpdate=!1}if(this._handles&&this._handles.length<=0&&S.markAsInstancedRendered(this.gameObject,!1),this._isInstancingEnabled&&this._handles)for(let e=0;e<this._handles.length;e++){const t=this._handles[e];es(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&&!Jl.isUsingReflectionProbe(e)&&(e.envMap=this.context.scene.environment);else Vr&&console.warn("[Renderer] sharedMaterials not initialized yet: "+this.name)}}onBeforeRenderThree=(e,t,i,n,o,r)=>{if(o.envMapIntensity!==void 0){const a=this.hasLightmap?Math.PI:1,l=this.context.mainCameraComponent?.environmentIntensity??1;o.envMapIntensity=Math.max(0,l*this.context.sceneLighting.environmentIntensity/a)}if(this._lightmaps)for(const a of this._lightmaps)a.updateLightmapUniforms(o),a.applyLightmap()};onAfterRender(){if(this._isInstancingEnabled&&this._handles)for(let e=0;e<this._handles.length;e++){const t=this._handles[e];es(t.object,!0)}this.reflectionProbeUsage!==0&&this._reflectionProbe&&this._reflectionProbe.onUnset(this),this.static&&this.gameObject.matrixAutoUpdate&&(this.gameObject.matrixAutoUpdate=!1)}applyStencil(){Us.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(),pe.LateUpdate),this._probeAnchorLastFrame=this.probeAnchor)}*_updateReflectionProbe(){const e=this.probeAnchor||this.gameObject,t=!!this.probeAnchor;this._reflectionProbe=Jl.get(e,this.context,t,this.probeAnchor)}setVisibility(e){if(!this.isMultiMaterialObject(this.gameObject))es(this.gameObject,e);else for(const t of this.gameObject.children)this.isMeshOrSkinnedMesh(t)&&es(t,e)}isMultiMaterialObject(e){return e.type==="Group"}isMeshOrSkinnedMesh(e){return e.type==="Mesh"||e.type==="SkinnedMesh"}};ps([f()],jn.prototype,"receiveShadows");ps([f()],jn.prototype,"shadowCastingMode");ps([f()],jn.prototype,"lightmapIndex");ps([f(c.Vector4)],jn.prototype,"lightmapScaleOffset");ps([f()],jn.prototype,"enableInstancing");ps([f()],jn.prototype,"renderOrder");ps([f()],jn.prototype,"allowOcclusionWhenDynamic");ps([f(c.Object3D)],jn.prototype,"probeAnchor");ps([f()],jn.prototype,"reflectionProbeUsage");let mi=jn;class Mc extends mi{}class tg extends Mc{_needUpdateBoundingSphere=!1;awake(){super.awake(),v_&&console.log('SkinnedMeshRenderer for "'+this.name+'"',this),this.allowOcclusionWhenDynamic=!1;for(const e of this.sharedMeshes)e.parent?.updateWorldMatrix(!1,!0),this.markBoundsDirty()}onAfterRender(){if(super.onAfterRender(),this._needUpdateBoundingSphere){for(const e of this.sharedMeshes)if(e instanceof c.SkinnedMesh){this._needUpdateBoundingSphere=!1;try{const t=e.geometry,i=ne.getRaycastMesh(e);i&&(e.geometry=i),e.computeBoundingSphere(),e.geometry=t}catch(t){console.error(`Error updating bounding sphere for ${e.name}`,t)}}}if(v_){for(const e of this.sharedMeshes)if(e instanceof c.SkinnedMesh&&e.boundingSphere){const t=V(e.boundingSphere.center).applyMatrix4(e.matrixWorld);B.DrawWireSphere(t,e.boundingSphere.radius,"red")}}}markBoundsDirty(){this._needUpdateBoundingSphere=!0}}var uO=Object.defineProperty,j0=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&uO(e,t,n),n};const Ch=w("debuggltfexport");class ig extends nt{sceneRoot}const ng=class $r extends k{binary=!0;objects=[];ext;async exportNow(e,t){Ch&&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:$r.calculateCenter(this.objects),...t},n=await this.export(this.objects,i).catch(o=>(console.error(o),!1));return n===!1?!1:(this.binary?e.endsWith(".glb")||(e+=".glb"):e.endsWith(".gltf")||(e+=".gltf"),this.binary?$r.saveArrayBuffer(n,e):$r.saveJson(n,e),!0)}async export(e,t){if(!e||e.length<=0){console.warn("No objects set to export");return}const i=new q.GLTFExporter;i.register(h=>new L0(h)),i.register(h=>new k0(h)),Jm(i,this.context),$r.filterTopmostParent(e);const n={trs:!1,onlyVisible:!0,truncateDrawRange:!1,binary:!0,maxTextureSize:1/0,embedImages:!0,includeCustomExtensions:!0,animations:t?.animations||$r.collectAnimations(e),...t},o=new Array,r=new c.Object3D;t?.pivot&&r.position.sub(t.pivot),Ch&&console.log("EXPORT",e),e.forEach(h=>{h&&Ep(h)&&(r.children.push(h),h.matrixAutoUpdate=!1,h.matrix.copy(h.matrixWorld),S.getComponentsInChildren(h,mi).forEach(d=>{S.isActiveInHierarchy(d.gameObject)&&d.setInstancingEnabled(!1)}),h.traverse(d=>{if(!Ep(d)){const u=d.parent;d.removeFromParent(),o.push(()=>{u&&u.add(d)})}}))});const a=new Pm(r);return t?.needleComponents&&(this.ext=new E0),this.ext&&(this.ext.registerExport(i),this.ext.context=a),new Promise((h,d)=>{Ch&&console.log("Starting glTF export.");try{i?.parse(r,u=>{l(),h(u)},u=>{l(),d(u)},n)}catch(u){console.error(u),d(u)}finally{o.forEach(u=>u()),Ch&&console.log("Finished glTF export.")}});function l(){e.forEach(h=>{h&&(h.matrixAutoUpdate=!0,S.getComponentsInChildren(h,mi).forEach(d=>{S.isActiveInHierarchy(d.gameObject)&&d.setInstancingEnabled(!1)}))})}}static saveArrayBuffer(e,t){this.save(new Blob([e],{type:"application/octet-stream"}),t)}static saveJson(e,t){this.save("data: text/json;charset=utf-8,"+encodeURIComponent(JSON.stringify(e)),t)}static save(e,t){const i=document.createElement("a");i.style.display="none",document.body.appendChild(i),typeof e=="string"?i.href=e:i.href=URL.createObjectURL(e),i.download=t,i.click(),i.remove()}static collectAnimations(e,t){t=t||[];for(const i of e)i&&i.traverseVisible(n=>{n.animations&&n.animations.length>0&&t.push(...n.animations)});return t}static calculateCenter(e,t){const i=t||new c.Vector3;return i.set(0,0,0),e.forEach(n=>{i.add(X(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}}}};j0([f()],ng.prototype,"binary");j0([f(c.Object3D)],ng.prototype,"objects");let sg=ng;typeof globalThis!==void 0&&!("OffscreenCanvas"in globalThis)&&(globalThis.OffscreenCanvas=class{canvas;constructor(e,t){return this.canvas=document.createElement("canvas"),this.canvas.width=e,this.canvas.height=t,this.canvas.convertToBlob=(i,n)=>new Promise(o=>{this.canvas.toBlob(o,i,n)}),this.canvas}});const fO=w("debugprogress");function B0(s){s=s||new Date;const e=s.getMonth()+1,t=s.getDate(),i=s.getHours(),n=s.getMinutes(),o=s.getSeconds(),r=(e<10?"0":"")+e,a=(t<10?"0":"")+t,l=(i<10?"0":"")+i,h=(n<10?"0":"")+n,d=(o<10?"0":"")+o;return s.getFullYear()+r+a+"-"+l+h+d}class ie{static start(e,t){typeof t=="string"&&(t={parentScope:t});const i=new pO(e,t);bl.set(e,i)}static report(e,t){const i=bl.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=bl.get(e);t&&(t.end(),bl.delete(e))}}const bl=new Map;class pO{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?bl.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??!!fO,this.showLogs&&console.time(this.scopeLabel),this.onProgress=t?.onProgress}report(e,t=!1){if(e){if(e.totalSteps!==void 0&&(this.lastTotalSteps=e.totalSteps),e.currentStep!==void 0&&(this.lastStep=e.currentStep),e.autoStep!==void 0){if(e.currentStep===void 0){this.lastStep===void 0&&(this.lastStep=0);const n=typeof e.autoStep=="number"?e.autoStep:1;this.lastStep+=this.lastAutoStepWeight,this.lastAutoStepWeight=n,e.currentStep=this.lastStep}e.totalSteps=this.lastTotalSteps}e.progress!==void 0?this.selfProgress=e.progress:e.currentStep!==void 0&&e.totalSteps!==void 0&&(this.selfProgress=e.currentStep/e.totalSteps)}if(this.childScopes.length>0){let n=0,o=0;for(const a of this.childScopes)n+=a.selfProgress,o+=1;o>0&&(n/=o);const r=this.lastAutoStepWeight/(this.lastTotalSteps??1);this.totalProgress=this.selfProgress+n*r}else this.totalProgress=this.selfProgress;this.selfProgress=Math.min(1,this.selfProgress),this.totalProgress=Math.min(1,this.totalProgress);let i=(this.totalProgress*100).toFixed(3)+"%";this.childScopes.length>0&&(i+=" ("+(this.selfProgress*100).toFixed(3)+"% self)"),e?.message&&(i=e.message+" – "+i),this.lastStep!==void 0&&this.lastTotalSteps!==void 0&&(i="Step "+(this.lastStep+(this.lastAutoStepWeight!=1?"–"+(this.lastStep+this.lastAutoStepWeight):"")+"/"+this.lastTotalSteps)+" "+i),t?this.totalReports++:(this.selfReports++,this.totalReports++),this.showLogs&&console.timeLog(this.scopeLabel,i),this.onProgress&&this.onProgress(this.totalProgress),this.parentScope&&this.parentScope.report(void 0,!0)}end(){this.report({progress:1,autoStep:!0},!0),this.showLogs&&(console.timeLog(this.scopeLabel,"Total reports: "+this.totalReports,"Self reports: "+this.selfReports),console.timeEnd(this.scopeLabel));let e=!1;for(const t of this.childScopes)if(!(t.selfProgress>=1)){e=!0;break}e&&console.warn("Progress end with child scopes that are still running",this),this.onProgress=void 0}}const Oe="</StageRoot/Materials";function mO(s,e,t){const i=new Map,n=_=>{const g=_.type___needle,v=i.get(g)||new Map;if(i.set(g,v),!v.has(_)){const b=`${g}${v.size?`_${v.size}`:""}`;v.set(_,b)}return v.get(_)},o=s.colorNode?Ph(s.colorNode):[],r=s.colorNode?`color3f inputs:diffuseColor.connect = ${Oe}/${e}/${n(o.values().next().value)}.outputs:out>`:"",a=s.roughnessNode?Ph(s.roughnessNode):[],l=s.roughnessNode?`float inputs:roughness.connect = ${Oe}/${e}/${n(a.values().next().value)}.outputs:out>`:"",h=s.normalNode?Ph(s.normalNode):[],d=s.normalNode?`float3 inputs:normal.connect = ${Oe}/${e}/${n(h.values().next().value)}.outputs:out>`:"",u=s.metalnessNode?Ph(s.metalnessNode):[],p=s.metalnessNode?`float inputs:metallic.connect = ${Oe}/${e}/${n(u.values().next().value)}.outputs:out>`:"",m=new Set([...o,...a,...h,...u]),y=_O(m,e,t,n);return console.debug(y),`
|
|
1026
|
+
`,defines:{USE_LIGHTMAP:""}})}}var cO=Object.defineProperty,ps=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&cO(e,t,n),n};const Vr=w("debugrenderer"),v_=w("debugskinnedmesh"),w_=w("noinstancing"),hO=w("wireframe");class I0{path=null;asset=null;default}class dO{_renderer;_targets=[];_indexMapMaxIndex;_indexMap;_changed=!1;get changed(){return this._changed}set changed(e){e===!0&&Vr&&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),o=e.gameObject;if(this._targets=[],o)switch(o.type){case"Group":this._targets=[...o.children];break;case"SkinnedMesh":case"Mesh":this._targets.push(o);break}let r=!1,a,l=0;for(let h=0;h<this._targets.length;h++){const d=this._targets[h];if(!d)continue;const u=d.material;if(u){u.shadowSide=u.side;for(let p=0;p<t.length;p++){const m=t[p];if(!m){r=!0;continue}if(u.name===m.name){a===void 0&&(a=new Map),a.set(p,h),l=Math.max(l,p);break}}}}if(r){this._indexMapMaxIndex=l,this._indexMap=a;const h=`Renderer ${e.name} was initialized with missing materials - this may lead to unexpected behaviour when trying to access sharedMaterials by index.`;console.warn(h),Ii()&&he("Found renderer with missing materials: please check the console for details.")}return new Proxy(this,{get(h,d){if(typeof d=="string"){const u=parseInt(d);if(!isNaN(u))return n(u)}return h[d]},set(h,d,u){return typeof d=="string"&&i(u,Number.parseInt(d)),Reflect.set(h,d,u)?(u instanceof c.Material&&(h.changed=!0),!0):!1}})}get length(){return this._indexMapMaxIndex!==void 0?this._indexMapMaxIndex+1:this._targets.length}*[Symbol.iterator](){for(let e=0;e<this.length;e++)yield this.getMaterial(e)}resolveIndex(e){const t=this._indexMap;return t&&t.has(e)?t.get(e):e}setMaterial(e,t){if(t=this.resolveIndex(t),t<0||t>=this._targets.length)return;const i=this._targets[t];!i||i.material===void 0||(i.material=e,this.changed=!0)}getMaterial(e){if(e=this.resolveIndex(e),e<0)return null;const t=this._targets;if(e>=t.length)return null;const i=t[e];return i?i.material:null}}const jn=class td extends k{static setInstanced(e,t){const i=pc(e,td);return i.setInstancingEnabled(t),i}static isInstanced(e){const t=sr(e,td);return t?t.isInstancingActive:Li.isUsingInstancing(e)}static setVisible(e,t){es(e,t)}receiveShadows=!1;shadowCastingMode=0;lightmapIndex=-1;lightmapScaleOffset=new c.Vector4(1,1,0,0);enableInstancing=void 0;renderOrder=void 0;allowOcclusionWhenDynamic=!0;probeAnchor;reflectionProbeUsage=0;_lightmaps;get sharedMesh(){if(this.gameObject.type==="Mesh")return this.gameObject;if(this.gameObject.type==="SkinnesMesh")return this.gameObject;if(this.gameObject.type==="Group")return this.gameObject.children[0]}_sharedMeshes=[];get sharedMeshes(){if(this.destroyed||!this.gameObject)return this._sharedMeshes;if(this._sharedMeshes.length=0,this.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 c.Material?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 dO(this,this._originalMaterials)),this._sharedMaterials):null}static get shouldSuppressInstancing(){return w_}_lightmapTextureOverride=void 0;get lightmap(){return this._lightmaps?.length?this._lightmaps[0].lightmap:null}set lightmap(e){if(this._lightmapTextureOverride=e,e===void 0&&(e=this.context.lightmaps.tryGetLightmap(this.sourceId,this.lightmapIndex)),this._lightmaps?.length)for(const t of this._lightmaps)t.lightmap=e}get hasLightmap(){const e=this.lightmap;return e!=null}allowProgressiveLoading=!0;_firstFrame=-1;registering(){this.enabled||this.setVisibility(!1)}awake(){if(this._firstFrame=this.context.time.frame,Vr&&console.log("Renderer ",this.name,this),this.clearInstancingState(),this.probeAnchor&&Vr&&this.probeAnchor.add(new c.AxesHelper(.2)),this._reflectionProbe=null,this.isMultiMaterialObject(this.gameObject)){for(const e of this.gameObject.children)this.context.addBeforeRenderListener(e,this.onBeforeRenderThree),e.layers.mask=this.gameObject.layers.mask;if(this.renderOrder!==void 0){let e=0;for(let t=0;t<this.gameObject.children.length;t++){const i=this.gameObject.children[t];if(!(!this.isMeshOrSkinnedMesh(i)||S.getComponent(i,td))){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(),hO)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 o=new Td(this.gameObject,this.context);this._lightmaps.push(o)}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 o;i>=this._lightmaps.length?(o=new Td(n,this.context),this._lightmaps.push(o)):o=this._lightmaps[i],o.init(this.lightmapIndex,this.lightmapScaleOffset,t)}}}else Vr&&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=Ko.instance.setup(this,this.gameObject,this.context,null,{rend:this,foundMeshes:0,useMatrixWorldAutoUpdate:this.useInstanceMatrixWorldAutoUpdate()}),this._handles)return S.markAsInstancedRendered(this.gameObject,!0),!0}else if(this._handles!==null){for(const t of this._handles)t.updateInstanceMatrix(!0),t.add();return S.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&&!w_&&(this.setInstancingEnabled(!0),Li.markDirty(this.gameObject)),this.gameObject.frustumCulled=this.allowOcclusionWhenDynamic,this.isMultiMaterialObject(this.gameObject))for(let e=0;e<this.gameObject.children.length;e++){const t=this.gameObject.children[e];t.frustumCulled=this.allowOcclusionWhenDynamic}}onEnable(){this.sharedMeshes,this.setVisibility(!0),this._isInstancingEnabled||this.enableInstancing==!0||Array.isArray(this.enableInstancing)&&this.enableInstancing.some(t=>t)?this.__internalDidAwakeAndStart&&this.setInstancingEnabled(!0):this.enabled&&this.applyStencil(),this.updateReflectionProbe()}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()),Vr==this.name&&this.gameObject instanceof c.Mesh){this.gameObject.geometry.computeBoundingSphere();const e=V(this.gameObject.geometry.boundingSphere.center).applyMatrix4(this.gameObject.matrixWorld);B.DrawWireSphere(e,this.gameObject.geometry.boundingSphere.radius,56831)}if(this.isMultiMaterialObject(this.gameObject)&&this.gameObject.children?.length>0)for(const e of this.gameObject.children)this.applySettings(e);else this.applySettings(this.gameObject);if(this.sharedMaterials?.changed&&(this.sharedMaterials.changed=!1,this.applyLightmapping()),this._handles?.length&&this.gameObject[ql]===!0){this.gameObject[ql]=!1;for(let t=this._handles.length-1;t>=0;t--)this._handles[t].updateInstanceMatrix();this.gameObject.matrixWorldNeedsUpdate=!1}if(this._handles&&this._handles.length<=0&&S.markAsInstancedRendered(this.gameObject,!1),this._isInstancingEnabled&&this._handles)for(let e=0;e<this._handles.length;e++){const t=this._handles[e];es(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&&!Jl.isUsingReflectionProbe(e)&&(e.envMap=this.context.scene.environment);else Vr&&console.warn("[Renderer] sharedMaterials not initialized yet: "+this.name)}}onBeforeRenderThree=(e,t,i,n,o,r)=>{if(o.envMapIntensity!==void 0){const a=this.hasLightmap?Math.PI:1,l=this.context.mainCameraComponent?.environmentIntensity??1;o.envMapIntensity=Math.max(0,l*this.context.sceneLighting.environmentIntensity/a)}if(this._lightmaps)for(const a of this._lightmaps)a.updateLightmapUniforms(o),a.applyLightmap()};onAfterRender(){if(this._isInstancingEnabled&&this._handles)for(let e=0;e<this._handles.length;e++){const t=this._handles[e];es(t.object,!0)}this.reflectionProbeUsage!==0&&this._reflectionProbe&&this._reflectionProbe.onUnset(this),this.static&&this.gameObject.matrixAutoUpdate&&(this.gameObject.matrixAutoUpdate=!1)}applyStencil(){Us.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(),pe.LateUpdate),this._probeAnchorLastFrame=this.probeAnchor)}*_updateReflectionProbe(){const e=this.probeAnchor||this.gameObject,t=!!this.probeAnchor;this._reflectionProbe=Jl.get(e,this.context,t,this.probeAnchor)}setVisibility(e){if(!this.isMultiMaterialObject(this.gameObject))es(this.gameObject,e);else for(const t of this.gameObject.children)this.isMeshOrSkinnedMesh(t)&&es(t,e)}isMultiMaterialObject(e){return e.type==="Group"}isMeshOrSkinnedMesh(e){return e.type==="Mesh"||e.type==="SkinnedMesh"}};ps([f()],jn.prototype,"receiveShadows");ps([f()],jn.prototype,"shadowCastingMode");ps([f()],jn.prototype,"lightmapIndex");ps([f(c.Vector4)],jn.prototype,"lightmapScaleOffset");ps([f()],jn.prototype,"enableInstancing");ps([f()],jn.prototype,"renderOrder");ps([f()],jn.prototype,"allowOcclusionWhenDynamic");ps([f(c.Object3D)],jn.prototype,"probeAnchor");ps([f()],jn.prototype,"reflectionProbeUsage");let mi=jn;class Mc extends mi{}class tg extends Mc{_needUpdateBoundingSphere=!1;awake(){super.awake(),v_&&console.log('SkinnedMeshRenderer for "'+this.name+'"',this),this.allowOcclusionWhenDynamic=!1;for(const e of this.sharedMeshes)e.parent?.updateWorldMatrix(!1,!0),this.markBoundsDirty()}onAfterRender(){if(super.onAfterRender(),this._needUpdateBoundingSphere){for(const e of this.sharedMeshes)if(e instanceof c.SkinnedMesh){this._needUpdateBoundingSphere=!1;try{const t=e.geometry,i=ne.getRaycastMesh(e);i&&(e.geometry=i),e.computeBoundingSphere(),e.geometry=t}catch(t){console.error(`Error updating bounding sphere for ${e.name}`,t)}}}if(v_){for(const e of this.sharedMeshes)if(e instanceof c.SkinnedMesh&&e.boundingSphere){const t=V(e.boundingSphere.center).applyMatrix4(e.matrixWorld);B.DrawWireSphere(t,e.boundingSphere.radius,"red")}}}markBoundsDirty(){this._needUpdateBoundingSphere=!0}}var uO=Object.defineProperty,j0=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&uO(e,t,n),n};const Ch=w("debuggltfexport");class ig extends nt{sceneRoot}const ng=class $r extends k{binary=!0;objects=[];ext;async exportNow(e,t){Ch&&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:$r.calculateCenter(this.objects),...t},n=await this.export(this.objects,i).catch(o=>(console.error(o),!1));return n===!1?!1:(this.binary?e.endsWith(".glb")||(e+=".glb"):e.endsWith(".gltf")||(e+=".gltf"),this.binary?$r.saveArrayBuffer(n,e):$r.saveJson(n,e),!0)}async export(e,t){if(!e||e.length<=0){console.warn("No objects set to export");return}const i=new q.GLTFExporter;i.register(h=>new L0(h)),i.register(h=>new k0(h)),Jm(i,this.context),$r.filterTopmostParent(e);const n={trs:!1,onlyVisible:!0,truncateDrawRange:!1,binary:!0,maxTextureSize:1/0,embedImages:!0,includeCustomExtensions:!0,animations:t?.animations||$r.collectAnimations(e),...t},o=new Array,r=new c.Object3D;t?.pivot&&r.position.sub(t.pivot),Ch&&console.log("EXPORT",e),e.forEach(h=>{h&&Ep(h)&&(r.children.push(h),h.matrixAutoUpdate=!1,h.matrix.copy(h.matrixWorld),S.getComponentsInChildren(h,mi).forEach(d=>{S.isActiveInHierarchy(d.gameObject)&&d.setInstancingEnabled(!1)}),h.traverse(d=>{if(!Ep(d)){const u=d.parent;d.removeFromParent(),o.push(()=>{u&&u.add(d)})}}))});const a=new Pm(r);return t?.needleComponents&&(this.ext=new E0),this.ext&&(this.ext.registerExport(i),this.ext.context=a),new Promise((h,d)=>{Ch&&console.log("Starting glTF export.");try{i?.parse(r,u=>{l(),h(u)},u=>{l(),d(u)},n)}catch(u){console.error(u),d(u)}finally{o.forEach(u=>u()),Ch&&console.log("Finished glTF export.")}});function l(){e.forEach(h=>{h&&(h.matrixAutoUpdate=!0,S.getComponentsInChildren(h,mi).forEach(d=>{S.isActiveInHierarchy(d.gameObject)&&d.setInstancingEnabled(!1)}))})}}static saveArrayBuffer(e,t){this.save(new Blob([e],{type:"application/octet-stream"}),t)}static saveJson(e,t){this.save("data: text/json;charset=utf-8,"+encodeURIComponent(JSON.stringify(e)),t)}static save(e,t){const i=document.createElement("a");i.style.display="none",document.body.appendChild(i),typeof e=="string"?i.href=e:i.href=URL.createObjectURL(e),i.download=t,i.click(),i.remove()}static collectAnimations(e,t){t=t||[];for(const i of e)i&&i.traverseVisible(n=>{n.animations&&n.animations.length>0&&t.push(...n.animations)});return t}static calculateCenter(e,t){const i=t||new c.Vector3;return i.set(0,0,0),e.forEach(n=>{i.add(X(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}}}};j0([f()],ng.prototype,"binary");j0([f(c.Object3D)],ng.prototype,"objects");let sg=ng;typeof globalThis!==void 0&&!("OffscreenCanvas"in globalThis)&&(globalThis.OffscreenCanvas=class{canvas;constructor(e,t){return this.canvas=document.createElement("canvas"),this.canvas.width=e,this.canvas.height=t,this.canvas.convertToBlob=(i,n)=>new Promise(o=>{this.canvas.toBlob(o,i,n)}),this.canvas}});const fO=w("debugprogress");function B0(s){s=s||new Date;const e=s.getMonth()+1,t=s.getDate(),i=s.getHours(),n=s.getMinutes(),o=s.getSeconds(),r=(e<10?"0":"")+e,a=(t<10?"0":"")+t,l=(i<10?"0":"")+i,h=(n<10?"0":"")+n,d=(o<10?"0":"")+o;return s.getFullYear()+r+a+"-"+l+h+d}class ie{static start(e,t){typeof t=="string"&&(t={parentScope:t});const i=new pO(e,t);bl.set(e,i)}static report(e,t){const i=bl.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=bl.get(e);t&&(t.end(),bl.delete(e))}}const bl=new Map;class pO{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?bl.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??!!fO,this.showLogs&&console.time(this.scopeLabel),this.onProgress=t?.onProgress}report(e,t=!1){if(e){if(e.totalSteps!==void 0&&(this.lastTotalSteps=e.totalSteps),e.currentStep!==void 0&&(this.lastStep=e.currentStep),e.autoStep!==void 0){if(e.currentStep===void 0){this.lastStep===void 0&&(this.lastStep=0);const n=typeof e.autoStep=="number"?e.autoStep:1;this.lastStep+=this.lastAutoStepWeight,this.lastAutoStepWeight=n,e.currentStep=this.lastStep}e.totalSteps=this.lastTotalSteps}e.progress!==void 0?this.selfProgress=e.progress:e.currentStep!==void 0&&e.totalSteps!==void 0&&(this.selfProgress=e.currentStep/e.totalSteps)}if(this.childScopes.length>0){let n=0,o=0;for(const a of this.childScopes)n+=a.selfProgress,o+=1;o>0&&(n/=o);const r=this.lastAutoStepWeight/(this.lastTotalSteps??1);this.totalProgress=this.selfProgress+n*r}else this.totalProgress=this.selfProgress;this.selfProgress=Math.min(1,this.selfProgress),this.totalProgress=Math.min(1,this.totalProgress);let i=(this.totalProgress*100).toFixed(3)+"%";this.childScopes.length>0&&(i+=" ("+(this.selfProgress*100).toFixed(3)+"% self)"),e?.message&&(i=e.message+" – "+i),this.lastStep!==void 0&&this.lastTotalSteps!==void 0&&(i="Step "+(this.lastStep+(this.lastAutoStepWeight!=1?"–"+(this.lastStep+this.lastAutoStepWeight):"")+"/"+this.lastTotalSteps)+" "+i),t?this.totalReports++:(this.selfReports++,this.totalReports++),this.showLogs&&console.timeLog(this.scopeLabel,i),this.onProgress&&this.onProgress(this.totalProgress),this.parentScope&&this.parentScope.report(void 0,!0)}end(){this.report({progress:1,autoStep:!0},!0),this.showLogs&&(console.timeLog(this.scopeLabel,"Total reports: "+this.totalReports,"Self reports: "+this.selfReports),console.timeEnd(this.scopeLabel));let e=!1;for(const t of this.childScopes)if(!(t.selfProgress>=1)){e=!0;break}e&&console.warn("Progress end with child scopes that are still running",this),this.onProgress=void 0}}const Oe="</StageRoot/Materials";function mO(s,e,t){const i=new Map,n=b=>{const g=b.type___needle,v=i.get(g)||new Map;if(i.set(g,v),!v.has(b)){const _=`${g}${v.size?`_${v.size}`:""}`;v.set(b,_)}return v.get(b)},o=s.colorNode?Ph(s.colorNode):[],r=s.colorNode?`color3f inputs:diffuseColor.connect = ${Oe}/${e}/${n(o.values().next().value)}.outputs:out>`:"",a=s.roughnessNode?Ph(s.roughnessNode):[],l=s.roughnessNode?`float inputs:roughness.connect = ${Oe}/${e}/${n(a.values().next().value)}.outputs:out>`:"",h=s.normalNode?Ph(s.normalNode):[],d=s.normalNode?`float3 inputs:normal.connect = ${Oe}/${e}/${n(h.values().next().value)}.outputs:out>`:"",u=s.metalnessNode?Ph(s.metalnessNode):[],p=s.metalnessNode?`float inputs:metallic.connect = ${Oe}/${e}/${n(u.values().next().value)}.outputs:out>`:"",m=new Set([...o,...a,...h,...u]),y=_O(m,e,t,n);return console.debug(y),`
|
|
1027
1027
|
|
|
1028
1028
|
def Material "${e}" ${s.name?`(
|
|
1029
1029
|
displayName = "${s.name}"
|
|
@@ -1043,7 +1043,7 @@ Texture:`,i),this.setLightmapDebugMaterial()):Tr&&console.log("Use debuglightmap
|
|
|
1043
1043
|
|
|
1044
1044
|
${y}
|
|
1045
1045
|
|
|
1046
|
-
}`}function Ph(s){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 v=new Set,
|
|
1046
|
+
}`}function Ph(s){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 v=new Set,_=x=>{if(!(!x.isNode||v.has(x))){x.nodeType___needle||(x.nodeType___needle=e(x)),x.shaderNode?(x.type___needle="ShaderCallNodeInternal",x.shaderNodeLayoutName___needle=x.shaderNode.layout.name.slice(3)):x.type___needle=x.type,v.add(x);for(const T in x)x[T]?.isNode&&(_(x[T]),x.nodeType___needle||=x[T].nodeType___needle),Array.isArray(x[T])&&x[T].forEach(O=>{O.isNode&&(_(O),x.nodeType___needle||=O.nodeType___needle)})}};return _(g),v},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)return!0;if(g.convertTo==="vec3"&&g.node.value.isVector3)return!0;if(g.convertTo==="vec2"&&g.node.value.isVector2)return!0;if(g.convertTo==="color"&&g.node.value.isColor)return!0;if(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(;o(g);)!g.node&&g.shaderNode?g=g.inputNodes[0]:g=g.node??g.aNode??g.bNode??g.cNode;return g},o=g=>{const v=["UniformNode","UniformGroupNode","ShaderNodeInternal"];return!g||i(g)||v.includes(g.type___needle)||g.type___needle===void 0},r=(g,v)=>{for(const _ of v)for(const x in _){if(_[x]?.isNode&&_[x]===g)return{parent:_,label:x};if(Array.isArray(_[x])&&_[x].find(O=>O.isNode&&O===g))return{parent:_,label:x}}return null},a=(g,v)=>{if(g.shaderNode)g.inputNodes[0]=n(g.inputNodes[0]);else if(Array.isArray(g.nodes))for(let _=0;_<g.nodes.length;_++)g.nodes[_]&&o(g.nodes[_])&&(g.nodes[_]=n(g.nodes[_]));else v.forEach(_=>{g[_]&&o(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"))},h=(g,v)=>{v.label==="cNode"&&v.parent.type==="MathNode"&&v.parent.method==="mix"||(v.parent.type==="JoinNode"?g.nodeType___needle="float":g.nodeType___needle=v.parent.nodeType___needle)},d=g=>g?.type==="ConvertNode"&&g.nodeType___needle==="color"&&g.node.nodeType___needle==="vec4",u=(g,v)=>{g.convertTo="vec3",g.nodeType___needle="vec3";const _={type:"ConvertNode",convertTo:"color",node:g,isNode:!0,nodeType___needle:"color",type___needle:"ConvertNode"},x=r(g,v);return x?.parent&&(x.parent[x.label]=_),_},p=g=>g?.type==="ConvertNode"&&g.node.type==="TextureNode"&&g.nodeType___needle!==g.node.nodeType___needle,m=g=>{const v=new Set;for(let _ of g)if(!o(_)){if(l(_),_.type=="SplitNode"){const x=r(_,g);if(_.components.length===1)_.nodeType___needle="float";else if(x)_.nodeType___needle=x.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&&h(_,r(_,g)),d(_)&&v.add(u(_,g)),p(_)){_.node.nodeType___needle=_.convertTo;const x=r(_,g);x?.parent&&(x.parent[x.label]=_.node),_=_.node}v.add(_)}return v},y=t(s);return m(y)}function gO(s,e){switch(e){case"float4":return s.isVector4?`(${s.x}, ${s.y}, ${s.z}, ${s.w})`:`(${s}, ${s}, ${s}, ${s})`;case"float3":return s.isVector3?`(${s.x}, ${s.y}, ${s.z})`:`(${s}, ${s}, ${s})`;case"float2":return s.isVector2?`(${s.x}, ${s.y})`:`(${s}, ${s})`;case"color3f":return s.isColor?`(${s.r}, ${s.g}, ${s.b})`:`(${s}, ${s}, ${s})`;default:return s.isVector4||s.isVector3||s.isVector2?`${s.x}`:s.isColor?`${s.r}`:`${s}`}}function yO(s,e,t,i){const n=" ",o=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=s.type___needle,l=s.nodeType___needle,h=o(l);let d=r(l),u="";const p=new Array;switch(a){case"UniformGroupNode":case"UniformNode":return"";case"TimerNode":u="time_float";break;case"ConstNode":u="constant_"+h,p.push(`${d} inputs:value = ${gO(s.value,d)}`);break;case"JoinNode":u="combine"+s.nodes.length+"_"+h;let m=1;for(const x of s.nodes)p.push(`float inputs:in${m++}.connect = ${Oe}/${e}/${t(x)}.outputs:out>`);break;case"ConvertNode":u="convert_"+o(s.node.nodeType___needle)+"_"+h,s.node&&p.push(`${r(s.node.nodeType___needle)} inputs:in.connect = ${Oe}/${e}/${t(s.node)}.outputs:out>`);break;case"MathNode":u=s.method+"_"+h,s.aNode&&!s.bNode&&p.push(`${r(s.aNode.nodeType___needle)} inputs:in.connect = ${Oe}/${e}/${t(s.aNode)}.outputs:out>`),s.aNode&&s.bNode&&!s.cNode&&(p.push(`${r(s.aNode.nodeType___needle)} inputs:in1.connect = ${Oe}/${e}/${t(s.aNode)}.outputs:out>`),p.push(`${r(s.bNode.nodeType___needle)} inputs:in2.connect = ${Oe}/${e}/${t(s.bNode)}.outputs:out>`)),s.aNode&&s.bNode&&s.cNode&&s.method=="clamp"&&(p.push(`${r(s.aNode.nodeType___needle)} inputs:in.connect = ${Oe}/${e}/${t(s.aNode)}.outputs:out>`),p.push(`${r(s.bNode.nodeType___needle)} inputs:low.connect = ${Oe}/${e}/${t(s.bNode)}.outputs:out>`),p.push(`${r(s.cNode.nodeType___needle)} inputs:high.connect = ${Oe}/${e}/${t(s.cNode)}.outputs:out>`)),s.aNode&&s.bNode&&s.cNode&&s.method=="mix"&&(p.push(`${r(s.aNode.nodeType___needle)} inputs:fg.connect = ${Oe}/${e}/${t(s.bNode)}.outputs:out>`),p.push(`${r(s.bNode.nodeType___needle)} inputs:bg.connect = ${Oe}/${e}/${t(s.aNode)}.outputs:out>`),p.push(`float inputs:mix.connect = ${Oe}/${e}/${t(s.cNode)}.outputs:out>`));break;case"OperatorNode":let b="";switch(s.op){case"*":b="multiply";break;case"/":b="divide";break;case"+":b="add";break;case"-":b="subtract";break}if(u=b+"_"+h,s.aNode&&!s.bNode&&p.push(`${r(s.aNode.nodeType___needle)} inputs:in.connect = ${Oe}/${e}/${t(s.aNode)}.outputs:out>`),s.aNode&&s.bNode){const x=r(s.aNode.nodeType___needle),T=r(s.bNode.nodeType___needle);(x==="color3f"&&T==="float"||T==="float"&&T==="color3f")&&(u=b+"_color3FA"),p.push(`${x} inputs:in1.connect = ${Oe}/${e}/${t(s.aNode)}.outputs:out>`),p.push(`${T} inputs:in2.connect = ${Oe}/${e}/${t(s.bNode)}.outputs:out>`)}break;case"TextureNode":s.uvNode?(u="tiledimage_"+h,p.push(`float2 inputs:texcoord.connect = ${Oe}/${e}/${t(s.uvNode)}.outputs:out>`)):u="image_"+h;const g=s._value,v=rg.includes(g.format),_=bO(g);p.push(`asset inputs:file = @textures/${_}.${v?"png":"jpg"}@`),i[_]={texture:g,scale:void 0};break;case"NormalMapNode":d="float3",u="normalmap",p.push(`${d} inputs:in.connect = ${Oe}/${e}/${t(s.node)}.outputs:out>`);break;case"AttributeNode":u="geompropvalue_"+h,p.push('string inputs:geomprop = "st"');break;case"ShaderCallNodeInternal":u=s.shaderNodeLayoutName___needle+"_"+h,p.push(`${d} inputs:in.connect = ${Oe}/${e}/${t(s.inputNodes[0])}.outputs:out>`);break;case"SplitNode":u="swizzle_"+o(s.node.nodeType___needle)+"_"+h,p.push(`${r(s.node.nodeType___needle)} inputs:in.connect = ${Oe}/${e}/${t(s.node)}.outputs:out>`),p.push(`string inputs:channels = "${s.components}"`);break}return`
|
|
1047
1047
|
${n}def Shader "${t(s)}"
|
|
1048
1048
|
${n}{
|
|
1049
1049
|
${n}uniform token info:id = "ND_${u}"
|
|
@@ -1074,8 +1074,8 @@ Texture:`,i),this.setLightmapDebugMaterial()):Tr&&console.log("Use debuglightmap
|
|
|
1074
1074
|
${h}
|
|
1075
1075
|
)
|
|
1076
1076
|
`}}const Ar=`
|
|
1077
|
-
`,At="</StageRoot/Materials";class N0{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+=Ar,this.str+=this.applyIndent(t)):this.str+=" "+t):this.str+=this.applyIndent(t),this.str+=Ar,this.indent+=1}closeBlock(e="}"){this.indent-=1,this.str+=this.applyIndent(e)+Ar}beginArray(e){e=this.applyIndent(e+" = ["),this.str+=e,this.str+=Ar,this.indent+=1}closeArray(){this.indent-=1,this.str+=this.applyIndent("]")+Ar}appendLine(e=""){e=this.applyIndent(e),this.str+=e,this.str+=Ar}toString(){return this.str}applyIndent(e){let t="";for(let i=0;i<this.indent;i++)t+=" ";return t+e}}class SO{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 og,this.output="",this.animations=[]}}class Of{ar={anchoring:{type:"plane"},planeAnchoring:{alignment:"horizontal"}};quickLookCompatible=!1;extensions=[];maxTextureSize=4096;exportInvisible=!1}let V0=class{debug;pruneUnusedNodes;sceneAnchoringOptions=new Of;extensions=[];keepObject;beforeWritingDocument;constructor(){this.debug=!1,this.pruneUnusedNodes=!0}async parse(e,t=new Of){t=Object.assign(new Of,t),this.sceneAnchoringOptions=t;const i=new SO(e,this,t);this.extensions=i.extensions;const n=i.files,o="model.usda";n[o]=null;const r=i.materials,a=i.textures;ie.report("export-usdz","Invoking onBeforeBuildDocument"),await id(i,"onBeforeBuildDocument"),ie.report("export-usdz","Done onBeforeBuildDocument"),ie.report("export-usdz","Reparent bones to common ancestor");const l=[],h=new Set;e?.traverse(
|
|
1078
|
-
`+i.output;this.debug&&console.log(m),n[o]=q.strToU8(m),i.output="",ie.report("export-usdz",{message:"Exporting textures",autoStep:10}),ie.start("export-usdz-textures",{parentScope:"export-usdz",logTimings:!1});const y=new c.WebGLRenderer({antialias:!1,alpha:!0,premultipliedAlpha:!1,preserveDrawingBuffer:!0}),
|
|
1077
|
+
`,At="</StageRoot/Materials";class N0{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+=Ar,this.str+=this.applyIndent(t)):this.str+=" "+t):this.str+=this.applyIndent(t),this.str+=Ar,this.indent+=1}closeBlock(e="}"){this.indent-=1,this.str+=this.applyIndent(e)+Ar}beginArray(e){e=this.applyIndent(e+" = ["),this.str+=e,this.str+=Ar,this.indent+=1}closeArray(){this.indent-=1,this.str+=this.applyIndent("]")+Ar}appendLine(e=""){e=this.applyIndent(e),this.str+=e,this.str+=Ar}toString(){return this.str}applyIndent(e){let t="";for(let i=0;i<this.indent;i++)t+=" ";return t+e}}class SO{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 og,this.output="",this.animations=[]}}class Of{ar={anchoring:{type:"plane"},planeAnchoring:{alignment:"horizontal"}};quickLookCompatible=!1;extensions=[];maxTextureSize=4096;exportInvisible=!1}let V0=class{debug;pruneUnusedNodes;sceneAnchoringOptions=new Of;extensions=[];keepObject;beforeWritingDocument;constructor(){this.debug=!1,this.pruneUnusedNodes=!0}async parse(e,t=new Of){t=Object.assign(new Of,t),this.sceneAnchoringOptions=t;const i=new SO(e,this,t);this.extensions=i.extensions;const n=i.files,o="model.usda";n[o]=null;const r=i.materials,a=i.textures;ie.report("export-usdz","Invoking onBeforeBuildDocument"),await id(i,"onBeforeBuildDocument"),ie.report("export-usdz","Done onBeforeBuildDocument"),ie.report("export-usdz","Reparent bones to common ancestor");const l=[],h=new Set;e?.traverse(_=>{if(!(!t.exportInvisible&&!_.visible)&&_ instanceof c.SkinnedMesh){const x=_.skeleton.bones,T=U0(x);if(T){const O={object:_,originalParent:_.parent,newParent:T};l.push(O),h.add(O.object.uuid),O.newParent&&h.add(O.newParent.uuid),O.originalParent&&h.add(O.originalParent.uuid)}}});for(const _ of l){const{object:x,originalParent:T,newParent:O}=_;O.add(x)}ie.report("export-usdz","Traversing hierarchy"),e&&$0(e,i.document,i,this.keepObject),ie.report("export-usdz","Invoking onAfterBuildDocument"),await id(i,"onAfterBuildDocument");const u=i.extensions.find(_=>_.extensionName==="Behaviour")?.getAllTargetUuids()??new Set;if(this.pruneUnusedNodes){const _={allBehaviorTargets:u,debug:!1,boneReparentings:h,quickLookCompatible:i.quickLookCompatible};this.debug&&x_(i.document,"Hierarchy BEFORE pruning",_),W0(i.document,_),this.debug&&x_(i.document,"Hierarchy AFTER pruning")}else this.debug&&console.log("Pruning of empty nodes is disabled. This may result in a larger USDZ file.");ie.report("export-usdz",{message:"Parsing document",autoStep:10}),await CO(i,()=>(ie.report("export-usdz","Building materials"),AO(r,a,t.quickLookCompatible))),ie.report("export-usdz","Invoking onAfterSerialize"),await id(i,"onAfterSerialize");for(const _ of l){const{object:x,originalParent:T,newParent:O}=_;T&&T.add(x)}i.exporter?.beforeWritingDocument?.();const m=i.document.buildHeader(i)+`
|
|
1078
|
+
`+i.output;this.debug&&console.log(m),n[o]=q.strToU8(m),i.output="",ie.report("export-usdz",{message:"Exporting textures",autoStep:10}),ie.start("export-usdz-textures",{parentScope:"export-usdz",logTimings:!1});const y=new c.WebGLRenderer({antialias:!1,alpha:!0,premultipliedAlpha:!1,preserveDrawingBuffer:!0}),b=Object.keys(a).length;ie.report("export-usdz-textures",{totalSteps:b*3,currentStep:0});const g=async _=>{const x=a[_],T=x.texture,O=rg.includes(T.format);let M={imageData:T.image};ie.report("export-usdz-textures",{message:"read back texture",autoStep:!0});const E=x.scale!==void 0&&x.scale.x!==1&&x.scale.y!==1&&x.scale.z!==1&&x.scale.w!==1;(T.isCompressedTexture||T.isRenderTargetTexture||E)&&(M=await H0(T,t.maxTextureSize,y,x.scale)),ie.report("export-usdz-textures",{message:"convert texture to canvas",autoStep:!0});const j=await OO(M.imageBitmap||M.imageData,t.maxTextureSize).catch(L=>{console.error("Error converting texture to canvas",T,L)});if(j){ie.report("export-usdz-textures",{message:"convert canvas to blob",autoStep:!0});const L=await j.convertToBlob({type:O?"image/png":"image/jpeg",quality:.95});n[`textures/${_}.${O?"png":"jpg"}`]=new Uint8Array(await L.arrayBuffer())}else console.warn("Can`t export texture: ",T)};for(const _ in a)await g(_);y.dispose(),ie.end("export-usdz-textures");let v=0;for(const _ in n){const x=n[_],T=34+_.length;v+=T;const O=v&63;if(O!==4){const M=64-O,E=new Uint8Array(M);n[_]=[x,{extra:{12345:E}}]}v=x.length}return ie.report("export-usdz","zip archive"),q.zipSync(n,{level:0})}};function $0(s,e,t,i){if(!t.exportInvisible&&!s.visible)return;let n,o,r;const a={position:s.position,quaternion:s.quaternion,scale:s.scale};if(s.position.x===0&&s.position.y===0&&s.position.z===0&&(a.position=null),s.quaternion.x===0&&s.quaternion.y===0&&s.quaternion.z===0&&s.quaternion.w===1&&(a.quaternion=null),s.scale.x===1&&s.scale.y===1&&s.scale.z===1&&(a.scale=null),(s instanceof c.Mesh||s instanceof c.SkinnedMesh)&&(o=s.geometry,r=s.material),i&&!i(s)&&(o=void 0,r=void 0),(s instanceof c.Mesh||s instanceof c.SkinnedMesh)&&r&&typeof r=="object"&&(r instanceof c.MeshStandardMaterial||r instanceof c.MeshBasicMaterial||r.isMeshPhysicalNodeMaterial||r instanceof c.Material&&r.type==="MeshLineMaterial")){const l=kh(s),h=s instanceof c.SkinnedMesh?s:null;n=new ze(s.uuid,l,a,o,r,void 0,h,s.animations)}else if(s instanceof c.PerspectiveCamera||s instanceof c.OrthographicCamera){const l=kh(s);n=new ze(s.uuid,l,a,void 0,void 0,s)}else{const l=kh(s);n=new ze(s.uuid,l,a,void 0,void 0,void 0,void 0,s.animations)}if(n){if(n.displayName=s.userData?.name||s.name,n.visibility=s.visible?void 0:"invisible",e&&e.add(n),e=n,t.extensions)for(const l of t.extensions)l.onExportObject&&l.onExportObject.call(l,s,n,t)}else{const l=kh(s),h=new ze(s.uuid,l,{position:s.position,quaternion:s.quaternion,scale:s.scale});e&&e.add(h),e=h}for(const l of s.children)$0(l,e,t,i)}function x_(s,e,...t){const i={};let n=0;function o(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 d={object:r};r.material&&(d.mat=!0),r.geometry&&(d.geo=!0),r.camera&&(d.cam=!0),r.skinnedMesh&&(d.skin=!0),a[l]._self=d;for(const u of r.children)u&&o(u,a[l])}o(s,i),console.log(e+" ("+n+" nodes)",i,...t)}function W0(s,e){let t=!0;const i=new Array,n=new Array;if(s.children.length===0)t=!0;else{const h=[...s.children];for(const d of h)if(d){const u=W0(d,e);e.debug&&(u?i.push(d):n.push(d)),t=t&&u}}const o=e.allBehaviorTargets.has(s.uuid),r=s.geometry||s.material||s.camera&&!e.quickLookCompatible||s.skinnedMesh||!1,a=e.boneReparentings.has(s.uuid),l=t&&!o&&!r&&!a;return l?(e.debug&&console.log("Pruned object:",(s.displayName||s.name)+" ("+s.uuid+")",{isVisible:r,isBehaviorSourceOrTarget:o,allChildsWerePruned:t,isBoneReparenting:a,object:s,prunedChilds:i,keptChilds:n}),s.parent?.remove(s)):e.debug&&console.log("Kept object:",(s.displayName||s.name)+" ("+s.uuid+")",{isVisible:r,isBehaviorSourceOrTarget:o,allChildsWerePruned:t,isBoneReparenting:a,object:s,prunedChilds:i,keptChilds:n}),l}async function CO(s,e){ie.start("export-usdz-resources","export-usdz");const t=[];for(const l of s.document.children)G0(l,s,t);const i=t.length;for(let l=0;l<i;l++)ie.report("export-usdz-resources",{totalSteps:i,currentStep:l}),await new Promise((h,d)=>{t[l](),h()});ie.end("export-usdz-resources");const n=new N0,o=s.exporter.sceneAnchoringOptions.ar;n.beginBlock(`def Xform "${s.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 = "${o.anchoring.type}"`),o.anchoring.type==="plane"&&n.appendLine(`token preliminary:planeAnchoring:alignment = "${o.planeAnchoring.alignment}"`),o.anchoring.type==="image"&&n.appendLine(`rel preliminary:imageAnchoring:referenceImage = </${s.document.name}/Scenes/Scene/AnchoringReferenceImage>`),n.appendLine();const r=l=>{if(!l)return 0;let h=1;for(const d of l.children)h+=r(d);return h},a=r(s.document);ie.start("export-usdz-xforms","export-usdz"),ie.report("export-usdz-xforms",{totalSteps:a,currentStep:1});for(const l of s.document.children)X0(l,n,s);ie.end("export-usdz-xforms"),ie.report("export-usdz","invoke onAfterHierarchy"),await id(s,"onAfterHierarchy",n),n.closeBlock(),n.closeBlock(),n.appendLine(e()),n.closeBlock(),ie.report("export-usdz","write to string"),s.output+=n.toString()}function G0(s,e,t){if(!s)return;const i=s.geometry,n=s.material;if(i)if(n&&("isMeshStandardMaterial"in n&&n.isMeshStandardMaterial||"isMeshBasicMaterial"in n&&n.isMeshBasicMaterial||n.type==="MeshLineMaterial")){const o="geometries/"+Rp(i,s.name)+".usda";if(!(o in e.files)){const r=()=>{const a=EO(i,s.skinnedMesh?.skeleton?.bones,e.quickLookCompatible);e.files[o]=kO(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 o of s.children)G0(o,e,t)}async function id(s,e,t=null){if(s.extensions){for(const i of s.extensions)if(i&&typeof i[e]=="function"){const o=i[e].call(i,s,t);o instanceof Promise&&await o}}}let Oh=null,Et=null,Mf,Lr,Mh;async function H0(s,e=1/0,t=null,i=void 0){Mf||(Mf=new c.PlaneGeometry(2,2,1,1)),Lr||(Lr=new c.ShaderMaterial({uniforms:{blitTexture:new c.Uniform$1(s),flipY:new c.Uniform$1(!1),scale:new c.Uniform$1(new c.Vector4(1,1,1,1))},vertexShader:`
|
|
1081
1081
|
varying vec2 vUv;
|
|
@@ -1111,7 +1111,7 @@ ${h}
|
|
|
1111
1111
|
`}function kO(s,e){let t=MO();return t+=s,q.strToU8(t)}function kh(s){return s.name.replace(/[-<>\(\)\[\]§$%&\/\\\=\?\,\;]/g,"")+"_"+s.id}function S_(s){return ji(s.name||"bone_"+s.uuid)}function Rp(s,e){return ji(s.name||"Geometry")+"_"+s.id}function uu(s){return ji(s.name||"Material")+"_"+s.id}function na(s,e){let t=S_(s),i=s.parent;for(;i&&i!==e;)t=S_(i)+"/"+t,i=i.parent;return t}function X0(s,e,t){if(s==null)return;ie.report("export-usdz-xforms",{message:"buildXform "+s.displayName||s.name,autoStep:!0});const i=s.transform,n=s.geometry,o=s.material,r=s.camera,a=s.name;if(s.animations)for(const m of s.animations)t.animations.push(m);const l=n&&n.isBufferGeometry&&n.attributes.skinIndex!==void 0&&n.attributes.skinIndex.count>0,h=l?"SkelRoot":"Xform",d=new Array,u=o&&o instanceof c.MeshBasicMaterial&&o.color&&o.color.r===1&&o.color.g===1&&o.color.b===1&&!o.map&&o.opacity===1&&n?.attributes.color;if(n?.attributes.color&&!u&&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.",s.displayName),e.appendLine(),n?(e.beginBlock(`def ${h} "${a}"`,"(",!1),t.quickLookCompatible&&o&&o.side===c.DoubleSide&&!l?e.appendLine(`prepend references = @./geometries/${Rp(n)}.usda@</Geometry_doubleSided>`):e.appendLine(`prepend references = @./geometries/${Rp(n)}.usda@</Geometry>`),u||d.push("MaterialBindingAPI"),l&&d.push("SkelBindingAPI")):r&&!t.quickLookCompatible?e.beginBlock(`def Camera "${a}"`,"(",!1):s.type!==void 0?e.beginBlock(`def ${s.type} "${a}"`):e.beginBlock(`def Xform "${a}"`,"(",!1),s.type===void 0&&(s.extraSchemas?.length&&d.push(...s.extraSchemas),d.length&&e.appendLine(`prepend apiSchemas = [${d.map(m=>`"${m}"`).join(", ")}]`)),s.displayName&&e.appendLine(`displayName = "${F0(s.displayName)}"`),(r||s.type===void 0)&&(e.closeBlock(")"),e.beginBlock()),n&&o){if(!u){const m=uu(o);e.appendLine(`rel material:binding = </StageRoot/Materials/${m}>`)}!t.quickLookCompatible&&o.side===c.DoubleSide&&(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):s.type===void 0&&i&&(p=p||i.position!==null||i.quaternion!==null||i.scale!==null,i.position&&(s.needsTranslate=!0,e.appendLine(`double3 xformOp:translate = (${te(i.position.x)}, ${te(i.position.y)}, ${te(i.position.z)})`)),i.quaternion&&(s.needsOrient=!0,e.appendLine(`quatf xformOp:orient = (${te(i.quaternion.w)}, ${te(i.quaternion.x)}, ${te(i.quaternion.y)}, ${te(i.quaternion.z)})`)),i.scale&&(s.needsScale=!0,e.appendLine(`double3 xformOp:scale = (${te(i.scale.x)}, ${te(i.scale.y)}, ${te(i.scale.z)})`))),s.visibility!==void 0&&e.appendLine(`token visibility = "${s.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(be)}`),e.appendLine(`float verticalAperture = ${((Math.abs(r.top)+Math.abs(r.bottom))*10).toPrecision(be)}`),e.appendLine('token projection = "orthographic"')):"isPerspectiveCamera"in r&&r.isPerspectiveCamera&&(e.appendLine(`float2 clippingRange = (${r.near.toPrecision(be)}, ${r.far.toPrecision(be)})`),e.appendLine(`float focalLength = ${r.getFocalLength().toPrecision(be)}`),e.appendLine(`float focusDistance = ${r.focus.toPrecision(be)}`),e.appendLine(`float horizontalAperture = ${r.getFilmWidth().toPrecision(be)}`),e.appendLine('token projection = "perspective"'),e.appendLine(`float verticalAperture = ${r.getFilmHeight().toPrecision(be)}`))),s.onSerialize&&s.onSerialize(e,t),s.type===void 0){const m=new Array;s.needsTranslate&&m.push('"xformOp:translate"'),s.needsOrient&&m.push('"xformOp:orient"'),s.needsScale&&m.push('"xformOp:scale"'),m.length&&e.appendLine(`uniform token[] xformOpOrder = [${m.join(", ")}]`)}if(s.children){e.appendLine();for(const m of s.children)X0(m,e,t)}e.closeBlock()}function te(s){return Number.isInteger(s)?s.toString():s.toFixed(10)}function C_(s){const e=s.elements;return`( ${Eh(e,0)}, ${Eh(e,4)}, ${Eh(e,8)}, ${Eh(e,12)} )`}function Eh(s,e){return`(${te(s[e+0])}, ${te(s[e+1])}, ${te(s[e+2])}, ${te(s[e+3])})`}function EO(s,e=[],t=!0){return`
|
|
1112
1112
|
def "Geometry"
|
|
1113
1113
|
${RO(s,e,t)}
|
|
1114
|
-
`}function RO(s,e=[],t=!0){const i="Geometry",n=s.attributes,o=n.position.count,r=e&&e.length>0,a=[],l=[];let h=new Array,d=n.skinIndex;if(r){const p=[];for(const g of e)a.push({bone:g,index:e.indexOf(g)}),p.push(g.uuid);let m=1e4;for(;p.length<e.length&&m-- >0;)for(const g of a){const v=g.bone.children;for(const
|
|
1114
|
+
`}function RO(s,e=[],t=!0){const i="Geometry",n=s.attributes,o=n.position.count,r=e&&e.length>0,a=[],l=[];let h=new Array,d=n.skinIndex;if(r){const p=[];for(const g of e)a.push({bone:g,index:e.indexOf(g)}),p.push(g.uuid);let m=1e4;for(;p.length<e.length&&m-- >0;)for(const g of a){const v=g.bone.children;for(const _ of v)p.indexOf(_.uuid)===-1&&e.indexOf(_)!==-1&&(a.push({bone:_,index:e.indexOf(_)}),p.push(_.uuid))}m<=0&&console.error("Failed to sort bones in skinned mesh",a,e,p);for(const g of z0(e))a.push({bone:g,index:a.length});const y=a[0].bone.parent;a.sort((g,v)=>na(g.bone,y)>na(v.bone,y)?1:-1),a.map(g=>'"'+na(g.bone,y)+'"').join(", ");for(const g in a)l[a[g].index]=parseInt(g);const b=n.skinIndex;h=new Array;for(let g=0;g<b.count;g++){const v=b.getX(g),_=b.getY(g),x=b.getZ(g),T=b.getW(g);h.push(l[v],l[_],l[x],l[T])}d=new c.BufferAttribute(new Uint16Array(h),4)}const u=n.skinWeight&&n.skinIndex;return`
|
|
1115
1115
|
{
|
|
1116
1116
|
def Mesh "${i}" ${u?`(
|
|
1117
1117
|
prepend apiSchemas = ["SkelBindingAPI"]
|
|
@@ -1171,7 +1171,7 @@ def "${i}_doubleSided" (
|
|
|
1171
1171
|
def "Materials"
|
|
1172
1172
|
{
|
|
1173
1173
|
${i.join("")}
|
|
1174
|
-
}`}function Mi(s){return ji(s.name)+"_"+(s.source?.id??s.id)}function Ms(s,e,t,i,n,o,r=void 0,a=void 0){const l=Mi(s),h=l+(a!==void 0&&a!==1?"_"+a:""),d=t&&a!==void 0&&a!==1,u=d?new c.Vector4(1,1,1,a):void 0;a===void 0&&(a=1),d&&(a=1),u&&u.w<=.05&&(u.w=.05),i[h]={texture:s,scale:u};const p=s.channel>0?"st"+s.channel:"st";o.add(s.channel);const m=rg.includes(s.format),y={1e3:"repeat",1001:"clamp",1002:"mirror"},
|
|
1174
|
+
}`}function Mi(s){return ji(s.name)+"_"+(s.source?.id??s.id)}function Ms(s,e,t,i,n,o,r=void 0,a=void 0){const l=Mi(s),h=l+(a!==void 0&&a!==1?"_"+a:""),d=t&&a!==void 0&&a!==1,u=d?new c.Vector4(1,1,1,a):void 0;a===void 0&&(a=1),d&&(a=1),u&&u.w<=.05&&(u.w=.05),i[h]={texture:s,scale:u};const p=s.channel>0?"st"+s.channel:"st";o.add(s.channel);const m=rg.includes(s.format),y={1e3:"repeat",1001:"clamp",1002:"mirror"},b=s.repeat.clone(),g=s.offset.clone(),v=s.rotation,_=Math.sin(v),x=Math.cos(v);g.y=1-g.y-b.y,t?(b.x===0&&(b.x=1e-4),b.y===0&&(b.y=1e-4),g.x=g.x/b.x,g.y=g.y/b.y,g.x+=_/b.x,g.y+=x-1):(g.x+=_*b.x,g.y+=(1-x)*b.y);const T=uu(n),O=b.x!=1||b.y!=1||g.x!=0||g.y!=0||v!=0,M=`${At}/${T}/${"uvReader_"+p}.outputs:result>`,E=`${At}/${T}/Transform2d_${e}.outputs:result>`,j=e!=="normal"&&r&&(r.r!==1||r.g!==1||r.b!==1||a!==1)||!1,L=e==="normal",z=n instanceof c.MeshStandardMaterial&&n.normalScale?n.normalScale.x*2:2,$=z.toFixed(be),R=(-1*(z/2)).toFixed(be),U=(1-z).toFixed(be);return`
|
|
1175
1175
|
${O?`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 = ${M}
|
|
1183
|
-
float2 inputs:scale = ${M_(
|
|
1183
|
+
float2 inputs:scale = ${M_(b)}
|
|
1184
1184
|
float2 inputs:translation = ${M_(g)}
|
|
1185
1185
|
float inputs:rotation = ${(v/Math.PI*180).toFixed(be)}
|
|
1186
1186
|
float2 outputs:result
|
|
@@ -1256,14 +1256,14 @@ ${l.has(1)?`
|
|
|
1256
1256
|
`:""}
|
|
1257
1257
|
${a.join(`
|
|
1258
1258
|
`)}`:""}
|
|
1259
|
-
}`}function O_(s){return`(${s.r}, ${s.g}, ${s.b})`}function M_(s){return`(${s.x}, ${s.y})`}const rg=[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 gt{static global_id=0;id;trigger;action;exclusive=!1;makeExclusive(e){return this.exclusive=e,this}constructor(e,t,i){this.id="Behavior_"+ji(e)+"_"+gt.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 o=0;o<this.trigger.length;o++){const r=this.trigger[o];n+="<"+r.id+">",o+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 o of this.trigger)o.writeTo(t,i),i.appendLine();else this.trigger.writeTo(t,i);i.appendLine(),this.action.writeTo(t,i),i.closeBlock()}}const Dr=new Set;function Tp(s,e){let t="";if(Array.isArray(s)){Dr.clear();let i="[ ";for(let n=0;n<s.length;n++){let o=s[n];if(!o){console.warn("Invalid target object in behavior",s+". Is the object exported?");continue}if(typeof o=="string"){if(Dr.has(o))continue;i+=o,Dr.add(o)}else if(typeof o=="object"){if(o.isObject3D&&(o=e.findById(o.uuid),!o)){console.warn("Invalid target object in behavior",s+". Is the object exported?");continue}const r=o.getPath?.call(o);if(Dr.has(r))continue;i+=r,Dr.add(r)}n+1<s.length&&(i+=", ")}i+=" ]",t=i,Dr.clear()}else if(typeof s=="object"){const i=s;if(i.isObject3D&&(s=e.findById(i.uuid)),!s)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=s.getPath?.call(s)}return t}class Hs{static global_id=0;id;targetId;tokenId;type;distance;constructor(e,t){e&&(this.targetId=e),t?this.id=t:this.id="Trigger_"+Hs.global_id++}writeTo(e,t){t.beginBlock(`def Preliminary_Trigger "${this.id}"`),this.targetId&&(typeof this.targetId!="string"&&(this.targetId=Tp(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 k_(s,e={direct:!0,indirect:!0}){const t=ze.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"')},s.add(t)}class wt{static __sceneStartTrigger;static sceneStartTrigger(){if(this.__sceneStartTrigger!==void 0)return this.__sceneStartTrigger;const e=new Hs(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 Hs(e);if(Array.isArray(e)&&e.length>1)for(const n of e)n instanceof ze&&k_(n,t);else e instanceof ze&&k_(e,t);return i.tokenId="TapGesture",i}static isTapTrigger(e){return e?.tokenId==="TapGesture"}static proximityToCameraTrigger(e,t){const i=new Hs(e);return i.tokenId="ProximityToCamera",i.distance=t,i}}class To{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 Wt{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 Wt,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+="_"+Wt.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=Tp(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=Tp(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 Ai{x=0;y=0;z=0;constructor(e,t,i){this.x=e,this.y=t,this.z=i}static get up(){return new Ai(0,1,0)}static get right(){return new Ai(1,0,0)}static get forward(){return new Ai(0,0,1)}static get back(){return new Ai(0,0,-1)}static get zero(){return new Ai(0,0,0)}}class le{static sequence(...e){return new To("Group_"+To.getId(),e).makeSequence()}static parallel(...e){return new To("Group_"+To.getId(),e).makeParallel()}static fadeAction(e,t,i){const n=new Wt(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 o=new Wt(e);o.tokenId="StartAnimation";const r=t.start,a=t.duration,l=t.speed,h=t.clipName;if(o.comment=`Animation: ${h}, start=${r*60}, length=${a*60}, end=${(r+a)*60}`,o.animationName=h,o.start=r,o.duration=a,o.animationSpeed=l,o.reversed=i,o.pingPong=n,o.multiplePerformOperation="allow",i&&(o.start-=a),n){o.pingPong=!1;const d=o.clone();return d.reversed=!i,d.start=o.start,d.reversed&&(d.start-=a),le.sequence(o,d)}return o}static waitAction(e){const t=new Wt;return t.tokenId="Wait",t.duration=e,t.motionType=void 0,t}static lookAtCameraAction(e,t,i,n){const o=new Wt(e);return o.tokenId="LookAtCamera",o.duration=t===void 0?9999999999999:t,o.front=i??Ai.forward,o.up=n??Ai.up,o}static emphasize(e,t,i="bounce",n=1,o="basic"){const r=new Wt(e);return r.tokenId="Emphasize",r.duration=t,r.style=o??"basic",r.motionType=i,r.moveDistance=n,r}static transformAction(e,t,i,n,o="inout"){const r=new Wt(e);return r.tokenId="Transform",r.duration=i,r.duration=Math.max(1e-6,i),r.type=n,r.easeType=i>0?o:"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,o="spatial"){const r=new Wt(e);return r.tokenId="Audio",r.type=i,r.audio=t,r.gain=n,r.auralMode=o,r.multiplePerformOperation="allow",r}static impulseAction(e,t){const i=new Wt(e);return i.tokenId="Impulse",i.velocity=t,i}}class DO{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 ag extends DO{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||ze.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=le.fadeAction(this.object,0,!0),this._enableAction)}disable(){return this._disableAction?this._disableAction:(this._disableAction=le.fadeAction(this.object,0,!1),this._disableAction)}}class Y0{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 bn=w("debugusdzanimation"),Ap=w("debugusdzanimationserialization");class Vs{_start;get start(){return this._start===void 0&&(this._start=this.ext.getStartTimeByClip(this.clip)),this._start}get duration(){return this.clip?.duration??ke.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=c.PropertyBinding.parseTrackName(t.name);let n=c.PropertyBinding.findNode(this.root,i.nodeName);if(n)if(!e)e=n;else{if(n===e||Vs.isDescendantOf(e,n))continue;if(!Vs.isDescendantOf(n,e)){for(;!Vs.isDescendantOf(n,e)&&n.parent;)n=n.parent;Vs.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 ke{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=ke.restPoseClipDuration,i&&i.tracks){const o=Math.max(...i.tracks.map(r=>r.times[r.times.length-1]));o!==this.duration&&(console.warn("USDZExporter: Animation clip duration does not match the maximum time value in the tracks.",i,o,this.duration),this.duration=o)}const n=S.getComponent(e,rt);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 – 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."),A()&&he("[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,o=this.rot?.times,r=this.scale?.times,a=[];if(e&&n)for(const l of n)a.push(l);if(t&&o)for(const l of o)a.push(l);if(i&&r)for(const l of r)a.push(l);return a.includes(0)||a.push(0),a.sort((l,h)=>l-h),[...new Set(a)]}*getValues(e,t=!0,i=!0,n=!0){const o=new c.Vector3,r=new c.Quaternion,a=new c.Vector3(1,1,1),l=this.target,h=t?this.pos?.createInterpolant():void 0,d=i?this.rot?.createInterpolant():void 0,u=n?this.scale?.createInterpolant():void 0;h||o.set(l.position.x,l.position.y,l.position.z),d||r.set(l.quaternion.x,l.quaternion.y,l.quaternion.z,l.quaternion.w),u||a.set(l.scale.x,l.scale.y,l.scale.z),h&&h.valueSize!==3&&(h.valueSize=3),d&&d.valueSize!==4&&(d.valueSize=4),u&&u.valueSize!==3&&(u.valueSize=3);const p=0;for(let m=0-p;m<e.length+p;m++){let y=0,_=0;if(m<0?(y=e[0],_=y-ke.animationDurationPadding/2+1/60):m>=e.length?(y=e[e.length-1],_=y+ke.animationDurationPadding/2-1/60):(y=e[m],_=y),h){const g=h.evaluate(y);o.set(g[0],g[1],g[2])}if(d){const g=d.evaluate(y);r.set(g[0],g[1],g[2],g[3])}if(u){const g=u.evaluate(y);a.set(g[0],g[1],g[2])}if(this.useRootMotion&&l===this.root){const g=new c.Matrix4;g.compose(o,r,a),g.multiply(l.matrix),g.decompose(o,r,a)}yield{time:_,translation:o,rotation:r,scale:a,index:m}}}}class fu{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:(ke.restPoseClipDuration+ke.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 – 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);bn&&console.log("registerAnimation",e,t);const n=this.injectRestPoses?1:0,o=(this.rootToRegisteredClip.get(e)?.length??0)+n,r=this.rootTargetMap.get(e),a=new Set(r);if(t&&t.tracks)for(const h of t.tracks){const d=c.PropertyBinding.parseTrackName(h.name),u=c.PropertyBinding.findNode(e,d.nodeName);if(!u){console.warn("no object found for track",h.name,"using "+e.name+" instead");continue}this.dict.has(u)||this.dict.set(u,[]);const p=this.dict.get(u);if(!p){console.warn("no transform data found for target ",u,"at slot "+o+", this is likely a bug");continue}a.delete(u),this.injectRestPoses&&!p[0]&&(console.log("Injecting rest pose",u,t,"at slot",o),p[0]=new ke(null,u,null));let m=p[o];m||(m=new ke(e,u,t),p[o]=m),m.addTrack(h),r?.includes(u)||r?.push(u)}bn&&console.log("Unregistered nodes for this clip",a,"clip",t,"at slot",o,"for root",e,"targets",r);for(const h of a){const d=this.dict.get(h);if(!d)continue;if(this.injectRestPoses&&!d[0]){console.warn("Adding rest pose for ",h,t,"at slot",o,"This is likely a bug, should have been added earlier.");const p=new ke(null,h,null);d[0]=p}let u=d[o];u||(bn&&console.log("Adding padding clip for ",h,t,"at slot",o),u=new ke(e,h,t),d[o]=u)}const l=new Vs(this,e,t);if(this.rootAndClipToRegisteredAnimationMap.set(i,l),bn&&console.log({root:e,clip:t,info:l}),t){const h=this.rootToRegisteredClip.get(e);if(h?h.push(t):this.rootToRegisteredClip.set(e,[t]),!this.clipToStartTime.get(t)){this.lastClipEndTime==null&&(this.lastClipEndTime=ke.restPoseClipDuration);let u=this.lastClipEndTime+ke.animationDurationPadding,p=u+t.duration;const m=Math.round(u*60)/60,y=Math.round(p*60)/60;Math.abs(m-u)<.01&&(u=m),Math.abs(y-p)<.01&&(p=y),u=Math.ceil(u),p=u+t.duration,this.clipToStartTime.set(t,u),this.lastClipEndTime=p}}return l}onAfterHierarchy(e){bn&&console.log("Animation clips per animation target node",this.dict)}onAfterBuildDocument(e){bn&&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 o=[];for(const r of i){const a=this.dict.get(r);if(!a){console.error("No data found for target on USDZ export – please report a bug!",r);continue}n===void 0&&(n=a?.length),n!==a?.length&&console.error("Different array lengths for targets – please report a bug!",a);for(let l=0;l<a.length;l++){let h=a[l];if(!h){const u=l-(this.injectRestPoses?1:0);a[l]=new ke(null,r,this.rootToRegisteredClip.get(t)[u]),h=a[l]}const d=h.getDuration();if(o[l]===void 0)o[l]=d;else if(o[l]!==d){console.error("Error during UDSZ export: Encountered different animation durations for animated targets. Please report a bug!",{datas:a,target:r}),o[l]=d;continue}}}}for(const t of this.serializers){const i=t.model?.parent,n=i?.isDynamic===!0;Ap&&console.log(n,t.model?.parent),n&&t.registerCallback(i)}}onExportObject(e,t,i){S.foreachComponent(e,o=>{const r=o;typeof r.createAnimation=="function"&&r.createAnimation(this,t,i)},!1);const n=new IO(e,this);this.serializers.push(n),n.registerCallback(t)}}class IO{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)),Ap&&console.log("REPARENT",e),this.model=e,this.callback&&this.model.addEventListener("serialize",this.callback)}skinnedMeshExport(e,t,i){const n=this.model,o=this.animationData;if(n&&n.skinnedMesh){let r=function(R){const U=[];for(const[N,K]of R){let ee=`${N} : [`;const ce=[];for(const me of K)ce.push(`(${te(me.x)}, ${te(me.y)}, ${te(me.z)})`);ee=ee.concat(ce.join(", ")),ee=ee.concat("],"),U.push(ee)}return U},a=function(R){const U=[];for(const[N,K]of R){let ee=`${N} : [`;const ce=[];for(const me of K)ce.push(`(${te(me.w)}, ${te(me.x)}, ${te(me.y)}, ${te(me.z)})`);ee=ee.concat(ce.join(", ")),ee=ee.concat("],"),U.push(ee)}return U},l=function(R){let U,N=!0;const K=new Map;for(const[ce,me]of R){U===void 0&&(U=me.length),U!==me.length&&(N=!1);let He=0;for(const wi of me)He++,wi||(K.has(ce)||K.set(ce,[]),K.get(ce).push(He))}bn&&console.log("Bone count: ",R.size,"TransformData entries per bone: ",U,"Undefined bone entries: ",K),console.assert(N,"All bones should have the same number of TransformData entries",R),console.assert(K.size===0,"All TransformData entries should be set",K);const ee=[];for(const[ce,me]of R)for(let He=0;He<me.length;He++){const wi=me[He],ah=i.getStartTimeByClip(wi.clip);ee.length<=He&&ee.push({pos:[],rot:[],scale:[],timeOffset:ah});const Cs=ee[He];Cs.pos.push(...wi.getSortedTimesArray(!0,!1,!1)),Cs.rot.push(...wi.getSortedTimesArray(!1,!0,!1)),Cs.scale.push(...wi.getSortedTimesArray(!1,!1,!0))}for(const ce of ee)ce.pos.sort((me,He)=>me-He),ce.rot.sort((me,He)=>me-He),ce.scale.sort((me,He)=>me-He),ce.pos=[...new Set(ce.pos)],ce.rot=[...new Set(ce.rot)],ce.scale=[...new Set(ce.scale)];return ee},h=function(R,U,N){const K=new Map,ee=new Map,ce=new Map,me=U.length;for(const He of N){const wi=R.get(He);let ah;wi?console.assert(wi.length===me,"We should have the same number of TransformData entries for each bone",wi,U):ah=new ke(null,He,null);for(let Cs=0;Cs<me;Cs++){const Gu=wi?wi[Cs]:ah,Mr=U[Cs];for(const{time:Wa,translation:Ga}of Gu.getValues(Mr.pos,!0,!1,!1)){const Wi=(Wa+Mr.timeOffset)*60;K.has(Wi)||K.set(Wi,new Array),K.get(Wi).push(Ga.clone())}for(const{time:Wa,rotation:Ga}of Gu.getValues(Mr.rot,!1,!0,!1)){const Wi=(Wa+Mr.timeOffset)*60;ee.has(Wi)||ee.set(Wi,new Array),ee.get(Wi).push(Ga.clone())}for(const{time:Wa,scale:Ga}of Gu.getValues(Mr.scale,!1,!1,!0)){const Wi=(Wa+Mr.timeOffset)*60;ce.has(Wi)||ce.set(Wi,new Array),ce.get(Wi).push(Ga.clone())}}}return{position:K.size==0?void 0:K,quaternion:ee.size==0?void 0:ee,scale:ce.size==0?void 0:ce}},d=function(R){const U=[];for(const N of R)U.push(`(${te(N.x)}, ${te(N.y)}, ${te(N.z)})`);return U.join(", ")},u=function(R){const U=[];for(const N of R)U.push(`(${te(N.w)}, ${te(N.x)}, ${te(N.y)}, ${te(N.z)})`);return U.join(", ")},p=function(R){const U=new Map;if(bn){const N=new Array;for(const[K,ee]of o)N.push(K.uuid+": "+ee.length+" "+ee.map(ce=>ce.clip?.uuid.substring(0,6)).join(" "));console.log(`getPerBoneTransformData
|
|
1259
|
+
}`}function O_(s){return`(${s.r}, ${s.g}, ${s.b})`}function M_(s){return`(${s.x}, ${s.y})`}const rg=[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 gt{static global_id=0;id;trigger;action;exclusive=!1;makeExclusive(e){return this.exclusive=e,this}constructor(e,t,i){this.id="Behavior_"+ji(e)+"_"+gt.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 o=0;o<this.trigger.length;o++){const r=this.trigger[o];n+="<"+r.id+">",o+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 o of this.trigger)o.writeTo(t,i),i.appendLine();else this.trigger.writeTo(t,i);i.appendLine(),this.action.writeTo(t,i),i.closeBlock()}}const Dr=new Set;function Tp(s,e){let t="";if(Array.isArray(s)){Dr.clear();let i="[ ";for(let n=0;n<s.length;n++){let o=s[n];if(!o){console.warn("Invalid target object in behavior",s+". Is the object exported?");continue}if(typeof o=="string"){if(Dr.has(o))continue;i+=o,Dr.add(o)}else if(typeof o=="object"){if(o.isObject3D&&(o=e.findById(o.uuid),!o)){console.warn("Invalid target object in behavior",s+". Is the object exported?");continue}const r=o.getPath?.call(o);if(Dr.has(r))continue;i+=r,Dr.add(r)}n+1<s.length&&(i+=", ")}i+=" ]",t=i,Dr.clear()}else if(typeof s=="object"){const i=s;if(i.isObject3D&&(s=e.findById(i.uuid)),!s)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=s.getPath?.call(s)}return t}class Hs{static global_id=0;id;targetId;tokenId;type;distance;constructor(e,t){e&&(this.targetId=e),t?this.id=t:this.id="Trigger_"+Hs.global_id++}writeTo(e,t){t.beginBlock(`def Preliminary_Trigger "${this.id}"`),this.targetId&&(typeof this.targetId!="string"&&(this.targetId=Tp(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 k_(s,e={direct:!0,indirect:!0}){const t=ze.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"')},s.add(t)}class wt{static __sceneStartTrigger;static sceneStartTrigger(){if(this.__sceneStartTrigger!==void 0)return this.__sceneStartTrigger;const e=new Hs(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 Hs(e);if(Array.isArray(e)&&e.length>1)for(const n of e)n instanceof ze&&k_(n,t);else e instanceof ze&&k_(e,t);return i.tokenId="TapGesture",i}static isTapTrigger(e){return e?.tokenId==="TapGesture"}static proximityToCameraTrigger(e,t){const i=new Hs(e);return i.tokenId="ProximityToCamera",i.distance=t,i}}class To{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 Wt{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 Wt,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+="_"+Wt.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=Tp(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=Tp(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 Ai{x=0;y=0;z=0;constructor(e,t,i){this.x=e,this.y=t,this.z=i}static get up(){return new Ai(0,1,0)}static get right(){return new Ai(1,0,0)}static get forward(){return new Ai(0,0,1)}static get back(){return new Ai(0,0,-1)}static get zero(){return new Ai(0,0,0)}}class le{static sequence(...e){return new To("Group_"+To.getId(),e).makeSequence()}static parallel(...e){return new To("Group_"+To.getId(),e).makeParallel()}static fadeAction(e,t,i){const n=new Wt(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 o=new Wt(e);o.tokenId="StartAnimation";const r=t.start,a=t.duration,l=t.speed,h=t.clipName;if(o.comment=`Animation: ${h}, start=${r*60}, length=${a*60}, end=${(r+a)*60}`,o.animationName=h,o.start=r,o.duration=a,o.animationSpeed=l,o.reversed=i,o.pingPong=n,o.multiplePerformOperation="allow",i&&(o.start-=a),n){o.pingPong=!1;const d=o.clone();return d.reversed=!i,d.start=o.start,d.reversed&&(d.start-=a),le.sequence(o,d)}return o}static waitAction(e){const t=new Wt;return t.tokenId="Wait",t.duration=e,t.motionType=void 0,t}static lookAtCameraAction(e,t,i,n){const o=new Wt(e);return o.tokenId="LookAtCamera",o.duration=t===void 0?9999999999999:t,o.front=i??Ai.forward,o.up=n??Ai.up,o}static emphasize(e,t,i="bounce",n=1,o="basic"){const r=new Wt(e);return r.tokenId="Emphasize",r.duration=t,r.style=o??"basic",r.motionType=i,r.moveDistance=n,r}static transformAction(e,t,i,n,o="inout"){const r=new Wt(e);return r.tokenId="Transform",r.duration=i,r.duration=Math.max(1e-6,i),r.type=n,r.easeType=i>0?o:"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,o="spatial"){const r=new Wt(e);return r.tokenId="Audio",r.type=i,r.audio=t,r.gain=n,r.auralMode=o,r.multiplePerformOperation="allow",r}static impulseAction(e,t){const i=new Wt(e);return i.tokenId="Impulse",i.velocity=t,i}}class DO{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 ag extends DO{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||ze.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=le.fadeAction(this.object,0,!0),this._enableAction)}disable(){return this._disableAction?this._disableAction:(this._disableAction=le.fadeAction(this.object,0,!1),this._disableAction)}}class Y0{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 bn=w("debugusdzanimation"),Ap=w("debugusdzanimationserialization");class Vs{_start;get start(){return this._start===void 0&&(this._start=this.ext.getStartTimeByClip(this.clip)),this._start}get duration(){return this.clip?.duration??ke.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=c.PropertyBinding.parseTrackName(t.name);let n=c.PropertyBinding.findNode(this.root,i.nodeName);if(n)if(!e)e=n;else{if(n===e||Vs.isDescendantOf(e,n))continue;if(!Vs.isDescendantOf(n,e)){for(;!Vs.isDescendantOf(n,e)&&n.parent;)n=n.parent;Vs.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 ke{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=ke.restPoseClipDuration,i&&i.tracks){const o=Math.max(...i.tracks.map(r=>r.times[r.times.length-1]));o!==this.duration&&(console.warn("USDZExporter: Animation clip duration does not match the maximum time value in the tracks.",i,o,this.duration),this.duration=o)}const n=S.getComponent(e,rt);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 – 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."),A()&&he("[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,o=this.rot?.times,r=this.scale?.times,a=[];if(e&&n)for(const l of n)a.push(l);if(t&&o)for(const l of o)a.push(l);if(i&&r)for(const l of r)a.push(l);return a.includes(0)||a.push(0),a.sort((l,h)=>l-h),[...new Set(a)]}*getValues(e,t=!0,i=!0,n=!0){const o=new c.Vector3,r=new c.Quaternion,a=new c.Vector3(1,1,1),l=this.target,h=t?this.pos?.createInterpolant():void 0,d=i?this.rot?.createInterpolant():void 0,u=n?this.scale?.createInterpolant():void 0;h||o.set(l.position.x,l.position.y,l.position.z),d||r.set(l.quaternion.x,l.quaternion.y,l.quaternion.z,l.quaternion.w),u||a.set(l.scale.x,l.scale.y,l.scale.z),h&&h.valueSize!==3&&(h.valueSize=3),d&&d.valueSize!==4&&(d.valueSize=4),u&&u.valueSize!==3&&(u.valueSize=3);const p=0;for(let m=0-p;m<e.length+p;m++){let y=0,b=0;if(m<0?(y=e[0],b=y-ke.animationDurationPadding/2+1/60):m>=e.length?(y=e[e.length-1],b=y+ke.animationDurationPadding/2-1/60):(y=e[m],b=y),h){const g=h.evaluate(y);o.set(g[0],g[1],g[2])}if(d){const g=d.evaluate(y);r.set(g[0],g[1],g[2],g[3])}if(u){const g=u.evaluate(y);a.set(g[0],g[1],g[2])}if(this.useRootMotion&&l===this.root){const g=new c.Matrix4;g.compose(o,r,a),g.multiply(l.matrix),g.decompose(o,r,a)}yield{time:b,translation:o,rotation:r,scale:a,index:m}}}}class fu{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:(ke.restPoseClipDuration+ke.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 – 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);bn&&console.log("registerAnimation",e,t);const n=this.injectRestPoses?1:0,o=(this.rootToRegisteredClip.get(e)?.length??0)+n,r=this.rootTargetMap.get(e),a=new Set(r);if(t&&t.tracks)for(const h of t.tracks){const d=c.PropertyBinding.parseTrackName(h.name),u=c.PropertyBinding.findNode(e,d.nodeName);if(!u){console.warn("no object found for track",h.name,"using "+e.name+" instead");continue}this.dict.has(u)||this.dict.set(u,[]);const p=this.dict.get(u);if(!p){console.warn("no transform data found for target ",u,"at slot "+o+", this is likely a bug");continue}a.delete(u),this.injectRestPoses&&!p[0]&&(console.log("Injecting rest pose",u,t,"at slot",o),p[0]=new ke(null,u,null));let m=p[o];m||(m=new ke(e,u,t),p[o]=m),m.addTrack(h),r?.includes(u)||r?.push(u)}bn&&console.log("Unregistered nodes for this clip",a,"clip",t,"at slot",o,"for root",e,"targets",r);for(const h of a){const d=this.dict.get(h);if(!d)continue;if(this.injectRestPoses&&!d[0]){console.warn("Adding rest pose for ",h,t,"at slot",o,"This is likely a bug, should have been added earlier.");const p=new ke(null,h,null);d[0]=p}let u=d[o];u||(bn&&console.log("Adding padding clip for ",h,t,"at slot",o),u=new ke(e,h,t),d[o]=u)}const l=new Vs(this,e,t);if(this.rootAndClipToRegisteredAnimationMap.set(i,l),bn&&console.log({root:e,clip:t,info:l}),t){const h=this.rootToRegisteredClip.get(e);if(h?h.push(t):this.rootToRegisteredClip.set(e,[t]),!this.clipToStartTime.get(t)){this.lastClipEndTime==null&&(this.lastClipEndTime=ke.restPoseClipDuration);let u=this.lastClipEndTime+ke.animationDurationPadding,p=u+t.duration;const m=Math.round(u*60)/60,y=Math.round(p*60)/60;Math.abs(m-u)<.01&&(u=m),Math.abs(y-p)<.01&&(p=y),u=Math.ceil(u),p=u+t.duration,this.clipToStartTime.set(t,u),this.lastClipEndTime=p}}return l}onAfterHierarchy(e){bn&&console.log("Animation clips per animation target node",this.dict)}onAfterBuildDocument(e){bn&&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 o=[];for(const r of i){const a=this.dict.get(r);if(!a){console.error("No data found for target on USDZ export – please report a bug!",r);continue}n===void 0&&(n=a?.length),n!==a?.length&&console.error("Different array lengths for targets – please report a bug!",a);for(let l=0;l<a.length;l++){let h=a[l];if(!h){const u=l-(this.injectRestPoses?1:0);a[l]=new ke(null,r,this.rootToRegisteredClip.get(t)[u]),h=a[l]}const d=h.getDuration();if(o[l]===void 0)o[l]=d;else if(o[l]!==d){console.error("Error during UDSZ export: Encountered different animation durations for animated targets. Please report a bug!",{datas:a,target:r}),o[l]=d;continue}}}}for(const t of this.serializers){const i=t.model?.parent,n=i?.isDynamic===!0;Ap&&console.log(n,t.model?.parent),n&&t.registerCallback(i)}}onExportObject(e,t,i){S.foreachComponent(e,o=>{const r=o;typeof r.createAnimation=="function"&&r.createAnimation(this,t,i)},!1);const n=new IO(e,this);this.serializers.push(n),n.registerCallback(t)}}class IO{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)),Ap&&console.log("REPARENT",e),this.model=e,this.callback&&this.model.addEventListener("serialize",this.callback)}skinnedMeshExport(e,t,i){const n=this.model,o=this.animationData;if(n&&n.skinnedMesh){let r=function(R){const U=[];for(const[N,K]of R){let ee=`${N} : [`;const ce=[];for(const me of K)ce.push(`(${te(me.x)}, ${te(me.y)}, ${te(me.z)})`);ee=ee.concat(ce.join(", ")),ee=ee.concat("],"),U.push(ee)}return U},a=function(R){const U=[];for(const[N,K]of R){let ee=`${N} : [`;const ce=[];for(const me of K)ce.push(`(${te(me.w)}, ${te(me.x)}, ${te(me.y)}, ${te(me.z)})`);ee=ee.concat(ce.join(", ")),ee=ee.concat("],"),U.push(ee)}return U},l=function(R){let U,N=!0;const K=new Map;for(const[ce,me]of R){U===void 0&&(U=me.length),U!==me.length&&(N=!1);let He=0;for(const wi of me)He++,wi||(K.has(ce)||K.set(ce,[]),K.get(ce).push(He))}bn&&console.log("Bone count: ",R.size,"TransformData entries per bone: ",U,"Undefined bone entries: ",K),console.assert(N,"All bones should have the same number of TransformData entries",R),console.assert(K.size===0,"All TransformData entries should be set",K);const ee=[];for(const[ce,me]of R)for(let He=0;He<me.length;He++){const wi=me[He],ah=i.getStartTimeByClip(wi.clip);ee.length<=He&&ee.push({pos:[],rot:[],scale:[],timeOffset:ah});const Cs=ee[He];Cs.pos.push(...wi.getSortedTimesArray(!0,!1,!1)),Cs.rot.push(...wi.getSortedTimesArray(!1,!0,!1)),Cs.scale.push(...wi.getSortedTimesArray(!1,!1,!0))}for(const ce of ee)ce.pos.sort((me,He)=>me-He),ce.rot.sort((me,He)=>me-He),ce.scale.sort((me,He)=>me-He),ce.pos=[...new Set(ce.pos)],ce.rot=[...new Set(ce.rot)],ce.scale=[...new Set(ce.scale)];return ee},h=function(R,U,N){const K=new Map,ee=new Map,ce=new Map,me=U.length;for(const He of N){const wi=R.get(He);let ah;wi?console.assert(wi.length===me,"We should have the same number of TransformData entries for each bone",wi,U):ah=new ke(null,He,null);for(let Cs=0;Cs<me;Cs++){const Gu=wi?wi[Cs]:ah,Mr=U[Cs];for(const{time:Wa,translation:Ga}of Gu.getValues(Mr.pos,!0,!1,!1)){const Wi=(Wa+Mr.timeOffset)*60;K.has(Wi)||K.set(Wi,new Array),K.get(Wi).push(Ga.clone())}for(const{time:Wa,rotation:Ga}of Gu.getValues(Mr.rot,!1,!0,!1)){const Wi=(Wa+Mr.timeOffset)*60;ee.has(Wi)||ee.set(Wi,new Array),ee.get(Wi).push(Ga.clone())}for(const{time:Wa,scale:Ga}of Gu.getValues(Mr.scale,!1,!1,!0)){const Wi=(Wa+Mr.timeOffset)*60;ce.has(Wi)||ce.set(Wi,new Array),ce.get(Wi).push(Ga.clone())}}}return{position:K.size==0?void 0:K,quaternion:ee.size==0?void 0:ee,scale:ce.size==0?void 0:ce}},d=function(R){const U=[];for(const N of R)U.push(`(${te(N.x)}, ${te(N.y)}, ${te(N.z)})`);return U.join(", ")},u=function(R){const U=[];for(const N of R)U.push(`(${te(N.w)}, ${te(N.x)}, ${te(N.y)}, ${te(N.z)})`);return U.join(", ")},p=function(R){const U=new Map;if(bn){const N=new Array;for(const[K,ee]of o)N.push(K.uuid+": "+ee.length+" "+ee.map(ce=>ce.clip?.uuid.substring(0,6)).join(" "));console.log(`getPerBoneTransformData
|
|
1260
1260
|
`+N.join(`
|
|
1261
|
-
`))}for(const N of R){const K=o.get(N);K&&U.set(N,K)}return U},m=function(R){const U=p(R),N=l(U);return h(U,N,R)};const y=n.skinnedMesh.skeleton,_=new Array,g=[],v=[];for(const R of y.bones){g.push(R),v.push(R.uuid);const U=y.boneInverses[y.bones.indexOf(R)];_.push({bone:R,inverse:U})}let b=1e4;for(;v.length<y.bones.length&&b-- >0;)for(const R of g){const U=R.children;for(const N of U)if(v.indexOf(N.uuid)===-1&&y.bones.indexOf(N)!==-1){g.push(N),v.push(N.uuid);const K=y.boneInverses[y.bones.indexOf(N)];_.push({bone:N,inverse:K})}}b<=0&&console.error("Failed to sort bones in skinned mesh",n.skinnedMesh,y.bones,v);for(const R of z0(y.bones))_.push({bone:R,inverse:R.matrixWorld.clone().invert()});const x=_[0].bone.parent;x||console.error("No bone parent found for skinned mesh during USDZ export",n.skinnedMesh),_.sort((R,U)=>na(R.bone,x)>na(U.bone,x)?1:-1);const T=t.quickLookCompatible,O=[],M=[],E=[],j=[];for(const{bone:R}of _){if(T){const U=R.scale;U.x==0&&(U.x=1e-5),U.y==0&&(U.y=1e-5),U.z==0&&(U.z=1e-5),O.push(new c.Matrix4().compose(R.position,R.quaternion,R.scale))}else O.push(R.matrix.clone());M.push(R.position),E.push(R.quaternion),j.push(R.scale)}const L=_.map(R=>'"'+na(R.bone,x)+'"').join(", "),z=_.map(R=>C_(R.inverse.clone().invert())).join(", ");e.beginBlock('def Skeleton "Rig"'),e.appendLine(`uniform matrix4d[] bindTransforms = [${z}]`),e.appendLine(`uniform token[] joints = [${L}]`),e.appendLine('uniform token purpose = "guide"'),e.appendLine(`uniform matrix4d[] restTransforms = [${O.map(R=>C_(R)).join(", ")}]`);const $=m(_.map(R=>R.bone));if(bn){let R=1e7,U=0;for(const N of $.position?.keys()??[])R=Math.min(R,N),U=Math.max(U,N);console.log("Time samples",R,U,$)}if(e.beginBlock('def SkelAnimation "_anim"'),e.appendLine(`uniform token[] joints = [${L}]`),e.appendLine(`quatf[] rotations = [${u(E)}]`),$&&$.quaternion){e.beginBlock("quatf[] rotations.timeSamples = {","");const R=a($.quaternion);for(const U of R)e.appendLine(U);e.closeBlock()}if(e.appendLine(`half3[] scales = [${d(j)}]`),$&&$.scale){e.beginBlock("half3[] scales.timeSamples = {","");const R=r($.scale);for(const U of R)e.appendLine(U);e.closeBlock()}if(e.appendLine(`float3[] translations = [${d(M)}]`),$&&$.position){e.beginBlock("float3[] translations.timeSamples = {","");const R=r($.position);for(const U of R)e.appendLine(U);e.closeBlock()}e.closeBlock(),e.closeBlock()}}onSerialize(e,t){if(!this.model)return;const i=this.animationData.get(this.object);if(i)for(let d=0;d<i.length;d++)i[d]===void 0&&(i[d]=new ke(null,this.object,null));const n=this.ext;this.skinnedMeshExport(e,t,n);const o=this.object,r=this.model,a=this.animationData.get(o);if(!a||o.isSkinnedMesh)return;Ap&&console.log("SERIALIZE",this.model.name,this.object.type,a);const l=Intl.NumberFormat("en-US",{maximumFractionDigits:3,minimumFractionDigits:0,useGrouping:!1});function h(d,u){if(d.some(m=>m&&{position:m.pos,rotation:m.rot,scale:m.scale}[u])){switch(u){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 m=0;m<d.length;m++){const y=d[m];if(!y)continue;const _=n.getStartTimeByClip(y.clip),g=y.getSortedTimesArray(u==="position",u==="rotation",u==="scale");if(!g||g.length===0){console.error("got an animated object but no time values?",o,y);continue}const v=!y.clip,b=u==="position"&&(y.pos||v),x=u==="rotation"&&(y.rot||v),T=u==="scale"&&(y.scale||v);if(b||x||T){const O=y.clip?.name??"rest",M=y.getDuration();bn&&console.log("Write .timeSamples:",O,_,M,d),e.appendLine("# "+O+": start="+l.format(_*ke.frameRate)+", length="+l.format(M*ke.frameRate)+", frames="+y.getFrames())}if(b)for(const{time:O,translation:M}of y.getValues(g,!0,!1,!1)){const j=`${l.format((_+O)*ke.frameRate)}: (${te(M.x)}, ${te(M.y)}, ${te(M.z)}),`;e.appendLine(j)}if(x)for(const{time:O,rotation:M}of y.getValues(g,!1,!0,!1)){const j=`${l.format((_+O)*ke.frameRate)}: (${te(M.w)}, ${te(M.x)}, ${te(M.y)}, ${te(M.z)}),`;e.appendLine(j)}if(T)for(const{time:O,scale:M}of y.getValues(g,!1,!1,!0)){const j=`${l.format((_+O)*ke.frameRate)}: (${te(M.x)}, ${te(M.y)}, ${te(M.z)}),`;e.appendLine(j)}}e.closeBlock()}}h(a,"position"),h(a,"rotation"),h(a,"scale")}}const jO=w("debugusdz");class dr{static getName(e){const t=e.split(".").pop();let n=e.split(".").slice(0,-1).join(".").split("/").pop()?.replace(".","_");return n||(n="Audio_"+Math.random().toString(36).substring(2,15)),ji(n)+"."+t}get extensionName(){return"Audio"}files=new Array;onExportObject(e,t,i){const n=S.getComponents(e,pi);if(n.length)for(const o of n){if(!o.clip||typeof o.clip!="string"||!o.playOnAwake)continue;const r=o.clip.split("/").pop()||"Audio",a=dr.getName(o.clip),l=ji(a);if(!this.files.some(h=>h.path===o.clip)){this.files.push({path:o.clip,name:a});const h=a.toLowerCase();i.quickLookCompatible&&!h.endsWith(".mp3")&&!h.endsWith(".wav")&&!h.endsWith(".m4a")&&console.error("Audio file "+o.clip+" from "+o.name+" is not an MP3 or WAV file. QuickLook may not support playing it.")}i.quickLookCompatible||t.addEventListener("serialize",(h,d)=>{h.appendLine(),h.beginBlock(`def SpatialAudio "${l}"`,"(",!1),h.appendLine(`displayName = "${r}"`),h.closeBlock(")"),h.beginBlock(),h.appendLine(`uniform asset filePath = @audio/${a}@`),h.appendLine(`uniform token auralMode = "${o.spatialBlend>0?"spatial":"nonSpatial"}"`),h.appendLine(`uniform token playbackMode = "${o.loop?"loopFromStage":"onceFromStart"}"`),h.appendLine(`uniform float gain = ${o.volume}`),h.closeBlock()})}}async onAfterSerialize(e){for(const t of this.files){const i="audio/"+t.name;if(e.files[i]){jO&&console.warn("Audio file with name "+i+" already exists in the context. Skipping.");continue}const r=await(await(await fetch(t.path)).blob()).arrayBuffer(),a=new Uint8Array(r);e.files[i]=a}}}var BO=Object.defineProperty,Ee=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&BO(e,t,n),n};const E_=w("debugusdzbehaviours");function kc(s){s&&(s.getComponentInParent(ma)||(A()&&console.debug('Raycaster on "'+s.name+'" was automatically added, because no raycaster was found in the parent hierarchy.'),s.addComponent(fi)))}class ur extends k{object;target;duration=1;relativeMotion=!1;coroutine=null;targetPos=new c.Vector3;targetRot=new c.Quaternion;targetScale=new c.Vector3;start(){kc(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=X(this.object).clone(),t=X(this.target).clone(),i=ue(this.object).clone(),n=ue(this.target).clone(),o=Ie(this.object).clone(),r=Ie(this.target).clone(),a=e.distanceTo(t),l=i.angleTo(n),h=o.distanceTo(r);if(a<.01&&l<.01&&h<.01){ot(this.object,t),Ji(this.object,n),aa(this.object,r),this.coroutine=null;return}let d=0,u=0;for(;d<1;)d+=this.context.time.deltaTime/this.duration,d>1&&(d=1),u=d<.5?4*d*d*d:1-Math.pow(-2*d+2,3)/2,this.targetPos.lerpVectors(e,t,u),this.targetRot.slerpQuaternions(i,n,u),this.targetScale.lerpVectors(o,r,u),ot(this.object,this.targetPos),Ji(this.object,this.targetRot),aa(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(),o=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(o),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 gt("Move to "+this.target?.name,wt.tapTrigger(this.gameObject),le.transformAction(this.object,this.target,this.duration,this.relativeMotion?"relative":"absolute"));e.addBehavior(t)}}}Ee([f(c.Object3D)],ur.prototype,"object");Ee([f(c.Object3D)],ur.prototype,"target");Ee([f()],ur.prototype,"duration");Ee([f()],ur.prototype,"relativeMotion");const pu=class Tt extends k{materialToSwitch;variantMaterial;fadeDuration=0;start(){this._objectsWithThisMaterial=this.objectsWithThisMaterial,kc(this.gameObject),A()&&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 c.Mesh)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):gv(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=[],Tt._materialTriggersPerId={},Tt.variantSwitchIndex=0,this.materialToSwitch&&await ne.NEEDLE_progressive.assignTextureLOD(this.materialToSwitch,0),this.variantMaterial&&await ne.NEEDLE_progressive.assignTextureLOD(this.variantMaterial,0)}createBehaviours(e,t,i){this.objectsWithThisMaterial.find(o=>o.uuid===t.uuid)&&this.targetModels.push(t),this.gameObject.uuid===t.uuid&&(this.selfModel=t,this.materialToSwitch&&(Tt._materialTriggersPerId[this.materialToSwitch.uuid]||(Tt._materialTriggersPerId[this.materialToSwitch.uuid]=[]),Tt._materialTriggersPerId[this.materialToSwitch.uuid].push(this)))}afterCreateDocument(e,t){if(!this.materialToSwitch)return;const i=Tt._materialTriggersPerId[this.materialToSwitch.uuid];if(i){const n={};for(const o of i){const r=o.createVariants();r&&r.length>0&&(n[o.selfModel.uuid]=r)}for(const o of i){const r=[];for(const a in n)a!==o.selfModel.uuid&&r.push(...n[a]);o.createAndAttachBehaviors(e,n[o.selfModel.uuid],r)}}delete Tt._materialTriggersPerId[this.materialToSwitch.uuid]}createAndAttachBehaviors(e,t,i){const n=[],o=Math.max(0,this.fadeDuration);n.push(le.fadeAction([...this.targetModels,...i],o,!1)),n.push(le.fadeAction(t,o,!0)),e.addBehavior(new gt("Select_"+this.selfModel.name,wt.tapTrigger(this.selfModel),le.parallel(...n))),Tt._parallelStartHiddenActions.push(...t),Tt._startHiddenBehaviour||(Tt._startHiddenBehaviour=new gt("StartHidden_"+this.selfModel.name,wt.sceneStartTrigger(),le.fadeAction(Tt._parallelStartHiddenActions,o,!1)),e.addBehavior(Tt._startHiddenBehaviour))}static getMaterialName(e){return ji(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_"+Tt.variantSwitchIndex+++"_"+Tt.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())&&ze.createEmptyParent(t),t.parent&&t.parent.add(i),e.push(i)}return e}};Ee([f(c.Material)],pu.prototype,"materialToSwitch");Ee([f(c.Material)],pu.prototype,"variantMaterial");Ee([f()],pu.prototype,"fadeDuration");let lg=pu;const Ec=class Pe extends k{target;toggleOnClick=!1;targetState=!0;hideSelf=!0;start(){kc(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[Pe.wasVisible]===void 0&&(this.gameObject[Pe.wasVisible]=this.gameObject.activeSelf),this.target[Pe.wasVisible]===void 0&&(this.target[Pe.wasVisible]=this.target.activeSelf),this.stateBeforeCreatingDocument=this.gameObject[Pe.wasVisible],this.targetStateBeforeCreatingDocument=this.target[Pe.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,o=this.targetState;if(this.toggleOnClick)if(o=!this.targetStateBeforeCreatingDocument,!this.selfModelClone.geometry)(!this.selfModel.parent||this.selfModel.parent.isEmpty())&&og.createEmptyParent(this.selfModel),this.toggleModel=this.selfModel.deepClone(),this.toggleModel.name+="_toggle",this.selfModel.parent.add(this.toggleModel);else{if(!this.gameObject[Pe.toggleClone]){const l=this.selfModelClone.clone();l.setMatrix(new c.Matrix4),l.name+="_toggle"+Pe.clonedToggleIndex++,i.add(l),this.gameObject[Pe.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[Pe.toggleClone];if(!this.gameObject[Pe.reverseToggleClone]){const l=this.selfModelClone.clone();l.setMatrix(new c.Matrix4),l.name+="_toggleReverse"+Pe.clonedToggleIndex++,i.add(l),this.gameObject[Pe.reverseToggleClone]=l}this.toggleModel=this.gameObject[Pe.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(le.fadeAction(n,0,!1)),a.push(le.fadeAction(this.toggleModel,0,!0)),a.push(le.fadeAction(this.targetModel,0,o)),e.addBehavior(new gt("Toggle_"+n.name+"_ToggleTo"+(o?"On":"Off"),wt.tapTrigger(n),le.parallel(...a)));const l=[];l.push(le.fadeAction(this.toggleModel,0,!1)),l.push(le.fadeAction(n,0,!0)),l.push(le.fadeAction(this.targetModel,0,!o)),e.addBehavior(new gt("Toggle_"+n.name+"_ToggleTo"+(o?"Off":"On"),wt.tapTrigger(this.toggleModel),le.parallel(...l)))}}else{const a=[];this.hideSelf&&a.push(le.fadeAction(n,0,!1)),a.push(le.fadeAction(this.targetModel,0,o)),e.addBehavior(new gt("Toggle_"+n.name+"_ToggleTo"+(o?"On":"Off"),wt.tapTrigger(n),a.length>1?le.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),Ei.add(r,e)}}afterSerialize(e,t){this.gameObject[Pe.wasVisible]!==void 0&&(this.gameObject.visible=this.gameObject[Pe.wasVisible],delete this.gameObject[Pe.wasVisible]),this.target&&this.target[Pe.wasVisible]!==void 0&&(this.target.visible=this.target[Pe.wasVisible],delete this.target[Pe.wasVisible]),delete this.gameObject[Pe.toggleClone],delete this.gameObject[Pe.reverseToggleClone]}};Ee([f(c.Object3D)],Ec.prototype,"target");Ee([f()],Ec.prototype,"toggleOnClick");Ee([f()],Ec.prototype,"targetState");Ee([f()],Ec.prototype,"hideSelf");let cg=Ec;class Ei extends k{static _fadeBehaviour;static _fadeObjects=[];static add(e,t){const i=Array.isArray(e)?e:[e];for(const n of i)Ei._fadeObjects.includes(n)||(console.log("adding hide on start",n),Ei._fadeObjects.push(n));Ei._fadeBehaviour===void 0&&(Ei._fadeBehaviour=new gt("HideOnStart",wt.sceneStartTrigger(),le.fadeAction(Ei._fadeObjects,0,!1)),t.addBehavior(Ei._fadeBehaviour))}start(){S.setActive(this.gameObject,!1)}createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&(this.wasVisible||Ei.add(t,e))}wasVisible=!1;beforeCreateDocument(){this.wasVisible=S.isActiveSelf(this.gameObject)}}class Oa extends k{target;duration=.5;motionType="bounce";beforeCreateDocument(){}createBehaviours(e,t,i){if(this.target&&t.uuid===this.gameObject.uuid){const n=new gt("emphasize "+this.name,wt.tapTrigger(this.gameObject),le.emphasize(this.target,this.duration,this.motionType,void 0,"basic"));e.addBehavior(n)}}afterCreateDocument(e,t){}}Ee([f()],Oa.prototype,"target");Ee([f()],Oa.prototype,"duration");Ee([f()],Oa.prototype,"motionType");class Qs extends k{target;clip="";toggleOnClick=!1;trigger="tap";start(){kc(this.gameObject)}ensureAudioSource(){if(!this.target){const e=this.gameObject.addComponent(pi);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 o=this.target?this.target.gameObject:this.gameObject;dr.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 c.Mesh&&p.visible&&(l=!0)}),l=!0;const h=e.addAudioClip(n);let d=le.playAudioAction(o,h,"play",r,a);this.target&&this.target.loop&&(d=le.sequence(d).makeLooping());const u=this.name?"_"+this.name:"";if(l&&this.trigger==="tap"){this.toggleOnClick&&(d.multiplePerformOperation="stop");const p=new gt("playAudio"+u,wt.tapTrigger(t),d);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 gt("playAudioOnStart"+u,wt.sceneStartTrigger(),d);e.addBehavior(p)}}}}Ee([f(pi)],Qs.prototype,"target");Ee([f(URL)],Qs.prototype,"clip");Ee([f()],Qs.prototype,"toggleOnClick");const hg=class pn extends k{animator;stateName;trigger="tap";animation;get target(){return this.animator?.gameObject||this.animation?.gameObject}start(){kc(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(pn.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.';A()&&he(e),console.warn(e,...pn.rootsWithExclusivePlayback)}pn.animationActions=[],pn.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 fu);if(!n)return;const o=n.getClipCount(this.target)>1;o&&(A()&&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."),pn.rootsWithExclusivePlayback.add(this.target));const r=this.name?this.name:"";i.traverse(a=>{if(a.uuid===this.target?.uuid){const l=pn.getActionForSequences(i,a,this.animationSequence,this.animationLoopAfterSequence,this.randomOffsetNormalized),h=new gt(this.trigger+"_"+r+"_toPlayAnimation_"+this.stateName+"_on_"+this.target?.name,this.trigger=="tap"?wt.tapTrigger(this.selfModel):wt.sceneStartTrigger(),l);o&&h.makeExclusive(!0),e.addBehavior(h)}})}static getActionForSequences(e,t,i,n,o){const r=(l,h)=>{let d=pn.animationActions.find(u=>u.affectedObjects==l&&u.start==h.start&&u.duration==h.duration&&u.animationSpeed==h.speed);return d||(d=le.startAnimationAction(l,h),pn.animationActions.push(d)),d},a=le.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:le.sequence();for(const h of n)l.addAction(r(t,h));l.makeLooping(),a!==l&&a.addAction(l)}return o&&o>0&&a.actions.unshift(le.waitAction(o)),a}static getAndRegisterAnimationSequences(e,t,i){if(!t)return;const n=t.getComponent(rt),o=t.getComponent(Ft);if(!n&&!o)return;if(n&&!i)throw new Error("PlayAnimationOnClick: No stateName specified for animator "+n.name+" on "+t.name);let r=[],a=[];if(o){const y=e.registerAnimation(t,o.clip);y&&(o.loop?a.push(y):r.push(y));let _=0;if(o.minMaxOffsetNormalized){const g=o.minMaxOffsetNormalized.x,v=o.minMaxOffsetNormalized.y;_=(o.clip?.duration||1)*(g+Math.random()*(v-g))}return{animationSequence:r,animationLoopAfterSequence:a,randomTimeOffset:_}}const l=n?.runtimeAnimatorController;let h=l?.findState(i),d=[],u=[];if(l&&h){const y=new Array;y.push(h);let _=!1;for(;y.length<100;){if(!h||h===null||!h.transitions||h.transitions.length===0){h.motion?.isLooping&&(_=!0);break}const g=h.transitions.find(b=>b.conditions.length===0),v=g?l.getState(g.destinationState,0):null;if(v&&y.includes(v)){h=v,_=!0;break}else if(g){if(h=v,!h)break;y.push(h)}else{_=h.motion?.isLooping??!1;break}}if(_&&h){const g=y.indexOf(h);d=y.slice(0,g),u=y.slice(g),E_&&console.log("found loop from "+i,"states until loop",d,"states looping",u)}else d=y,u=[],E_&&console.log("found no loop from "+i,"states",d);if(!u.length){const g=d[d.length-1],v=g.motion?.clip;if(v){let b;if(e.holdClipMap.has(v))b=e.holdClipMap.get(v);else{const x=g.name+"_hold";b=v.clone(),b.duration=1,b.name=x;const T=v.duration;b.tracks=v.tracks.map(O=>{const M=O.clone();M.times=new Float32Array([0,T]);const E=O.values.length,j=O.getValueSize(),L=O.values.slice(E-j,E);return M.values=new Float32Array(2*j),M.values.set(L,0),M.values.set(L,j),M}),b.name=x,e.holdClipMap.set(v,b)}if(b){const x={name:b.name,motion:{clip:b,isLooping:!1,name:b.name},speed:1,transitions:[],behaviours:[],hash:g.hash+1};u.push(x)}}}}if(d.length===1&&(!d[0].motion?.clip||d[0].motion?.clip.tracks?.length===0)){r=new Array;const y=e.registerAnimation(t,null);y&&r.push(y);return}if(d=d.filter(y=>y.motion?.clip&&y.motion?.clip.tracks?.length>0),u=u.filter(y=>y.motion?.clip&&y.motion?.clip.tracks?.length>0),d.length===0&&u.length===0){console.warn("No clips found for state "+i+" on "+n?.name+", can't export animation data");return}const p=(y,_)=>{if(!t)return;const g=e.registerAnimation(t,y.motion.clip??null);g?(g.speed=y.speed,_.push(g)):console.warn("Couldn't register animation for state "+y.name+" on "+n?.name)};if(d.length>0){r=new Array;for(const y of d)p(y,r)}if(u.length>0){a=new Array;for(const y of u)p(y,a)}let m=0;if(n&&l&&n.minMaxOffsetNormalized){const y=n.minMaxOffsetNormalized.x,_=n.minMaxOffsetNormalized.y;m=((d.length?d[0]:u.length?u[0]:null)?.motion.clip?.duration||1)*(y+Math.random()*(_-y))}return{animationSequence:r,animationLoopAfterSequence:a,randomTimeOffset:m}}createAnimation(e,t,i){if(!this.target||!this.animator&&!this.animation)return;const n=pn.getAndRegisterAnimationSequences(e,this.target,this.stateName);n&&(this.animationSequence=n.animationSequence,this.animationLoopAfterSequence=n.animationLoopAfterSequence,this.randomOffsetNormalized=n.randomTimeOffset,this.stateAnimationModel=t)}};Ee([f(rt)],hg.prototype,"animator");Ee([f()],hg.prototype,"stateName");let ec=hg;class Ma extends k{getType(){}target;getDuration(){}}Ee([f(c.Object3D)],Ma.prototype,"target");class Rc extends k{target}Ee([f(Ma)],Rc.prototype,"target");class Tc extends Ma{type=1;duration=1;getType(){switch(this.type){case 1:return"hide";case 0:return"show"}}getDuration(){return this.duration}}Ee([f()],Tc.prototype,"type");Ee([f()],Tc.prototype,"duration");class dg extends Rc{}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 Qi.getOrCreate().createQRCode()}createQuicklookButton(){if(this._quicklookButton)return this._quicklookButton;const e=document.createElement("button");this._quicklookButton=e,e.dataset.needle="quicklook-button";const t=exports.DeviceUtilities.supportsQuickLookAR();e.innerText="View in AR",e.prepend(pt("view_in_ar"));let i=!1,n=null;return e.addEventListener("click",()=>{n=yc(Tn),n||(i=!0,n=new Tn),i&&(n.objectToExport=F.Current.scene),n?(e.classList.add("this-mode-is-requested"),n.exportAndOpen().then(()=>{e.classList.remove("this-mode-is-requested")}).catch(o=>{e.classList.remove("this-mode-is-requested"),console.error(o)})):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(pt("view_in_ar")),i.title="Click to start an AR session",i.addEventListener("click",()=>H.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)"),exports.DeviceUtilities.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(pt("panorama_photosphere")),i.title="Click to start a VR session",i.addEventListener("click",()=>H.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)"),exports.DeviceUtilities.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(pt("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&&Se("This page doesn't allow popups. Please paste "+n+" into your browser.")}),this.listenToXRSessionState(t),this.hideElementDuringXRSession(t),exports.DeviceUtilities.isMozillaXR()||navigator.xr?.addEventListener("devicechange",()=>{navigator.xr?.isSessionSupported("immersive-vr")?t.style.display="none":t.style.display=""}),t}createQRCode(){return Qi.getOrCreate().createQRCode()}updateSessionSupported(e,t){if(!("xr"in navigator)){e.style.display="none";return}H.isSessionSupported(t).then(i=>{e.style.display=i?"":"none",A()&&!i&&console.log('[WebXR] "'+t+'" is not supported on this device – make sure your server runs using HTTPS and you have a device connected that supports '+t)})}hideElementDuringXRSession(e){Wd(t=>{e["previous-display"]=e.style.display,e.style.display="none"}),hm(t=>{e["previous-display"]!=null&&(e.style.display=e["previous-display"])})}listenToXRSessionState(e,t){t&&(H.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"))}),H.onSessionRequestEnd(i=>{e.classList.remove("this-mode-is-requested"),e.classList.remove("other-mode-is-requested"),e.disabled=e["was-disabled"]}))}}var FO=Object.defineProperty,UO=Object.getOwnPropertyDescriptor,at=(s,e,t,i)=>{for(var n=i>1?void 0:i?UO(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&FO(e,t,n),n};const Fl=w("debugspriterenderer"),zO=w("wireframe");class Zo{static cache={};static getOrCreateGeometry(e){if(e.__cached_geometry)return e.__cached_geometry;if(e.guid&&Zo.cache[e.guid])return Fl&&console.log("Take cached geometry for sprite",e.guid),Zo.cache[e.guid];const t=new c.BufferGeometry;e.__cached_geometry=t;const i=new Float32Array(e.triangles.length*3),n=new Float32Array(e.triangles.length*2);for(let o=0;o<e.triangles.length;o+=1){const r=e.triangles[o];i[o*3]=-e.vertices[r].x,i[o*3+1]=e.vertices[r].y,i[o*3+2]=0;const a=e.uv[r];n[o*2]=a.x,n[o*2+1]=1-a.y}return t.setAttribute("position",new c.BufferAttribute(i,3)),t.setAttribute("uv",new c.BufferAttribute(n,2)),e.guid&&(this.cache[e.guid]=t),Fl&&console.log("Built sprite geometry",e,t),t}}class NO{x;y}function K0(s){s&&(s.colorSpace!=c.SRGBColorSpace&&(s.colorSpace=c.SRGBColorSpace,s.needsUpdate=!0),s.minFilter==c.NearestFilter&&s.magFilter==c.NearestFilter&&(s.anisotropy=1,s.needsUpdate=!0))}let ms=class{constructor(e){e&&(this.texture=e,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 c.Mesh(Zo.getOrCreateGeometry(this),this.material)),this._mesh}_mesh;get material(){return this._material||(this.texture&&K0(this.texture),this._material=new c.MeshBasicMaterial({map:this.texture,color:16777215,side:c.DoubleSide,transparent:!0})),this._material}_material;getGeometry(){return Zo.getOrCreateGeometry(this)}};at([f()],ms.prototype,"guid",2);at([f(c.Texture)],ms.prototype,"texture",2);at([$e()],ms.prototype,"triangles",2);at([$e()],ms.prototype,"uv",2);at([$e()],ms.prototype,"vertices",2);const Tf=Symbol("spriteOwner");class ga{sprites;constructor(){this.sprites=[]}}at([f(ms)],ga.prototype,"sprites",2);const ug=class Lp{static create(){const e=new Lp;return e.spriteSheet=new ga,e}constructor(){}clone(){const e=new Lp;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 ga,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&&(K0(n),!i.__hasLoadedProgressive)){i.__hasLoadedProgressive=!0;const o=n;ne.NEEDLE_progressive.assignTextureLOD(n,0).then(r=>{r instanceof c.Texture&&(i.texture=r,e?.map===o&&(e.map=r,e.needsUpdate=!0))})}}};at([f(ga)],ug.prototype,"spriteSheet",2);at([f()],ug.prototype,"index",2);let sa=ug;class Zt extends k{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=sa.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);Fl&&console.log("[SpriteSheet] Set index to "+t+" (was "+this.spriteIndex+")",e),this.spriteIndex=t}else e instanceof ms?(this._spriteSheet||(this._spriteSheet=sa.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=sa.create(),Fl&&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 Fl&&console.warn("Sprite not found",this.spriteIndex,t.spriteSheet.sprites),!1;if(this._currentSprite)this._currentSprite.geometry=Zo.getOrCreateGeometry(i),this._currentSprite.material.map=i.texture;else{const n=new c.MeshBasicMaterial({color:16777215,side:c.DoubleSide});if(zO&&(n.wireframe=!0),this.color&&(n.color||(n.color=new c.Color),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 o=i.texture;o[Tf]!==void 0&&o[Tf]!==this&&this.spriteFrames>1&&(o=i.texture=o.clone()),o[Tf]=this,n.map=o}this.sharedMaterial=n,this._currentSprite=new c.Mesh(Zo.getOrCreateGeometry(i),n),this._currentSprite.renderOrder=Math.round(this.renderOrder),ne.NEEDLE_progressive.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}}at([f()],Zt.prototype,"drawMode",2);at([f(NO)],Zt.prototype,"size",2);at([f(Z)],Zt.prototype,"color",2);at([f(c.Material)],Zt.prototype,"sharedMaterial",2);at([f()],Zt.prototype,"transparent",2);at([f()],Zt.prototype,"cutoutThreshold",2);at([f()],Zt.prototype,"castShadows",2);at([f()],Zt.prototype,"renderOrder",2);at([f()],Zt.prototype,"toneMapped",2);at([f(sa)],Zt.prototype,"sprite",1);const R_=w("debugwebxr"),VO=new c.Matrix4().makeRotationY(Math.PI);class hi extends k{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 c.Matrix4;_createdPlacementObject=null;_reparentedComponents=[];_placementScene=new c.Scene;_reticle=[];_hits=[];_placementStartTime=-1;_rigPlacementMatrix;_anchor=null;userInput;onEnable(){this.customReticle?.preload()}supportsXR(e){return e==="immersive-ar"}onEnterXR(e){R_&&console.log("ENTER WEBXR: SessionRoot start..."),this._anchor=null,hi._hasPlaced=!1,this.gameObject.updateMatrixWorld(),this._startOffset.copy(this.gameObject.matrixWorld);const t=new c.Object3D;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=Bt(this._placementScene.children),n=i.getCenter(new c.Vector3),o=i.getSize(new c.Vector3),r=new c.Matrix4;r.makeTranslation(n.x,n.y-o.y*.5,n.z),this._startOffset.multiply(r)}this._reparentedComponents.length=0,this._reparentedComponents.push({comp:this,originalObject:this.gameObject}),S.addComponent(t,this);for(const i of this._reticle)ui(i);this._reticle.length=0,this._isPlacing=!0,this.context.input.addEventListener("pointerup",this.onPlaceScene,{queue:Ht.Early})}onLeaveXR(){this.context.input.removeEventListener("pointerup",this.onPlaceScene,{queue:Ht.Early}),this.onRevertSceneChanges(),this._anchor=null,hi._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 o=n.getHitTest();o&&(i=!0,this.updateReticleAndHits(e.xr,n.index,o,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 Ad(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 o=this._reticle[t];if(!o){if(this.customReticle)if(this.customReticle.asset)o=Xo(this.customReticle.asset);else{this.customReticle.loadAssetAsync();return}else o=new c.Mesh(new c.RingGeometry(.07,.09,32).rotateX(-Math.PI/2),new c.MeshBasicMaterial({side:c.DoubleSide,depthTest:!1,depthWrite:!1,transparent:!0,opacity:1,color:15658734})),o.name="AR Placement Reticle";if(R_){const r=new c.AxesHelper(1);r.position.y+=.01,o.add(r)}this._reticle[t]=o,o.matrixAutoUpdate=!1,o.visible=!1}if(o.lastPos=o.lastPos||i.position.clone(),o.lastQuat=o.lastQuat||i.quaternion.clone(),o.position.copy(o.lastPos.lerp(i.position,this.context.time.deltaTime/.1)),o.lastPos.copy(o.position),o.quaternion.copy(o.lastQuat.slerp(i.quaternion,this.context.time.deltaTime/.05)),o.lastQuat.copy(o.quaternion),o.scale.set(n,n,n),this.customReticle&&this.applyViewBasedTransform(o),o.updateMatrix(),o.visible=!0,o.parent!==this.context.scene&&this.context.scene.add(o),this._placementStartTime<0&&(this._placementStartTime=this.context.time.realtimeSinceStartup),this.autoPlace)if(this.upVec.set(0,1,0).applyQuaternion(o.quaternion),this.upVec.dot(V(0,1,0))>.9){let a=o["autoplace:timer"]||0;a>=1?(o.visible=!1,this.onPlaceScene(null)):(a+=this.context.time.deltaTime,o["autoplace:timer"]=a)}else o["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(H.active?.isTrackingImages){console.warn("Scene Placement is disabled while images are being tracked");return}let i=this._hits[0];if(e&&e.origin instanceof dm){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),hi._hasPlaced=!0,this.useXRAnchor&&this.onCreateAnchor(H.active,i),this.context.xr)for(const n of this.context.xr.controllers)n.cancelHitTestSource()};onSetScale(){if(!hi._hasPlaced)return;const e=H.active?.rig?.gameObject;if(e){const t=H.active?.rigScale||1,i=1/this._arScale*t,n=new c.Matrix4().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)S.addComponent(e.originalObject,e.comp)}async onCreateAnchor(e,t){if(t.createAnchor===void 0){console.warn("Hit does not support creating an anchor",t),A()&&he("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 c.Vector3(0,1,0);lookPoint=new c.Vector3;worldUpVec=new c.Vector3(0,1,0);applyViewBasedTransform(e){const t=this.context.mainCamera,i=e,n=t.worldPosition,o=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=o.y,e.lookAt(n))}onApplyPose(e){const t=H.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(VO),t.matrix.premultiply(this._startOffset),t.matrix.decompose(t.position,t.quaternion,t.scale),i.add(t)}}class Ad{static up=new c.Vector3(0,1,0);static zero=new c.Vector3(0,0,0);static one=new c.Vector3(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 c.Matrix4,this.plane=new c.Plane,this.plane.setFromNormalAndCoplanarPoint(Ad.up,Ad.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:Ht.Early}),this.context.input.addEventListener("pointerdown",this.onPointerDownLate,{queue:Ht.Late}),this.context.input.addEventListener("pointerup",this.onPointerUpEarly,{queue:Ht.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:Ht.Early}),this.context.input.removeEventListener("pointerdown",this.onPointerDownLate,{queue:Ht.Late}),this.context.input.removeEventListener("pointerup",this.onPointerUpEarly,{queue:Ht.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=exports.DeviceUtilities.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 o=this.prev.get(i.identifier);if(o){const r=this.getPositionOnPlane(i.clientX,i.clientY);o.x=r.x,o.z=r.z,o.screenx=i.clientX,o.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),o=n.x-i.x,r=n.z-i.z;if(o===0&&r===0)return;this.oneFingerDrag&&this.addMovement(o,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),o=this.prev.get(i.identifier);if(!n||!o)return;if(this.twoFingerRotate){const r=Math.atan2(t.clientY-i.clientY,t.clientX-i.clientX),a=Math.atan2(n.screeny-o.screeny,n.screenx-o.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),h=n.screenx-o.screenx,d=n.screeny-o.screeny,u=Math.sqrt(h*h+d*d),p=l-u;Math.abs(p)>2&&this.addScale(p)}n.screenx=t.clientX,n.screeny=t.clientY,o.screenx=i.clientX,o.screeny=i.clientY}}};_raycaster=new c.Raycaster;_intersection=new c.Vector3;_screenPos=new c.Vector3;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 c.Matrix4;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 zs=w("debugautosync"),Af=Symbol("syncerId");class $O{_syncers={};getOrCreateSyncer(e){if(!e.guid)return null;if(this._syncers[e.guid])return this._syncers[e.guid];const t=new WO(e);return t[Af]=e.guid,this._syncers[t[Af]]=t,t}removeSyncer(e){delete this._syncers[e[Af]]}}const fg=new $O;class WO{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||(zs&&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];zs&&console.log("SEND",this.comp.guid,this.networkingKey),e.send(this.networkingKey,{guid:this.comp.guid,property:t,data:i},Xi.Queued),delete this.changedProperties[t]}};onHandleReceiving=e=>{if(zs&&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 GO(s,e){let t=e!==s;return!t&&s&&e&&(Array.isArray(s)&&Array.isArray(e)||typeof s=="object"&&typeof e=="object")&&(t=!0),t}const Ul=Symbol("AutoSyncHandler");function HO(s){if(s[Ul])return s[Ul];const e=fg.getOrCreateSyncer(s);return e?.init(s),s[Ul]=e,e}function qO(s){const e=s[Ul];e&&(fg.removeSyncer(e),e.destroy(),delete s[Ul])}const pg=function(s=null){return function(e,t){let i="";typeof t=="string"?i=t:i=t.name;let n=null,o;typeof s=="string"?o=e[s]:typeof s=="function"&&(o=s),o==null&&(A()||zs)&&s!=null&&console.warn('syncField: no callback function found for property "'+i+'"','"'+s+'"');const r=e,a=r.__internalAwake;if(typeof a!="function"){(zs||A())&&console.error('@syncField can currently only used on Needle Engine Components, custom object of type "'+e?.constructor?.name+'" is not supported',e);return}zs&&console.log(i);const l=Symbol(i);r.__internalAwake=function(){if(this[l]!==void 0)return;if(this[l]=this[i],n=fg.getOrCreateSyncer(this),Object.getOwnPropertyDescriptor(this,i)?.set===void 0){let u=!1;Object.defineProperty(this,i,{set:function(p){const m=this[l];if(this[l]=p,u){(A()||zs)&&console.warn("Recursive call detected",i);return}u=!0;try{const y=GO(p,m);zs&&console.log("SyncField assignment",i,"changed?",y,p,o),y&&o?.call(this,p,m)!==!1&&HO(this)?.notifyChanged(i,p)}finally{u=!1}},get:function(){return this[l]},configurable:!0,enumerable:!0})}n?.init(this),a.call(this)};const h=r.__internalDestroy;r.__internalDestroy=function(){qO(this),h.call(this)}}};var XO=Object.defineProperty,mu=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&XO(e,t,n),n};const Lt=w("debugplayersync"),gu=class Z0 extends k{static async setupFrom(e,t){const i=Y.getOrCreateFromUrl(e);if(!i.asset){const r=await i.loadAssetAsync();r&&S.getOrAddComponent(r,Yi)}const n=new Z0;n._internalInit(t),n.asset=i;const o=new c.Object3D;return o.guid=e,S.addComponent(o,n),n}autoSync=!0;asset;onPlayerSpawned;_localInstance;awake(){this.watchTabVisible(),this.onPlayerSpawned||(this.onPlayerSpawned=new oe)}onEnable(){this.context.connection.beginListen(Q.RoomStateSent,this.onJoinedRoom),this.context.connection.beginListen(Q.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(Q.LeftRoom,this.destroyInstance),this.context.connection.isInRoom&&this.onJoinedRoom()}onDisable(){this.context.connection.stopListen(Q.RoomStateSent,this.onJoinedRoom),this.context.connection.stopListen(Q.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(Q.LeftRoom,this.destroyInstance)}onJoinedRoom=()=>{Lt&&console.log("PlayerSync.joinedRoom. autoSync is set to "+this.autoSync),this.autoSync&&this.getInstance()};async getInstance(){if(this._localInstance)return this._localInstance;if(Lt&&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=S.getComponentsInChildren(e,Yi);if(Lt&&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!"),S.destroySynced(e)}else this._localInstance=void 0,console.warn("PlayerSync: failed instantiating asset!");return this._localInstance}destroyInstance=()=>{this._localInstance?.then(e=>{Lt&&console.log("PlayerSync.destroyInstance",e),uc(e,this.context.connection,!0,{saveInRoom:!1})}),this._localInstance=void 0};watchTabVisible(){window.addEventListener("visibilitychange",e=>{if(document.visibilityState==="visible")for(let t=Yi.all.length-1;t>=0;t--){const i=Yi.all[t];(!i.owner||!this.context.connection.userIsInRoom(i.owner))&&i.doDestroy()}})}};mu([f()],gu.prototype,"autoSync");mu([f(Y)],gu.prototype,"asset");mu([f(oe)],gu.prototype,"onPlayerSpawned");let mg=gu;var J0=(s=>(s.OwnerChanged="ownerChanged",s))(J0||{});const Dp=class ut extends k{static _all=[];static get all(){return ut._all}static _local=[];static get local(){return ut._local}static getFor(e){if(e instanceof c.Object3D)return S.getComponentInParent(e,ut);if(e instanceof k)return S.getComponentInParent(e.gameObject,ut)}static isLocalPlayer(e){return ut.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 oe;onFirstOwnerChangeEvent=new oe;hasOwner=!1;owner;dontDestroy=!1;get isLocalPlayer(){return this.owner===this.context.connection.connectionId}onOwnerChange(e,t){Lt&&console.log(`PlayerSync.onOwnerChange: ${t} → ${e} (me: ${this.context.connection.connectionId})`);const i=ut._local.indexOf(this);i>=0&&ut._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){ut._local.push(this);const r=new CustomEvent("local-owner-changed",{detail:n});this.dispatchEvent(r)}const o=new CustomEvent("owner-changed",{detail:n});this.dispatchEvent(o),ut.dispatchEvent("ownerChanged",o)}awake(){ut.all.push(this),Lt&&console.log("Registered new PlayerState",this.guid,ut.all.length-1,ut.all),this.context.connection.beginListen(Q.UserLeftRoom,this.onUserLeftRoom)}async start(){Lt&&console.log("PLAYERSTATE.START, owner: "+this.owner,this.context.connection.usersInRoom([])),this.owner?(this.context.connection.isInRoom||await Ln(300),this.context.connection.userIsInRoom(this.owner)==!1&&(Lt&&console.log(`PlayerSync.start → doDestroy "${this.name}" because user "${this.owner}" is not in room anymore...`,"Currently in room:",...this.context.connection.usersInRoom()),this.doDestroy())):this.owner||(Lt&&console.warn("PlayerState.start → owner is undefined!",this.name),setTimeout(()=>{!this.destroyed&&!this.owner?this.dontDestroy?Lt&&console.warn("PlayerState.start → owner is still undefined but dontDestroy is set to true",this.name):(Lt&&console.warn(`PlayerState.start → owner is still undefined: destroying "${this.name}" instance now`),this.doDestroy()):Lt&&console.log("PlayerState.start → owner is assigned",this.owner)},2e3))}doDestroy(){Lt&&console.log("PlayerSync.doDestroy → syncDestroy",this.name),uc(this.gameObject,this.context.connection,!0,{saveInRoom:!1})}onDestroy(){if(Lt&&console.warn("PlayerState.onDestroy",this.owner),this.context.connection.stopListen(Q.UserLeftRoom,this.onUserLeftRoom),ut.all.splice(ut.all.indexOf(this),1),this.isLocalPlayer){const e=ut._local.indexOf(this);e>=0&&ut._local.splice(e,1)}}onUserLeftRoom=e=>{if(e.userId===this.owner){Lt&&console.log("PLAYERSYNC LEFT",this.owner),this.doDestroy();return}}};mu([pg(Dp.prototype.onOwnerChange)],Dp.prototype,"owner");let Yi=Dp;var QO=Object.defineProperty,ka=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&QO(e,t,n),n};class Bn extends k{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&&(exports.DeviceUtilities.isMobileDevice()||this.context.menu.showQRCodeButton(!0))}}ka([f()],Bn.prototype,"position");ka([f()],Bn.prototype,"showNeedleLogo");ka([f()],Bn.prototype,"showSpatialMenu");ka([f()],Bn.prototype,"createFullscreenButton");ka([f()],Bn.prototype,"createMuteButton");ka([f()],Bn.prototype,"createQRCodeButton");var YO=Object.defineProperty,gg=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&YO(e,t,n),n};const Ja=w("debugwebxr"),T_=new c.Quaternion().setFromAxisAngle(new c.Vector3(0,1,0),Math.PI);class Ys extends k{head;leftHand;rightHand;_leftHandMeshes;_rightHandMeshes;_syncTransforms;async onEnterXR(e){if(!this.activeAndEnabled)return;Ja&&console.warn("AVATAR ENTER XR",this.guid,this.sourceId,this,this.activeAndEnabled),this._syncTransforms&&(this._syncTransforms.length=0),await this.prepareAvatar();const t=Yi.getFor(this);if(t?.owner){const i=this.gameObject.addComponent(xe);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(xe);t&&t.destroy()}onUpdateXR(e){if(!this.activeAndEnabled)return;const t=Yi.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 h=S.getComponentsInChildren(this.head.asset,Ti);for(const d of h)d.enabled=!1,d.gameObject.visible=!1}}const n=e.xr.leftController,o=this.leftHand?.asset;n&&o?(o.position.copy(n.gripPosition),o.quaternion.copy(n.gripQuaternion),o.quaternion.multiply(T_),o.visible=n.isTracking,this.updateHandVisibility(n,o,this._leftHandMeshes)):o&&o.visible&&(o.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(T_),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(o=>{es(o,!n)})}}updateRemoteAvatarVisibility(){if(this.context.connection.isConnected){const e=Yi.getFor(this);if(e&&e.isLocalPlayer==!1){const t=H.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=S.getComponentsInChildren(this.head.asset,Ti);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};Yb.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 c.Object3D&&(this.head=new Y("",this.sourceId,this.head));else{const e=new c.Object3D;e.name="Head";const t=ir.createPrimitive(Go.Cube);e.add(t),this.gameObject.add(e),this.head=new Y("",this.sourceId,e),Ja&&console.log("Create head",e)}if(this.rightHand)this.rightHand instanceof c.Object3D&&(this.rightHand=new Y("",this.sourceId,this.rightHand));else{const e=new c.Object3D;e.name="Right Hand",this.gameObject.add(e),this.rightHand=new Y("",this.sourceId,e),Ja&&console.log("Create right hand",e)}if(this.leftHand)this.leftHand instanceof c.Object3D&&(this.leftHand=new Y("",this.sourceId,this.leftHand));else{const e=new c.Object3D;e.name="Left Hand",this.gameObject.add(e),this.leftHand=new Y("",this.sourceId,e),Ja&&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)}),Yi.isLocalPlayer(this.gameObject)&&(this._syncTransforms=S.getComponentsInChildren(this.gameObject,nn))}async loadAvatarObjects(e,t,i){const n=e.loadAssetAsync(),o=t.loadAssetAsync(),r=i.loadAssetAsync(),a=new Array;n&&a.push(n),o&&a.push(o),r&&a.push(r);const l=await Kp(a);Ja&&console.log("Avatar loaded results:",l)}}gg([f(Y)],Ys.prototype,"head");gg([f(Y)],Ys.prototype,"leftHand");gg([f(Y)],Ys.prototype,"rightHand");var KO=Object.defineProperty,yu=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&KO(e,t,n),n};const ks=w("debugwebxr"),Es=new Array;class cs extends k{createControllerModel=!0;createHandModel=!0;customLeftHand;customRightHand;static factory=new q.XRControllerModelFactory;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:i}=e;if(this.createControllerModel||this.createHandModel){if(i.hand){if(this.createHandModel){const n=await this.loadHandModel(this,i);if(!n||!i.connected||!i.isHand){n?.handObject&&Fr(n.handObject,!1),n?.handObject?.destroy();return}this._models.push({controller:i,model:n.handObject,handmesh:n.handmesh}),this._models.sort((o,r)=>o.controller.index-r.controller.index),this.scene.add(n.handObject),i.model=n.handObject}}else if(this.createControllerModel){const n=await i.getModelUrl();if(n){const o=await this.loadModel(i,n);if(!o||!i.connected||i.isHand)return;this._models.push({controller:i,model:o}),this._models.sort((r,a)=>r.controller.index-a.controller.index),this.scene.add(o),o.traverse(r=>{r.layers.set(2),r.matrixAutoUpdate=!1,r.updateMatrix()}),i.model=o}else i.targetRayMode!=="transient-pointer"&&console.warn("XRControllerModel: no model found for "+i.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&&(Fr(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&&(Fr(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(H.active&&(ks&&(Es[0]=Date.now()),this.updateRendering(H.active),ks)){const e=Date.now()-Es[0];Es.push(e),Es.length>=30&&(Es[0]=0,Es.reduce((t,i)=>t+i,0)/Es.length,Es.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){ks&&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 o=e.referenceSpace,r=this.context.renderer.xr.getHand(n.index);if(o&&e.frame.getJointPose){for(const a of n.inputSource.hand.values()){const l=r.joints[a.jointName];if(l){const h=n.getHandJointPose(a);if(h){const d=h.transform.position,u=h.transform.orientation;l.position.copy(d),l.quaternion.copy(u),l.matrixAutoUpdate=!1}l.visible=h!=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(Zr))}}}}async loadModel(e,t){if(!e.connected)return console.warn("XRControllerModel.onXRControllerAdded: controller is not connected anymore",e.side),null;const n=await Y.getOrCreate("",t).instantiate();return Fr(n),H.active?.isPassThrough&&n.traverseVisible(o=>{this.makeOccluder(o)}),n}async loadHandModel(e,t){const i=this.context,n=i.renderer.xr.getHand(t.index);n||(ks?B.DrawLabel(t.rayWorldPosition,"No hand found for index "+t.index,.05,5):console.warn("No hand found for index "+t.index));const o=new q.GLTFLoader;Tm(o,i),await Rd(o,i,this.sourceId??"");const r=Zm(o);let a="";const l=t.side==="left"?this.customLeftHand:this.customRightHand;l?(a=l.url.split(".").slice(0,-1).join("."),o.setPath("")):(a=t.inputSource.handedness==="left"?"left":"right",o.setPath("https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/"));const h=new c.Object3D;Fr(h);const d=new q.XRHandMeshModel(h,n,o.path,a,o,u=>{const p=r?.gltf;p?.scene.children?.length===0&&(p.scene.children[0]=u),r?.gltf&&en().createBuiltinComponents(e.context,e.sourceId||a,r.gltf,null,r),u.traverse(m=>{m.layers.set(2),H.active?.isPassThrough&&!l&&this.makeOccluder(m),m instanceof c.Mesh&&ne.NEEDLE_progressive.assignMeshLOD(m,0)}),t.connected||(ks&&B.DrawLabel(t.rayWorldPosition,"Hand is loaded but not connected anymore",.05,5),u.removeFromParent())});if(ks&&h.add(new c.AxesHelper(.5)),t.inputSource.hand){ks&&console.log(t.inputSource.hand);for(const u of t.inputSource.hand.values())if(n.joints[u.jointName]===void 0){const p=new c.Group;p.matrixAutoUpdate=!1,p.visible=!0,n.joints[u.jointName]=p,n.add(p)}}else ks&&B.DrawLabel(t.rayWorldPosition,"No inputSource.hand found for index "+t.index,.05,5);return{handObject:h,handmesh:d}}makeOccluder(e){if(e instanceof c.Mesh){let t=e.material;t instanceof c.Material&&(t=e.material=t.clone(),t.depthWrite=!0,t.depthTest=!0,t.colorWrite=!1,e.receiveShadow=!1,e.renderOrder=-100)}}}yu([f()],cs.prototype,"createControllerModel");yu([f()],cs.prototype,"createHandModel");yu([f(Y)],cs.prototype,"customLeftHand");yu([f(Y)],cs.prototype,"customRightHand");class _u extends k{}var ZO=Object.defineProperty,ro=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&ZO(e,t,n),n};const Lf=w("debugwebxr");class gi extends k{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=V(i.x,0,i.y);n.multiplyScalar(this.context.time.deltaTimeUnscaled*this.movementSpeed);const o=Ie(t);n.multiplyScalar(o.x),n.applyQuaternion(e.xr.poseOrientation),n.y=0,n.applyQuaternion(t.worldQuaternion),A()&&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 n=e.getStick("xr-standard-thumbstick").x;if(this._didApplyRotation)Math.abs(n)<.3&&(this._didApplyRotation=!1);else if(Math.abs(n)>.5){this._didApplyRotation=!0;const o=n>0?1:-1,r=X(this.context.mainCamera).clone();t.rotateY(o*D.toRadians(this.rotationStep));const l=X(this.context.mainCamera).clone().sub(r);l.y=0,t.position.sub(l)}}_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 o=e.getGesture("pinch");o&&(i=o.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 q.GroundedSkybox){const r=n.normal?.dot(V(0,1,0));if(r!==void 0&&r<.4)return}let o=n?.point;if(!o&&!this.useTeleportTarget){this._plane||(this._plane=new c.Plane(new c.Vector3(0,1,0),0));const r=t.worldPosition;this._plane.setFromNormalAndCoplanarPoint(new c.Vector3(0,1,0),r);const a=e.ray;o=r.clone(),this._plane.intersectLine(new c.Line3(a.origin,V(a.direction).multiplyScalar(1e4).add(a.origin)),o),o.distanceTo(r)>t.scale.x*10&&(o=null)}if(o){if(this.useTeleportTarget&&!S.getComponentInParent(n.object,_u))return;const r=o.clone();if(Lf&&B.DrawSphere(o,.025,16711680,5),this.context.mainCamera?.position){const l=this.context.xr?.getUserOffsetInRig();l&&(l.y=0,r.sub(l),Lf&&B.DrawWireSphere(l.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 o=i.rayWorldPosition,r=i.rayWorldQuaternion;n.position.copy(o),n.quaternion.copy(r);const a=e.rigScale,l=this.usePinchToTeleport&&i.isTeleportGesture,h=this._lastHitDistances[t],d=this._hitDistances[t]!=null,u=h??a;n.scale.set(a,a,u),n.visible=!0,n.layers.disableAll(),n.layers.enable(2);let p=n.material.opacity;l?p=1:this.showHits&&u<e.rigScale*.5?p=0:i.getButton("primary")?.pressed?p=.5:p=d?.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],o=!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,o=!1);const a=this.context.time.smoothedFps>=59?1:10;if((this.context.time.frame+i.index)%a!==0&&(o=!1),!o){const d=this._hitDiscs[t];d&&d.visible&&d.hit&&this.updateHitPointerPosition(i,d,d.hit.distance);continue}const l=this.context.physics.raycastFromRay(i.ray,{testObject:this.hitPointRaycastFilter,precise:!1});let h=l.find(d=>this.usePinchToTeleport&&i.isTeleportGesture?!0:this.isObjectWithInteractiveComponent(d.object));if(h||(h=l[0]),n&&(n.controller=i,n.hit=h),this._hitDistances[t]=h?.distance||null,h){this._lastHitDistances[t]=h.distance;const d=e.rigScale??1;Lf&&(B.DrawWireSphere(h.point,.025*d,16711680),B.DrawLabel(V(0,.2,0).add(h.point),h.object.name,.02,0)),n||(n=this.createHitPointObject(),this._hitDiscs[t]=n),n.hit=h,n.visible=h.distance>d*.05;let u=.01*(d+h.distance);const p=i.getButton("primary")?.pressed;p&&(u*=1.1),n.scale.set(u,u,u),n.layers.set(2);let m=n.material.opacity;if(p?m=1:m=h.distance<.15*d?.2:.6,n.material.opacity=D.lerp(n.material.opacity,m,this.context.time.deltaTimeUnscaled/.1),n.visible){if(h.normal){this.updateHitPointerPosition(i,n,h.distance);const y=h.normal.applyQuaternion(ue(h.object));n.quaternion.setFromUnitVectors(JO,y)}else this.updateHitPointerPosition(i,n,h.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 Cd(e)||e.isUI===!0?!0:e.isScene?!1:e.parent?this.isObjectWithInteractiveComponent(e.parent,t+1):!1}updateHitPointerPosition(e,t,i){const n=V(e.rayWorldPosition);n.add(V(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 c.Mesh(new c.SphereGeometry(.3,6,6),new c.MeshBasicMaterial({color:15658734,opacity:.7,transparent:!0,depthTest:!1,depthWrite:!1,side:c.DoubleSide}));return e.layers.disableAll(),e.layers.enable(2),e}createRayLineObject(){const e=new q.Line2;e.layers.disableAll(),e.layers.enable(2);const t=new q.LineGeometry;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 o=new q.LineMaterial({color:16777215,vertexColors:!0,worldUnits:!0,linewidth:.004,transparent:!0,depthWrite:!1,blending:c.AdditiveBlending,dashed:!1});return e.material=o,e}}ro([f()],gi.prototype,"movementSpeed");ro([f()],gi.prototype,"rotationStep");ro([f()],gi.prototype,"useTeleport");ro([f()],gi.prototype,"usePinchToTeleport");ro([f()],gi.prototype,"useTeleportTarget");ro([f()],gi.prototype,"useTeleportFade");ro([f()],gi.prototype,"showRays");ro([f()],gi.prototype,"showHits");const JO=new c.Vector3(0,1,0);var eM=Object.defineProperty,lt=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&eM(e,t,n),n};const el=w("debugwebxr"),tM=w("debugusdz"),Je=class Wr extends k{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(){H.getXRSync(this.context)}onEnable(){window.location.protocol!=="https:"&&he('<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&&(S.findObjectOfType(Tn)||(el&&console.log("WebXR: Adding USDZExporter"),this._usdzExporter=S.addComponent(this.gameObject,Tn),this._usdzExporter.objectToExport=this.context.scene,this._usdzExporter.autoExportAnimations=!0,this._usdzExporter.autoExportAudioSources=!0)),this.handleCreatingHTML(),this.handleOfferSession(),this.defaultAvatar===!0&&(el&&console.warn("WebXR: No default avatar set, using static default avatar"),this.defaultAvatar=new Y("https://cdn.needle.tools/static/avatars/DefaultAvatar.glb")),this.defaultAvatar&&(this._playerSync=this.gameObject.getOrAddComponent(mg),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 H.isVRSupported()&&this.createVRButton?H.offerSession("immersive-vr","default",this.context):this.createARButton&&await H.isARSupported()&&this.createARButton?H.offerSession("immersive-ar","default",this.context):!1}get session(){return H.active??null}get sessionMode(){return H.activeMode??null}get arSessionRoot(){return this._activeWebARSessionRoot}async enterVR(e){return H.start("immersive-vr",e,this.context)}async enterAR(e){return H.start("immersive-ar",e,this.context)}exitXR(){H.stop()}_exitXRMenuButton;_previousXRState=0;_spatialGrabRaycaster;_activeWebARSessionRoot=null;get isActiveWebXR(){return!Wr.activeWebXRComponent||Wr.activeWebXRComponent===this}onBeforeXR(e,t){if(!this.isActiveWebXR){console.warn(`WebXR: another WebXR component is already active (${Wr.activeWebXRComponent?.name}). This is ignored: ${this.name}`);return}Wr.activeWebXRComponent=this,e=="immersive-ar"&&this.useDepthSensing&&(t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.push("depth-sensing"))}async onEnterXR(e){if(!this.isActiveWebXR)return;el&&console.log("WebXR onEnterXR"),this._previousXRState=It.Global.Mask;const t=e.xr.isVR;if(It.Global.Set(t?wn.VR:wn.AR),e.xr.isAR){let i=S.findObjectOfType(hi);if(!i)if(this.usePlacementReticle){const n=new c.Object3D;for(const o of this.context.scene.children)n.add(o);this.context.scene.add(n),i=S.addComponent(n,hi),this._createdComponentsInSession.push(i)}else(el||A())&&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=S.findObjectOfType(Qo)??void 0,this._spatialGrabRaycaster||(this._spatialGrabRaycaster=this.gameObject.addComponent(Qo))),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){It.Global.Set(this._previousXRState),this._playerSync?.destroyInstance();for(const t of this._createdComponentsInSession)t.destroy();this._createdComponentsInSession.length=0,this._activeWebARSessionRoot=null,this.handleOfferSession(),lc(1).then(()=>Wr.activeWebXRComponent=null)}}setDefaultMovementEnabled(e){let t=this.gameObject.getComponent(gi);return!t&&e&&(t=this.gameObject.addComponent(gi),this._createdComponentsInSession.push(t)),t&&(t.enabled=e),t}setDefaultControllerRenderingEnabled(e){let t=this.gameObject.getComponent(cs);return!t&&e&&(t=this.gameObject.addComponent(cs),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=>{el&&console.log("WebXR.onAvatarSpawned",e);let t=S.getComponentInChildren(e,Ys);t??=S.addComponent(e,Ys)};getButtonsContainer(){return this.getButtonsFactory()}getButtonsFactory(){return this._buttonFactory||(this._buttonFactory=qs.getOrCreate()),this._buttonFactory}_buttonFactory;handleCreatingHTML(){if(this.createARButton||this.createVRButton||this.useQuicklookExport){if((exports.DeviceUtilities.isiOS()&&exports.DeviceUtilities.isSafari()||tM)&&this.useQuicklookExport){const t=S.findObjectOfType(Tn);if(!t||t&&t.allowCreateQuicklookButton){const i=this.getButtonsFactory().createQuicklookButton();this.addButton(i,50)}}if(this.createARButton){const t=this.getButtonsFactory().createARButton();this.addButton(t,50)}if(this.createVRButton){const t=this.getButtonsFactory().createVRButton();this.addButton(t,50)}}if(this.createSendToQuestButton&&!exports.DeviceUtilities.isQuest()&&H.isVRSupported().then(t=>{if(!t){const i=this.getButtonsFactory().createSendToQuestButton();this.addButton(i,50)}}),this.createQRCode){const t=yc(Bn);if(t&&t.createQRCodeButton===!1)A()&&console.warn("WebXR: QRCode button is disabled in the Needle Menu component");else if(!exports.DeviceUtilities.isMobileDevice()){const i=Qi.getOrCreate().createQRCode();this.addButton(i,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}};lt([f()],Je.prototype,"createVRButton");lt([f()],Je.prototype,"createARButton");lt([f()],Je.prototype,"createSendToQuestButton");lt([f()],Je.prototype,"createQRCode");lt([f()],Je.prototype,"useDefaultControls");lt([f()],Je.prototype,"showControllerModels");lt([f()],Je.prototype,"showHandModels");lt([f()],Je.prototype,"usePlacementReticle");lt([f(Y)],Je.prototype,"customARPlacementReticle");lt([f()],Je.prototype,"usePlacementAdjustment");lt([f()],Je.prototype,"arScale");lt([f()],Je.prototype,"useXRAnchor");lt([f()],Je.prototype,"autoPlace");lt([f()],Je.prototype,"autoCenter");lt([f()],Je.prototype,"useQuicklookExport");lt([f()],Je.prototype,"useDepthSensing");lt([f()],Je.prototype,"useSpatialGrab");lt([f(Y)],Je.prototype,"defaultAvatar");let bu=Je;const Rh=w("debugusdzbehaviours");class yg{get extensionName(){return"Behaviour"}behaviours=[];addBehavior(e){this.behaviours.push(e)}addAudioClip(e){if(!e||typeof e!="string")return"";const i="audio/"+dr.getName(e);return this.audioClips.push({clipUrl:e,filesKey:i}),i}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=>{S.foreachComponent(i,n=>{const o=n;if(typeof o.createBehaviours=="function"||typeof o.beforeCreateDocument=="function"||typeof o.afterCreateDocument=="function"||typeof o.afterSerialize=="function"){this.behaviourComponents.push(o);const r=o.beforeCreateDocument?.call(o,this,e);r instanceof Promise&&t.push(r)}},!1)}),Rh&&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 u of this.behaviourComponents)typeof u.afterCreateDocument=="function"&&u.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,o=new Set,r=Rh;let a=`graph LR
|
|
1261
|
+
`))}for(const N of R){const K=o.get(N);K&&U.set(N,K)}return U},m=function(R){const U=p(R),N=l(U);return h(U,N,R)};const y=n.skinnedMesh.skeleton,b=new Array,g=[],v=[];for(const R of y.bones){g.push(R),v.push(R.uuid);const U=y.boneInverses[y.bones.indexOf(R)];b.push({bone:R,inverse:U})}let _=1e4;for(;v.length<y.bones.length&&_-- >0;)for(const R of g){const U=R.children;for(const N of U)if(v.indexOf(N.uuid)===-1&&y.bones.indexOf(N)!==-1){g.push(N),v.push(N.uuid);const K=y.boneInverses[y.bones.indexOf(N)];b.push({bone:N,inverse:K})}}_<=0&&console.error("Failed to sort bones in skinned mesh",n.skinnedMesh,y.bones,v);for(const R of z0(y.bones))b.push({bone:R,inverse:R.matrixWorld.clone().invert()});const x=b[0].bone.parent;x||console.error("No bone parent found for skinned mesh during USDZ export",n.skinnedMesh),b.sort((R,U)=>na(R.bone,x)>na(U.bone,x)?1:-1);const T=t.quickLookCompatible,O=[],M=[],E=[],j=[];for(const{bone:R}of b){if(T){const U=R.scale;U.x==0&&(U.x=1e-5),U.y==0&&(U.y=1e-5),U.z==0&&(U.z=1e-5),O.push(new c.Matrix4().compose(R.position,R.quaternion,R.scale))}else O.push(R.matrix.clone());M.push(R.position),E.push(R.quaternion),j.push(R.scale)}const L=b.map(R=>'"'+na(R.bone,x)+'"').join(", "),z=b.map(R=>C_(R.inverse.clone().invert())).join(", ");e.beginBlock('def Skeleton "Rig"'),e.appendLine(`uniform matrix4d[] bindTransforms = [${z}]`),e.appendLine(`uniform token[] joints = [${L}]`),e.appendLine('uniform token purpose = "guide"'),e.appendLine(`uniform matrix4d[] restTransforms = [${O.map(R=>C_(R)).join(", ")}]`);const $=m(b.map(R=>R.bone));if(bn){let R=1e7,U=0;for(const N of $.position?.keys()??[])R=Math.min(R,N),U=Math.max(U,N);console.log("Time samples",R,U,$)}if(e.beginBlock('def SkelAnimation "_anim"'),e.appendLine(`uniform token[] joints = [${L}]`),e.appendLine(`quatf[] rotations = [${u(E)}]`),$&&$.quaternion){e.beginBlock("quatf[] rotations.timeSamples = {","");const R=a($.quaternion);for(const U of R)e.appendLine(U);e.closeBlock()}if(e.appendLine(`half3[] scales = [${d(j)}]`),$&&$.scale){e.beginBlock("half3[] scales.timeSamples = {","");const R=r($.scale);for(const U of R)e.appendLine(U);e.closeBlock()}if(e.appendLine(`float3[] translations = [${d(M)}]`),$&&$.position){e.beginBlock("float3[] translations.timeSamples = {","");const R=r($.position);for(const U of R)e.appendLine(U);e.closeBlock()}e.closeBlock(),e.closeBlock()}}onSerialize(e,t){if(!this.model)return;const i=this.animationData.get(this.object);if(i)for(let d=0;d<i.length;d++)i[d]===void 0&&(i[d]=new ke(null,this.object,null));const n=this.ext;this.skinnedMeshExport(e,t,n);const o=this.object,r=this.model,a=this.animationData.get(o);if(!a||o.isSkinnedMesh)return;Ap&&console.log("SERIALIZE",this.model.name,this.object.type,a);const l=Intl.NumberFormat("en-US",{maximumFractionDigits:3,minimumFractionDigits:0,useGrouping:!1});function h(d,u){if(d.some(m=>m&&{position:m.pos,rotation:m.rot,scale:m.scale}[u])){switch(u){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 m=0;m<d.length;m++){const y=d[m];if(!y)continue;const b=n.getStartTimeByClip(y.clip),g=y.getSortedTimesArray(u==="position",u==="rotation",u==="scale");if(!g||g.length===0){console.error("got an animated object but no time values?",o,y);continue}const v=!y.clip,_=u==="position"&&(y.pos||v),x=u==="rotation"&&(y.rot||v),T=u==="scale"&&(y.scale||v);if(_||x||T){const O=y.clip?.name??"rest",M=y.getDuration();bn&&console.log("Write .timeSamples:",O,b,M,d),e.appendLine("# "+O+": start="+l.format(b*ke.frameRate)+", length="+l.format(M*ke.frameRate)+", frames="+y.getFrames())}if(_)for(const{time:O,translation:M}of y.getValues(g,!0,!1,!1)){const j=`${l.format((b+O)*ke.frameRate)}: (${te(M.x)}, ${te(M.y)}, ${te(M.z)}),`;e.appendLine(j)}if(x)for(const{time:O,rotation:M}of y.getValues(g,!1,!0,!1)){const j=`${l.format((b+O)*ke.frameRate)}: (${te(M.w)}, ${te(M.x)}, ${te(M.y)}, ${te(M.z)}),`;e.appendLine(j)}if(T)for(const{time:O,scale:M}of y.getValues(g,!1,!1,!0)){const j=`${l.format((b+O)*ke.frameRate)}: (${te(M.x)}, ${te(M.y)}, ${te(M.z)}),`;e.appendLine(j)}}e.closeBlock()}}h(a,"position"),h(a,"rotation"),h(a,"scale")}}const jO=w("debugusdz");class dr{static getName(e){const t=e.split(".").pop();let n=e.split(".").slice(0,-1).join(".").split("/").pop()?.replace(".","_");return n||(n="Audio_"+Math.random().toString(36).substring(2,15)),ji(n)+"."+t}get extensionName(){return"Audio"}files=new Array;onExportObject(e,t,i){const n=S.getComponents(e,pi);if(n.length)for(const o of n){if(!o.clip||typeof o.clip!="string"||!o.playOnAwake)continue;const r=o.clip.split("/").pop()||"Audio",a=dr.getName(o.clip),l=ji(a);if(!this.files.some(h=>h.path===o.clip)){this.files.push({path:o.clip,name:a});const h=a.toLowerCase();i.quickLookCompatible&&!h.endsWith(".mp3")&&!h.endsWith(".wav")&&!h.endsWith(".m4a")&&console.error("Audio file "+o.clip+" from "+o.name+" is not an MP3 or WAV file. QuickLook may not support playing it.")}i.quickLookCompatible||t.addEventListener("serialize",(h,d)=>{h.appendLine(),h.beginBlock(`def SpatialAudio "${l}"`,"(",!1),h.appendLine(`displayName = "${r}"`),h.closeBlock(")"),h.beginBlock(),h.appendLine(`uniform asset filePath = @audio/${a}@`),h.appendLine(`uniform token auralMode = "${o.spatialBlend>0?"spatial":"nonSpatial"}"`),h.appendLine(`uniform token playbackMode = "${o.loop?"loopFromStage":"onceFromStart"}"`),h.appendLine(`uniform float gain = ${o.volume}`),h.closeBlock()})}}async onAfterSerialize(e){for(const t of this.files){const i="audio/"+t.name;if(e.files[i]){jO&&console.warn("Audio file with name "+i+" already exists in the context. Skipping.");continue}const r=await(await(await fetch(t.path)).blob()).arrayBuffer(),a=new Uint8Array(r);e.files[i]=a}}}var BO=Object.defineProperty,Ee=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&BO(e,t,n),n};const E_=w("debugusdzbehaviours");function kc(s){s&&(s.getComponentInParent(ma)||(A()&&console.debug('Raycaster on "'+s.name+'" was automatically added, because no raycaster was found in the parent hierarchy.'),s.addComponent(fi)))}class ur extends k{object;target;duration=1;relativeMotion=!1;coroutine=null;targetPos=new c.Vector3;targetRot=new c.Quaternion;targetScale=new c.Vector3;start(){kc(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=X(this.object).clone(),t=X(this.target).clone(),i=ue(this.object).clone(),n=ue(this.target).clone(),o=Ie(this.object).clone(),r=Ie(this.target).clone(),a=e.distanceTo(t),l=i.angleTo(n),h=o.distanceTo(r);if(a<.01&&l<.01&&h<.01){ot(this.object,t),Ji(this.object,n),aa(this.object,r),this.coroutine=null;return}let d=0,u=0;for(;d<1;)d+=this.context.time.deltaTime/this.duration,d>1&&(d=1),u=d<.5?4*d*d*d:1-Math.pow(-2*d+2,3)/2,this.targetPos.lerpVectors(e,t,u),this.targetRot.slerpQuaternions(i,n,u),this.targetScale.lerpVectors(o,r,u),ot(this.object,this.targetPos),Ji(this.object,this.targetRot),aa(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(),o=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(o),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 gt("Move to "+this.target?.name,wt.tapTrigger(this.gameObject),le.transformAction(this.object,this.target,this.duration,this.relativeMotion?"relative":"absolute"));e.addBehavior(t)}}}Ee([f(c.Object3D)],ur.prototype,"object");Ee([f(c.Object3D)],ur.prototype,"target");Ee([f()],ur.prototype,"duration");Ee([f()],ur.prototype,"relativeMotion");const pu=class Tt extends k{materialToSwitch;variantMaterial;fadeDuration=0;start(){this._objectsWithThisMaterial=this.objectsWithThisMaterial,kc(this.gameObject),A()&&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 c.Mesh)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):gv(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=[],Tt._materialTriggersPerId={},Tt.variantSwitchIndex=0,this.materialToSwitch&&await ne.NEEDLE_progressive.assignTextureLOD(this.materialToSwitch,0),this.variantMaterial&&await ne.NEEDLE_progressive.assignTextureLOD(this.variantMaterial,0)}createBehaviours(e,t,i){this.objectsWithThisMaterial.find(o=>o.uuid===t.uuid)&&this.targetModels.push(t),this.gameObject.uuid===t.uuid&&(this.selfModel=t,this.materialToSwitch&&(Tt._materialTriggersPerId[this.materialToSwitch.uuid]||(Tt._materialTriggersPerId[this.materialToSwitch.uuid]=[]),Tt._materialTriggersPerId[this.materialToSwitch.uuid].push(this)))}afterCreateDocument(e,t){if(!this.materialToSwitch)return;const i=Tt._materialTriggersPerId[this.materialToSwitch.uuid];if(i){const n={};for(const o of i){const r=o.createVariants();r&&r.length>0&&(n[o.selfModel.uuid]=r)}for(const o of i){const r=[];for(const a in n)a!==o.selfModel.uuid&&r.push(...n[a]);o.createAndAttachBehaviors(e,n[o.selfModel.uuid],r)}}delete Tt._materialTriggersPerId[this.materialToSwitch.uuid]}createAndAttachBehaviors(e,t,i){const n=[],o=Math.max(0,this.fadeDuration);n.push(le.fadeAction([...this.targetModels,...i],o,!1)),n.push(le.fadeAction(t,o,!0)),e.addBehavior(new gt("Select_"+this.selfModel.name,wt.tapTrigger(this.selfModel),le.parallel(...n))),Tt._parallelStartHiddenActions.push(...t),Tt._startHiddenBehaviour||(Tt._startHiddenBehaviour=new gt("StartHidden_"+this.selfModel.name,wt.sceneStartTrigger(),le.fadeAction(Tt._parallelStartHiddenActions,o,!1)),e.addBehavior(Tt._startHiddenBehaviour))}static getMaterialName(e){return ji(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_"+Tt.variantSwitchIndex+++"_"+Tt.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())&&ze.createEmptyParent(t),t.parent&&t.parent.add(i),e.push(i)}return e}};Ee([f(c.Material)],pu.prototype,"materialToSwitch");Ee([f(c.Material)],pu.prototype,"variantMaterial");Ee([f()],pu.prototype,"fadeDuration");let lg=pu;const Ec=class Pe extends k{target;toggleOnClick=!1;targetState=!0;hideSelf=!0;start(){kc(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[Pe.wasVisible]===void 0&&(this.gameObject[Pe.wasVisible]=this.gameObject.activeSelf),this.target[Pe.wasVisible]===void 0&&(this.target[Pe.wasVisible]=this.target.activeSelf),this.stateBeforeCreatingDocument=this.gameObject[Pe.wasVisible],this.targetStateBeforeCreatingDocument=this.target[Pe.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,o=this.targetState;if(this.toggleOnClick)if(o=!this.targetStateBeforeCreatingDocument,!this.selfModelClone.geometry)(!this.selfModel.parent||this.selfModel.parent.isEmpty())&&og.createEmptyParent(this.selfModel),this.toggleModel=this.selfModel.deepClone(),this.toggleModel.name+="_toggle",this.selfModel.parent.add(this.toggleModel);else{if(!this.gameObject[Pe.toggleClone]){const l=this.selfModelClone.clone();l.setMatrix(new c.Matrix4),l.name+="_toggle"+Pe.clonedToggleIndex++,i.add(l),this.gameObject[Pe.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[Pe.toggleClone];if(!this.gameObject[Pe.reverseToggleClone]){const l=this.selfModelClone.clone();l.setMatrix(new c.Matrix4),l.name+="_toggleReverse"+Pe.clonedToggleIndex++,i.add(l),this.gameObject[Pe.reverseToggleClone]=l}this.toggleModel=this.gameObject[Pe.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(le.fadeAction(n,0,!1)),a.push(le.fadeAction(this.toggleModel,0,!0)),a.push(le.fadeAction(this.targetModel,0,o)),e.addBehavior(new gt("Toggle_"+n.name+"_ToggleTo"+(o?"On":"Off"),wt.tapTrigger(n),le.parallel(...a)));const l=[];l.push(le.fadeAction(this.toggleModel,0,!1)),l.push(le.fadeAction(n,0,!0)),l.push(le.fadeAction(this.targetModel,0,!o)),e.addBehavior(new gt("Toggle_"+n.name+"_ToggleTo"+(o?"Off":"On"),wt.tapTrigger(this.toggleModel),le.parallel(...l)))}}else{const a=[];this.hideSelf&&a.push(le.fadeAction(n,0,!1)),a.push(le.fadeAction(this.targetModel,0,o)),e.addBehavior(new gt("Toggle_"+n.name+"_ToggleTo"+(o?"On":"Off"),wt.tapTrigger(n),a.length>1?le.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),Ei.add(r,e)}}afterSerialize(e,t){this.gameObject[Pe.wasVisible]!==void 0&&(this.gameObject.visible=this.gameObject[Pe.wasVisible],delete this.gameObject[Pe.wasVisible]),this.target&&this.target[Pe.wasVisible]!==void 0&&(this.target.visible=this.target[Pe.wasVisible],delete this.target[Pe.wasVisible]),delete this.gameObject[Pe.toggleClone],delete this.gameObject[Pe.reverseToggleClone]}};Ee([f(c.Object3D)],Ec.prototype,"target");Ee([f()],Ec.prototype,"toggleOnClick");Ee([f()],Ec.prototype,"targetState");Ee([f()],Ec.prototype,"hideSelf");let cg=Ec;class Ei extends k{static _fadeBehaviour;static _fadeObjects=[];static add(e,t){const i=Array.isArray(e)?e:[e];for(const n of i)Ei._fadeObjects.includes(n)||(console.log("adding hide on start",n),Ei._fadeObjects.push(n));Ei._fadeBehaviour===void 0&&(Ei._fadeBehaviour=new gt("HideOnStart",wt.sceneStartTrigger(),le.fadeAction(Ei._fadeObjects,0,!1)),t.addBehavior(Ei._fadeBehaviour))}start(){S.setActive(this.gameObject,!1)}createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&(this.wasVisible||Ei.add(t,e))}wasVisible=!1;beforeCreateDocument(){this.wasVisible=S.isActiveSelf(this.gameObject)}}class Oa extends k{target;duration=.5;motionType="bounce";beforeCreateDocument(){}createBehaviours(e,t,i){if(this.target&&t.uuid===this.gameObject.uuid){const n=new gt("emphasize "+this.name,wt.tapTrigger(this.gameObject),le.emphasize(this.target,this.duration,this.motionType,void 0,"basic"));e.addBehavior(n)}}afterCreateDocument(e,t){}}Ee([f()],Oa.prototype,"target");Ee([f()],Oa.prototype,"duration");Ee([f()],Oa.prototype,"motionType");class Qs extends k{target;clip="";toggleOnClick=!1;trigger="tap";start(){kc(this.gameObject)}ensureAudioSource(){if(!this.target){const e=this.gameObject.addComponent(pi);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 o=this.target?this.target.gameObject:this.gameObject;dr.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 c.Mesh&&p.visible&&(l=!0)}),l=!0;const h=e.addAudioClip(n);let d=le.playAudioAction(o,h,"play",r,a);this.target&&this.target.loop&&(d=le.sequence(d).makeLooping());const u=this.name?"_"+this.name:"";if(l&&this.trigger==="tap"){this.toggleOnClick&&(d.multiplePerformOperation="stop");const p=new gt("playAudio"+u,wt.tapTrigger(t),d);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 gt("playAudioOnStart"+u,wt.sceneStartTrigger(),d);e.addBehavior(p)}}}}Ee([f(pi)],Qs.prototype,"target");Ee([f(URL)],Qs.prototype,"clip");Ee([f()],Qs.prototype,"toggleOnClick");const hg=class pn extends k{animator;stateName;trigger="tap";animation;get target(){return this.animator?.gameObject||this.animation?.gameObject}start(){kc(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(pn.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.';A()&&he(e),console.warn(e,...pn.rootsWithExclusivePlayback)}pn.animationActions=[],pn.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 fu);if(!n)return;const o=n.getClipCount(this.target)>1;o&&(A()&&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."),pn.rootsWithExclusivePlayback.add(this.target));const r=this.name?this.name:"";i.traverse(a=>{if(a.uuid===this.target?.uuid){const l=pn.getActionForSequences(i,a,this.animationSequence,this.animationLoopAfterSequence,this.randomOffsetNormalized),h=new gt(this.trigger+"_"+r+"_toPlayAnimation_"+this.stateName+"_on_"+this.target?.name,this.trigger=="tap"?wt.tapTrigger(this.selfModel):wt.sceneStartTrigger(),l);o&&h.makeExclusive(!0),e.addBehavior(h)}})}static getActionForSequences(e,t,i,n,o){const r=(l,h)=>{let d=pn.animationActions.find(u=>u.affectedObjects==l&&u.start==h.start&&u.duration==h.duration&&u.animationSpeed==h.speed);return d||(d=le.startAnimationAction(l,h),pn.animationActions.push(d)),d},a=le.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:le.sequence();for(const h of n)l.addAction(r(t,h));l.makeLooping(),a!==l&&a.addAction(l)}return o&&o>0&&a.actions.unshift(le.waitAction(o)),a}static getAndRegisterAnimationSequences(e,t,i){if(!t)return;const n=t.getComponent(rt),o=t.getComponent(Ft);if(!n&&!o)return;if(n&&!i)throw new Error("PlayAnimationOnClick: No stateName specified for animator "+n.name+" on "+t.name);let r=[],a=[];if(o){const y=e.registerAnimation(t,o.clip);y&&(o.loop?a.push(y):r.push(y));let b=0;if(o.minMaxOffsetNormalized){const g=o.minMaxOffsetNormalized.x,v=o.minMaxOffsetNormalized.y;b=(o.clip?.duration||1)*(g+Math.random()*(v-g))}return{animationSequence:r,animationLoopAfterSequence:a,randomTimeOffset:b}}const l=n?.runtimeAnimatorController;let h=l?.findState(i),d=[],u=[];if(l&&h){const y=new Array;y.push(h);let b=!1;for(;y.length<100;){if(!h||h===null||!h.transitions||h.transitions.length===0){h.motion?.isLooping&&(b=!0);break}const g=h.transitions.find(_=>_.conditions.length===0),v=g?l.getState(g.destinationState,0):null;if(v&&y.includes(v)){h=v,b=!0;break}else if(g){if(h=v,!h)break;y.push(h)}else{b=h.motion?.isLooping??!1;break}}if(b&&h){const g=y.indexOf(h);d=y.slice(0,g),u=y.slice(g),E_&&console.log("found loop from "+i,"states until loop",d,"states looping",u)}else d=y,u=[],E_&&console.log("found no loop from "+i,"states",d);if(!u.length){const g=d[d.length-1],v=g.motion?.clip;if(v){let _;if(e.holdClipMap.has(v))_=e.holdClipMap.get(v);else{const x=g.name+"_hold";_=v.clone(),_.duration=1,_.name=x;const T=v.duration;_.tracks=v.tracks.map(O=>{const M=O.clone();M.times=new Float32Array([0,T]);const E=O.values.length,j=O.getValueSize(),L=O.values.slice(E-j,E);return M.values=new Float32Array(2*j),M.values.set(L,0),M.values.set(L,j),M}),_.name=x,e.holdClipMap.set(v,_)}if(_){const x={name:_.name,motion:{clip:_,isLooping:!1,name:_.name},speed:1,transitions:[],behaviours:[],hash:g.hash+1};u.push(x)}}}}if(d.length===1&&(!d[0].motion?.clip||d[0].motion?.clip.tracks?.length===0)){r=new Array;const y=e.registerAnimation(t,null);y&&r.push(y);return}if(d=d.filter(y=>y.motion?.clip&&y.motion?.clip.tracks?.length>0),u=u.filter(y=>y.motion?.clip&&y.motion?.clip.tracks?.length>0),d.length===0&&u.length===0){console.warn("No clips found for state "+i+" on "+n?.name+", can't export animation data");return}const p=(y,b)=>{if(!t)return;const g=e.registerAnimation(t,y.motion.clip??null);g?(g.speed=y.speed,b.push(g)):console.warn("Couldn't register animation for state "+y.name+" on "+n?.name)};if(d.length>0){r=new Array;for(const y of d)p(y,r)}if(u.length>0){a=new Array;for(const y of u)p(y,a)}let m=0;if(n&&l&&n.minMaxOffsetNormalized){const y=n.minMaxOffsetNormalized.x,b=n.minMaxOffsetNormalized.y;m=((d.length?d[0]:u.length?u[0]:null)?.motion.clip?.duration||1)*(y+Math.random()*(b-y))}return{animationSequence:r,animationLoopAfterSequence:a,randomTimeOffset:m}}createAnimation(e,t,i){if(!this.target||!this.animator&&!this.animation)return;const n=pn.getAndRegisterAnimationSequences(e,this.target,this.stateName);n&&(this.animationSequence=n.animationSequence,this.animationLoopAfterSequence=n.animationLoopAfterSequence,this.randomOffsetNormalized=n.randomTimeOffset,this.stateAnimationModel=t)}};Ee([f(rt)],hg.prototype,"animator");Ee([f()],hg.prototype,"stateName");let ec=hg;class Ma extends k{getType(){}target;getDuration(){}}Ee([f(c.Object3D)],Ma.prototype,"target");class Rc extends k{target}Ee([f(Ma)],Rc.prototype,"target");class Tc extends Ma{type=1;duration=1;getType(){switch(this.type){case 1:return"hide";case 0:return"show"}}getDuration(){return this.duration}}Ee([f()],Tc.prototype,"type");Ee([f()],Tc.prototype,"duration");class dg extends Rc{}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 Qi.getOrCreate().createQRCode()}createQuicklookButton(){if(this._quicklookButton)return this._quicklookButton;const e=document.createElement("button");this._quicklookButton=e,e.dataset.needle="quicklook-button";const t=exports.DeviceUtilities.supportsQuickLookAR();e.innerText="View in AR",e.prepend(pt("view_in_ar"));let i=!1,n=null;return e.addEventListener("click",()=>{n=yc(Tn),n||(i=!0,n=new Tn),i&&(n.objectToExport=F.Current.scene),n?(e.classList.add("this-mode-is-requested"),n.exportAndOpen().then(()=>{e.classList.remove("this-mode-is-requested")}).catch(o=>{e.classList.remove("this-mode-is-requested"),console.error(o)})):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(pt("view_in_ar")),i.title="Click to start an AR session",i.addEventListener("click",()=>H.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)"),exports.DeviceUtilities.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(pt("panorama_photosphere")),i.title="Click to start a VR session",i.addEventListener("click",()=>H.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)"),exports.DeviceUtilities.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(pt("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&&Se("This page doesn't allow popups. Please paste "+n+" into your browser.")}),this.listenToXRSessionState(t),this.hideElementDuringXRSession(t),exports.DeviceUtilities.isMozillaXR()||navigator.xr?.addEventListener("devicechange",()=>{navigator.xr?.isSessionSupported("immersive-vr")?t.style.display="none":t.style.display=""}),t}createQRCode(){return Qi.getOrCreate().createQRCode()}updateSessionSupported(e,t){if(!("xr"in navigator)){e.style.display="none";return}H.isSessionSupported(t).then(i=>{e.style.display=i?"":"none",A()&&!i&&console.log('[WebXR] "'+t+'" is not supported on this device – make sure your server runs using HTTPS and you have a device connected that supports '+t)})}hideElementDuringXRSession(e){Wd(t=>{e["previous-display"]=e.style.display,e.style.display="none"}),hm(t=>{e["previous-display"]!=null&&(e.style.display=e["previous-display"])})}listenToXRSessionState(e,t){t&&(H.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"))}),H.onSessionRequestEnd(i=>{e.classList.remove("this-mode-is-requested"),e.classList.remove("other-mode-is-requested"),e.disabled=e["was-disabled"]}))}}var FO=Object.defineProperty,UO=Object.getOwnPropertyDescriptor,at=(s,e,t,i)=>{for(var n=i>1?void 0:i?UO(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&FO(e,t,n),n};const Fl=w("debugspriterenderer"),zO=w("wireframe");class Zo{static cache={};static getOrCreateGeometry(e){if(e.__cached_geometry)return e.__cached_geometry;if(e.guid&&Zo.cache[e.guid])return Fl&&console.log("Take cached geometry for sprite",e.guid),Zo.cache[e.guid];const t=new c.BufferGeometry;e.__cached_geometry=t;const i=new Float32Array(e.triangles.length*3),n=new Float32Array(e.triangles.length*2);for(let o=0;o<e.triangles.length;o+=1){const r=e.triangles[o];i[o*3]=-e.vertices[r].x,i[o*3+1]=e.vertices[r].y,i[o*3+2]=0;const a=e.uv[r];n[o*2]=a.x,n[o*2+1]=1-a.y}return t.setAttribute("position",new c.BufferAttribute(i,3)),t.setAttribute("uv",new c.BufferAttribute(n,2)),e.guid&&(this.cache[e.guid]=t),Fl&&console.log("Built sprite geometry",e,t),t}}class NO{x;y}function K0(s){s&&(s.colorSpace!=c.SRGBColorSpace&&(s.colorSpace=c.SRGBColorSpace,s.needsUpdate=!0),s.minFilter==c.NearestFilter&&s.magFilter==c.NearestFilter&&(s.anisotropy=1,s.needsUpdate=!0))}let ms=class{constructor(e){e&&(this.texture=e,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 c.Mesh(Zo.getOrCreateGeometry(this),this.material)),this._mesh}_mesh;get material(){return this._material||(this.texture&&K0(this.texture),this._material=new c.MeshBasicMaterial({map:this.texture,color:16777215,side:c.DoubleSide,transparent:!0})),this._material}_material;getGeometry(){return Zo.getOrCreateGeometry(this)}};at([f()],ms.prototype,"guid",2);at([f(c.Texture)],ms.prototype,"texture",2);at([$e()],ms.prototype,"triangles",2);at([$e()],ms.prototype,"uv",2);at([$e()],ms.prototype,"vertices",2);const Tf=Symbol("spriteOwner");class ga{sprites;constructor(){this.sprites=[]}}at([f(ms)],ga.prototype,"sprites",2);const ug=class Lp{static create(){const e=new Lp;return e.spriteSheet=new ga,e}constructor(){}clone(){const e=new Lp;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 ga,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&&(K0(n),!i.__hasLoadedProgressive)){i.__hasLoadedProgressive=!0;const o=n;ne.NEEDLE_progressive.assignTextureLOD(n,0).then(r=>{r instanceof c.Texture&&(i.texture=r,e?.map===o&&(e.map=r,e.needsUpdate=!0))})}}};at([f(ga)],ug.prototype,"spriteSheet",2);at([f()],ug.prototype,"index",2);let sa=ug;class Zt extends k{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=sa.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);Fl&&console.log("[SpriteSheet] Set index to "+t+" (was "+this.spriteIndex+")",e),this.spriteIndex=t}else e instanceof ms?(this._spriteSheet||(this._spriteSheet=sa.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=sa.create(),Fl&&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 Fl&&console.warn("Sprite not found",this.spriteIndex,t.spriteSheet.sprites),!1;if(this._currentSprite)this._currentSprite.geometry=Zo.getOrCreateGeometry(i),this._currentSprite.material.map=i.texture;else{const n=new c.MeshBasicMaterial({color:16777215,side:c.DoubleSide});if(zO&&(n.wireframe=!0),this.color&&(n.color||(n.color=new c.Color),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 o=i.texture;o[Tf]!==void 0&&o[Tf]!==this&&this.spriteFrames>1&&(o=i.texture=o.clone()),o[Tf]=this,n.map=o}this.sharedMaterial=n,this._currentSprite=new c.Mesh(Zo.getOrCreateGeometry(i),n),this._currentSprite.renderOrder=Math.round(this.renderOrder),ne.NEEDLE_progressive.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}}at([f()],Zt.prototype,"drawMode",2);at([f(NO)],Zt.prototype,"size",2);at([f(Z)],Zt.prototype,"color",2);at([f(c.Material)],Zt.prototype,"sharedMaterial",2);at([f()],Zt.prototype,"transparent",2);at([f()],Zt.prototype,"cutoutThreshold",2);at([f()],Zt.prototype,"castShadows",2);at([f()],Zt.prototype,"renderOrder",2);at([f()],Zt.prototype,"toneMapped",2);at([f(sa)],Zt.prototype,"sprite",1);const R_=w("debugwebxr"),VO=new c.Matrix4().makeRotationY(Math.PI);class hi extends k{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 c.Matrix4;_createdPlacementObject=null;_reparentedComponents=[];_placementScene=new c.Scene;_reticle=[];_hits=[];_placementStartTime=-1;_rigPlacementMatrix;_anchor=null;userInput;onEnable(){this.customReticle?.preload()}supportsXR(e){return e==="immersive-ar"}onEnterXR(e){R_&&console.log("ENTER WEBXR: SessionRoot start..."),this._anchor=null,hi._hasPlaced=!1,this.gameObject.updateMatrixWorld(),this._startOffset.copy(this.gameObject.matrixWorld);const t=new c.Object3D;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=Bt(this._placementScene.children),n=i.getCenter(new c.Vector3),o=i.getSize(new c.Vector3),r=new c.Matrix4;r.makeTranslation(n.x,n.y-o.y*.5,n.z),this._startOffset.multiply(r)}this._reparentedComponents.length=0,this._reparentedComponents.push({comp:this,originalObject:this.gameObject}),S.addComponent(t,this);for(const i of this._reticle)ui(i);this._reticle.length=0,this._isPlacing=!0,this.context.input.addEventListener("pointerup",this.onPlaceScene,{queue:Ht.Early})}onLeaveXR(){this.context.input.removeEventListener("pointerup",this.onPlaceScene,{queue:Ht.Early}),this.onRevertSceneChanges(),this._anchor=null,hi._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 o=n.getHitTest();o&&(i=!0,this.updateReticleAndHits(e.xr,n.index,o,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 Ad(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 o=this._reticle[t];if(!o){if(this.customReticle)if(this.customReticle.asset)o=Xo(this.customReticle.asset);else{this.customReticle.loadAssetAsync();return}else o=new c.Mesh(new c.RingGeometry(.07,.09,32).rotateX(-Math.PI/2),new c.MeshBasicMaterial({side:c.DoubleSide,depthTest:!1,depthWrite:!1,transparent:!0,opacity:1,color:15658734})),o.name="AR Placement Reticle";if(R_){const r=new c.AxesHelper(1);r.position.y+=.01,o.add(r)}this._reticle[t]=o,o.matrixAutoUpdate=!1,o.visible=!1}if(o.lastPos=o.lastPos||i.position.clone(),o.lastQuat=o.lastQuat||i.quaternion.clone(),o.position.copy(o.lastPos.lerp(i.position,this.context.time.deltaTime/.1)),o.lastPos.copy(o.position),o.quaternion.copy(o.lastQuat.slerp(i.quaternion,this.context.time.deltaTime/.05)),o.lastQuat.copy(o.quaternion),o.scale.set(n,n,n),this.customReticle&&this.applyViewBasedTransform(o),o.updateMatrix(),o.visible=!0,o.parent!==this.context.scene&&this.context.scene.add(o),this._placementStartTime<0&&(this._placementStartTime=this.context.time.realtimeSinceStartup),this.autoPlace)if(this.upVec.set(0,1,0).applyQuaternion(o.quaternion),this.upVec.dot(V(0,1,0))>.9){let a=o["autoplace:timer"]||0;a>=1?(o.visible=!1,this.onPlaceScene(null)):(a+=this.context.time.deltaTime,o["autoplace:timer"]=a)}else o["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(H.active?.isTrackingImages){console.warn("Scene Placement is disabled while images are being tracked");return}let i=this._hits[0];if(e&&e.origin instanceof dm){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),hi._hasPlaced=!0,this.useXRAnchor&&this.onCreateAnchor(H.active,i),this.context.xr)for(const n of this.context.xr.controllers)n.cancelHitTestSource()};onSetScale(){if(!hi._hasPlaced)return;const e=H.active?.rig?.gameObject;if(e){const t=H.active?.rigScale||1,i=1/this._arScale*t,n=new c.Matrix4().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)S.addComponent(e.originalObject,e.comp)}async onCreateAnchor(e,t){if(t.createAnchor===void 0){console.warn("Hit does not support creating an anchor",t),A()&&he("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 c.Vector3(0,1,0);lookPoint=new c.Vector3;worldUpVec=new c.Vector3(0,1,0);applyViewBasedTransform(e){const t=this.context.mainCamera,i=e,n=t.worldPosition,o=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=o.y,e.lookAt(n))}onApplyPose(e){const t=H.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(VO),t.matrix.premultiply(this._startOffset),t.matrix.decompose(t.position,t.quaternion,t.scale),i.add(t)}}class Ad{static up=new c.Vector3(0,1,0);static zero=new c.Vector3(0,0,0);static one=new c.Vector3(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 c.Matrix4,this.plane=new c.Plane,this.plane.setFromNormalAndCoplanarPoint(Ad.up,Ad.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:Ht.Early}),this.context.input.addEventListener("pointerdown",this.onPointerDownLate,{queue:Ht.Late}),this.context.input.addEventListener("pointerup",this.onPointerUpEarly,{queue:Ht.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:Ht.Early}),this.context.input.removeEventListener("pointerdown",this.onPointerDownLate,{queue:Ht.Late}),this.context.input.removeEventListener("pointerup",this.onPointerUpEarly,{queue:Ht.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=exports.DeviceUtilities.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 o=this.prev.get(i.identifier);if(o){const r=this.getPositionOnPlane(i.clientX,i.clientY);o.x=r.x,o.z=r.z,o.screenx=i.clientX,o.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),o=n.x-i.x,r=n.z-i.z;if(o===0&&r===0)return;this.oneFingerDrag&&this.addMovement(o,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),o=this.prev.get(i.identifier);if(!n||!o)return;if(this.twoFingerRotate){const r=Math.atan2(t.clientY-i.clientY,t.clientX-i.clientX),a=Math.atan2(n.screeny-o.screeny,n.screenx-o.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),h=n.screenx-o.screenx,d=n.screeny-o.screeny,u=Math.sqrt(h*h+d*d),p=l-u;Math.abs(p)>2&&this.addScale(p)}n.screenx=t.clientX,n.screeny=t.clientY,o.screenx=i.clientX,o.screeny=i.clientY}}};_raycaster=new c.Raycaster;_intersection=new c.Vector3;_screenPos=new c.Vector3;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 c.Matrix4;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 zs=w("debugautosync"),Af=Symbol("syncerId");class $O{_syncers={};getOrCreateSyncer(e){if(!e.guid)return null;if(this._syncers[e.guid])return this._syncers[e.guid];const t=new WO(e);return t[Af]=e.guid,this._syncers[t[Af]]=t,t}removeSyncer(e){delete this._syncers[e[Af]]}}const fg=new $O;class WO{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||(zs&&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];zs&&console.log("SEND",this.comp.guid,this.networkingKey),e.send(this.networkingKey,{guid:this.comp.guid,property:t,data:i},Xi.Queued),delete this.changedProperties[t]}};onHandleReceiving=e=>{if(zs&&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 GO(s,e){let t=e!==s;return!t&&s&&e&&(Array.isArray(s)&&Array.isArray(e)||typeof s=="object"&&typeof e=="object")&&(t=!0),t}const Ul=Symbol("AutoSyncHandler");function HO(s){if(s[Ul])return s[Ul];const e=fg.getOrCreateSyncer(s);return e?.init(s),s[Ul]=e,e}function qO(s){const e=s[Ul];e&&(fg.removeSyncer(e),e.destroy(),delete s[Ul])}const pg=function(s=null){return function(e,t){let i="";typeof t=="string"?i=t:i=t.name;let n=null,o;typeof s=="string"?o=e[s]:typeof s=="function"&&(o=s),o==null&&(A()||zs)&&s!=null&&console.warn('syncField: no callback function found for property "'+i+'"','"'+s+'"');const r=e,a=r.__internalAwake;if(typeof a!="function"){(zs||A())&&console.error('@syncField can currently only used on Needle Engine Components, custom object of type "'+e?.constructor?.name+'" is not supported',e);return}zs&&console.log(i);const l=Symbol(i);r.__internalAwake=function(){if(this[l]!==void 0)return;if(this[l]=this[i],n=fg.getOrCreateSyncer(this),Object.getOwnPropertyDescriptor(this,i)?.set===void 0){let u=!1;Object.defineProperty(this,i,{set:function(p){const m=this[l];if(this[l]=p,u){(A()||zs)&&console.warn("Recursive call detected",i);return}u=!0;try{const y=GO(p,m);zs&&console.log("SyncField assignment",i,"changed?",y,p,o),y&&o?.call(this,p,m)!==!1&&HO(this)?.notifyChanged(i,p)}finally{u=!1}},get:function(){return this[l]},configurable:!0,enumerable:!0})}n?.init(this),a.call(this)};const h=r.__internalDestroy;r.__internalDestroy=function(){qO(this),h.call(this)}}};var XO=Object.defineProperty,mu=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&XO(e,t,n),n};const Lt=w("debugplayersync"),gu=class Z0 extends k{static async setupFrom(e,t){const i=Y.getOrCreateFromUrl(e);if(!i.asset){const r=await i.loadAssetAsync();r&&S.getOrAddComponent(r,Yi)}const n=new Z0;n._internalInit(t),n.asset=i;const o=new c.Object3D;return o.guid=e,S.addComponent(o,n),n}autoSync=!0;asset;onPlayerSpawned;_localInstance;awake(){this.watchTabVisible(),this.onPlayerSpawned||(this.onPlayerSpawned=new oe)}onEnable(){this.context.connection.beginListen(Q.RoomStateSent,this.onJoinedRoom),this.context.connection.beginListen(Q.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(Q.LeftRoom,this.destroyInstance),this.context.connection.isInRoom&&this.onJoinedRoom()}onDisable(){this.context.connection.stopListen(Q.RoomStateSent,this.onJoinedRoom),this.context.connection.stopListen(Q.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(Q.LeftRoom,this.destroyInstance)}onJoinedRoom=()=>{Lt&&console.log("PlayerSync.joinedRoom. autoSync is set to "+this.autoSync),this.autoSync&&this.getInstance()};async getInstance(){if(this._localInstance)return this._localInstance;if(Lt&&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=S.getComponentsInChildren(e,Yi);if(Lt&&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!"),S.destroySynced(e)}else this._localInstance=void 0,console.warn("PlayerSync: failed instantiating asset!");return this._localInstance}destroyInstance=()=>{this._localInstance?.then(e=>{Lt&&console.log("PlayerSync.destroyInstance",e),uc(e,this.context.connection,!0,{saveInRoom:!1})}),this._localInstance=void 0};watchTabVisible(){window.addEventListener("visibilitychange",e=>{if(document.visibilityState==="visible")for(let t=Yi.all.length-1;t>=0;t--){const i=Yi.all[t];(!i.owner||!this.context.connection.userIsInRoom(i.owner))&&i.doDestroy()}})}};mu([f()],gu.prototype,"autoSync");mu([f(Y)],gu.prototype,"asset");mu([f(oe)],gu.prototype,"onPlayerSpawned");let mg=gu;var J0=(s=>(s.OwnerChanged="ownerChanged",s))(J0||{});const Dp=class ut extends k{static _all=[];static get all(){return ut._all}static _local=[];static get local(){return ut._local}static getFor(e){if(e instanceof c.Object3D)return S.getComponentInParent(e,ut);if(e instanceof k)return S.getComponentInParent(e.gameObject,ut)}static isLocalPlayer(e){return ut.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 oe;onFirstOwnerChangeEvent=new oe;hasOwner=!1;owner;dontDestroy=!1;get isLocalPlayer(){return this.owner===this.context.connection.connectionId}onOwnerChange(e,t){Lt&&console.log(`PlayerSync.onOwnerChange: ${t} → ${e} (me: ${this.context.connection.connectionId})`);const i=ut._local.indexOf(this);i>=0&&ut._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){ut._local.push(this);const r=new CustomEvent("local-owner-changed",{detail:n});this.dispatchEvent(r)}const o=new CustomEvent("owner-changed",{detail:n});this.dispatchEvent(o),ut.dispatchEvent("ownerChanged",o)}awake(){ut.all.push(this),Lt&&console.log("Registered new PlayerState",this.guid,ut.all.length-1,ut.all),this.context.connection.beginListen(Q.UserLeftRoom,this.onUserLeftRoom)}async start(){Lt&&console.log("PLAYERSTATE.START, owner: "+this.owner,this.context.connection.usersInRoom([])),this.owner?(this.context.connection.isInRoom||await Ln(300),this.context.connection.userIsInRoom(this.owner)==!1&&(Lt&&console.log(`PlayerSync.start → doDestroy "${this.name}" because user "${this.owner}" is not in room anymore...`,"Currently in room:",...this.context.connection.usersInRoom()),this.doDestroy())):this.owner||(Lt&&console.warn("PlayerState.start → owner is undefined!",this.name),setTimeout(()=>{!this.destroyed&&!this.owner?this.dontDestroy?Lt&&console.warn("PlayerState.start → owner is still undefined but dontDestroy is set to true",this.name):(Lt&&console.warn(`PlayerState.start → owner is still undefined: destroying "${this.name}" instance now`),this.doDestroy()):Lt&&console.log("PlayerState.start → owner is assigned",this.owner)},2e3))}doDestroy(){Lt&&console.log("PlayerSync.doDestroy → syncDestroy",this.name),uc(this.gameObject,this.context.connection,!0,{saveInRoom:!1})}onDestroy(){if(Lt&&console.warn("PlayerState.onDestroy",this.owner),this.context.connection.stopListen(Q.UserLeftRoom,this.onUserLeftRoom),ut.all.splice(ut.all.indexOf(this),1),this.isLocalPlayer){const e=ut._local.indexOf(this);e>=0&&ut._local.splice(e,1)}}onUserLeftRoom=e=>{if(e.userId===this.owner){Lt&&console.log("PLAYERSYNC LEFT",this.owner),this.doDestroy();return}}};mu([pg(Dp.prototype.onOwnerChange)],Dp.prototype,"owner");let Yi=Dp;var QO=Object.defineProperty,ka=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&QO(e,t,n),n};class Bn extends k{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&&(exports.DeviceUtilities.isMobileDevice()||this.context.menu.showQRCodeButton(!0))}}ka([f()],Bn.prototype,"position");ka([f()],Bn.prototype,"showNeedleLogo");ka([f()],Bn.prototype,"showSpatialMenu");ka([f()],Bn.prototype,"createFullscreenButton");ka([f()],Bn.prototype,"createMuteButton");ka([f()],Bn.prototype,"createQRCodeButton");var YO=Object.defineProperty,gg=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&YO(e,t,n),n};const Ja=w("debugwebxr"),T_=new c.Quaternion().setFromAxisAngle(new c.Vector3(0,1,0),Math.PI);class Ys extends k{head;leftHand;rightHand;_leftHandMeshes;_rightHandMeshes;_syncTransforms;async onEnterXR(e){if(!this.activeAndEnabled)return;Ja&&console.warn("AVATAR ENTER XR",this.guid,this.sourceId,this,this.activeAndEnabled),this._syncTransforms&&(this._syncTransforms.length=0),await this.prepareAvatar();const t=Yi.getFor(this);if(t?.owner){const i=this.gameObject.addComponent(xe);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(xe);t&&t.destroy()}onUpdateXR(e){if(!this.activeAndEnabled)return;const t=Yi.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 h=S.getComponentsInChildren(this.head.asset,Ti);for(const d of h)d.enabled=!1,d.gameObject.visible=!1}}const n=e.xr.leftController,o=this.leftHand?.asset;n&&o?(o.position.copy(n.gripPosition),o.quaternion.copy(n.gripQuaternion),o.quaternion.multiply(T_),o.visible=n.isTracking,this.updateHandVisibility(n,o,this._leftHandMeshes)):o&&o.visible&&(o.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(T_),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(o=>{es(o,!n)})}}updateRemoteAvatarVisibility(){if(this.context.connection.isConnected){const e=Yi.getFor(this);if(e&&e.isLocalPlayer==!1){const t=H.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=S.getComponentsInChildren(this.head.asset,Ti);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};Yb.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 c.Object3D&&(this.head=new Y("",this.sourceId,this.head));else{const e=new c.Object3D;e.name="Head";const t=ir.createPrimitive(Go.Cube);e.add(t),this.gameObject.add(e),this.head=new Y("",this.sourceId,e),Ja&&console.log("Create head",e)}if(this.rightHand)this.rightHand instanceof c.Object3D&&(this.rightHand=new Y("",this.sourceId,this.rightHand));else{const e=new c.Object3D;e.name="Right Hand",this.gameObject.add(e),this.rightHand=new Y("",this.sourceId,e),Ja&&console.log("Create right hand",e)}if(this.leftHand)this.leftHand instanceof c.Object3D&&(this.leftHand=new Y("",this.sourceId,this.leftHand));else{const e=new c.Object3D;e.name="Left Hand",this.gameObject.add(e),this.leftHand=new Y("",this.sourceId,e),Ja&&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)}),Yi.isLocalPlayer(this.gameObject)&&(this._syncTransforms=S.getComponentsInChildren(this.gameObject,nn))}async loadAvatarObjects(e,t,i){const n=e.loadAssetAsync(),o=t.loadAssetAsync(),r=i.loadAssetAsync(),a=new Array;n&&a.push(n),o&&a.push(o),r&&a.push(r);const l=await Kp(a);Ja&&console.log("Avatar loaded results:",l)}}gg([f(Y)],Ys.prototype,"head");gg([f(Y)],Ys.prototype,"leftHand");gg([f(Y)],Ys.prototype,"rightHand");var KO=Object.defineProperty,yu=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&KO(e,t,n),n};const ks=w("debugwebxr"),Es=new Array;class cs extends k{createControllerModel=!0;createHandModel=!0;customLeftHand;customRightHand;static factory=new q.XRControllerModelFactory;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:i}=e;if(this.createControllerModel||this.createHandModel){if(i.hand){if(this.createHandModel){const n=await this.loadHandModel(this,i);if(!n||!i.connected||!i.isHand){n?.handObject&&Fr(n.handObject,!1),n?.handObject?.destroy();return}this._models.push({controller:i,model:n.handObject,handmesh:n.handmesh}),this._models.sort((o,r)=>o.controller.index-r.controller.index),this.scene.add(n.handObject),i.model=n.handObject}}else if(this.createControllerModel){const n=await i.getModelUrl();if(n){const o=await this.loadModel(i,n);if(!o||!i.connected||i.isHand)return;this._models.push({controller:i,model:o}),this._models.sort((r,a)=>r.controller.index-a.controller.index),this.scene.add(o),o.traverse(r=>{r.layers.set(2),r.matrixAutoUpdate=!1,r.updateMatrix()}),i.model=o}else i.targetRayMode!=="transient-pointer"&&console.warn("XRControllerModel: no model found for "+i.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&&(Fr(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&&(Fr(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(H.active&&(ks&&(Es[0]=Date.now()),this.updateRendering(H.active),ks)){const e=Date.now()-Es[0];Es.push(e),Es.length>=30&&(Es[0]=0,Es.reduce((t,i)=>t+i,0)/Es.length,Es.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){ks&&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 o=e.referenceSpace,r=this.context.renderer.xr.getHand(n.index);if(o&&e.frame.getJointPose){for(const a of n.inputSource.hand.values()){const l=r.joints[a.jointName];if(l){const h=n.getHandJointPose(a);if(h){const d=h.transform.position,u=h.transform.orientation;l.position.copy(d),l.quaternion.copy(u),l.matrixAutoUpdate=!1}l.visible=h!=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(Zr))}}}}async loadModel(e,t){if(!e.connected)return console.warn("XRControllerModel.onXRControllerAdded: controller is not connected anymore",e.side),null;const n=await Y.getOrCreate("",t).instantiate();return Fr(n),H.active?.isPassThrough&&n.traverseVisible(o=>{this.makeOccluder(o)}),n}async loadHandModel(e,t){const i=this.context,n=i.renderer.xr.getHand(t.index);n||(ks?B.DrawLabel(t.rayWorldPosition,"No hand found for index "+t.index,.05,5):console.warn("No hand found for index "+t.index));const o=new q.GLTFLoader;Tm(o,i),await Rd(o,i,this.sourceId??"");const r=Zm(o);let a="";const l=t.side==="left"?this.customLeftHand:this.customRightHand;l?(a=l.url.split(".").slice(0,-1).join("."),o.setPath("")):(a=t.inputSource.handedness==="left"?"left":"right",o.setPath("https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/"));const h=new c.Object3D;Fr(h);const d=new q.XRHandMeshModel(h,n,o.path,a,o,u=>{const p=r?.gltf;p?.scene.children?.length===0&&(p.scene.children[0]=u),r?.gltf&&en().createBuiltinComponents(e.context,e.sourceId||a,r.gltf,null,r),u.traverse(m=>{m.layers.set(2),H.active?.isPassThrough&&!l&&this.makeOccluder(m),m instanceof c.Mesh&&ne.NEEDLE_progressive.assignMeshLOD(m,0)}),t.connected||(ks&&B.DrawLabel(t.rayWorldPosition,"Hand is loaded but not connected anymore",.05,5),u.removeFromParent())});if(ks&&h.add(new c.AxesHelper(.5)),t.inputSource.hand){ks&&console.log(t.inputSource.hand);for(const u of t.inputSource.hand.values())if(n.joints[u.jointName]===void 0){const p=new c.Group;p.matrixAutoUpdate=!1,p.visible=!0,n.joints[u.jointName]=p,n.add(p)}}else ks&&B.DrawLabel(t.rayWorldPosition,"No inputSource.hand found for index "+t.index,.05,5);return{handObject:h,handmesh:d}}makeOccluder(e){if(e instanceof c.Mesh){let t=e.material;t instanceof c.Material&&(t=e.material=t.clone(),t.depthWrite=!0,t.depthTest=!0,t.colorWrite=!1,e.receiveShadow=!1,e.renderOrder=-100)}}}yu([f()],cs.prototype,"createControllerModel");yu([f()],cs.prototype,"createHandModel");yu([f(Y)],cs.prototype,"customLeftHand");yu([f(Y)],cs.prototype,"customRightHand");class _u extends k{}var ZO=Object.defineProperty,ro=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&ZO(e,t,n),n};const Lf=w("debugwebxr");class gi extends k{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=V(i.x,0,i.y);n.multiplyScalar(this.context.time.deltaTimeUnscaled*this.movementSpeed);const o=Ie(t);n.multiplyScalar(o.x),n.applyQuaternion(e.xr.poseOrientation),n.y=0,n.applyQuaternion(t.worldQuaternion),A()&&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 n=e.getStick("xr-standard-thumbstick").x;if(this._didApplyRotation)Math.abs(n)<.3&&(this._didApplyRotation=!1);else if(Math.abs(n)>.5){this._didApplyRotation=!0;const o=n>0?1:-1,r=X(this.context.mainCamera).clone();t.rotateY(o*D.toRadians(this.rotationStep));const l=X(this.context.mainCamera).clone().sub(r);l.y=0,t.position.sub(l)}}_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 o=e.getGesture("pinch");o&&(i=o.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 q.GroundedSkybox){const r=n.normal?.dot(V(0,1,0));if(r!==void 0&&r<.4)return}let o=n?.point;if(!o&&!this.useTeleportTarget){this._plane||(this._plane=new c.Plane(new c.Vector3(0,1,0),0));const r=t.worldPosition;this._plane.setFromNormalAndCoplanarPoint(new c.Vector3(0,1,0),r);const a=e.ray;o=r.clone(),this._plane.intersectLine(new c.Line3(a.origin,V(a.direction).multiplyScalar(1e4).add(a.origin)),o),o.distanceTo(r)>t.scale.x*10&&(o=null)}if(o){if(this.useTeleportTarget&&!S.getComponentInParent(n.object,_u))return;const r=o.clone();if(Lf&&B.DrawSphere(o,.025,16711680,5),this.context.mainCamera?.position){const l=this.context.xr?.getUserOffsetInRig();l&&(l.y=0,r.sub(l),Lf&&B.DrawWireSphere(l.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 o=i.rayWorldPosition,r=i.rayWorldQuaternion;n.position.copy(o),n.quaternion.copy(r);const a=e.rigScale,l=this.usePinchToTeleport&&i.isTeleportGesture,h=this._lastHitDistances[t],d=this._hitDistances[t]!=null,u=h??a;n.scale.set(a,a,u),n.visible=!0,n.layers.disableAll(),n.layers.enable(2);let p=n.material.opacity;l?p=1:this.showHits&&u<e.rigScale*.5?p=0:i.getButton("primary")?.pressed?p=.5:p=d?.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],o=!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,o=!1);const a=this.context.time.smoothedFps>=59?1:10;if((this.context.time.frame+i.index)%a!==0&&(o=!1),!o){const d=this._hitDiscs[t];d&&d.visible&&d.hit&&this.updateHitPointerPosition(i,d,d.hit.distance);continue}const l=this.context.physics.raycastFromRay(i.ray,{testObject:this.hitPointRaycastFilter,precise:!1});let h=l.find(d=>this.usePinchToTeleport&&i.isTeleportGesture?!0:this.isObjectWithInteractiveComponent(d.object));if(h||(h=l[0]),n&&(n.controller=i,n.hit=h),this._hitDistances[t]=h?.distance||null,h){this._lastHitDistances[t]=h.distance;const d=e.rigScale??1;Lf&&(B.DrawWireSphere(h.point,.025*d,16711680),B.DrawLabel(V(0,.2,0).add(h.point),h.object.name,.02,0)),n||(n=this.createHitPointObject(),this._hitDiscs[t]=n),n.hit=h,n.visible=h.distance>d*.05;let u=.01*(d+h.distance);const p=i.getButton("primary")?.pressed;p&&(u*=1.1),n.scale.set(u,u,u),n.layers.set(2);let m=n.material.opacity;if(p?m=1:m=h.distance<.15*d?.2:.6,n.material.opacity=D.lerp(n.material.opacity,m,this.context.time.deltaTimeUnscaled/.1),n.visible){if(h.normal){this.updateHitPointerPosition(i,n,h.distance);const y=h.normal.applyQuaternion(ue(h.object));n.quaternion.setFromUnitVectors(JO,y)}else this.updateHitPointerPosition(i,n,h.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 Cd(e)||e.isUI===!0?!0:e.isScene?!1:e.parent?this.isObjectWithInteractiveComponent(e.parent,t+1):!1}updateHitPointerPosition(e,t,i){const n=V(e.rayWorldPosition);n.add(V(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 c.Mesh(new c.SphereGeometry(.3,6,6),new c.MeshBasicMaterial({color:15658734,opacity:.7,transparent:!0,depthTest:!1,depthWrite:!1,side:c.DoubleSide}));return e.layers.disableAll(),e.layers.enable(2),e}createRayLineObject(){const e=new q.Line2;e.layers.disableAll(),e.layers.enable(2);const t=new q.LineGeometry;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 o=new q.LineMaterial({color:16777215,vertexColors:!0,worldUnits:!0,linewidth:.004,transparent:!0,depthWrite:!1,blending:c.AdditiveBlending,dashed:!1});return e.material=o,e}}ro([f()],gi.prototype,"movementSpeed");ro([f()],gi.prototype,"rotationStep");ro([f()],gi.prototype,"useTeleport");ro([f()],gi.prototype,"usePinchToTeleport");ro([f()],gi.prototype,"useTeleportTarget");ro([f()],gi.prototype,"useTeleportFade");ro([f()],gi.prototype,"showRays");ro([f()],gi.prototype,"showHits");const JO=new c.Vector3(0,1,0);var eM=Object.defineProperty,lt=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&eM(e,t,n),n};const el=w("debugwebxr"),tM=w("debugusdz"),Je=class Wr extends k{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(){H.getXRSync(this.context)}onEnable(){window.location.protocol!=="https:"&&he('<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&&(S.findObjectOfType(Tn)||(el&&console.log("WebXR: Adding USDZExporter"),this._usdzExporter=S.addComponent(this.gameObject,Tn),this._usdzExporter.objectToExport=this.context.scene,this._usdzExporter.autoExportAnimations=!0,this._usdzExporter.autoExportAudioSources=!0)),this.handleCreatingHTML(),this.handleOfferSession(),this.defaultAvatar===!0&&(el&&console.warn("WebXR: No default avatar set, using static default avatar"),this.defaultAvatar=new Y("https://cdn.needle.tools/static/avatars/DefaultAvatar.glb")),this.defaultAvatar&&(this._playerSync=this.gameObject.getOrAddComponent(mg),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 H.isVRSupported()&&this.createVRButton?H.offerSession("immersive-vr","default",this.context):this.createARButton&&await H.isARSupported()&&this.createARButton?H.offerSession("immersive-ar","default",this.context):!1}get session(){return H.active??null}get sessionMode(){return H.activeMode??null}get arSessionRoot(){return this._activeWebARSessionRoot}async enterVR(e){return H.start("immersive-vr",e,this.context)}async enterAR(e){return H.start("immersive-ar",e,this.context)}exitXR(){H.stop()}_exitXRMenuButton;_previousXRState=0;_spatialGrabRaycaster;_activeWebARSessionRoot=null;get isActiveWebXR(){return!Wr.activeWebXRComponent||Wr.activeWebXRComponent===this}onBeforeXR(e,t){if(!this.isActiveWebXR){console.warn(`WebXR: another WebXR component is already active (${Wr.activeWebXRComponent?.name}). This is ignored: ${this.name}`);return}Wr.activeWebXRComponent=this,e=="immersive-ar"&&this.useDepthSensing&&(t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.push("depth-sensing"))}async onEnterXR(e){if(!this.isActiveWebXR)return;el&&console.log("WebXR onEnterXR"),this._previousXRState=It.Global.Mask;const t=e.xr.isVR;if(It.Global.Set(t?wn.VR:wn.AR),e.xr.isAR){let i=S.findObjectOfType(hi);if(!i)if(this.usePlacementReticle){const n=new c.Object3D;for(const o of this.context.scene.children)n.add(o);this.context.scene.add(n),i=S.addComponent(n,hi),this._createdComponentsInSession.push(i)}else(el||A())&&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=S.findObjectOfType(Qo)??void 0,this._spatialGrabRaycaster||(this._spatialGrabRaycaster=this.gameObject.addComponent(Qo))),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){It.Global.Set(this._previousXRState),this._playerSync?.destroyInstance();for(const t of this._createdComponentsInSession)t.destroy();this._createdComponentsInSession.length=0,this._activeWebARSessionRoot=null,this.handleOfferSession(),lc(1).then(()=>Wr.activeWebXRComponent=null)}}setDefaultMovementEnabled(e){let t=this.gameObject.getComponent(gi);return!t&&e&&(t=this.gameObject.addComponent(gi),this._createdComponentsInSession.push(t)),t&&(t.enabled=e),t}setDefaultControllerRenderingEnabled(e){let t=this.gameObject.getComponent(cs);return!t&&e&&(t=this.gameObject.addComponent(cs),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=>{el&&console.log("WebXR.onAvatarSpawned",e);let t=S.getComponentInChildren(e,Ys);t??=S.addComponent(e,Ys)};getButtonsContainer(){return this.getButtonsFactory()}getButtonsFactory(){return this._buttonFactory||(this._buttonFactory=qs.getOrCreate()),this._buttonFactory}_buttonFactory;handleCreatingHTML(){if(this.createARButton||this.createVRButton||this.useQuicklookExport){if((exports.DeviceUtilities.isiOS()&&exports.DeviceUtilities.isSafari()||tM)&&this.useQuicklookExport){const t=S.findObjectOfType(Tn);if(!t||t&&t.allowCreateQuicklookButton){const i=this.getButtonsFactory().createQuicklookButton();this.addButton(i,50)}}if(this.createARButton){const t=this.getButtonsFactory().createARButton();this.addButton(t,50)}if(this.createVRButton){const t=this.getButtonsFactory().createVRButton();this.addButton(t,50)}}if(this.createSendToQuestButton&&!exports.DeviceUtilities.isQuest()&&H.isVRSupported().then(t=>{if(!t){const i=this.getButtonsFactory().createSendToQuestButton();this.addButton(i,50)}}),this.createQRCode){const t=yc(Bn);if(t&&t.createQRCodeButton===!1)A()&&console.warn("WebXR: QRCode button is disabled in the Needle Menu component");else if(!exports.DeviceUtilities.isMobileDevice()){const i=Qi.getOrCreate().createQRCode();this.addButton(i,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}};lt([f()],Je.prototype,"createVRButton");lt([f()],Je.prototype,"createARButton");lt([f()],Je.prototype,"createSendToQuestButton");lt([f()],Je.prototype,"createQRCode");lt([f()],Je.prototype,"useDefaultControls");lt([f()],Je.prototype,"showControllerModels");lt([f()],Je.prototype,"showHandModels");lt([f()],Je.prototype,"usePlacementReticle");lt([f(Y)],Je.prototype,"customARPlacementReticle");lt([f()],Je.prototype,"usePlacementAdjustment");lt([f()],Je.prototype,"arScale");lt([f()],Je.prototype,"useXRAnchor");lt([f()],Je.prototype,"autoPlace");lt([f()],Je.prototype,"autoCenter");lt([f()],Je.prototype,"useQuicklookExport");lt([f()],Je.prototype,"useDepthSensing");lt([f()],Je.prototype,"useSpatialGrab");lt([f(Y)],Je.prototype,"defaultAvatar");let bu=Je;const Rh=w("debugusdzbehaviours");class yg{get extensionName(){return"Behaviour"}behaviours=[];addBehavior(e){this.behaviours.push(e)}addAudioClip(e){if(!e||typeof e!="string")return"";const i="audio/"+dr.getName(e);return this.audioClips.push({clipUrl:e,filesKey:i}),i}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=>{S.foreachComponent(i,n=>{const o=n;if(typeof o.createBehaviours=="function"||typeof o.beforeCreateDocument=="function"||typeof o.afterCreateDocument=="function"||typeof o.afterSerialize=="function"){this.behaviourComponents.push(o);const r=o.beforeCreateDocument?.call(o,this,e);r instanceof Promise&&t.push(r)}},!1)}),Rh&&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 u of this.behaviourComponents)typeof u.afterCreateDocument=="function"&&u.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,o=new Set,r=Rh;let a=`graph LR
|
|
1262
1262
|
`,l="";function h(u){if(u instanceof To){r&&(a+=`subgraph Group_${u.id}
|
|
1263
1263
|
`);for(const p of u.actions)r&&(a+=`${u.id}[${u.id}] -- ${u.type},loops:${u.loops} --> ${p.id}[${p.id}]
|
|
1264
1264
|
`),h(p);r&&(a+=`end
|
|
1265
|
-
`)}else if(u instanceof Wt){u.tokenId==="StartAnimation"&&o.add(u);let p=u.tokenId;u.type!==void 0&&(p+=":"+u.type);const m=u.affectedObjects;if(m)if(Array.isArray(m))for(const
|
|
1266
|
-
${p}] -- ${p} --> ${
|
|
1265
|
+
`)}else if(u instanceof Wt){u.tokenId==="StartAnimation"&&o.add(u);let p=u.tokenId;u.type!==void 0&&(p+=":"+u.type);const m=u.affectedObjects;if(m)if(Array.isArray(m))for(const b of m)i.add(b),r&&(l+=`${u.id}[${u.id}
|
|
1266
|
+
${p}] -- ${p} --> ${b.uuid}(("${b.displayName||b.name||b.uuid}"))
|
|
1267
1267
|
`);else typeof m=="object"?(i.add(m),r&&(l+=`${u.id}[${u.id}
|
|
1268
1268
|
${p}] -- ${p} --> ${m.uuid}(("${m.displayName||m.name||m.uuid}"))
|
|
1269
1269
|
`)):typeof m=="string"&&i.add({uuid:m});const y=u.xFormTarget;y&&(typeof y=="object"?(i.add(y),r&&(l+=`${u.id}[${u.id}
|
|
@@ -1278,9 +1278,9 @@ ${m}]
|
|
|
1278
1278
|
title Animations
|
|
1279
1279
|
dateFormat X
|
|
1280
1280
|
axisFormat %s
|
|
1281
|
-
`;const p=Array.from(o),m=new Set;for(const v of p)if(v.affectedObjects&&typeof v.affectedObjects!="string"){if(Array.isArray(v.affectedObjects))for(const
|
|
1281
|
+
`;const p=Array.from(o),m=new Set;for(const v of p)if(v.affectedObjects&&typeof v.affectedObjects!="string"){if(Array.isArray(v.affectedObjects))for(const _ of v.affectedObjects)m.add(_);else m.add(v.affectedObjects);r&&(u+=`section ${v.animationName} (${v.id})
|
|
1282
1282
|
`,u+=`${v.id} : ${v.start}, ${v.duration}s
|
|
1283
|
-
`)}r&&o.size&&console.log(u);const y=new Set;for(const v of m){v.getPath||console.error("USDZExporter: Animation target object has no getPath method. This is likely a bug",v);let b=v.getPath();b.startsWith("<")&&(b=b.substring(1)),b.endsWith(">")&&(b=b.substring(0,b.length-1)),y.add({path:b,obj:v})}const _=Array.from(y).sort((v,b)=>v.path.length-b.path.length),g=new Array;for(let v=0;v<_.length;v++)for(let b=v+1;b<_.length;b++)if(_[b].path.startsWith(_[v].path)){const x=_[b],T=_[v];g.push({child:x.obj.displayName+" ("+x.path+")",parent:T.obj.displayName+" ("+T.path+")"})}g.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:g,playAnimationActions:o})}for(const u of new Set([...t,...i]))if(Array.isArray(u))for(const p of u)n.add(p.uuid);else n.add(u.uuid);Rh&&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){Rh&&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 r=await(await(await fetch(t)).blob()).arrayBuffer(),a=new Uint8Array(r);e.files[i]=a}this.behaviourComponentsCopy.length=0,this.audioClipsCopy.length=0}}class _g{get extensionName(){return"Physics"}onExportObject(e,t,i){const n=S.getComponents(e,Ne).filter(l=>l.enabled),o=S.getComponents(e,Kt).filter(l=>l.enabled&&!l.isTrigger);let r=n.length>0?n[0]:null;const a=o.length>0?o[0]:null;a&&!r&&(r=new Ne,r.isKinematic=!0),r&&t.addEventListener("serialize",(l,h)=>{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("}"),o.length>0){const d=o[0];l.beginBlock('def RealityKitStruct "material"',"{",!0);const u=d.sharedMaterial;u&&u.dynamicFriction!==void 0&&l.appendLine(`double dynamicFriction = ${d.sharedMaterial?.dynamicFriction}`),u&&u.bounciness!==void 0&&l.appendLine(`double restitution = ${d.sharedMaterial?.bounciness}`),u&&u.staticFriction!==void 0&&l.appendLine(`double staticFriction = ${d.sharedMaterial?.staticFriction}`),l.closeBlock("}")}l.closeBlock("}")}}),a&&(t.addEventListener("serialize",(l,h)=>{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 u=a.isTrigger?"Trigger":"Default";if(l.appendLine(`token type = "${u}"`),l.beginBlock('def RealityKitStruct "Shape"',"{",!0),a instanceof Sa){const p=a;l.appendLine('token shapeType = "Sphere"'),l.appendLine(`float radius = ${p.radius}`)}else if(a instanceof lu){const p=a;l.appendLine('token shapeType = "Box"'),l.appendLine(`float3 extent = (${p.size.x}, ${p.size.y}, ${p.size.z})`)}else if(a instanceof ls){const p=a;l.appendLine('token shapeType = "Capsule"'),l.appendLine(`float radius = ${p.radius}`),l.appendLine(`float height = ${p.height}`)}else if(a instanceof so&&a.sharedMesh?.geometry){const p=a.sharedMesh.geometry;p.boundingBox||p.computeBoundingBox();const m=a.sharedMesh.geometry.boundingBox;m&&(l.appendLine('token shapeType = "Box"'),l.appendLine(`float3 extent = (${m.max.x-m.min.x}, ${m.max.y-m.min.y}, ${m.max.z-m.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("}")}),o.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 iM=w("debugshadowcomponents");J.__webpack_exports__Block.prototype.interactable={get(){return this.interactive},set(s){this.interactable=s}};class Bi extends k{isRoot(){return this.Root?.gameObject===this.gameObject}get canvas(){const e=this.Root;return e?.isCanvas?e:null}get Canvas(){return this.canvas}markDirty(){jt.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=S.getComponentInParent(this.gameObject,Ac)),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=S.getComponentInParent(i,Bi),!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[ri]=this,this.setShadowComponentOwner(e);let n=!1;if(this.Root?.gameObject===this.gameObject)this.gameObject.add(e);else{const o=this._parentComponent.shadowComponent;o&&(o?.add(e),n=!0)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),fc&&e.add(new c.AxesHelper(.5)),this.onAfterAddedToScene(),n&&J.__webpack_exports__update(),iM&&console.warn("Added shadow component",this.shadowComponent)}setShadowComponentOwner(e){if(e&&(e[ri]===void 0||e[ri]===this)&&(e[ri]=this,e.children))for(const t of e.children)this.setShadowComponentOwner(t)}traverseOwnedShadowComponents(e,t,i){if(e&&e[ri]===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 Ac extends Bi{awake(){super.awake()}}var nM=Object.defineProperty,sM=Object.getOwnPropertyDescriptor,Lc=(s,e,t,i)=>{for(var n=i>1?void 0:i?sM(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&nM(e,t,n),n};const Df=w("debugui"),If=w("debuguilayout");class ew{width;height}class tw{x;y;width;height}const qi=new c.Vector3,tl=new c.Matrix4,Th=new c.Quaternion,Ea=class iw extends Bi{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 c.Vector2),this._anchoredPosition}set anchoredPosition(e){this._anchoredPosition=e}sizeDelta=new c.Vector2(100,100);pivot=new c.Vector2(.5,.5);anchorMin=new c.Vector2(0,0);anchorMax=new c.Vector2(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 c.Object3D,this.rectBlock.name=this.name,this.lastMatrix=new c.Matrix4,this._lastAnchoring=null,this._initialPosition=this.gameObject.position.clone(),this._initialPosition.z=0,this._anchoredPosition||(this._anchoredPosition=new c.Vector2),Ur(this,"_anchoredPosition",()=>{this.markDirty()}),Ur(this,"sizeDelta",()=>{this.markDirty()}),Ur(this,"pivot",()=>{this.markDirty()}),Ur(this,"anchorMin",()=>{this.markDirty()}),Ur(this,"anchorMax",()=>{this.markDirty()})}onEnable(){super.onEnable(),this.rectBlock||(this.rectBlock=new c.Object3D),this.lastMatrix||(this.lastMatrix=new c.Matrix4),this._lastAnchoring||(this._lastAnchoring=new c.Vector2),this._initialPosition||(this._initialPosition=new c.Vector3),this._anchoredPosition||(this._anchoredPosition=new c.Vector2),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(If?`${e.name} changed`:void 0)}get isDirty(){return this._transformNeedsUpdate||(this._transformNeedsUpdate=!this.lastMatrix.equals(this.gameObject.matrix)),this._transformNeedsUpdate}markDirty(){this._transformNeedsUpdate||(If&&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=S.getComponentInParent(this.gameObject.parent,iw):this._parentRectTransform=void 0,this._transformNeedsUpdate=!1,If&&console.warn("RectTransform → ApplyTransform",this.name+" because "+e),this.isRoot()?this.Root.screenspace||(t.rotation.y=Math.PI):(t.matrix.identity(),t.matrixAutoUpdate=!1,qi.set(0,0,0),this.applyPivot(qi),t.matrix.setPosition(qi.x,qi.y,0),(this.gameObject.quaternion.x||this.gameObject.quaternion.y||this.gameObject.quaternion.z)&&(Th.copy(this.gameObject.quaternion),Th.x*=-1,Th.z*=-1,tl.makeRotationFromQuaternion(Th),t.matrix.premultiply(tl)),qi.set(0,0,0),this.applyAnchoring(qi),this.canvas?.screenspace?qi.z+=.1:qi.z+=.01,tl.identity(),tl.setPosition(qi.x,qi.y,qi.z),t.matrix.premultiply(tl),t.matrix.scale(this.gameObject.scale)),this.lastMatrix.copy(this.gameObject.matrix);const i=!0;for(const n of Kd(this.gameObject,Bi,i,1)){if(n===this||!n.activeAndEnabled)continue;const o=n;o.onParentRectTransformChanged&&o.onParentRectTransformChanged(this)}}_lastAnchoring;applyAnchoring(e){this._lastAnchoring||(this._lastAnchoring=new c.Vector2);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 o=1-this.anchorMax.y-this.anchorMin.y;n-=i.height*.5*o,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},Df&&console.log(this.name,e);const t=new J.__webpack_exports__Block(e);return this._createdBlocks.push(t),t}createNewText(e){Df&&console.log(e),e={...this.getBasicOptions(),...e},Df&&console.log(this.name,e);const t=new J.__webpack_exports__Text(e);return this._createdTextBlocks.push(t),t}};Lc([f(c.Vector2)],Ea.prototype,"anchoredPosition",1);Lc([f(c.Vector2)],Ea.prototype,"sizeDelta",2);Lc([f(c.Vector2)],Ea.prototype,"pivot",2);Lc([f(c.Vector2)],Ea.prototype,"anchorMin",2);Lc([f(c.Vector2)],Ea.prototype,"anchorMax",2);let sn=Ea;var oM=Object.defineProperty,nw=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&oM(e,t,n),n};class Ra extends k{effectColor;effectDistance}nw([f(Z)],Ra.prototype,"effectColor");nw([f(c.Vector2)],Ra.prototype,"effectDistance");var rM=Object.defineProperty,aM=Object.getOwnPropertyDescriptor,sw=(s,e,t,i)=>{for(var n=i>1?void 0:i?aM(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&rM(e,t,n),n};const Ah={backgroundColor:new c.Color(1,1,1),backgroundOpacity:1,borderColor:new c.Color(1,1,1),borderOpacity:1},bg=class vl extends Bi{get isGraphic(){return!0}get color(){return this._color||(this._color=new Z(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 Z(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 c.Color(1,0,1);onColorChanged(){this.uiObject&&(this.sRGBColor.copy(this._color),this.sRGBColor.convertLinearToSRGB(),Ah.backgroundColor=this.sRGBColor,Ah.backgroundOpacity=this._color.alpha*this._alphaFactor,this.applyEffects(Ah,this._alphaFactor),this.uiObject.set(Ah),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=S.getComponent(this.gameObject,sn)),!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 J.SimpleStateBehavior(this.uiObject)),this.uiObject.setupState(e.state,e.attributes))}setOptions(e){this.makePanel(),this.uiObject&&this.uiObject.set(e)}awake(){super.awake(),this.makePanel(),Ur(this,"_color",()=>iP(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 t={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:.015};this.onBeforeCreate(t),this.applyEffects(t),this.onCreate(t),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(Ra);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(vl.textureCache.has(e))e=vl.textureCache.get(e);else if(!e.isRenderTargetTexture){const t=e.clone();t.colorSpace=c.LinearSRGBColorSpace,vl.textureCache.set(e,t),e=t}this.setOptions({backgroundImage:e,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"}),ne.NEEDLE_progressive.assignTextureLOD(e,0).then(t=>{t instanceof c.Texture&&(e&&vl.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)}};sw([f(Z)],bg.prototype,"color",1);sw([f()],bg.prototype,"raycastTarget",2);let Dc=bg;class Ic extends Dc{_flippedObject=!1;onAfterCreated(){this.uiObject&&!this._flippedObject&&(this._flippedObject=!0,this.uiObject.scale.y*=-1)}}var lM=Object.defineProperty,cM=Object.getOwnPropertyDescriptor,gs=(s,e,t,i)=>{for(var n=i>1?void 0:i?cM(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&lM(e,t,n),n};const bo=w("debugtext");var Qe=(s=>(s[s.UpperLeft=0]="UpperLeft",s[s.UpperCenter=1]="UpperCenter",s[s.UpperRight=2]="UpperRight",s[s.MiddleLeft=3]="MiddleLeft",s[s.MiddleCenter=4]="MiddleCenter",s[s.MiddleRight=5]="MiddleRight",s[s.LowerLeft=6]="LowerLeft",s[s.LowerCenter=7]="LowerCenter",s[s.LowerRight=8]="LowerRight",s))(Qe||{}),ow=(s=>(s[s.Normal=0]="Normal",s[s.Bold=1]="Bold",s[s.Italic=2]="Italic",s[s.BoldAndItalic=3]="BoldAndItalic",s))(ow||{});class St extends Dc{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 c.Color(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){bo&&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,bo&&(e.backgroundColor=16750848,e.backgroundOpacity=.5);const t=this.rectTransform;e={...e,...this.getTextOpts()},this.getAlignment(e),bo&&(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(bo&&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 o=new J.__webpack_exports__Inline({textContent:e.substring(0,i.startIndex),color:"inherit"});this.uiObject.add(o)}}else{this.uiObject.textContent="",this.setOptions({textContent:e});return}const n=[];for(;i;){const o=this.getNextTag(e,i.endIndex),r={fontFamily:this.uiObject?.get("fontFamily"),color:"inherit",textContent:""};if(o){r.textContent=this.getText(e,i,o),this.handleTag(i,r,n);const a=new J.__webpack_exports__Inline(r);this.uiObject?.add(a)}else{r.textContent=e.substring(i.endIndex),this.handleTag(i,r,n);const a=new J.__webpack_exports__Inline(r);this.uiObject?.add(a)}i=o}}}_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 o=0;o<this._textMeshUi.length;o++){if(e[o]===!0)continue;n=!0;const r=this._textMeshUi[o];r.textContent&&(Od(r,i),e[o]=!0)}if(!n)break;yield}}handleTag(e,t,i){if(!e.isEndTag){if(e.type.includes("color")){const n=new jf(e,{color:t.color});if(i.push(n),e.type.length>6){const o=parseInt("0x"+e.type.substring(7));t.color=o}else t.color=new c.Color(1,1,1)}else if(e.type=="b"){this.setFont(t,1);const n=new jf(e,{fontWeight:700});i.push(n)}else if(e.type=="i"){this.setFont(t,2);const n=new jf(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 o=e.substring(i+1,n);return{type:o,startIndex:i,endIndex:n+1,isEndTag:o.startsWith("/")}}return null}setFont(e,t){if(!this.font)return;const i=this.font,n=this.getFamilyNameWithCorrectSuffix(i,t);bo&&console.log("Selected font family:"+n);let o=J.__webpack_exports__FontLibrary.getFontFamily(n);switch(o||(o=J.__webpack_exports__FontLibrary.addFontFamily(n)),e.fontFamily=o,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=o.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=o.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(hM.includes(n))return bo&&console.warn("Unsupported font style: "+n),e;const o=e.lastIndexOf("/");let r=e;o>=0&&(r=r.substring(o+1));const a=r[0]===r[0].toUpperCase(),l=e.substring(0,i);switch(bo&&console.log("Select font: ",e,ow[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}}}gs([f()],St.prototype,"alignment",2);gs([f()],St.prototype,"verticalOverflow",2);gs([f()],St.prototype,"horizontalOverflow",2);gs([f()],St.prototype,"lineSpacing",2);gs([f()],St.prototype,"supportRichText",2);gs([f(URL)],St.prototype,"font",2);gs([f()],St.prototype,"fontStyle",2);gs([f()],St.prototype,"text",1);gs([f()],St.prototype,"fontSize",1);class jf{tag;previousValues;constructor(e,t){this.tag=e,this.previousValues=t}}const hM=["medium","mediumitalic","black","blackitalic","thin","thinitalic","extrabold","light","lightitalic","semibold"];class Yr{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/${uu(this.material)}>`),t.closeBlock()}}class vg{static singleLine(e,t,i){const n=new Yr("text_"+Yr.getId());return n.content=e,t&&(n.pointSize=t),i&&(n.depth=i),n}static multiLine(e,t,i,n,o,r){const a=new Yr("text_"+Yr.getId());return a.content=e,a.width=t,a.height=i,a.horizontalAlignment=n,a.verticalAlignment=o,r!==void 0&&(a.wrapMode=r),a}}const dM=new c.Matrix4().makeRotationY(Math.PI),uM=new c.Matrix4().makeScale(-1,1,-1);class vu{get extensionName(){return"text"}exportText(e,t,i){const n=S.getComponent(e,St);if(!n)return;const o=S.getComponent(e,sn);let r=100,a=100;o&&(r=o.width,a=o.height);const l=dM.clone();o&&l.premultiply(uM),t.setMatrix(l);const h=n.color.clone();t.material=new c.MeshStandardMaterial({color:h,emissive:h}),t.addEventListener("serialize",(d,u)=>{let p=n.text;p=p.replace(/\r/g,""),p=p.replace(/\n/g,"\\n");const m=vg.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,d)})}convertToTextSize(e){return 1/.0502*144*e}setOverflow(e,t){t.horizontalOverflow?e.wrapMode="singleLine":e.wrapMode="flowing"}setTextAlignment(e,t){switch(t){case Qe.LowerLeft:case Qe.MiddleLeft:case Qe.UpperLeft:e.horizontalAlignment="left";break;case Qe.LowerCenter:case Qe.MiddleCenter:case Qe.UpperCenter:e.horizontalAlignment="center";break;case Qe.LowerRight:case Qe.MiddleRight:case Qe.UpperRight:e.horizontalAlignment="right";break}switch(t){case Qe.LowerLeft:case Qe.LowerCenter:case Qe.LowerRight:e.verticalAlignment="bottom";break;case Qe.MiddleLeft:case Qe.MiddleCenter:case Qe.MiddleRight:e.verticalAlignment="middle";break;case Qe.UpperLeft:case Qe.UpperCenter:case Qe.UpperRight:e.verticalAlignment="top";break}}}var fM=Object.defineProperty,We=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&fM(e,t,n),n};const A_=w("debuguilayout");class fr{left=0;right=0;top=0;bottom=0;get vertical(){return this.top+this.bottom}get horizontal(){return this.left+this.right}}We([f()],fr.prototype,"left");We([f()],fr.prototype,"right");We([f()],fr.prototype,"top");We([f()],fr.prototype,"bottom");class _i extends k{_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&&(A_&&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(){A_&&console.log(this.name,this),this._rectTransform=this.gameObject.getComponent(sn);const e=this.gameObject.getComponentInParent(ya);e&&e.registerLayoutGroup(this),this._needsUpdate=!0}onDisable(){const e=this.gameObject.getComponentInParent(ya);e&&e.unregisterLayoutGroup(this)}set m_Spacing(e){e!==this.spacing&&(this._needsUpdate=!0,this.spacing=e)}get m_Spacing(){return this.spacing}}We([f()],_i.prototype,"childAlignment");We([f()],_i.prototype,"reverseArrangement");We([f()],_i.prototype,"spacing");We([f(fr)],_i.prototype,"padding");We([f()],_i.prototype,"minWidth");We([f()],_i.prototype,"minHeight");We([f()],_i.prototype,"flexibleHeight");We([f()],_i.prototype,"flexibleWidth");We([f()],_i.prototype,"preferredHeight");We([f()],_i.prototype,"preferredWidth");class ao extends _i{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 o=e.height;let r=o;n-=this.padding.horizontal,r-=this.padding.vertical,t==="x"?this.padding.horizontal:this.padding.vertical;const a=t==="x",l=a?"y":"x",h=a?this.childControlWidth:this.childControlHeight,d=a?this.childControlHeight:this.childControlWidth,u=a?this.childForceExpandWidth:this.childForceExpandHeight,p=a?this.childForceExpandHeight:this.childForceExpandWidth,m=a?r:n,y=a?i:o,_=.5*(a?this.childAlignment%3:Math.floor(this.childAlignment/3));let g=0;a?g+=this.padding.left:g+=this.padding.top;let v=0,b=0;for(let E=0;E<this.gameObject.children.length;E++){const j=this.gameObject.children[E],L=S.getComponent(j,sn);L?.activeAndEnabled&&(b+=1,a?v+=L.width:v+=L.height)}let x=0;const T=this.spacing*(b-1);if(u||h){let E=0;a?E=n-=T:E=r-=T,b>0&&(x=E/b)}let O=0;O+=this.padding.left,O-=this.padding.right,_!==0&&(g=y-v,g*=_,g-=T*_,a?(g-=this.padding.right*_,g+=this.padding.left*(1-_),g<this.padding.left&&(g=this.padding.left)):(g-=this.padding.bottom*_,g+=this.padding.top*(1-_),g<this.padding.top&&(g=this.padding.top)));let M=1;for(let E=0;E<this.gameObject.children.length;E++){const j=this.gameObject.children[E],L=S.getComponent(j,sn);if(L?.activeAndEnabled){L.pivot?.set(.5,.5),L.anchorMin.set(0,1),L.anchorMax.set(0,1);const z=i*.5+O*.5;L.anchoredPosition.x!==z&&(L.anchoredPosition.x=z);const $=o*-.5;L.anchoredPosition.y!==$&&(L.anchoredPosition.y=$),p&&d&&L.sizeDelta[l]!==m&&(L.sizeDelta[l]=m),u&&h&&L.sizeDelta[t]!==x&&(L.sizeDelta[t]=x);const R=a?L.width:L.height,U=R*.5;if(g+=U,u){const K=x*M-x*.5;K>g&&(g=K-x*.5+R+this.padding.left,g-=U)}let N=g;t==="y"&&(N=-N),L.anchoredPosition[t]!==N&&(L.anchoredPosition[t]=N),g+=U,g+=this.spacing,M+=1}}}}We([f()],ao.prototype,"childControlHeight");We([f()],ao.prototype,"childControlWidth");We([f()],ao.prototype,"childForceExpandHeight");We([f()],ao.prototype,"childForceExpandWidth");We([f()],ao.prototype,"childScaleHeight");We([f()],ao.prototype,"childScaleWidth");class wg extends ao{get primaryAxis(){return"y"}}class xg extends ao{get primaryAxis(){return"x"}}class Sg extends _i{onCalculateLayout(){}}var pM=Object.defineProperty,mM=Object.getOwnPropertyDescriptor,Fn=(s,e,t,i)=>{for(var n=i>1?void 0:i?mM(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&pM(e,t,n),n},rw=(s=>(s[s.ScreenSpaceOverlay=0]="ScreenSpaceOverlay",s[s.ScreenSpaceCamera=1]="ScreenSpaceCamera",s[s.WorldSpace=2]="WorldSpace",s[s.Undefined=-1]="Undefined",s))(rw||{});const Bf=w("debuguilayout"),Fi=class aw extends Ac{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 aw||(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,Bf&&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 c.Matrix4,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 lc(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(),jt.ensureUpdateMeshUI(J.ThreeMeshUI,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(),jt.ensureUpdateMeshUI(J.ThreeMeshUI,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 c.Matrix4);const e=!this._lastMatrixWorld.equals(this.gameObject.matrixWorld);Bf&&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(_i)),(t.isDirty||i?.isDirty)&&(Bf&&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(),pe.OnBeforeRender))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.onUpdateRenderMode(),Od(this.shadowComponent,this);for(const e of S.getComponentsInChildren(this.gameObject,Bi))Od(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 o=this.gameObject.getComponent(sn);let r=!1;o.sizeDelta.x!==this.context.domWidth&&(r=!0),o.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&&(o.sizeDelta.x=this.context.domWidth,o.sizeDelta.y=this.context.domHeight,o?.markDirty());break;case 2:this._lastWidth=-1,this._lastHeight=-1;break}}};Fn([f()],Fi.prototype,"renderOnTop",1);Fn([f()],Fi.prototype,"depthWrite",1);Fn([f()],Fi.prototype,"doubleSided",1);Fn([f()],Fi.prototype,"castShadows",1);Fn([f()],Fi.prototype,"receiveShadows",1);Fn([f()],Fi.prototype,"renderMode",1);Fn([f(Fi)],Fi.prototype,"rootCanvas",1);Fn([f()],Fi.prototype,"scaleFactor",1);Fn([f(qt)],Fi.prototype,"worldCamera",2);Fn([f()],Fi.prototype,"planeDistance",2);let ya=Fi;var gM=Object.defineProperty,yM=Object.getOwnPropertyDescriptor,Cg=(s,e,t,i)=>{for(var n=i>1?void 0:i?yM(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&gM(e,t,n),n};class Ks extends k{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(),pe.OnBeforeRender))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}_buffer=[];applyChangesNow(){this._buffer.length=0;for(const e of S.getComponentsInChildren(this.gameObject,Bi,this._buffer)){const t=e;t.setAlphaFactor&&t.setAlphaFactor(this._alpha)}}}Cg([f()],Ks.prototype,"alpha",1);Cg([f()],Ks.prototype,"interactable",2);Cg([f()],Ks.prototype,"blocksRaycasts",2);class Pg{get extensionName(){return"tmui"}onExportObject(e,t,i){const n=S.getComponent(e,ya);if(n&&n.enabled&&n.renderMode===rw.WorldSpace){const o=new vu,r=S.getComponent(e,sn),a=S.getComponent(e,Ks),l=new Array;if(r){if(!S.isActiveSelf(e)){const u=S.isActiveSelf(e);S.setActive(e,!0),r.onEnable(),r.updateTransform(),l.push(()=>{r.onDisable(),S.setActive(e,u)})}e.traverse(u=>{if(!S.isActiveInHierarchy(u)){const p=S.isActiveSelf(u);S.setActive(u,!0);const m=S.getComponent(u,Bi);m&&(m.onEnable(),l.push(()=>{m.onDisable()}));const y=S.getComponent(u,sn);y&&(y.onEnable(),y.updateTransform(),y.onApplyTransform(),l.push(()=>{y.onDisable()}));const _=S.getComponent(u,St);_&&(_.onEnable(),l.push(()=>{_.onDisable()})),l.push(()=>{S.setActive(u,p)})}}),r.width,r.height;const h=ze.createEmpty(),d=r.shadowComponent;if(t.add(h),d){const u=d.matrix;h.setMatrix(u);const p=new Map,m=new Map;p.set(d,h),m.set(d,a?a.alpha:1),d.traverse(y=>{if(y===d)return;const _=ze.createEmpty();_.setMatrix(y.matrix);const g=y.parent,v=!!g&&typeof g.textContent=="string"&&g.textContent.length>0;let b=m.get(g)||1;const x=S.getComponent(y,Ks);if(x&&(b*=x.alpha),y instanceof c.Mesh&&v){const O=y[ri];O?o.exportText(O.gameObject,_,i):console.error("Error when exporting UI: shadow component owner not found. This is likely a bug.",y)}if(y instanceof c.Mesh&&!v){const O=y.geometry.clone();O.scale(1,1,-1),this.flipWindingOrder(O),_.geometry=O;const M=new c.Color,E=y.material.opacity;M.copy(y.material.color),_.material=new c.MeshBasicMaterial({color:M,opacity:E*b,map:y.material.map,transparent:!0})}p.set(y,_),m.set(y,b);const T=p.get(g);if(!T){console.error("Error when exporting UI: shadow component parent not found!",y,y.parent);return}T.add(_)})}}for(const h of l)h()}}flipWindingOrder(e){const t=e.index.array;for(let i=0,n=t.length/3;i<n;i++){const o=t[i*3];t[i*3]=t[i*3+2],t[i*3+2]=o}e.index.needsUpdate=!0}}const wl=w("debugusdz");function _M(s,e){const t=[],i=S.getComponentsInChildren(s,rt),n=S.getComponentsInChildren(s,Ft),o=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||o.includes(a))continue;const h=new ec;h.animator=a,h.stateName=l.name,h.trigger="start",h.name="PlayAnimationOnClick_implicitAtStart_"+h.stateName;const d=new c.Object3D;S.addComponent(d,h),r.push(d),o.push(a),s.add(d)}else for(const a of i){if(!a||!a.runtimeAnimatorController||!a.enabled)continue;wl&&console.log(a);const l=[];for(const h of a.runtimeAnimatorController.enumerateActions()){wl&&console.log(h);const d=h.getClip();l.includes(d)||l.push(d)}t.push({root:a.gameObject,clips:l})}if(e.injectImplicitBehaviours)for(const a of n){if(!a||!a.clip||!a.enabled||!a.playAutomatically||o.includes(a))continue;const l=new ec;l.animation=a,l.stateName=a.clip.name,l.trigger="start",l.name="PlayAnimationOnClick_implicitAtStart_"+l.stateName;const h=new c.Object3D;S.addComponent(h,l),r.push(h),o.push(a),s.add(h)}else for(const a of n){wl&&console.log(a);const l=[];for(const h of a.animations)l.includes(h)||l.push(h);t.push({root:a.gameObject,clips:l})}wl&&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 bM(s,e){const t=S.getComponentsInChildren(s,pi),i=S.getComponentsInChildren(s,Qs),n=new Array,o=new Array;wl&&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 Qs;a.target=r,a.name="PlayAudioOnClick_implicitAtStart_",a.trigger="start";const l=new c.Object3D;S.addComponent(l,a),console.log("implicit PlayAudioOnStart",l,a),o.push(l),n.push(r),s.add(l)}return o}function vM(s){return new gt("DisableAtStart",wt.sceneStartTrigger(),le.fadeAction(s,0,!1))}function L_(s,e){const t=s.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 o=document.createElement("a");o.id="needle-usdz-link",o.style.display="none",o.rel="ar",o.href="",o.target="_blank",i.appendChild(o);const r=document.createElement("img");return r.id="button",o.appendChild(r),s.domElement.shadowRoot.appendChild(i),o}var wM=Object.defineProperty,_t=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&wM(e,t,n),n};const ii=w("debugusdz"),xM=w("debugusdzpruning");class pr{callToAction;checkoutTitle;checkoutSubtitle;callToActionURL}_t([f()],pr.prototype,"callToAction");_t([f()],pr.prototype,"checkoutTitle");_t([f()],pr.prototype,"checkoutSubtitle");_t([f()],pr.prototype,"callToActionURL");const Jt=class xl extends k{static beforeExport=new oe;static afterExport=new oe;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=exports.DeviceUtilities.supportsQuickLookAR(),t=exports.DeviceUtilities.isiOS()||exports.DeviceUtilities.isiPad();!this.button&&(ii||e||t)&&(this.allowCreateQuicklookButton&&(this.button=this.createQuicklookButton()),this.lastCallback=this.quicklookCallback.bind(this),this.link=L_(this.context,e),this.link.addEventListener("message",this.lastCallback)),ii&&Se("USDZ Exporter enabled: "+this.name),document.getElementById("open-in-ar")?.addEventListener("click",this.onClickedOpenInARElement),Gl.registerExporter(this)}onDisable(){this.button?.remove(),this.link?.removeEventListener("message",this.lastCallback),ii&&Se("USDZ Exporter disabled: "+this.name),document.getElementById("open-in-ar")?.removeEventListener("click",this.onClickedOpenInARElement),Gl.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+="-"+B0(),En()||(e!==""&&(e+="-"),e+="MadeWithNeedle"),this.link||(this.link=L_(this.context,exports.DeviceUtilities.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;xl.beforeExport.invoke({exporter:this});const t=await this.export(this.objectToExport).finally(()=>{xl.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 – please report a bug!",n),null))):i}_currentExportTasks=new Map;_previousTimeScale=1;async internalExport(e){ie.start("export-usdz",{onProgress:O=>{this.dispatchEvent(new CustomEvent("export-progress",{detail:{progress:O}}))}}),ie.report("export-usdz",{message:"Starting export",totalSteps:40,currentStep:0}),ie.report("export-usdz",{message:"Load progressive textures",autoStep:5}),ie.start("export-usdz-textures","export-usdz");const t=S.getComponentsInChildren(e,Zt);for(const O of t)O&&O.enabled&&O.updateSprite(!0);const i=S.getComponentsInChildren(e,mi),n=new Array;let o=0;for(const O of i){for(const M of O.sharedMeshes)if(M){const E=ne.NEEDLE_progressive.assignMeshLOD(M,0);E instanceof Promise&&n.push(new Promise((j,L)=>{E.then(()=>{o++,ie.report("export-usdz-textures",{message:"Loaded progressive mesh",currentStep:o,totalSteps:n.length}),j()}).catch(z=>L(z))}))}for(const M of O.sharedMaterials)if(M){const E=ne.NEEDLE_progressive.assignTextureLOD(M,0);E instanceof Promise&&n.push(new Promise((j,L)=>{E.then(()=>{o++,ie.report("export-usdz-textures",{message:"Loaded progressive texture",currentStep:o,totalSteps:n.length}),j()}).catch(z=>L(z))}))}}ii&&Se("Progressive Loading: "+n.length),await Promise.all(n),ii&&Se("Progressive Loading: done"),ie.end("export-usdz-textures");const r=It.Global.Mask;It.Global.Set(wn.AR);const a=new V0,l=new fu(this.quickLookCompatible);let h;const d=[];this.interactive&&(d.push(new yg),d.push(new dr),globalThis.NEEDLE_USE_RAPIER&&S.getComponentsInChildren(e,Ne).length>0&&(this.physics?(h=new _g,d.push(h)):A()&&console.warn("USDZExporter: Physics export is disabled, but there are active Rigidbody components in the scene. They will not be exported.")),d.push(new vu),d.push(new Pg));const u=[l,...d,...this.extensions],p={self:this,exporter:a,extensions:u,object:e};ie.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,ie.report("export-usdz","auto export animations and audio sources");const m=new Array;this.autoExportAnimations&&m.push(..._M(e,l)),u.find(O=>O.extensionName==="Audio")&&this.autoExportAudioSources&&m.push(...bM(e)),a.debug=ii,a.pruneUnusedNodes=!xM;const _=Ko.instance.objs.map(O=>O.batchedMesh);a.keepObject=O=>{let M=!0;const E=S.getComponent(O,mi);return E&&!E.enabled&&(M=!1),M&&_.includes(O)&&(M=!1),M&&S.getComponentInParent(O,Pc)&&(M=!1),M&&S.getComponentInParent(O,In)&&(M=!1),ii&&!M&&console.log("USDZExporter: Discarding object",O),M},a.beforeWritingDocument=()=>{if(A()&&l&&h){const O=l.animatedRoots;for(const M of O){const E=S.getComponentsInChildren(M,Ne).filter(L=>L.enabled),j=S.getComponents(M,Kt).filter(L=>L.enabled&&!L.isTrigger);(E.length>0||j.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.",M)}}};const g=new Array;this.objectToExport&&this.quickLookCompatible&&this.interactive&&this.objectToExport.traverse(O=>{O.visible||g.push(O)});const v=u.find(O=>O.extensionName==="Behaviour");this.interactive&&v&&g.length>0&&v.addBehavior(vM(g));let b=!0;this.quickLookCompatible&&!this.interactive&&(b=!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"),ie.report("export-usdz","Invoking exporter.parse");const x=await a.parse(this.objectToExport,{ar:{anchoring:{type:this.anchoringType},planeAnchoring:{alignment:this.planeAnchoringAlignment}},extensions:u,quickLookCompatible:this.quickLookCompatible,maxTextureSize:this.maxTextureSize,exportInvisible:b}),T=new Blob([x],{type:"model/vnd.usdz+zip"});this.revertWebARSessionRoot(),this.context.time.timeScale=this._previousTimeScale,ie.report("export-usdz","Invoking after-export"),this.dispatchEvent(new CustomEvent("after-export",{detail:p}));for(const O of m)S.destroy(O);return It.Global.Set(r),ie.end("export-usdz"),T}openInQuickLook(e,t){const i=e instanceof Blob?URL.createObjectURL(e):e,n=this.buildQuicklookOverlay();ii&&console.log("QuickLook Overlay",n);const o=n.callToAction?encodeURIComponent(n.callToAction):"",r=n.checkoutTitle?encodeURIComponent(n.checkoutTitle):"",a=n.checkoutSubtitle?encodeURIComponent(n.checkoutSubtitle):"";this.link.href=i+`#callToAction=${o}&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){xl.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&&he("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&&Se("Quicklook url: "+n),n&&(En()?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),En()||(console.log("Custom Quicklook banner text requires pro license: https://needle.tools/pricing"),e.callToAction="Close",e.checkoutTitle="🌵 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 c.Matrix4().makeRotationY(Math.PI);static invertForwardQuaternion=new c.Quaternion().setFromEuler(new c.Euler(0,Math.PI,0));_rootSessionRootWasAppliedTo=null;_rootPositionBeforeExport=new c.Vector3;_rootRotationBeforeExport=new c.Quaternion;_rootScaleBeforeExport=new c.Vector3;getARScaleAndTarget(){if(!this.objectToExport)return{scale:1,_invertForward:!1,target:this.gameObject,sessionRoot:null};const e=S.findObjectOfType(bu);let t=S.getComponentInParent(this.objectToExport,hi);t||(t=S.getComponentInChildren(this.objectToExport,hi));let i=1,n=!1;const o=this.objectToExport;return e?i=e.arScale:t&&(i=t.arScale,n=t.invertForward),{scale:1/i,_invertForward:n,target:o,sessionRoot:t?.gameObject??null}}applyWebARSessionRoot(){if(!this.objectToExport)return;const{scale:e,_invertForward:t,target:i,sessionRoot:n}=this.getARScaleAndTarget(),o=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(xl.invertForwardQuaternion),i.updateMatrix(),i.updateMatrixWorld(!0),n&&o&&i.matrix.premultiply(o)}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 t=qs.getOrCreate().createQuicklookButton();return t.parentNode||this.context.menu.appendChild(t),t}};_t([f(c.Object3D)],Jt.prototype,"objectToExport");_t([f()],Jt.prototype,"autoExportAnimations");_t([f()],Jt.prototype,"autoExportAudioSources");_t([f()],Jt.prototype,"exportFileName");_t([f(URL)],Jt.prototype,"customUsdzFile");_t([f(pr)],Jt.prototype,"customBranding");_t([f()],Jt.prototype,"anchoringType");_t([f()],Jt.prototype,"maxTextureSize");_t([f()],Jt.prototype,"planeAnchoringAlignment");_t([f()],Jt.prototype,"interactive");_t([f()],Jt.prototype,"physics");_t([f()],Jt.prototype,"allowCreateQuicklookButton");_t([f()],Jt.prototype,"quickLookCompatible");let Tn=Jt;var SM=Object.defineProperty,CM=Object.getOwnPropertyDescriptor,Og=(s,e,t,i)=>{for(var n=CM(e,t),o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&SM(e,t,n),n};class Ta extends k{get fog(){return this._fog||(this._fog=new c.Fog(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)}}Og([f()],Ta.prototype,"near");Og([f()],Ta.prototype,"far");Og([f(c.Color)],Ta.prototype,"color");var PM=Object.defineProperty,Mg=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&PM(e,t,n),n};class mr extends k{objectBounds=!1;color;isGizmo=!0;_gizmoObject=null;_boxHelper=null;onEnable(){this.isGizmo&&!fc||(this._gizmoObject||(this.objectBounds?this._gizmoObject=new c.BoxHelper(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=ym(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),pe.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){for(;this._boxHelper;)this._boxHelper?.update(),yield}}Mg([f()],mr.prototype,"objectBounds");Mg([f(c.Color)],mr.prototype,"color");Mg([f()],mr.prototype,"isGizmo");var OM=Object.defineProperty,kg=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&OM(e,t,n),n};class Aa extends k{isGizmo=!1;color0;color1;gridHelper;size;divisions;offset;onEnable(){if(this.isGizmo&&!fc)return;const e=this.size,t=this.divisions;this.gridHelper||(this.gridHelper=new c.GridHelper(e,t,this.color0??new c.Color(.4,.4,.4),this.color1??new c.Color(.6,.6,.6)),this.offset!==void 0&&(this.gridHelper.position.y+=this.offset)),this.gridHelper&&this.gameObject.add(this.gridHelper)}onDisable(){this.gridHelper&&(this.gameObject.remove(this.gridHelper),this.gridHelper=null)}}kg([f()],Aa.prototype,"isGizmo");kg([f(c.Color)],Aa.prototype,"color0");kg([f(c.Color)],Aa.prototype,"color1");var MM=Object.defineProperty,Eg=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&MM(e,t,n),n};class Rg extends k{connectedBody;get rigidBody(){return this._rigidBody}_rigidBody=null;onEnable(){this._rigidBody||(this._rigidBody=this.gameObject.getComponent(Ne)),this.rigidBody&&this.connectedBody&&this.startCoroutine(this.create())}*create(){yield,this.rigidBody&&this.connectedBody&&this.activeAndEnabled&&this.createJoint(this.rigidBody,this.connectedBody)}}Eg([f(Ne)],Rg.prototype,"connectedBody");class Tg extends Rg{createJoint(e,t){this.context.physics.engine?.addFixedJoint(e,t)}}class jc extends Rg{anchor;axis;createJoint(e,t){this.axis&&this.anchor&&this.context.physics.engine?.addHingeJoint(e,t,this.anchor,this.axis)}}Eg([f(c.Vector3)],jc.prototype,"anchor");Eg([f(c.Vector3)],jc.prototype,"axis");var kM=Object.defineProperty,EM=Object.getOwnPropertyDescriptor,Un=(s,e,t,i)=>{for(var n=i>1?void 0:i?EM(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&kM(e,t,n),n};function Ff(s){return s*Math.PI/180}const D_=300,Rs=w("debuglights");class ei extends k{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 c.Color(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}Rs&&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 c.Color(this.color??16777215),Rs&&console.log(this.name,this)}onEnable(){Rs&&console.log("ENABLE LIGHT",this.name),this.createLight(),!this.isBaked&&(this.light&&(this.light.visible=!0,this.light.intensity=this._intensity,Rs&&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(),pe.LateUpdate))}onDisable(){Rs&&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=S.getComponentInParent(this.gameObject,hi)??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 c.DirectionalLight(this.color,this.intensity*Math.PI);if(t.position.set(0,0,-D_*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(t.target),Wo(t.target,0,0,0),this.light=t,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),Rs){const r=new c.DirectionalLightHelper(this.light,.2,this.color);this.context.scene.add(r)}break;case 0:const i=new c.SpotLight(this.color,this.intensity*Math.PI,this.range,Ff(this.spotAngle/2),1-Ff(this.innerSpotAngle/2)/Ff(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 o=new c.PointLight(this.color,this.intensity*Math.PI,this.range);this.light=o;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),Rs&&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=D_*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,Rs&&this.context.scene.add(new c.CameraHelper(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)}}Un([f()],ei.prototype,"type",2);Un([f(c.Color)],ei.prototype,"color",1);Un([f()],ei.prototype,"shadowNearPlane",1);Un([f()],ei.prototype,"shadowBias",1);Un([f()],ei.prototype,"shadowNormalBias",1);Un([f()],ei.prototype,"shadows",1);Un([f()],ei.prototype,"lightmapBakeType",2);Un([f()],ei.prototype,"intensity",1);Un([f()],ei.prototype,"shadowDistance",1);Un([f()],ei.prototype,"shadowResolution",1);new c.Vector3(0,0,0);var RM=Object.defineProperty,Bc=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&RM(e,t,n),n};const Uf=w("debuglods"),TM=w("nolods");class La{screenRelativeTransitionHeight;distance;renderers}Bc([f()],La.prototype,"screenRelativeTransitionHeight");Bc([f()],La.prototype,"distance");Bc([f(mi)],La.prototype,"renderers");class AM{model;get renderers(){return this.model.renderers}constructor(e){this.model=e}}class Fc extends k{fadeMode=0;localReferencePoint=void 0;lodCount=0;size=0;animateCrossFading=!1;lodModels;_lods=[];_settings=[];_lodsHandler;start(){if(Uf&&console.log("LODGROUP",this.name,this.lodModels,this),!TM&&!this._lodsHandler&&this.gameObject&&this.lodModels&&Array.isArray(this.lodModels)){const e=[];for(const i of this.lodModels){const n=new AM(i);this._lods.push(n);for(const o of n.renderers)e.includes(o)||e.push(o)}this._lodsHandler=new Array;for(let i=0;i<e.length;i++){const n=new c.LOD;this._lodsHandler.push(n),this.gameObject.add(n)}const t=new c.Object3D;t.name="Cull "+this.name;for(let i=0;i<e.length;i++){const n=e[i],o=this._lodsHandler[i],r=n.gameObject;Uf&&console.log(i,r.name);for(const a of this._lods){const l=a.model.distance;let h=null;if(a.renderers.includes(n)?h=r:h=t,h.type==="Group"){console.warn(`LODGroup ${this.name}: Group or MultiMaterial object's are not supported as LOD object: ${h.name}`);continue}Uf&&console.log("LEVEL",h.name,l),o.autoUpdate=!1,this.onAddLodLevel(o,h,a.model.distance)}}}}onAfterRender(){if(!this.gameObject||!this._lodsHandler)return;const e=this.context.mainCamera;if(e)for(const t of this._lodsHandler){t.update(e);const i=t.getCurrentLevel(),n=t.levels[i];t.layers.mask=n.object.layers.mask}}onAddLodLevel(e,t,i){if(t===this.gameObject){console.warn("LODGroup component must be on parent object and not mesh directly at the moment",t.name,t);return}e.addLevel(t,i*this._distanceFactor,.01);const n={lod:e,levelIndex:e.levels.length-1,distance:i};this._settings.push(n)}_distanceFactor=1;distanceFactor(e){if(e!==this._distanceFactor){this._distanceFactor=e;for(const t of this._settings){const i=t.lod.levels[t.levelIndex];i.distance=t.distance*e}}}}Bc([f(c.Vector3)],Fc.prototype,"localReferencePoint");Bc([f(La)],Fc.prototype,"lodModels");var LM=Object.defineProperty,lw=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&LM(e,t,n),n};const Lh=w("debugnestedgltf");class Uc extends k{filePath;loaded=new oe;loadAssetInParent=!0;_isLoadingOrDoneLoading=!1;listenToProgress(e){this.filePath?.beginListenDownload(e)}preload(){return this.filePath?.preload()||null}async start(){if(this._isLoadingOrDoneLoading)return;Lh&&console.log(this,this.guid);const e=this.gameObject.parent;if(e&&this.filePath){this._isLoadingOrDoneLoading=!0;const t=new on;t.idProvider=new mt(this.hash(this.guid)),t.parent=this.loadAssetInParent!==!1?e:this.gameObject,this.gameObject.updateMatrix();const i=this.gameObject.matrix;Lh&&console.log("Load nested:",this.filePath?.url??this.filePath,this.gameObject.position);const n=await this.filePath?.instantiate?.call(this.filePath,t);Lh&&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})),Lh&&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}}lw([f(Y)],Uc.prototype,"filePath");lw([f(oe)],Uc.prototype,"loaded");var DM=Object.defineProperty,Ag=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&DM(e,t,n),n};const IM=w("debugnet"),wu=class Ip extends k{url=null;urlParameterName=null;localhost=null;awake(){IM&&console.log(this),this.context.connection.registerProvider(this)}getWebsocketUrl(){let e=this.url?Ip.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){const o=w(this.urlParameterName);o&&typeof o=="string"&&(e=o)}if(!e)return null;const i=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(e);return i?.groups?i?.groups.socket_prefix?e:"wss://"+i?.groups.url:null}static GetUrl(e,t){let i=e;const n=Ip.IsLocalNetwork()&&t;if(n&&(i=t),e?.startsWith("/")){const o=n?i:window.location.origin;o?.endsWith("/")&&e.startsWith("/")&&(e=e.substring(1)),i=o+e}return i}static IsLocalNetwork(e=window.location.hostname){return Ii(e)}};Ag([f()],wu.prototype,"url");Ag([f()],wu.prototype,"urlParameterName");Ag([f()],wu.prototype,"localhost");let Lg=wu;var jM=Object.defineProperty,xu=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&jM(e,t,n),n};class gr extends k{referenceSpace;from;affectPosition=!1;affectRotation=!1;alignLookDirection=!1;levelLookDirection=!1;levelPosition=!1;positionOffset=new c.Vector3(0,0,0);rotationOffset=new c.Vector3(0,0,0);offset=new c.Vector3(0,0,0);update(){if(!this.from)return;var e=X(this.from),t=ue(this.from);this.offset.copy(this.positionOffset);const i=this.offset.length();if(this.referenceSpace&&this.offset.transformDirection(this.referenceSpace.matrixWorld).multiplyScalar(i),e.add(this.offset),this.levelPosition&&this.referenceSpace){const a=new c.Plane(this.gameObject.up,0),l=X(this.referenceSpace);a.setFromNormalAndCoplanarPoint(this.gameObject.up,l);const h=new c.Vector3(0,0,0);a.projectPoint(e,h),e.copy(h)}this.affectPosition&&ot(this.gameObject,e);const n=new c.Euler(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),o=new c.Quaternion().setFromEuler(n);this.affectRotation&&Ji(this.gameObject,t.multiply(o));const r=new c.Vector3;this.from.getWorldDirection(r).multiplyScalar(50),this.levelLookDirection&&(r.y=0),this.alignLookDirection&&this.gameObject.lookAt(r)}}xu([f(S)],gr.prototype,"referenceSpace");xu([f(S)],gr.prototype,"from");xu([f(c.Vector3)],gr.prototype,"positionOffset");xu([f(c.Vector3)],gr.prototype,"rotationOffset");var BM=Object.defineProperty,lo=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&BM(e,t,n),n};class Xt{time=0;value=0;inTangent=1/0;inWeight;outTangent=1/0;outWeight;weightedMode;constructor(e=0,t=0){this.time=e,this.value=t}}lo([f()],Xt.prototype,"time");lo([f()],Xt.prototype,"value");lo([f()],Xt.prototype,"inTangent");lo([f()],Xt.prototype,"inWeight");lo([f()],Xt.prototype,"outTangent");lo([f()],Xt.prototype,"outWeight");lo([f()],Xt.prototype,"weightedMode");const cw=class Sl{static linearFromTo(e,t,i){const n=new Sl,o=new Xt;o.time=0,o.value=e;const r=new Xt;return r.time=i,r.value=t,n.keys.push(o,r),n}static constant(e){const t=new Sl,i=new Xt;return i.time=0,i.value=e,t.keys.push(i),t}keys=[];clone(){const e=new Sl;return e.keys=this.keys?.map(t=>{const i=new Xt;return i.time=t.time,i.value=t.value,i.inTangent=t.inTangent,i.inWeight=t.inWeight,i.outTangent=t.outTangent,i.outWeight=t.outWeight,i.weightedMode=t.weightedMode,i})||[],e}get duration(){return!this.keys||this.keys.length==0?0:this.keys[this.keys.length-1].time}evaluate(e){if(!this.keys||this.keys.length==0)return 0;if(this.keys.length===1)return this.keys[0].value;if(this.keys[0].time>=e)return this.keys[0].value;for(let t=0;t<this.keys.length;t++){const i=this.keys[t];if(i.time<=e)if(t+1<this.keys.length){const o=this.keys[t+1];if(o.time<e)continue;return!isFinite(i.outTangent)||!isFinite(o.inTangent)?i.value:Sl.interpolateValue(e,i,o)}else return i.value}return this.keys[this.keys.length-1].value}static interpolateValue(e,t,i){const n=t.time,o=t.value,r=t.outTangent,a=i.time,l=i.value,h=i.inTangent,d=a-n,u=d*d,p=u*d,m=((r+h)*d-2*(l-o))/p,y=(3*(l-o)-(h+2*r)*d)/u,_=r,g=o,v=e-n,b=v*v,x=b*v;return m*x+y*b+_*v+g}};lo([f(Xt)],cw.prototype,"keys");let zc=cw;var FM=Object.defineProperty,C=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&FM(e,t,n),n};const Dh=w("debugparticles");var Zn=(s=>(s[s.Billboard=0]="Billboard",s[s.Stretch=1]="Stretch",s[s.HorizontalBillboard=2]="HorizontalBillboard",s[s.VerticalBillboard=3]="VerticalBillboard",s[s.Mesh=4]="Mesh",s))(Zn||{});class yr{alphaKeys=[];colorKeys=[];get duration(){return 1}evaluate(e,t){let i,n=0,o=null,r=0;for(let a=0;a<this.alphaKeys.length;a++){const l=this.alphaKeys[a];(l.time<e||!i)&&(i=l,n=a)}for(let a=0;a<this.colorKeys.length;a++){const l=this.colorKeys[a];(l.time<e||!o)&&(o=l,r=a)}if(o)if(r+1<this.colorKeys.length){const l=this.colorKeys[r+1],h=D.remap(e,o.time,l.time,0,1);t.r=D.lerp(o.color.r,l.color.r,h),t.g=D.lerp(o.color.g,l.color.g,h),t.b=D.lerp(o.color.b,l.color.b,h)}else t.r=o.color.r,t.g=o.color.g,t.b=o.color.b;if(i)if(n+1<this.alphaKeys.length){const l=this.alphaKeys[n+1],h=D.remap(e,i.time,l.time,0,1);t.alpha=D.lerp(i.alpha,l.alpha,h)}else t.alpha=i.alpha;return t}}C([f()],yr.prototype,"alphaKeys");C([f()],yr.prototype,"colorKeys");var tc=(s=>(s[s.Local=0]="Local",s[s.World=1]="World",s[s.Custom=2]="Custom",s))(tc||{}),Ld=(s=>(s[s.Sphere=0]="Sphere",s[s.SphereShell=1]="SphereShell",s[s.Hemisphere=2]="Hemisphere",s[s.HemisphereShell=3]="HemisphereShell",s[s.Cone=4]="Cone",s[s.Box=5]="Box",s[s.Mesh=6]="Mesh",s[s.ConeShell=7]="ConeShell",s[s.ConeVolume=8]="ConeVolume",s[s.ConeVolumeShell=9]="ConeVolumeShell",s[s.Circle=10]="Circle",s[s.CircleEdge=11]="CircleEdge",s[s.SingleSidedEdge=12]="SingleSidedEdge",s[s.MeshRenderer=13]="MeshRenderer",s[s.SkinnedMeshRenderer=14]="SkinnedMeshRenderer",s[s.BoxShell=15]="BoxShell",s[s.BoxEdge=16]="BoxEdge",s[s.Donut=17]="Donut",s[s.Rectangle=18]="Rectangle",s[s.Sprite=19]="Sprite",s[s.SpriteRenderer=20]="SpriteRenderer",s))(Ld||{});const ys=class Cl{static constant(e){const t=new Cl;return t.setConstant(e),t}static betweenTwoConstants(e,t){const i=new Cl;return i.setMinMaxConstant(e,t),i}static curve(e,t=1){const i=new Cl;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 Cl;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,o=e*this.curveMax.duration;return D.lerp(this.curveMin.evaluate(n),this.curveMax.evaluate(o),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}};C([f()],ys.prototype,"mode");C([f()],ys.prototype,"constant");C([f()],ys.prototype,"constantMin");C([f()],ys.prototype,"constantMax");C([f(zc)],ys.prototype,"curve");C([f(zc)],ys.prototype,"curveMin");C([f(zc)],ys.prototype,"curveMax");C([f()],ys.prototype,"curveMultiplier");let G=ys;const co=class ft{static constant(e){const t=new ft;return t.constant(e),t}static betweenTwoColors(e,t){const i=new ft;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 Z(0,0,0,1);static _temp2=new Z(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,ft._temp),ft._temp;case 2:case"TwoColors":return ft._temp.lerpColors(this.colorMin,this.colorMax,i);case 3:case"TwoGradients":return this.gradientMin.evaluate(e,ft._temp),this.gradientMax.evaluate(e,ft._temp2),ft._temp.lerp(ft._temp2,i);case 4:case"RandomColor":const o=Math.random();return this.gradientMin.evaluate(e,ft._temp),this.gradientMax.evaluate(e,ft._temp2),ft._temp.lerp(ft._temp2,o)}return ft._temp.set(16777215),ft._temp.alpha=1,ft._temp}};C([f()],co.prototype,"mode");C([f(Z)],co.prototype,"color");C([f(Z)],co.prototype,"colorMin");C([f(Z)],co.prototype,"colorMax");C([f(yr)],co.prototype,"gradient");C([f(yr)],co.prototype,"gradientMin");C([f(yr)],co.prototype,"gradientMax");let _r=co;var jp=(s=>(s[s.Hierarchy=0]="Hierarchy",s[s.Local=1]="Local",s[s.Shape=2]="Shape",s))(jp||{});class Ct{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}C([f(G)],Ct.prototype,"gravityModifier");C([f(_r)],Ct.prototype,"startColor");C([f(G)],Ct.prototype,"startDelay");C([f(G)],Ct.prototype,"startLifetime");C([f(G)],Ct.prototype,"startRotation");C([f(G)],Ct.prototype,"startRotationX");C([f(G)],Ct.prototype,"startRotationY");C([f(G)],Ct.prototype,"startRotationZ");C([f(G)],Ct.prototype,"startSize");C([f(G)],Ct.prototype,"startSizeX");C([f(G)],Ct.prototype,"startSizeY");C([f(G)],Ct.prototype,"startSizeZ");C([f(G)],Ct.prototype,"startSpeed");class Dd{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 _s{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}}C([f()],_s.prototype,"enabled");C([f()],_s.prototype,"bursts");C([f(G)],_s.prototype,"rateOverTime");C([f()],_s.prototype,"rateOverTimeMultiplier");C([f(G)],_s.prototype,"rateOverDistance");C([f()],_s.prototype,"rateOverDistanceMultiplier");class Su{enabled;color}C([f(_r)],Su.prototype,"color");class br{enabled;separateAxes;size;sizeMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;_time=0;_temp=new c.Vector3;evaluate(e,t,i){if(t||(t=this._temp),!this.enabled)return t.x=t.y=t.z=1,t;if(this.separateAxes)t.x=this.x.evaluate(e,i)*this.xMultiplier,t.y=this.y.evaluate(e,i)*this.yMultiplier,t.z=this.z.evaluate(e,i)*this.zMultiplier;else{const n=this.size.evaluate(e,i)*this.sizeMultiplier;t.x=n}return t}}C([f(G)],br.prototype,"size");C([f(G)],br.prototype,"x");C([f(G)],br.prototype,"y");C([f(G)],br.prototype,"z");const Ge=class Pl{get type(){return Ld[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 Pl}shapeType=5;enabled=!0;alignToDirection=!1;angle=0;arc=360;arcSpread;arcSpeedMultiplier;arcMode;boxThickness;position;rotation;_rotation=new c.Euler;scale;radius;radiusThickness;sphericalDirectionAmount;randomDirectionAmount;randomPositionAmount;meshShapeType;meshRenderer;_meshObj;_meshGeometry;setMesh(e){this.meshRenderer=e,e?(this._meshObj=e.sharedMeshes[Math.floor(Math.random()*e.sharedMeshes.length)],this._meshGeometry=this._meshObj.geometry):(this._meshObj=void 0,this._meshGeometry=void 0)}system;_space;_worldSpaceMatrix=new c.Matrix4;_worldSpaceMatrixInverse=new c.Matrix4;constructor(){Dh&&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 c.Vector3(0,0,0);_temp=new c.Vector3(0,0,0);_triangle=new c.Triangle;onInitialize(e){this._vector.set(0,0,0),e.mesh=void 0,e.mesh_geometry=void 0;const t=this._temp.copy(this.position),i=this._space===1;i&&t.applyQuaternion(this.system.worldQuaternion);let n=this.radius;if(i&&(n*=this.system.worldScale.x),this.enabled){switch(this.shapeType){case 5:Dh&&B.DrawWireBox(this.position,this.scale,14540253,1),this._vector.x=Math.random()*this.scale.x-this.scale.x/2,this._vector.y=Math.random()*this.scale.y-this.scale.y/2,this._vector.z=Math.random()*this.scale.z-this.scale.z/2,this._vector.add(t);break;case 4:this.randomConePoint(this.position,this.angle,n,this.radiusThickness,this.arc,this.arcMode,this._vector);break;case 0:this.randomSpherePoint(this.position,n,this.radiusThickness,this.arc,this._vector);break;case 10:this.randomCirclePoint(this.position,n,this.radiusThickness,this.arc,this._vector);break;case 13:const o=this.meshRenderer;o?.destroyed==!1&&this.setMesh(o);const r=e.mesh=this._meshObj,a=e.mesh_geometry=this._meshGeometry;if(r&&a)switch(this.meshShapeType){case 0:{const l=a.getAttribute("position"),h=Math.floor(Math.random()*l.count);this._vector.fromBufferAttribute(l,h),this._vector.applyMatrix4(r.matrixWorld),e.mesh_normal=h}break;case 1:break;case 2:{const l=a.index;if(l){let h=Math.random(),d=Math.random();h+d>1&&(h=1-h,d=1-d);const u=Math.floor(Math.random()*(l.count/3));let p=u*3,m=u*3+1,y=u*3+2;p=l.getX(p),m=l.getX(m),y=l.getX(y);const _=a.getAttribute("position");this._triangle.a.fromBufferAttribute(_,p),this._triangle.b.fromBufferAttribute(_,m),this._triangle.c.fromBufferAttribute(_,y),this._vector.set(0,0,0).addScaledVector(this._triangle.a,h).addScaledVector(this._triangle.b,d).addScaledVector(this._triangle.c,1-(h+d)),this._vector.applyMatrix4(r.matrixWorld),e.mesh_normal=u}}break}break;default:this._vector.set(0,0,0),A()&&!globalThis.__particlesystem_shapetype_unsupported&&(console.warn("ParticleSystem ShapeType is not supported:",Ld[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)),Dh&&B.DrawSphere(this._vector,.03,16711680,.5,!0)}_dir=new c.Vector3;getDirection(e,t){if(!this.enabled)return this._dir.set(0,0,1),this._dir;switch(this.shapeType){case 5:this._dir.set(0,0,1);break;case 4:this._dir.set(0,0,1);break;case 10:case 0:const i=t.x,n=t.y,o=t.z;this._dir.set(i,n,o),this.system?.worldspace?this._dir.sub(this.system.worldPos):this._dir.sub(this.position);break;case 13:const r=e.mesh,a=e.mesh_geometry;if(r&&a)switch(this.meshShapeType){case 0:{const l=a.getAttribute("normal"),h=e.mesh_normal;this._dir.fromBufferAttribute(l,h)}break;case 1:break;case 2:{const l=a.index;if(l){const h=e.mesh_normal,d=l.getX(h*3),u=l.getX(h*3+1),p=l.getX(h*3+2),m=a.getAttribute("position"),y=V(),_=V(),g=V();y.fromBufferAttribute(m,d),_.fromBufferAttribute(m,u),g.fromBufferAttribute(m,p),y.sub(_),g.sub(_),y.cross(g),this._dir.copy(y).multiplyScalar(-1);const v=ue(r);this._dir.applyQuaternion(v)}}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),Dh&&(B.DrawSphere(t,.01,8925952,.5,!0),B.DrawDirection(t,this._dir,8925952,.5,!0)),this._dir}static _randomQuat=new c.Quaternion;static _tempVec=new c.Vector3;randomizePosition(e,t){if(t<=0)return;const i=Pl._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=Pl._randomQuat,n=Pl._tempVec;n.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).normalize(),i.setFromAxisAngle(n,t*Math.random()*Math.PI),e.applyQuaternion(i)}spherizeDirection(e,t){if(t===0)return;const i=Math.random()*Math.PI*2,n=Math.acos(1-Math.random()*2),o=Math.sin(n)*Math.cos(i),r=Math.sin(n)*Math.sin(i),a=Math.cos(n),l=new c.Vector3(o,r,a);e.lerp(l,t)}randomSpherePoint(e,t,i,n,o){const r=Math.random(),a=Math.random(),l=2*Math.PI*r*(n/360),h=Math.acos(2*a-1),d=D.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,u=e.x+this.scale.x*(-d*Math.sin(h)*Math.cos(l)),p=e.y+this.scale.y*(d*Math.sin(h)*Math.sin(l)),m=e.z+this.scale.z*(d*Math.cos(h));o.x=u,o.y=p,o.z=m}randomCirclePoint(e,t,i,n,o){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,h=e.x+this.scale.x*l*Math.cos(a),d=e.y+this.scale.y*l*Math.sin(a),u=e.z;o.x=h,o.y=d,o.z=u}_loopTime=0;_loopDirection=1;randomConePoint(e,t,i,n,o,r,a){let l=0,h=0;switch(r){case 0:l=Math.random(),h=Math.random();break;case 2:this._loopTime>1&&(this._loopDirection=-1),this._loopTime<0&&(this._loopDirection=1);case 1:l=.5,h=Math.random(),this._loopTime+=this.system.deltaTime*this._loopDirection;break}let d=2*Math.PI*l*(o/360);switch(r){case 2:case 1:d+=Math.PI+.5,d+=this._loopTime*Math.PI*2,d%=D.toRadians(o);break}const u=Math.acos(2*h-1),p=D.lerp(1,1-Math.pow(1-Math.random(),Math.PI),n)*i,m=e.x+-p*Math.sin(u)*Math.cos(d),y=e.y+p*Math.sin(u)*Math.sin(d),_=e.z;a.x=m*this.scale.x,a.y=y*this.scale.y,a.z=_*this.scale.z}};C([f()],Ge.prototype,"shapeType");C([f()],Ge.prototype,"enabled");C([f()],Ge.prototype,"alignToDirection");C([f()],Ge.prototype,"angle");C([f()],Ge.prototype,"arc");C([f()],Ge.prototype,"arcSpread");C([f()],Ge.prototype,"arcSpeedMultiplier");C([f()],Ge.prototype,"arcMode");C([f(c.Vector3)],Ge.prototype,"boxThickness");C([f(c.Vector3)],Ge.prototype,"position");C([f(c.Vector3)],Ge.prototype,"rotation");C([f(c.Vector3)],Ge.prototype,"scale");C([f()],Ge.prototype,"radius");C([f()],Ge.prototype,"radiusThickness");C([f()],Ge.prototype,"sphericalDirectionAmount");C([f()],Ge.prototype,"randomDirectionAmount");C([f()],Ge.prototype,"randomPositionAmount");C([f()],Ge.prototype,"meshShapeType");C([f(Mc)],Ge.prototype,"meshRenderer");let Dg=Ge;class fe{damping;enabled;frequency;octaveCount;octaveMultiplier;octaveScale;positionAmount;quality;remap;remapEnabled;remapMultiplier;remapX;remapXMultiplier;remapY;remapYMultiplier;remapZ;remapZMultiplier;scrollSpeedMultiplier;separateAxes;strengthMultiplier;strengthX;strengthXMultiplier;strengthY;strengthYMultiplier;strengthZ;strengthZMultiplier;_noise;_time=0;update(e){this._time+=e.time.deltaTime*this.scrollSpeedMultiplier}_temp=new c.Vector3;apply(e,t,i,n,o,r){if(!this.enabled)return;this._noise||(this._noise=se.createNoise4D(()=>0));const a=this._temp.set(t.x,t.y,t.z).multiplyScalar(this.frequency),l=this._noise(a.x,a.y,a.z,this._time),h=this._noise(a.x,a.y,a.z,this._time+1e3*this.frequency),d=this._noise(a.x,a.y,a.z,this._time+2e3*this.frequency);this._temp.set(l,h,d).normalize();const u=o/r;let p=this.positionAmount.evaluate(u);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(u)*1.5),this._temp.multiplyScalar(p)),i.x+=this._temp.x,i.y+=this._temp.y,i.z+=this._temp.z}}C([f()],fe.prototype,"damping");C([f()],fe.prototype,"enabled");C([f()],fe.prototype,"frequency");C([f()],fe.prototype,"octaveCount");C([f()],fe.prototype,"octaveMultiplier");C([f()],fe.prototype,"octaveScale");C([f(G)],fe.prototype,"positionAmount");C([f()],fe.prototype,"quality");C([f(G)],fe.prototype,"remap");C([f()],fe.prototype,"remapEnabled");C([f()],fe.prototype,"remapMultiplier");C([f(G)],fe.prototype,"remapX");C([f()],fe.prototype,"remapXMultiplier");C([f(G)],fe.prototype,"remapY");C([f()],fe.prototype,"remapYMultiplier");C([f(G)],fe.prototype,"remapZ");C([f()],fe.prototype,"remapZMultiplier");C([f()],fe.prototype,"scrollSpeedMultiplier");C([f()],fe.prototype,"separateAxes");C([f()],fe.prototype,"strengthMultiplier");C([f(G)],fe.prototype,"strengthX");C([f()],fe.prototype,"strengthXMultiplier");C([f(G)],fe.prototype,"strengthY");C([f()],fe.prototype,"strengthYMultiplier");C([f(G)],fe.prototype,"strengthZ");C([f()],fe.prototype,"strengthZMultiplier");class Re{enabled;attachRibbonToTransform=!1;colorOverLifetime;colorOverTrail;dieWithParticles=!0;inheritParticleColor=!0;lifetime;lifetimeMultiplier;minVertexDistance=.2;mode=0;ratio=1;ribbonCount=1;shadowBias=0;sizeAffectsLifetime=!1;sizeAffectsWidth=!1;splitSubEmitterRibbons=!1;textureMode=0;widthOverTrail;widthOverTrailMultiplier;worldSpace=!1;getWidth(e,t,i,n){const o=this.widthOverTrail.evaluate(i,n);return e*=o,e}getColor(e,t,i){const n=this.colorOverTrail.evaluate(i),o=this.colorOverLifetime.evaluate(t);e.x*=n.r*o.r,e.y*=n.g*o.g,e.z*=n.b*o.b,"alpha"in n&&"alpha"in o&&(e.w*=n.alpha*o.alpha)}}C([f()],Re.prototype,"enabled");C([f()],Re.prototype,"attachRibbonToTransform");C([f(_r)],Re.prototype,"colorOverLifetime");C([f(_r)],Re.prototype,"colorOverTrail");C([f()],Re.prototype,"dieWithParticles");C([f()],Re.prototype,"inheritParticleColor");C([f(G)],Re.prototype,"lifetime");C([f()],Re.prototype,"lifetimeMultiplier");C([f()],Re.prototype,"minVertexDistance");C([f()],Re.prototype,"mode");C([f()],Re.prototype,"ratio");C([f()],Re.prototype,"ribbonCount");C([f()],Re.prototype,"shadowBias");C([f()],Re.prototype,"sizeAffectsLifetime");C([f()],Re.prototype,"sizeAffectsWidth");C([f()],Re.prototype,"splitSubEmitterRibbons");C([f()],Re.prototype,"textureMode");C([f(G)],Re.prototype,"widthOverTrail");C([f()],Re.prototype,"widthOverTrailMultiplier");C([f()],Re.prototype,"worldSpace");class Ae{enabled;space=0;orbitalX;orbitalY;orbitalZ;orbitalXMultiplier;orbitalYMultiplier;orbitalZMultiplier;orbitalOffsetX;orbitalOffsetY;orbitalOffsetZ;speedModifier;speedModifierMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;_system;update(e){this._system=e}_temp=new c.Vector3;_temp2=new c.Vector3;_temp3=new c.Vector3;_hasOrbital=!1;_index=0;_orbitalMatrix=new c.Matrix4;init(e){this._index==0&&(e.debug=!0),this._index+=1,e.orbitx=this.orbitalX.evaluate(Math.random()),e.orbity=this.orbitalY.evaluate(Math.random()),e.orbitz=this.orbitalZ.evaluate(Math.random()),this._hasOrbital=e.orbitx!=0||e.orbity!=0||e.orbitz!=0}apply(e,t,i,n,o,r,a){if(!this.enabled)return;const l=r/a,h=this.speedModifier.evaluate(l)*this.speedModifierMultiplier,d=this.x.evaluate(l),u=this.y.evaluate(l),p=this.z.evaluate(l);if(this._temp.set(-d,u,p),this._system&&this._system.main.simulationSpace===1&&this._temp.applyQuaternion(this._system.worldQuaternion),this._hasOrbital&&this._system?.worldPos){const y=this._temp2.set(i.x,i.y,i.z),_=this.orbitalXMultiplier,g=this.orbitalYMultiplier,v=this.orbitalZMultiplier,b=h*Math.PI*2*10,x=Math.cos(b*_),T=Math.sin(b*_),O=Math.cos(b*g),M=Math.sin(b*g),E=Math.cos(b*v),j=Math.sin(b*v),L=y.x*(O*E)+y.y*(O*j)+y.z*-M,z=y.x*(T*M*E-x*j)+y.y*(T*M*j+x*E)+y.z*(T*O),$=y.x*(x*M*E+T*j)+y.y*(x*M*j-T*E)+y.z*(x*O),R=this._temp3.set(y.x-L,y.y-z,y.z-$);R.normalize(),R.multiplyScalar(.2/o*Math.max(this.orbitalXMultiplier,this.orbitalYMultiplier,this.orbitalZMultiplier)),n.x+=R.x,n.y+=R.y,n.z+=R.z}n.x+=this._temp.x,n.y+=this._temp.y,n.z+=this._temp.z,n.x*=h,n.y*=h,n.z*=h}}C([f()],Ae.prototype,"enabled");C([f()],Ae.prototype,"space");C([f(G)],Ae.prototype,"orbitalX");C([f(G)],Ae.prototype,"orbitalY");C([f(G)],Ae.prototype,"orbitalZ");C([f()],Ae.prototype,"orbitalXMultiplier");C([f()],Ae.prototype,"orbitalYMultiplier");C([f()],Ae.prototype,"orbitalZMultiplier");C([f()],Ae.prototype,"orbitalOffsetX");C([f()],Ae.prototype,"orbitalOffsetY");C([f()],Ae.prototype,"orbitalOffsetZ");C([f(G)],Ae.prototype,"speedModifier");C([f()],Ae.prototype,"speedModifierMultiplier");C([f(G)],Ae.prototype,"x");C([f()],Ae.prototype,"xMultiplier");C([f(G)],Ae.prototype,"y");C([f()],Ae.prototype,"yMultiplier");C([f(G)],Ae.prototype,"z");C([f()],Ae.prototype,"zMultiplier");class Pt{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}}C([f()],Pt.prototype,"animation");C([f()],Pt.prototype,"enabled");C([f()],Pt.prototype,"cycleCount");C([f(G)],Pt.prototype,"frameOverTime");C([f()],Pt.prototype,"frameOverTimeMultiplier");C([f()],Pt.prototype,"numTilesX");C([f()],Pt.prototype,"numTilesY");C([f(G)],Pt.prototype,"startFrame");C([f()],Pt.prototype,"startFrameMultiplier");C([f()],Pt.prototype,"rowMode");C([f()],Pt.prototype,"rowIndex");C([f()],Pt.prototype,"spriteCount");C([f()],Pt.prototype,"timeMode");class an{enabled;separateAxes;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t){return this.enabled?this.separateAxes?0:this.z.evaluate(e,t)*-1:0}}C([f()],an.prototype,"enabled");C([f()],an.prototype,"separateAxes");C([f(G)],an.prototype,"x");C([f()],an.prototype,"xMultiplier");C([f(G)],an.prototype,"y");C([f()],an.prototype,"yMultiplier");C([f(G)],an.prototype,"z");C([f()],an.prototype,"zMultiplier");class Ni{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}}C([f()],Ni.prototype,"enabled");C([f()],Ni.prototype,"range");C([f()],Ni.prototype,"separateAxes");C([f(G)],Ni.prototype,"x");C([f()],Ni.prototype,"xMultiplier");C([f(G)],Ni.prototype,"y");C([f()],Ni.prototype,"yMultiplier");C([f(G)],Ni.prototype,"z");C([f()],Ni.prototype,"zMultiplier");class et{enabled;dampen;drag;dragMultiplier;limit;limitMultiplier;separateAxes;limitX;limitXMultiplier;limitY;limitYMultiplier;limitZ;limitZMultiplier;multiplyDragByParticleSize=!1;multiplyDragByParticleVelocity=!1;space;_temp=new c.Vector3;_temp2=new c.Vector3;apply(e,t,i,n,o,r,a){if(this.enabled){const l=this.limit.evaluate(o)*this.limitMultiplier;if(t.length()>l){this._temp.copy(t).normalize().multiplyScalar(l);const d=this.dampen*.5;t.x=D.lerp(t.x,this._temp.x,d),t.y=D.lerp(t.y,this._temp.y,d),t.z=D.lerp(t.z,this._temp.z,d),i.x=D.lerp(i.x,this._temp.x,d),i.y=D.lerp(i.y,this._temp.y,d),i.z=D.lerp(i.z,this._temp.z,d)}}}}C([f()],et.prototype,"enabled");C([f()],et.prototype,"dampen");C([f(G)],et.prototype,"drag");C([f()],et.prototype,"dragMultiplier");C([f(G)],et.prototype,"limit");C([f()],et.prototype,"limitMultiplier");C([f()],et.prototype,"separateAxes");C([f(G)],et.prototype,"limitX");C([f()],et.prototype,"limitXMultiplier");C([f(G)],et.prototype,"limitY");C([f()],et.prototype,"limitYMultiplier");C([f(G)],et.prototype,"limitZ");C([f()],et.prototype,"limitZMultiplier");C([f()],et.prototype,"multiplyDragByParticleSize");C([f()],et.prototype,"multiplyDragByParticleVelocity");C([f()],et.prototype,"space");const Nc=class hw{enabled;curve;curveMultiplier;mode;clone(){const e=new hw;return e.enabled=this.enabled,e.curve=this.curve?.clone(),e.curveMultiplier=this.curveMultiplier,e.mode=this.mode,e}system;get _lastWorldPosition(){return this.system._iv_lastWorldPosition||(this.system._iv_lastWorldPosition=new c.Vector3),this.system._iv_lastWorldPosition}get _velocity(){return this.system._iv_velocity||(this.system._iv_velocity=new c.Vector3),this.system._iv_velocity}_temp=new c.Vector3;_firstUpdate=!0;awake(e){this.system=e,this.reset()}reset(){this._firstUpdate=!0}update(e){this.enabled&&this.system.worldspace!==!1&&(this._firstUpdate?(this._firstUpdate=!1,this._velocity.set(0,0,0),this._lastWorldPosition.copy(this.system.worldPos)):this._lastWorldPosition&&(this._velocity.copy(this.system.worldPos).sub(this._lastWorldPosition).multiplyScalar(1/this.system.deltaTime),this._lastWorldPosition.copy(this.system.worldPos)))}applyInitial(e){if(this.enabled&&this.system.worldspace!==!1&&this.mode===0){const t=this.curve.evaluate(Math.random(),Math.random());this._temp.copy(this._velocity).multiplyScalar(t),e.x+=this._temp.x,e.y+=this._temp.y,e.z+=this._temp.z}}_frames=0;applyCurrent(e,t,i){if(this.enabled&&this.system&&this.system.worldspace!==!1&&this.mode===1){const n=this.curve.evaluate(t,i);this._temp.copy(this._velocity).multiplyScalar(n),e.x+=this._temp.x,e.y+=this._temp.y,e.z+=this._temp.z}}};C([f()],Nc.prototype,"enabled");C([f(G)],Nc.prototype,"curve");C([f()],Nc.prototype,"curveMultiplier");C([f()],Nc.prototype,"mode");let Ig=Nc;class ti{enabled;range;separateAxes;size;sizeMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t,i,n){const o=e.length(),r=D.remap(o,this.range.x,this.range.y,0,1),a=this.size.evaluate(r,i);return n.x*=a,n.y*=a,n.z*=a,n}}C([f()],ti.prototype,"enabled");C([f(c.Vector2)],ti.prototype,"range");C([f()],ti.prototype,"separateAxes");C([f(G)],ti.prototype,"size");C([f()],ti.prototype,"sizeMultiplier");C([f(G)],ti.prototype,"x");C([f()],ti.prototype,"xMultiplier");C([f(G)],ti.prototype,"y");C([f()],ti.prototype,"yMultiplier");C([f(G)],ti.prototype,"z");C([f()],ti.prototype,"zMultiplier");class Da{enabled;range;color;evaluate(e,t,i){const n=e.length(),o=D.remap(n,this.range.x,this.range.y,0,1),r=this.color.evaluate(o,t);i.x*=r.r,i.y*=r.g,i.z*=r.b,"alpha"in r&&(i.w*=r.alpha)}}C([f()],Da.prototype,"enabled");C([f(c.Vector2)],Da.prototype,"range");C([f(_r)],Da.prototype,"color");new c.Vector3(1,1,1);new c.Vector3(0,0,1);class jg{constructor(e,t,i,n){this.system=e,this.particleSystem=t,this.subSystem=i,this.subParticleSystem=n,this.subParticleSystem&&this.subParticleSystem&&(this.subParticleSystem.onlyUsedByOther=!0);const o=1e3;this._circularBuffer=new di(()=>new se.Matrix4,o)}type="NeedleParticleSubEmitter";emitterType;emitterProbability;q_=new c.Quaternion;v_=new c.Vector3;v2_=new c.Vector3;_emitterMatrix=new se.Matrix4;_circularBuffer;clone(){throw new Error("Method not implemented.")}initialize(e){e.emissionState={burstIndex:0,burstWaveIndex:0,time:0,waitEmiting:0},this._emitterMatrix.copy(this.subSystem.matrixWorld).invert().premultiply(this.system.matrixWorld),this._emitterMatrix.setPosition(0,0,0),this.emitterType===Bp.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===Bp.Death){let n=e.life;if(e[Kr]!==void 0&&(n=e[Kr]),!(e.age+t*1.2>=n))return;const r=this.subSystem.main.maxParticles-this.subSystem.currentParticles;e.emissionState.waitEmiting=r}const i=new se.Matrix4;i.set(1,0,0,e.position.x,0,1,0,e.position.y,0,0,1,e.position.z,0,0,0,1),this.particleSystem.worldSpace||i.multiplyMatrices(this._emitterMatrix,i),this.subParticleSystem.emit(t,e.emissionState,i)}}var UM=Object.defineProperty,Te=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&UM(e,t,n),n};const Fs=w("debugparticles"),zM=w("noprogressive"),NM=w("debugprogressive");var Bp=(s=>(s[s.Birth=0]="Birth",s[s.Collision=1]="Collision",s[s.Death=2]="Death",s[s.Trigger=3]="Trigger",s[s.Manual=4]="Manual",s))(Bp||{});class Vi extends k{renderMode;particleMaterial;trailMaterial;particleMesh;maxParticleSize;minParticleSize;velocityScale;cameraVelocityScale;lengthScale;start(){if(this.maxParticleSize!==.5&&this.minParticleSize!==0&&A()){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"){Fs&&console.debug("ParticleSystemRenderer.getMaterial: MeshStandardMaterial detected, converting to MeshBasicMaterial. See https://github.com/Alchemist0823/three.quarks/issues/101"),"map"in t&&t.map&&(t.map.colorSpace=c.LinearSRGBColorSpace,t.map.premultiplyAlpha=!1);const i=new c.MeshBasicMaterial;i.copy(t),e?this.trailMaterial=i:this.particleMaterial=i}t.map&&(t.map.colorSpace=c.LinearSRGBColorSpace,t.map.premultiplyAlpha=!1),e&&t.side===c.FrontSide&&(t=t.clone(),t.side=c.BackSide,e?this.trailMaterial=t:this.particleMaterial=t)}return t&&!zM&&t._didRequestTextureLOD===void 0&&(t._didRequestTextureLOD=0,NM&&console.log("Load material LOD",t.name),ne.NEEDLE_progressive.assignTextureLOD(t,0)),t}getMesh(e){let t=null;if(!t&&(this.particleMesh instanceof c.Mesh&&(t=this.particleMesh.geometry),t===null)){t=new c.PlaneGeometry(1,1);const n=t.attributes.uv;for(let o=0;o<n.count;o++)n.setX(o,1-n.getX(o))}return new c.Mesh(t,this.getMaterial())}}Te([f()],Vi.prototype,"renderMode");Te([f(c.Material)],Vi.prototype,"particleMaterial");Te([f(c.Material)],Vi.prototype,"trailMaterial");Te([f()],Vi.prototype,"maxParticleSize");Te([f()],Vi.prototype,"minParticleSize");Te([f()],Vi.prototype,"velocityScale");Te([f()],Vi.prototype,"cameraVelocityScale");Te([f()],Vi.prototype,"lengthScale");class Ih{_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 Bg{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 VM extends Bg{genValue(){return this.system.textureSheetAnimation.getStartIndex()}}class $M extends Bg{_lastPosition=new c.Vector3;_lastDistance=0;update(){const e=X(this.system.gameObject);this._lastDistance=this._lastPosition.distanceTo(e),this._lastPosition.copy(e)}genValue(){if(!this.system.isPlaying||!this.system.emission.enabled||this.system.currentParticles>=this.system.maxParticles)return 0;let e=this.system.emission.rateOverTime.evaluate(this.system.time/this.system.duration,Math.random());if(this.system.deltaTime>0){const n=this.system.emission.rateOverDistance.evaluate(this.system.time/this.system.duration,Math.random());let r=this._lastDistance/this.system.deltaTime*n;Number.isFinite(r)||(r=0),e+=r}const t=this.system.emission.getBurst();t>0&&(e+=t/this.system.deltaTime);const i=this.system.maxParticles-this.system.currentParticles;return D.clamp(e,0,i/this.system.deltaTime)}}class WM extends Bg{genValue(){return this.system.isPlaying,0}}class ho{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 GM extends ho{type="NeedleTextureSheet";update(e,t){const i=this.system.textureSheetAnimation;if(i.enabled){const n=e.age/e.life,o=i.evaluate(n);o!==void 0&&(e.uvTile=o)}}}const I_=Symbol("particleRotation");class HM extends ho{type="NeedleRotation";initialize(e){e[I_]=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[I_])*t:this.system.renderer.renderMode===Zn.Billboard&&(e.rotation=Math.PI),this.system.rotationBySpeed.enabled)){const n=e.velocity.length();e.rotation+=this.system.rotationBySpeed.evaluate(i,n)*t}}}const j_=Symbol("sizeLerpFactor"),qM=new c.Vector3;class XM extends ho{type="NeedleSize";_minSize=0;_maxSize=1;initialize(e){e[j_]=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[j_]).x);let o=1;this.system.renderer.renderMode!==Zn.Mesh&&(o=this.system.worldScale.x/this.system.cameraScale);const r=V(e.startSize).multiplyScalar(n*o);if(e.size.set(r.x,r.y,r.z),this.system.localspace){const a=dw(this.system,qM);e.size.x*=a.x,e.size.y*=a.y,e.size.z*=a.z}}}const Kr=Symbol("particleLife"),zf=Symbol("trailLifetime"),B_=Symbol("trailStartLength"),Nf=Symbol("trailWidthRandom");class QM extends ho{type="NeedleTrail";initialize(e){e instanceof se.TrailParticle&&(e[Kr]=e.life,this.system.trails.enabled&&this.system.trails.dieWithParticles===!1&&(e[zf]=this.system.trails.lifetime.evaluate(Math.random(),Math.random()),e.life+=e[zf]),e[B_]=e.length,e[Nf]=Math.random())}update(e){if(this.system.trails?.enabled&&e instanceof se.TrailParticle){const t=e,i=e.age/e[Kr],n=e.previous.values(),o=e.previous.length;for(let r=0;r<o;r++){const l=n.next().value,h=1-r/(o-1),d=e.size;if(d.x<=0&&!this.system.trails.sizeAffectsWidth){const u=20*this.system.trails.widthOverTrail.evaluate(.5,t[Nf]);d.x=u,d.y=u,d.z=u}l.size=this.system.trails.getWidth(d.x,i,h,t[Nf]),l.color.copy(e.color),this.system.trails.getColor(l.color,i,h)}if(e.age>e[Kr]){e.velocity.set(0,0,0);const r=(e.age-e[Kr])/e[zf];t.length=D.lerp(e[B_],0,r)}}}}const jh=Symbol("startVelocity"),F_=Symbol("gravityModifier"),Vf=Symbol("gravitySpeed"),Bh=Symbol("velocity lerp factor"),Fp=new c.Vector3;class YM extends ho{type="NeedleVelocity";_gravityDirection=new c.Vector3;initialize(e){const t=this.system.main.simulationSpeed;e.startSpeed=this.system.main.startSpeed.evaluate(Math.random(),Math.random());const i=this.system.shape.getDirection(e,e.position);e.velocity.x=i.x*e.startSpeed,e.velocity.y=i.y*e.startSpeed,e.velocity.z=i.z*e.startSpeed,this.system.inheritVelocity?.enabled&&this.system.inheritVelocity.applyInitial(e.velocity),e[jh]?e[jh].copy(e.velocity):e[jh]=e.velocity.clone();const n=this.system.main.gravityModifier.evaluate(Math.random(),Math.random());e[F_]=n*t,e[Vf]=n*t*.5,e[Bh]=Math.random(),this.system.velocityOverLifetime?.init(e),this._gravityDirection.set(0,-1,0),this.system.main.simulationSpace===tc.Local&&this._gravityDirection.applyQuaternion(this.system.worldQuaternionInverted).normalize()}update(e,t){const i=e[jh],n=e[F_];if(n!==0){const u=n*e[Vf];Fp.copy(this._gravityDirection).multiplyScalar(u),e[Vf]+=t*.05,i.add(Fp)}e.velocity.copy(i);const o=e.age/e.life;this.system.inheritVelocity?.enabled&&this.system.inheritVelocity.applyCurrent(e.velocity,o,e[Bh]);const r=this.system.noise;r.enabled&&r.apply(0,e.position,e.velocity,t,e.age,e.life);const a=this.system.sizeBySpeed;a?.enabled&&(e.size=a.evaluate(e.velocity,o,e[Bh],e.size));const l=this.system.colorBySpeed;l?.enabled&&l.evaluate(e.velocity,e[Bh],e.color);const h=this.system.velocityOverLifetime;h.enabled&&h.apply(e,0,e.position,e.velocity,t,e.age,e.life);const d=this.system.limitVelocityOverLifetime;if(d.enabled&&d.apply(e.position,i,e.velocity,e.size,o,t,1),this.system.worldspace){const u=this.system.worldScale;e.velocity.x*=u.x,e.velocity.y*=u.y,e.velocity.z*=u.z}}}const U_=Symbol("colorLerpFactor"),z_=new Z(1,1,1,1),vo=new Z(1,1,1,1);class KM extends ho{type="NeedleColor";initialize(e){}_init(e){const t=this.system.renderer.particleMaterial;vo.copy(this.system.main.startColor.evaluate(Math.random())),t?.color&&(z_.copy(t.color),vo.multiply(z_)),vo.convertLinearToSRGB(),e.startColor.set(vo.r,vo.g,vo.b,vo.alpha),e.color.copy(e.startColor),e[U_]=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[U_]);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 ZM{system;emission;get anim(){return this.system.textureSheetAnimation}constructor(e){this.system=e,this.emission=new $M(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 Ih(this.system.main.startLifetime)}get startSpeed(){return new Ih(this.system.main.startSpeed)}get startRotation(){return new Ih(this.system.main.startRotation)}get startSize(){return new Ih(this.system.main.startSize)}startLength;get startColor(){return new se.ConstantColor(new se.Vector4(1,1,1,1))}get emissionOverTime(){return this.emission}get emissionOverDistance(){return new WM(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 se.RenderMode.Trail;switch(this.system.renderer.renderMode){case Zn.Billboard:return se.RenderMode.BillBoard;case Zn.Stretch:return se.RenderMode.StretchedBillBoard;case Zn.HorizontalBillboard:return se.RenderMode.HorizontalBillBoard;case Zn.VerticalBillboard:return se.RenderMode.VerticalBillBoard;case Zn.Mesh:return se.RenderMode.Mesh}return se.RenderMode.BillBoard}rendererEmitterSettings={startLength:new se.ConstantValue(220),followLocalOrigin:!1};get speedFactor(){let e=this.system.main.simulationSpeed;return this.system.renderer?.renderMode===Zn.Stretch&&(e*=this.system.renderer.velocityScale??1),e}flatWhiteTexture;clonedTexture={original:void 0,clone:void 0};get texture(){const e=this.material;if(e&&e.map){const t=e.map;if(this.clonedTexture.original!==t||!this.clonedTexture.clone){const i=t.clone();i.premultiplyAlpha=!1,i.colorSpace=c.LinearSRGBColorSpace,this.clonedTexture.original=t,this.clonedTexture.clone=i}return this.clonedTexture.clone}return this.flatWhiteTexture||(this.flatWhiteTexture=Em(new Z(1,1,1,1),1)),this.flatWhiteTexture}get startTileIndex(){return new VM(this.system)}get uTileCount(){return this.anim.enabled?this.anim?.numTilesX:void 0}get vTileCount(){return this.anim.enabled?this.anim?.numTilesY:void 0}get renderOrder(){return 1}get blending(){return this.system.renderer.particleMaterial?.blending??c.NormalBlending}get transparent(){return this.system.renderer.transparent}get worldSpace(){return this.system.main.simulationSpace===tc.World}}class JM{burstParticleIndex=0;burstParticleCount=0;isBursting=!1;travelDistance=0;previousWorldPos;burstIndex=0;burstWaveIndex=0;time=0;waitEmiting=0}const Ot=class sd extends k{play(e=!1){e&&S.foreachComponent(this.gameObject,t=>{t instanceof sd&&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&&S.foreachComponent(this.gameObject,t=>{t instanceof sd&&t!==this&&t.pause(!1)},!0),this._isPlaying=!1}stop(e=!0,t=!1){e&&S.foreachComponent(this.gameObject,i=>{i instanceof sd&&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 JM),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===tc.World}get localspace(){return this.main.simulationSpace===tc.Local}__worldQuaternion=new c.Quaternion;get worldQuaternion(){return this.__worldQuaternion}_worldQuaternionInverted=new c.Quaternion;get worldQuaternionInverted(){return this._worldQuaternionInverted}_worldScale=new c.Vector3;get worldScale(){return this._worldScale}_worldPositionFrame=-1;_worldPos=new c.Vector3;get worldPos(){return this._worldPositionFrame!==this.context.time.frame&&(this._worldPositionFrame=this.context.time.frame,X(this.gameObject,this._worldPos)),this._worldPos}get matrixWorld(){return this._container.matrixWorld}get isSubsystem(){return this._isUsedAsSubsystem}addBehaviour(e){return this._particleSystem?(e instanceof ho&&(e.system=this),Fs&&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&&((A()||Fs)&&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 Dd)){const n=new Dd;ua(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 Id)){const n=new Id;ua(n,i),e[t]=n}}Fs&&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(Vi),!this.main)throw new Error("Not Supported: ParticleSystem needs a serialized MainModule. Creating new particle systems at runtime is currently not supported.");this._container=new c.Object3D,this._container.matrixAutoUpdate=!1,this.context.scene.add(this._container),this._batchSystem=new se.BatchedParticleRenderer,this._batchSystem.name=this.gameObject.name,this._container.add(this._batchSystem),this._interface=new ZM(this),this._particleSystem=new se.ParticleSystem(this._interface),this._particleSystem.addBehavior(new XM(this)),this._particleSystem.addBehavior(new KM(this)),this._particleSystem.addBehavior(new GM(this)),this._particleSystem.addBehavior(new HM(this)),this._particleSystem.addBehavior(new YM(this)),this._particleSystem.addBehavior(new QM(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),Fs&&(console.log(this),this.gameObject.add(new c.AxesHelper(1)))}start(){this.addSubParticleSystems(),this.updateLayers(),this.renderer.particleMesh instanceof c.Mesh&&this._interface.renderMode==se.RenderMode.Mesh&&ne.NEEDLE_progressive.assignMeshLOD(this.renderer.particleMesh,0).then(e=>{e&&this.particleSystem&&this._interface.renderMode==se.RenderMode.Mesh&&(this.particleSystem.instancingGeometry=e)})}onDestroy(){this._container?.removeFromParent(),this._batchSystem?.removeFromParent(),this._particleSystem?.emitter.removeFromParent(),this._particleSystem?.dispose()}onEnable(){this.main&&(this.inheritVelocity&&(this.inheritVelocity.system=this),this._batchSystem&&(this._batchSystem.visible=!0),this.playOnAwake&&this.play(),this._isPlaying=this.playOnAwake)}onDisable(){this._batchSystem&&(this._batchSystem.visible=!1)}onBeforeRender(){this.main&&(this._didPreWarm===!1&&this.main?.prewarm===!0&&(this._didPreWarm=!0,this.preWarm()),this.onUpdate(),this.onSimulate(this.deltaTime))}preWarm(){if(!this.emission?.enabled||this.emission.rateOverTime.getMax()<=0)return;const t=1/60,i=this.main.duration,n=this.main.startLifetime.getMax(),r=Math.min(Math.max(i,n)/Math.max(.01,this.main.simulationSpeed),1e3),a=Math.ceil(r/t),l=Date.now();Fs&&console.log(`Particles ${this.name} - Prewarm for ${a} frames (${r} sec). Duration: ${i}, Lifetime: ${n}`);for(let h=0;h<a&&!(this.currentParticles>=this.maxParticles);h++){const d=Date.now()-l;if(d>2e3){console.warn(`Particles ${this.name} - Prewarm took too long. Aborting: ${d}`);break}this.onUpdate(),this.onSimulate(t)}}_lastBatchesCount=-1;onSimulate(e){if(this._batchSystem){let t=this.context.time.frameCount%60===0;this._lastBatchesCount!==this._batchSystem.batches.length&&(this._lastBatchesCount=this._batchSystem.batches.length,t=!0),t&&this.updateLayers(),this._batchSystem.update(e)}this._time+=e,this._time>this.duration&&(this._time=0)}updateLayers(){if(this._batchSystem)for(let e=0;e<this._batchSystem.batches.length;e++){const t=this._batchSystem.batches[e];t.layers.disableAll();const i=this.layer;t.layers.mask=1<<i}}onUpdate(){if(this._bursts&&(this.emission.bursts=this._bursts,delete this._bursts),!this._isPlaying)return;const e=this.context.mainCamera;if(e){const n=Ie(e);this._cameraScale=n.x}const t=!this.worldspace,i=this.gameObject;if(ue(i,this.__worldQuaternion),this._worldQuaternionInverted.copy(this.__worldQuaternion).invert(),Ie(this.gameObject,this._worldScale),t&&this._container&&this.gameObject?.parent){const n=dw(this,Fp);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():A()&&console.warn("SubParticleSystem serialization issue(?)",e.particleSystem,e));const t=e.particleSystem?._particleSystem;if(t){e.particleSystem._isUsedAsSubsystem=!0;const i=new jg(this,this._particleSystem,e.particleSystem,t);i.emitterType=e.type,i.emitterProbability=e.emitProbability,this._particleSystem.addBehavior(i)}else Fs&&console.warn("Could not add SubParticleSystem",e,this)}}};Te([f(Su)],Ot.prototype,"colorOverLifetime");Te([f(Ct)],Ot.prototype,"main");Te([f(_s)],Ot.prototype,"emission");Te([f(br)],Ot.prototype,"sizeOverLifetime");Te([f(Dg)],Ot.prototype,"shape");Te([f(fe)],Ot.prototype,"noise");Te([f(Re)],Ot.prototype,"trails");Te([f(Ae)],Ot.prototype,"velocityOverLifetime");Te([f(et)],Ot.prototype,"limitVelocityOverLifetime");Te([f(Ig)],Ot.prototype,"inheritVelocity");Te([f(Da)],Ot.prototype,"colorBySpeed");Te([f(Pt)],Ot.prototype,"textureSheetAnimation");Te([f(an)],Ot.prototype,"rotationOverLifetime");Te([f(Ni)],Ot.prototype,"rotationBySpeed");Te([f(ti)],Ot.prototype,"sizeBySpeed");let ic=Ot;class Id{particleSystem;emitProbability=1;properties;type;_deserialize(e,t){const i=this.particleSystem;if(i instanceof ic)return;let n="";i&&typeof i.guid=="string"&&(n=i.guid,this.particleSystem=S.findByGuid(n,t)),Fs&&!(this.particleSystem instanceof ic)&&console.warn("Could not find particle system for sub emitter",n,t,this)}}function dw(s,e){if(e.set(1,1,1),s.gameObject.parent&&s.localspace)switch(s.main.scalingMode){case jp.Local:e=Ie(s.gameObject.parent,e),e.x=1/e.x,e.y=1/e.y,e.z=1/e.z;break;default:if(!s.unsupported_scaling_mode){s.unsupported_scaling_mode=!0;const t="ParticleSystem scale mode "+jp[s.main.scalingMode]+" is not supported";A()&&he(t),console.warn(t,s.name,s)}e=Ie(s.gameObject,e);break}return e}var ek=Object.defineProperty,Fg=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&ek(e,t,n),n};class Ia extends k{strength=1;radius=2;targets=[];update(){const e=this.gameObject.worldPosition,t=-this.strength*this.context.time.deltaTime;this.targets?.forEach(i=>{if(!i)return;const n=i.gameObject.worldPosition.sub(e),o=n.length();if(o>this.radius)return;let r=t;o>1?r/=o*o:r/=Math.max(.05,o),i.applyImpulse(n.multiplyScalar(r))})}}Fg([f()],Ia.prototype,"strength");Fg([f()],Ia.prototype,"radius");Fg([f(Ne)],Ia.prototype,"targets");class _a extends k{_didAssignPlayerColor=!1;onEnable(){this.context.connection.beginListen(Q.JoinedRoom,this.tryAssignColor),this._didAssignPlayerColor||this.startCoroutine(this.waitForConnection())}onDisable(){this.context.connection.stopListen(Q.JoinedRoom,this.tryAssignColor)}*waitForConnection(){for(;!this.destroyed&&this.activeAndEnabled&&(yield km(.2),!this.tryAssignColor()););}tryAssignColor=()=>{const e=S.getComponentInParent(this.gameObject,Yi);if(e&&e.owner)return this._didAssignPlayerColor=!0,this.assignUserColor(e.owner),!0;const t=S.getComponentInParent(this.gameObject,xe);return t?.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(t.connectionId),!0):!1};assignUserColor(e){const t=_a.hashCode(e),i=_a.colorFromHashCode(t);if(this.gameObject.type==="Mesh"){const n=this.gameObject;this.assignColor(i,e,n)}else if(this.gameObject.children)for(const n of this.gameObject.children){const o=n;o.material&&o.material.color&&this.assignColor(i,e,o)}}assignColor(e,t,i){let n=i.material;n&&(n._playerMaterial!==t&&(n=n.clone(),n._playerMaterial=t,i.material=n),n.color=e)}static hashCode(e){var t=0,i,n;if(e.length===0)return t;for(i=0;i<e.length;i++)n=e.charCodeAt(i),t=(t<<5)-t+n,t|=0;return t}static colorFromHashCode(e){const t=(e&16711680)>>16,i=(e&65280)>>8,n=e&255;return new c.Color(t/255,i/255,n/255)}}const Ol=w("debugpost");let Up=null;function tk(s){Up=s}function uw(s){let e=s.gameObject;for(;e;){for(const t of Kd(e))if(t.isPostProcessingManager===!0)return t;e=e.parent}return null}function ik(s){let e=uw(s);if(!e)if(Up){Ol&&console.warn("Adding postprocessing manager to the scene.");const t=s.scene;e=Zi(t,Up)}else A()&&console.warn("No post processing manager found");return e}const Ke={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 Be=null;function nk(s){Ol==="verbose"&&console.debug("Before ordering effects",[...s]),Be||(Be=new Map,Be.set(exports.MODULES.POSTPROCESSING.MODULE.NormalPass,Ke.NormalPass),Be.set(exports.MODULES.POSTPROCESSING.MODULE.DepthDownsamplingPass,Ke.DepthDownsamplingPass),Be.set(exports.MODULES.POSTPROCESSING.MODULE.SMAAEffect,Ke.SMAA),Be.set(exports.MODULES.POSTPROCESSING.MODULE.SSAOEffect,Ke.SSAO),Be.set(exports.MODULES.POSTPROCESSING_AO.MODULE.N8AOPostPass,Ke.SSAO),Be.set(exports.MODULES.POSTPROCESSING_AO.MODULE.N8AOPass,Ke.SSAO),Be.set(exports.MODULES.POSTPROCESSING.MODULE.TiltShiftEffect,Ke.TiltShift),Be.set(exports.MODULES.POSTPROCESSING.MODULE.DepthOfFieldEffect,Ke.DepthOfField),Be.set(exports.MODULES.POSTPROCESSING.MODULE.ChromaticAberrationEffect,Ke.ChromaticAberration),Be.set(exports.MODULES.POSTPROCESSING.MODULE.BloomEffect,Ke.Bloom),Be.set(exports.MODULES.POSTPROCESSING.MODULE.SelectiveBloomEffect,Ke.Bloom),Be.set(exports.MODULES.POSTPROCESSING.MODULE.VignetteEffect,Ke.Vignette),Be.set(exports.MODULES.POSTPROCESSING.MODULE.PixelationEffect,Ke.Pixelation),Be.set(exports.MODULES.POSTPROCESSING.MODULE.ToneMappingEffect,Ke.ToneMapping),Be.set(exports.MODULES.POSTPROCESSING.MODULE.HueSaturationEffect,Ke.HueSaturation),Be.set(exports.MODULES.POSTPROCESSING.MODULE.BrightnessContrastEffect,Ke.BrightnessContrast)),s.sort((e,t)=>{const i=typeof e.priority=="number"?e.priority:Be.get(e.effect.constructor)??Number.NEGATIVE_INFINITY,n=typeof t.priority=="number"?t.priority:Be.get(t.effect.constructor)??Number.NEGATIVE_INFINITY;return i===Number.NEGATIVE_INFINITY?(Ol&&console.warn("Unknown effect found: ",e.constructor.name,e),1):n===Number.NEGATIVE_INFINITY?(Ol&&console.warn("Unknown effect found: ",t.constructor.name,t),-1):i-n}),Ol==="verbose"&&console.debug("After ordering effects",[...s])}var sk=Object.defineProperty,ok=Object.getOwnPropertyDescriptor,fw=(s,e,t,i)=>{for(var n=ok(e,t),o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&sk(e,t,n),n};const rk=w("debugpost");class I{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;rk&&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}}fw([f()],I.prototype,"overrideState");fw([f()],I.prototype,"value");class ak extends Ui{constructor(){super([I])}onSerialize(e,t){}onDeserialize(e,t){const i=t.target,n=t.path;let o;if(i&&n&&(o=i[n]),(typeof o!="object"||typeof o=="object"&&o.isVolumeParameter!==!0)&&(o=new I),typeof e=="object"&&"value"in e){const r=e.value;o.initialize(r),o.overrideState=e.overrideState}else o.value=e;return o}}new ak;var lk=Object.defineProperty,ck=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&lk(e,t,n),n};const $f=w("debugpost");class Ve extends k{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 I?n.initialize(i):n!==void 0&&(this[t]=i)}}active=!0;_manager=null;onEnable(){super.onEnable(),$f&&console.warn("Enable",this.constructor.name+(this.__internalDidAwakeAndStart?"":" (awake)")),this.__internalDidAwakeAndStart&&(this.active=!0),this.onEffectEnabled()}onDisable(){super.onDisable(),$f&&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=ik(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(){$f&&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 I&&i.__init()}}onEditorModification(e){const t=e.propertyName;if(this[t]instanceof I){const i=e.value;return this[t].value=i,!0}}}ck([f()],Ve.prototype,"active");var hk=Object.defineProperty,dk=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&hk(e,t,n),n};const uk=w("debugpost"),zp={};function $i(s,e){zp[s]=e}function fk(s){return s.__type in zp?zp[s.__type]:(uk&&s.__type&&console.warn("Unknown postprocessing type",s.__type,s),Ve)}class Cu{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)}}dk([$e([s=>fk(s),Ve])],Cu.prototype,"components");var pk=Object.defineProperty,mk=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&pk(e,t,n),n};const gk=w("debugpost");class Vc extends Ve{get typeName(){return"Antialiasing"}preset=new I(2);onCreateEffect(){const e=new exports.MODULES.POSTPROCESSING.MODULE.SMAAEffect({preset:this.preset?.value??exports.MODULES.POSTPROCESSING.MODULE.SMAAPreset.HIGH,edgeDetectionMode:exports.MODULES.POSTPROCESSING.MODULE.EdgeDetectionMode.LUMA});return this.preset.onValueChanged=t=>{gk&&console.log("Antialiasing preset changed to",t),e.applyPreset(t)},e}}mk([f(I)],Vc.prototype,"preset");$i("Antialiasing",Vc);var yk=Object.defineProperty,Ug=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&yk(e,t,n),n};const Pu=class pw extends Ve{static useSelectiveBloom=!1;get typeName(){return"Bloom"}threshold=new I(.9);intensity=new I(1);scatter=new I(.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=pw.useSelectiveBloom),this.selectiveBloom){const t=e=new exports.MODULES.POSTPROCESSING.MODULE.SelectiveBloomEffect(this.context.scene,this.context.mainCamera,{blendFunction:exports.MODULES.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 exports.MODULES.POSTPROCESSING.MODULE.BloomEffect({blendFunction:exports.MODULES.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});return this.intensity.onValueChanged=t=>{e.intensity=t},this.threshold.onValueChanged=t=>{e.luminanceMaterial.threshold=Math.pow(t,2.2)},this.scatter.onValueChanged=t=>{e.luminancePass.enabled=!0,e.luminanceMaterial.smoothing=t,e.mipmapBlurPass&&(e.mipmapBlurPass.radius=c.MathUtils.lerp(.1,.9,t))},e}};Ug([f(I)],Pu.prototype,"threshold");Ug([f(I)],Pu.prototype,"intensity");Ug([f(I)],Pu.prototype,"scatter");let Ou=Pu;$i("Bloom",Ou);var _k=Object.defineProperty,bk=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&_k(e,t,n),n};class $c extends Ve{get typeName(){return"ChromaticAberration"}intensity=new I(0);onCreateEffect(){const e=new exports.MODULES.POSTPROCESSING.MODULE.ChromaticAberrationEffect;return e.offset=new c.Vector2(0,0),e.radialModulation=!0,e.modulationOffset=.15,this.intensity.valueProcessor=t=>t*.02,this.intensity.onValueChanged=t=>{e.offset.x=-t,e.offset.y=t},e}}bk([f(I)],$c.prototype,"intensity");$i("ChromaticAberration",$c);var Ml=(s=>(s[s.None=0]="None",s[s.Neutral=1]="Neutral",s[s.ACES=2]="ACES",s[s.AgX=3]="AgX",s[s.KhronosNeutral=4]="KhronosNeutral",s))(Ml||{});const N_=new Map;function Wf(s){switch(s){case 0:return c.LinearToneMapping;case 1:return c.ReinhardToneMapping;case 2:return c.ACESFilmicToneMapping;case 3:return c.AgXToneMapping;case 4:return c.NeutralToneMapping;default:return N_.has(s)||(N_.set(s,!0),console.warn("[Postprocessing] Unknown tone mapping mode",s)),c.NeutralToneMapping}}function vk(s){switch(s){case c.LinearToneMapping:return 0;case c.ACESFilmicToneMapping:return 2;case c.AgXToneMapping:return 3;case c.NeutralToneMapping:return 1;case c.ReinhardToneMapping:return 1;default:return 0}}function od(s){switch(s){case c.LinearToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR;case c.ACESFilmicToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.ACES_FILMIC;case c.AgXToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.AGX;case c.NeutralToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.NEUTRAL;case c.ReinhardToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.REINHARD;default:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR}}var wk=Object.defineProperty,mw=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&wk(e,t,n),n};const Gf=w("debugpost");class Zs extends Ve{get typeName(){return"ToneMapping"}mode=new I(void 0);exposure=new I(1);setMode(e){const t=Ml[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=uw(this);e&&super.onEffectEnabled(e)}_tonemappingEffect=null;onCreateEffect(){if(this.mode.isInitialized==!1){const i=vk(this.context.renderer.toneMapping);Gf&&console.log("[PostProcessing] Initializing ToneMapping mode to renderer.toneMapping",this.context.renderer.toneMapping+" → "+i),this.mode.initialize(i)}this._tonemappingEffect?.dispose();const e=Wf(this.mode.value),t=this._tonemappingEffect=new exports.MODULES.POSTPROCESSING.MODULE.ToneMappingEffect({mode:od(e)});return this.mode.onValueChanged=i=>{if(typeof i=="string")i=Wv(i),t.mode=od(i);else{const n=Wf(i);t.mode=od(n)}t.name="ToneMapping ("+Ml[i]+")",Gf&&console.log("[PostProcessing] ToneMapping mode changed to",Ml[i],e,t.mode)},Gf&&console.log("[PostProcessing] Use ToneMapping",Ml[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=Wf(this.mode.value)),this.exposure.overrideState&&this.exposure.value!==void 0)){const e=Math.max(0,this.exposure.value);this.context.renderer.toneMappingExposure=e}}}mw([f(I)],Zs.prototype,"mode");mw([f(I)],Zs.prototype,"exposure");$i("Tonemapping",Zs);var xk=Object.defineProperty,Mu=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&xk(e,t,n),n};class uo extends Ve{get typeName(){return"ColorAdjustments"}remap=!0;postExposure=new I(1);contrast=new I(0);hueShift=new I(0);saturation=new I(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(o=>o instanceof Zs);t||(t=new Zs,this.postprocessingContext?.components.push(t)),this.postExposure.onValueChanged=o=>{this.postExposure.overrideState&&t?t.exposure.value=o: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 exports.MODULES.POSTPROCESSING.MODULE.BrightnessContrastEffect;this.contrast.onValueChanged=o=>i.contrast=o;const n=new exports.MODULES.POSTPROCESSING.MODULE.HueSaturationEffect;return this.hueShift.onValueChanged=o=>n.hue=o,this.saturation.onValueChanged=o=>n.saturation=o,e.push(i),e.push(n),e}}Mu([f(I)],uo.prototype,"postExposure");Mu([f(I)],uo.prototype,"contrast");Mu([f(I)],uo.prototype,"hueShift");Mu([f(I)],uo.prototype,"saturation");$i("ColorAdjustments",uo);var Sk=Object.defineProperty,vr=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&Sk(e,t,n),n};const Ck=w("debugpost");class ln extends Ve{get typeName(){return"DepthOfField"}mode;focusDistance=new I(1);focalLength=new I(.2);aperture=new I(20);gaussianMaxRadius=new I;resolutionScale=new I(1/window.devicePixelRatio);bokehScale=new I;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){Ck&&console.warn("DepthOfField: Mode is set to Off");return}const e=new exports.MODULES.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(){}}vr([f()],ln.prototype,"mode");vr([f(I)],ln.prototype,"focusDistance");vr([f(I)],ln.prototype,"focalLength");vr([f(I)],ln.prototype,"aperture");vr([f(I)],ln.prototype,"gaussianMaxRadius");vr([f(I)],ln.prototype,"resolutionScale");vr([f(I)],ln.prototype,"bokehScale");$i("DepthOfField",ln);class nc extends Ve{effect;constructor(e){super(),this.effect=e}get typeName(){return this.effect.constructor.name}onCreateEffect(){return this.effect}}var Pk=Object.defineProperty,Ok=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&Pk(e,t,n),n};class Wc extends Ve{get typeName(){return"PixelationEffect"}granularity=new I(10);onCreateEffect(){const e=new exports.MODULES.POSTPROCESSING.MODULE.PixelationEffect;return this.granularity.onValueChanged=t=>{e.granularity=t},e}}Ok([f(I)],Wc.prototype,"granularity");$i("PixelationEffect",Wc);var Mk=Object.defineProperty,Gc=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&Mk(e,t,n),n};class bs extends Ve{get typeName(){return"ScreenSpaceAmbientOcclusion"}intensity=new I(2);falloff=new I(1);samples=new I(9);color=new I(new c.Color(0,0,0));luminanceInfluence=new I(.7);onBeforeRender(){if(this._ssao&&this.context.mainCamera instanceof c.PerspectiveCamera){const e=this.context.mainCamera.far-this.context.mainCamera.near;this._ssao.ssaoMaterial.worldDistanceFalloff=e*.01,this._ssao.ssaoMaterial.worldDistanceThreshold=this.context.mainCamera.far}}_ssao;onCreateEffect(){const e=this.context.mainCamera,t=new exports.MODULES.POSTPROCESSING.MODULE.NormalPass(this.context.scene,e),i=new exports.MODULES.POSTPROCESSING.MODULE.DepthDownsamplingPass({normalBuffer:t.texture,resolutionScale:.5}),n=this._ssao=new exports.MODULES.POSTPROCESSING.MODULE.SSAOEffect(e,t.texture,{normalDepthBuffer:i.texture,worldDistanceThreshold:1,worldDistanceFalloff:1,worldProximityThreshold:.1,worldProximityFalloff:2,intensity:1,blendFunction:exports.MODULES.POSTPROCESSING.MODULE.BlendFunction.MULTIPLY,luminanceInfluence:.5});this.intensity.onValueChanged=r=>{n.intensity=r},this.falloff.onValueChanged=r=>{n.ssaoMaterial.radius=r*.1},this.samples.onValueChanged=r=>{n.ssaoMaterial.samples=r},this.color.onValueChanged=r=>{n.color||(n.color=new c.Color),n.color.copy(r)},this.luminanceInfluence.onValueChanged=r=>{n.luminanceInfluence=r};const o=new Array;return o.push(t),o.push(i),o.push(n),o}}Gc([f(I)],bs.prototype,"intensity");Gc([f(I)],bs.prototype,"falloff");Gc([f(I)],bs.prototype,"samples");Gc([f(I)],bs.prototype,"color");Gc([f(I)],bs.prototype,"luminanceInfluence");$i("ScreenSpaceAmbientOcclusion",bs);var kk=Object.defineProperty,wr=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&kk(e,t,n),n};const Ek=w("debugN8AO");var Np=(s=>(s[s.Performance=0]="Performance",s[s.Low=1]="Low",s[s.Medium=2]="Medium",s[s.High=3]="High",s[s.Ultra=4]="Ultra",s))(Np||{});class cn extends Ve{get typeName(){return"ScreenSpaceAmbientOcclusionN8"}get pass(){return this._ssao}gammaCorrection=!0;aoRadius=new I(1);falloff=new I(1);intensity=new I(1);color=new I(new c.Color(0,0,0));screenspaceRadius=!1;quality=2;_ssao;onValidate(){this._ssao&&(this._ssao.setQualityMode(Np[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 exports.MODULES.POSTPROCESSING_AO.MODULE.N8AOPostPass(this.context.scene,e,t,i);n.name="SSAO_N8";const o=Np[this.quality];n.setQualityMode(o),n.configuration.transparencyAware=!1;const r=new c.WebGLRenderTarget(t,i);return n.configuration.beautyRenderTarget=r,n.configuration.autoRenderBeauty=!1,n.configuration.gammaCorrection=this.gammaCorrection,n.configuration.screenSpaceRadius=this.screenspaceRadius,Ek&&(n.enableDebugMode(),console.log(n),setInterval(()=>{console.log("SSAO",n.lastTime)},1e3),setInterval(()=>{console.log("SSAO",n.enabled,{ssao:n,autoRenderBeauty:n.configuration.autoRenderBeauty})},4e3)),this.intensity.onValueChanged=a=>{n.configuration.intensity=a},this.falloff.onValueChanged=a=>{n.configuration.distanceFalloff=a},this.aoRadius.onValueChanged=a=>{n.configuration.aoRadius=a},this.color.onValueChanged=a=>{n.color||(n.color=new c.Color),n.configuration.color.copy(a)},n}}wr([yt(),f()],cn.prototype,"gammaCorrection");wr([f(I)],cn.prototype,"aoRadius");wr([f(I)],cn.prototype,"falloff");wr([f(I)],cn.prototype,"intensity");wr([f(I)],cn.prototype,"color");wr([yt(),f()],cn.prototype,"screenspaceRadius");wr([yt(),f()],cn.prototype,"quality");$i("ScreenSpaceAmbientOcclusionN8",cn);var Rk=Object.defineProperty,Tk=Object.getOwnPropertyDescriptor,gw=(s,e,t,i)=>{for(var n=Tk(e,t),o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&Rk(e,t,n),n};class Hc extends Ve{get typeName(){return"Sharpening"}order=Ke.Sharpening;_effect;onCreateEffect(){return this._effect??=new(Ak()),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}gw([f()],Hc.prototype,"amount");gw([f()],Hc.prototype,"radius");function Ak(){const s=`
|
|
1283
|
+
`)}r&&o.size&&console.log(u);const y=new Set;for(const v of m){v.getPath||console.error("USDZExporter: Animation target object has no getPath method. This is likely a bug",v);let _=v.getPath();_.startsWith("<")&&(_=_.substring(1)),_.endsWith(">")&&(_=_.substring(0,_.length-1)),y.add({path:_,obj:v})}const b=Array.from(y).sort((v,_)=>v.path.length-_.path.length),g=new Array;for(let v=0;v<b.length;v++)for(let _=v+1;_<b.length;_++)if(b[_].path.startsWith(b[v].path)){const x=b[_],T=b[v];g.push({child:x.obj.displayName+" ("+x.path+")",parent:T.obj.displayName+" ("+T.path+")"})}g.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:g,playAnimationActions:o})}for(const u of new Set([...t,...i]))if(Array.isArray(u))for(const p of u)n.add(p.uuid);else n.add(u.uuid);Rh&&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){Rh&&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 r=await(await(await fetch(t)).blob()).arrayBuffer(),a=new Uint8Array(r);e.files[i]=a}this.behaviourComponentsCopy.length=0,this.audioClipsCopy.length=0}}class _g{get extensionName(){return"Physics"}onExportObject(e,t,i){const n=S.getComponents(e,Ne).filter(l=>l.enabled),o=S.getComponents(e,Kt).filter(l=>l.enabled&&!l.isTrigger);let r=n.length>0?n[0]:null;const a=o.length>0?o[0]:null;a&&!r&&(r=new Ne,r.isKinematic=!0),r&&t.addEventListener("serialize",(l,h)=>{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("}"),o.length>0){const d=o[0];l.beginBlock('def RealityKitStruct "material"',"{",!0);const u=d.sharedMaterial;u&&u.dynamicFriction!==void 0&&l.appendLine(`double dynamicFriction = ${d.sharedMaterial?.dynamicFriction}`),u&&u.bounciness!==void 0&&l.appendLine(`double restitution = ${d.sharedMaterial?.bounciness}`),u&&u.staticFriction!==void 0&&l.appendLine(`double staticFriction = ${d.sharedMaterial?.staticFriction}`),l.closeBlock("}")}l.closeBlock("}")}}),a&&(t.addEventListener("serialize",(l,h)=>{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 u=a.isTrigger?"Trigger":"Default";if(l.appendLine(`token type = "${u}"`),l.beginBlock('def RealityKitStruct "Shape"',"{",!0),a instanceof Sa){const p=a;l.appendLine('token shapeType = "Sphere"'),l.appendLine(`float radius = ${p.radius}`)}else if(a instanceof lu){const p=a;l.appendLine('token shapeType = "Box"'),l.appendLine(`float3 extent = (${p.size.x}, ${p.size.y}, ${p.size.z})`)}else if(a instanceof ls){const p=a;l.appendLine('token shapeType = "Capsule"'),l.appendLine(`float radius = ${p.radius}`),l.appendLine(`float height = ${p.height}`)}else if(a instanceof so&&a.sharedMesh?.geometry){const p=a.sharedMesh.geometry;p.boundingBox||p.computeBoundingBox();const m=a.sharedMesh.geometry.boundingBox;m&&(l.appendLine('token shapeType = "Box"'),l.appendLine(`float3 extent = (${m.max.x-m.min.x}, ${m.max.y-m.min.y}, ${m.max.z-m.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("}")}),o.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 iM=w("debugshadowcomponents");J.__webpack_exports__Block.prototype.interactable={get(){return this.interactive},set(s){this.interactable=s}};class Bi extends k{isRoot(){return this.Root?.gameObject===this.gameObject}get canvas(){const e=this.Root;return e?.isCanvas?e:null}get Canvas(){return this.canvas}markDirty(){jt.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=S.getComponentInParent(this.gameObject,Ac)),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=S.getComponentInParent(i,Bi),!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[ri]=this,this.setShadowComponentOwner(e);let n=!1;if(this.Root?.gameObject===this.gameObject)this.gameObject.add(e);else{const o=this._parentComponent.shadowComponent;o&&(o?.add(e),n=!0)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),fc&&e.add(new c.AxesHelper(.5)),this.onAfterAddedToScene(),n&&J.__webpack_exports__update(),iM&&console.warn("Added shadow component",this.shadowComponent)}setShadowComponentOwner(e){if(e&&(e[ri]===void 0||e[ri]===this)&&(e[ri]=this,e.children))for(const t of e.children)this.setShadowComponentOwner(t)}traverseOwnedShadowComponents(e,t,i){if(e&&e[ri]===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 Ac extends Bi{awake(){super.awake()}}var nM=Object.defineProperty,sM=Object.getOwnPropertyDescriptor,Lc=(s,e,t,i)=>{for(var n=i>1?void 0:i?sM(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&nM(e,t,n),n};const Df=w("debugui"),If=w("debuguilayout");class ew{width;height}class tw{x;y;width;height}const qi=new c.Vector3,tl=new c.Matrix4,Th=new c.Quaternion,Ea=class iw extends Bi{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 c.Vector2),this._anchoredPosition}set anchoredPosition(e){this._anchoredPosition=e}sizeDelta=new c.Vector2(100,100);pivot=new c.Vector2(.5,.5);anchorMin=new c.Vector2(0,0);anchorMax=new c.Vector2(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 c.Object3D,this.rectBlock.name=this.name,this.lastMatrix=new c.Matrix4,this._lastAnchoring=null,this._initialPosition=this.gameObject.position.clone(),this._initialPosition.z=0,this._anchoredPosition||(this._anchoredPosition=new c.Vector2),Ur(this,"_anchoredPosition",()=>{this.markDirty()}),Ur(this,"sizeDelta",()=>{this.markDirty()}),Ur(this,"pivot",()=>{this.markDirty()}),Ur(this,"anchorMin",()=>{this.markDirty()}),Ur(this,"anchorMax",()=>{this.markDirty()})}onEnable(){super.onEnable(),this.rectBlock||(this.rectBlock=new c.Object3D),this.lastMatrix||(this.lastMatrix=new c.Matrix4),this._lastAnchoring||(this._lastAnchoring=new c.Vector2),this._initialPosition||(this._initialPosition=new c.Vector3),this._anchoredPosition||(this._anchoredPosition=new c.Vector2),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(If?`${e.name} changed`:void 0)}get isDirty(){return this._transformNeedsUpdate||(this._transformNeedsUpdate=!this.lastMatrix.equals(this.gameObject.matrix)),this._transformNeedsUpdate}markDirty(){this._transformNeedsUpdate||(If&&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=S.getComponentInParent(this.gameObject.parent,iw):this._parentRectTransform=void 0,this._transformNeedsUpdate=!1,If&&console.warn("RectTransform → ApplyTransform",this.name+" because "+e),this.isRoot()?this.Root.screenspace||(t.rotation.y=Math.PI):(t.matrix.identity(),t.matrixAutoUpdate=!1,qi.set(0,0,0),this.applyPivot(qi),t.matrix.setPosition(qi.x,qi.y,0),(this.gameObject.quaternion.x||this.gameObject.quaternion.y||this.gameObject.quaternion.z)&&(Th.copy(this.gameObject.quaternion),Th.x*=-1,Th.z*=-1,tl.makeRotationFromQuaternion(Th),t.matrix.premultiply(tl)),qi.set(0,0,0),this.applyAnchoring(qi),this.canvas?.screenspace?qi.z+=.1:qi.z+=.01,tl.identity(),tl.setPosition(qi.x,qi.y,qi.z),t.matrix.premultiply(tl),t.matrix.scale(this.gameObject.scale)),this.lastMatrix.copy(this.gameObject.matrix);const i=!0;for(const n of Kd(this.gameObject,Bi,i,1)){if(n===this||!n.activeAndEnabled)continue;const o=n;o.onParentRectTransformChanged&&o.onParentRectTransformChanged(this)}}_lastAnchoring;applyAnchoring(e){this._lastAnchoring||(this._lastAnchoring=new c.Vector2);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 o=1-this.anchorMax.y-this.anchorMin.y;n-=i.height*.5*o,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},Df&&console.log(this.name,e);const t=new J.__webpack_exports__Block(e);return this._createdBlocks.push(t),t}createNewText(e){Df&&console.log(e),e={...this.getBasicOptions(),...e},Df&&console.log(this.name,e);const t=new J.__webpack_exports__Text(e);return this._createdTextBlocks.push(t),t}};Lc([f(c.Vector2)],Ea.prototype,"anchoredPosition",1);Lc([f(c.Vector2)],Ea.prototype,"sizeDelta",2);Lc([f(c.Vector2)],Ea.prototype,"pivot",2);Lc([f(c.Vector2)],Ea.prototype,"anchorMin",2);Lc([f(c.Vector2)],Ea.prototype,"anchorMax",2);let sn=Ea;var oM=Object.defineProperty,nw=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&oM(e,t,n),n};class Ra extends k{effectColor;effectDistance}nw([f(Z)],Ra.prototype,"effectColor");nw([f(c.Vector2)],Ra.prototype,"effectDistance");var rM=Object.defineProperty,aM=Object.getOwnPropertyDescriptor,sw=(s,e,t,i)=>{for(var n=i>1?void 0:i?aM(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&rM(e,t,n),n};const Ah={backgroundColor:new c.Color(1,1,1),backgroundOpacity:1,borderColor:new c.Color(1,1,1),borderOpacity:1},bg=class vl extends Bi{get isGraphic(){return!0}get color(){return this._color||(this._color=new Z(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 Z(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 c.Color(1,0,1);onColorChanged(){this.uiObject&&(this.sRGBColor.copy(this._color),this.sRGBColor.convertLinearToSRGB(),Ah.backgroundColor=this.sRGBColor,Ah.backgroundOpacity=this._color.alpha*this._alphaFactor,this.applyEffects(Ah,this._alphaFactor),this.uiObject.set(Ah),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=S.getComponent(this.gameObject,sn)),!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 J.SimpleStateBehavior(this.uiObject)),this.uiObject.setupState(e.state,e.attributes))}setOptions(e){this.makePanel(),this.uiObject&&this.uiObject.set(e)}awake(){super.awake(),this.makePanel(),Ur(this,"_color",()=>iP(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 t={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:.015};this.onBeforeCreate(t),this.applyEffects(t),this.onCreate(t),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(Ra);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(vl.textureCache.has(e))e=vl.textureCache.get(e);else if(!e.isRenderTargetTexture){const t=e.clone();t.colorSpace=c.LinearSRGBColorSpace,vl.textureCache.set(e,t),e=t}this.setOptions({backgroundImage:e,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"}),ne.NEEDLE_progressive.assignTextureLOD(e,0).then(t=>{t instanceof c.Texture&&(e&&vl.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)}};sw([f(Z)],bg.prototype,"color",1);sw([f()],bg.prototype,"raycastTarget",2);let Dc=bg;class Ic extends Dc{_flippedObject=!1;onAfterCreated(){this.uiObject&&!this._flippedObject&&(this._flippedObject=!0,this.uiObject.scale.y*=-1)}}var lM=Object.defineProperty,cM=Object.getOwnPropertyDescriptor,gs=(s,e,t,i)=>{for(var n=i>1?void 0:i?cM(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&lM(e,t,n),n};const bo=w("debugtext");var Qe=(s=>(s[s.UpperLeft=0]="UpperLeft",s[s.UpperCenter=1]="UpperCenter",s[s.UpperRight=2]="UpperRight",s[s.MiddleLeft=3]="MiddleLeft",s[s.MiddleCenter=4]="MiddleCenter",s[s.MiddleRight=5]="MiddleRight",s[s.LowerLeft=6]="LowerLeft",s[s.LowerCenter=7]="LowerCenter",s[s.LowerRight=8]="LowerRight",s))(Qe||{}),ow=(s=>(s[s.Normal=0]="Normal",s[s.Bold=1]="Bold",s[s.Italic=2]="Italic",s[s.BoldAndItalic=3]="BoldAndItalic",s))(ow||{});class St extends Dc{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 c.Color(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){bo&&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,bo&&(e.backgroundColor=16750848,e.backgroundOpacity=.5);const t=this.rectTransform;e={...e,...this.getTextOpts()},this.getAlignment(e),bo&&(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(bo&&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 o=new J.__webpack_exports__Inline({textContent:e.substring(0,i.startIndex),color:"inherit"});this.uiObject.add(o)}}else{this.uiObject.textContent="",this.setOptions({textContent:e});return}const n=[];for(;i;){const o=this.getNextTag(e,i.endIndex),r={fontFamily:this.uiObject?.get("fontFamily"),color:"inherit",textContent:""};if(o){r.textContent=this.getText(e,i,o),this.handleTag(i,r,n);const a=new J.__webpack_exports__Inline(r);this.uiObject?.add(a)}else{r.textContent=e.substring(i.endIndex),this.handleTag(i,r,n);const a=new J.__webpack_exports__Inline(r);this.uiObject?.add(a)}i=o}}}_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 o=0;o<this._textMeshUi.length;o++){if(e[o]===!0)continue;n=!0;const r=this._textMeshUi[o];r.textContent&&(Od(r,i),e[o]=!0)}if(!n)break;yield}}handleTag(e,t,i){if(!e.isEndTag){if(e.type.includes("color")){const n=new jf(e,{color:t.color});if(i.push(n),e.type.length>6){const o=parseInt("0x"+e.type.substring(7));t.color=o}else t.color=new c.Color(1,1,1)}else if(e.type=="b"){this.setFont(t,1);const n=new jf(e,{fontWeight:700});i.push(n)}else if(e.type=="i"){this.setFont(t,2);const n=new jf(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 o=e.substring(i+1,n);return{type:o,startIndex:i,endIndex:n+1,isEndTag:o.startsWith("/")}}return null}setFont(e,t){if(!this.font)return;const i=this.font,n=this.getFamilyNameWithCorrectSuffix(i,t);bo&&console.log("Selected font family:"+n);let o=J.__webpack_exports__FontLibrary.getFontFamily(n);switch(o||(o=J.__webpack_exports__FontLibrary.addFontFamily(n)),e.fontFamily=o,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=o.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=o.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(hM.includes(n))return bo&&console.warn("Unsupported font style: "+n),e;const o=e.lastIndexOf("/");let r=e;o>=0&&(r=r.substring(o+1));const a=r[0]===r[0].toUpperCase(),l=e.substring(0,i);switch(bo&&console.log("Select font: ",e,ow[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}}}gs([f()],St.prototype,"alignment",2);gs([f()],St.prototype,"verticalOverflow",2);gs([f()],St.prototype,"horizontalOverflow",2);gs([f()],St.prototype,"lineSpacing",2);gs([f()],St.prototype,"supportRichText",2);gs([f(URL)],St.prototype,"font",2);gs([f()],St.prototype,"fontStyle",2);gs([f()],St.prototype,"text",1);gs([f()],St.prototype,"fontSize",1);class jf{tag;previousValues;constructor(e,t){this.tag=e,this.previousValues=t}}const hM=["medium","mediumitalic","black","blackitalic","thin","thinitalic","extrabold","light","lightitalic","semibold"];class Yr{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/${uu(this.material)}>`),t.closeBlock()}}class vg{static singleLine(e,t,i){const n=new Yr("text_"+Yr.getId());return n.content=e,t&&(n.pointSize=t),i&&(n.depth=i),n}static multiLine(e,t,i,n,o,r){const a=new Yr("text_"+Yr.getId());return a.content=e,a.width=t,a.height=i,a.horizontalAlignment=n,a.verticalAlignment=o,r!==void 0&&(a.wrapMode=r),a}}const dM=new c.Matrix4().makeRotationY(Math.PI),uM=new c.Matrix4().makeScale(-1,1,-1);class vu{get extensionName(){return"text"}exportText(e,t,i){const n=S.getComponent(e,St);if(!n)return;const o=S.getComponent(e,sn);let r=100,a=100;o&&(r=o.width,a=o.height);const l=dM.clone();o&&l.premultiply(uM),t.setMatrix(l);const h=n.color.clone();t.material=new c.MeshStandardMaterial({color:h,emissive:h}),t.addEventListener("serialize",(d,u)=>{let p=n.text;p=p.replace(/\r/g,""),p=p.replace(/\n/g,"\\n");const m=vg.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,d)})}convertToTextSize(e){return 1/.0502*144*e}setOverflow(e,t){t.horizontalOverflow?e.wrapMode="singleLine":e.wrapMode="flowing"}setTextAlignment(e,t){switch(t){case Qe.LowerLeft:case Qe.MiddleLeft:case Qe.UpperLeft:e.horizontalAlignment="left";break;case Qe.LowerCenter:case Qe.MiddleCenter:case Qe.UpperCenter:e.horizontalAlignment="center";break;case Qe.LowerRight:case Qe.MiddleRight:case Qe.UpperRight:e.horizontalAlignment="right";break}switch(t){case Qe.LowerLeft:case Qe.LowerCenter:case Qe.LowerRight:e.verticalAlignment="bottom";break;case Qe.MiddleLeft:case Qe.MiddleCenter:case Qe.MiddleRight:e.verticalAlignment="middle";break;case Qe.UpperLeft:case Qe.UpperCenter:case Qe.UpperRight:e.verticalAlignment="top";break}}}var fM=Object.defineProperty,We=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&fM(e,t,n),n};const A_=w("debuguilayout");class fr{left=0;right=0;top=0;bottom=0;get vertical(){return this.top+this.bottom}get horizontal(){return this.left+this.right}}We([f()],fr.prototype,"left");We([f()],fr.prototype,"right");We([f()],fr.prototype,"top");We([f()],fr.prototype,"bottom");class _i extends k{_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&&(A_&&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(){A_&&console.log(this.name,this),this._rectTransform=this.gameObject.getComponent(sn);const e=this.gameObject.getComponentInParent(ya);e&&e.registerLayoutGroup(this),this._needsUpdate=!0}onDisable(){const e=this.gameObject.getComponentInParent(ya);e&&e.unregisterLayoutGroup(this)}set m_Spacing(e){e!==this.spacing&&(this._needsUpdate=!0,this.spacing=e)}get m_Spacing(){return this.spacing}}We([f()],_i.prototype,"childAlignment");We([f()],_i.prototype,"reverseArrangement");We([f()],_i.prototype,"spacing");We([f(fr)],_i.prototype,"padding");We([f()],_i.prototype,"minWidth");We([f()],_i.prototype,"minHeight");We([f()],_i.prototype,"flexibleHeight");We([f()],_i.prototype,"flexibleWidth");We([f()],_i.prototype,"preferredHeight");We([f()],_i.prototype,"preferredWidth");class ao extends _i{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 o=e.height;let r=o;n-=this.padding.horizontal,r-=this.padding.vertical,t==="x"?this.padding.horizontal:this.padding.vertical;const a=t==="x",l=a?"y":"x",h=a?this.childControlWidth:this.childControlHeight,d=a?this.childControlHeight:this.childControlWidth,u=a?this.childForceExpandWidth:this.childForceExpandHeight,p=a?this.childForceExpandHeight:this.childForceExpandWidth,m=a?r:n,y=a?i:o,b=.5*(a?this.childAlignment%3:Math.floor(this.childAlignment/3));let g=0;a?g+=this.padding.left:g+=this.padding.top;let v=0,_=0;for(let E=0;E<this.gameObject.children.length;E++){const j=this.gameObject.children[E],L=S.getComponent(j,sn);L?.activeAndEnabled&&(_+=1,a?v+=L.width:v+=L.height)}let x=0;const T=this.spacing*(_-1);if(u||h){let E=0;a?E=n-=T:E=r-=T,_>0&&(x=E/_)}let O=0;O+=this.padding.left,O-=this.padding.right,b!==0&&(g=y-v,g*=b,g-=T*b,a?(g-=this.padding.right*b,g+=this.padding.left*(1-b),g<this.padding.left&&(g=this.padding.left)):(g-=this.padding.bottom*b,g+=this.padding.top*(1-b),g<this.padding.top&&(g=this.padding.top)));let M=1;for(let E=0;E<this.gameObject.children.length;E++){const j=this.gameObject.children[E],L=S.getComponent(j,sn);if(L?.activeAndEnabled){L.pivot?.set(.5,.5),L.anchorMin.set(0,1),L.anchorMax.set(0,1);const z=i*.5+O*.5;L.anchoredPosition.x!==z&&(L.anchoredPosition.x=z);const $=o*-.5;L.anchoredPosition.y!==$&&(L.anchoredPosition.y=$),p&&d&&L.sizeDelta[l]!==m&&(L.sizeDelta[l]=m),u&&h&&L.sizeDelta[t]!==x&&(L.sizeDelta[t]=x);const R=a?L.width:L.height,U=R*.5;if(g+=U,u){const K=x*M-x*.5;K>g&&(g=K-x*.5+R+this.padding.left,g-=U)}let N=g;t==="y"&&(N=-N),L.anchoredPosition[t]!==N&&(L.anchoredPosition[t]=N),g+=U,g+=this.spacing,M+=1}}}}We([f()],ao.prototype,"childControlHeight");We([f()],ao.prototype,"childControlWidth");We([f()],ao.prototype,"childForceExpandHeight");We([f()],ao.prototype,"childForceExpandWidth");We([f()],ao.prototype,"childScaleHeight");We([f()],ao.prototype,"childScaleWidth");class wg extends ao{get primaryAxis(){return"y"}}class xg extends ao{get primaryAxis(){return"x"}}class Sg extends _i{onCalculateLayout(){}}var pM=Object.defineProperty,mM=Object.getOwnPropertyDescriptor,Fn=(s,e,t,i)=>{for(var n=i>1?void 0:i?mM(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&pM(e,t,n),n},rw=(s=>(s[s.ScreenSpaceOverlay=0]="ScreenSpaceOverlay",s[s.ScreenSpaceCamera=1]="ScreenSpaceCamera",s[s.WorldSpace=2]="WorldSpace",s[s.Undefined=-1]="Undefined",s))(rw||{});const Bf=w("debuguilayout"),Fi=class aw extends Ac{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 aw||(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,Bf&&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 c.Matrix4,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 lc(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(),jt.ensureUpdateMeshUI(J.ThreeMeshUI,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(),jt.ensureUpdateMeshUI(J.ThreeMeshUI,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 c.Matrix4);const e=!this._lastMatrixWorld.equals(this.gameObject.matrixWorld);Bf&&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(_i)),(t.isDirty||i?.isDirty)&&(Bf&&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(),pe.OnBeforeRender))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.onUpdateRenderMode(),Od(this.shadowComponent,this);for(const e of S.getComponentsInChildren(this.gameObject,Bi))Od(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 o=this.gameObject.getComponent(sn);let r=!1;o.sizeDelta.x!==this.context.domWidth&&(r=!0),o.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&&(o.sizeDelta.x=this.context.domWidth,o.sizeDelta.y=this.context.domHeight,o?.markDirty());break;case 2:this._lastWidth=-1,this._lastHeight=-1;break}}};Fn([f()],Fi.prototype,"renderOnTop",1);Fn([f()],Fi.prototype,"depthWrite",1);Fn([f()],Fi.prototype,"doubleSided",1);Fn([f()],Fi.prototype,"castShadows",1);Fn([f()],Fi.prototype,"receiveShadows",1);Fn([f()],Fi.prototype,"renderMode",1);Fn([f(Fi)],Fi.prototype,"rootCanvas",1);Fn([f()],Fi.prototype,"scaleFactor",1);Fn([f(qt)],Fi.prototype,"worldCamera",2);Fn([f()],Fi.prototype,"planeDistance",2);let ya=Fi;var gM=Object.defineProperty,yM=Object.getOwnPropertyDescriptor,Cg=(s,e,t,i)=>{for(var n=i>1?void 0:i?yM(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&gM(e,t,n),n};class Ks extends k{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(),pe.OnBeforeRender))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}_buffer=[];applyChangesNow(){this._buffer.length=0;for(const e of S.getComponentsInChildren(this.gameObject,Bi,this._buffer)){const t=e;t.setAlphaFactor&&t.setAlphaFactor(this._alpha)}}}Cg([f()],Ks.prototype,"alpha",1);Cg([f()],Ks.prototype,"interactable",2);Cg([f()],Ks.prototype,"blocksRaycasts",2);class Pg{get extensionName(){return"tmui"}onExportObject(e,t,i){const n=S.getComponent(e,ya);if(n&&n.enabled&&n.renderMode===rw.WorldSpace){const o=new vu,r=S.getComponent(e,sn),a=S.getComponent(e,Ks),l=new Array;if(r){if(!S.isActiveSelf(e)){const u=S.isActiveSelf(e);S.setActive(e,!0),r.onEnable(),r.updateTransform(),l.push(()=>{r.onDisable(),S.setActive(e,u)})}e.traverse(u=>{if(!S.isActiveInHierarchy(u)){const p=S.isActiveSelf(u);S.setActive(u,!0);const m=S.getComponent(u,Bi);m&&(m.onEnable(),l.push(()=>{m.onDisable()}));const y=S.getComponent(u,sn);y&&(y.onEnable(),y.updateTransform(),y.onApplyTransform(),l.push(()=>{y.onDisable()}));const b=S.getComponent(u,St);b&&(b.onEnable(),l.push(()=>{b.onDisable()})),l.push(()=>{S.setActive(u,p)})}}),r.width,r.height;const h=ze.createEmpty(),d=r.shadowComponent;if(t.add(h),d){const u=d.matrix;h.setMatrix(u);const p=new Map,m=new Map;p.set(d,h),m.set(d,a?a.alpha:1),d.traverse(y=>{if(y===d)return;const b=ze.createEmpty();b.setMatrix(y.matrix);const g=y.parent,v=!!g&&typeof g.textContent=="string"&&g.textContent.length>0;let _=m.get(g)||1;const x=S.getComponent(y,Ks);if(x&&(_*=x.alpha),y instanceof c.Mesh&&v){const O=y[ri];O?o.exportText(O.gameObject,b,i):console.error("Error when exporting UI: shadow component owner not found. This is likely a bug.",y)}if(y instanceof c.Mesh&&!v){const O=y.geometry.clone();O.scale(1,1,-1),this.flipWindingOrder(O),b.geometry=O;const M=new c.Color,E=y.material.opacity;M.copy(y.material.color),b.material=new c.MeshBasicMaterial({color:M,opacity:E*_,map:y.material.map,transparent:!0})}p.set(y,b),m.set(y,_);const T=p.get(g);if(!T){console.error("Error when exporting UI: shadow component parent not found!",y,y.parent);return}T.add(b)})}}for(const h of l)h()}}flipWindingOrder(e){const t=e.index.array;for(let i=0,n=t.length/3;i<n;i++){const o=t[i*3];t[i*3]=t[i*3+2],t[i*3+2]=o}e.index.needsUpdate=!0}}const wl=w("debugusdz");function _M(s,e){const t=[],i=S.getComponentsInChildren(s,rt),n=S.getComponentsInChildren(s,Ft),o=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||o.includes(a))continue;const h=new ec;h.animator=a,h.stateName=l.name,h.trigger="start",h.name="PlayAnimationOnClick_implicitAtStart_"+h.stateName;const d=new c.Object3D;S.addComponent(d,h),r.push(d),o.push(a),s.add(d)}else for(const a of i){if(!a||!a.runtimeAnimatorController||!a.enabled)continue;wl&&console.log(a);const l=[];for(const h of a.runtimeAnimatorController.enumerateActions()){wl&&console.log(h);const d=h.getClip();l.includes(d)||l.push(d)}t.push({root:a.gameObject,clips:l})}if(e.injectImplicitBehaviours)for(const a of n){if(!a||!a.clip||!a.enabled||!a.playAutomatically||o.includes(a))continue;const l=new ec;l.animation=a,l.stateName=a.clip.name,l.trigger="start",l.name="PlayAnimationOnClick_implicitAtStart_"+l.stateName;const h=new c.Object3D;S.addComponent(h,l),r.push(h),o.push(a),s.add(h)}else for(const a of n){wl&&console.log(a);const l=[];for(const h of a.animations)l.includes(h)||l.push(h);t.push({root:a.gameObject,clips:l})}wl&&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 bM(s,e){const t=S.getComponentsInChildren(s,pi),i=S.getComponentsInChildren(s,Qs),n=new Array,o=new Array;wl&&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 Qs;a.target=r,a.name="PlayAudioOnClick_implicitAtStart_",a.trigger="start";const l=new c.Object3D;S.addComponent(l,a),console.log("implicit PlayAudioOnStart",l,a),o.push(l),n.push(r),s.add(l)}return o}function vM(s){return new gt("DisableAtStart",wt.sceneStartTrigger(),le.fadeAction(s,0,!1))}function L_(s,e){const t=s.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 o=document.createElement("a");o.id="needle-usdz-link",o.style.display="none",o.rel="ar",o.href="",o.target="_blank",i.appendChild(o);const r=document.createElement("img");return r.id="button",o.appendChild(r),s.domElement.shadowRoot.appendChild(i),o}var wM=Object.defineProperty,_t=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&wM(e,t,n),n};const ii=w("debugusdz"),xM=w("debugusdzpruning");class pr{callToAction;checkoutTitle;checkoutSubtitle;callToActionURL}_t([f()],pr.prototype,"callToAction");_t([f()],pr.prototype,"checkoutTitle");_t([f()],pr.prototype,"checkoutSubtitle");_t([f()],pr.prototype,"callToActionURL");const Jt=class xl extends k{static beforeExport=new oe;static afterExport=new oe;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=exports.DeviceUtilities.supportsQuickLookAR(),t=exports.DeviceUtilities.isiOS()||exports.DeviceUtilities.isiPad();!this.button&&(ii||e||t)&&(this.allowCreateQuicklookButton&&(this.button=this.createQuicklookButton()),this.lastCallback=this.quicklookCallback.bind(this),this.link=L_(this.context,e),this.link.addEventListener("message",this.lastCallback)),ii&&Se("USDZ Exporter enabled: "+this.name),document.getElementById("open-in-ar")?.addEventListener("click",this.onClickedOpenInARElement),Gl.registerExporter(this)}onDisable(){this.button?.remove(),this.link?.removeEventListener("message",this.lastCallback),ii&&Se("USDZ Exporter disabled: "+this.name),document.getElementById("open-in-ar")?.removeEventListener("click",this.onClickedOpenInARElement),Gl.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+="-"+B0(),En()||(e!==""&&(e+="-"),e+="MadeWithNeedle"),this.link||(this.link=L_(this.context,exports.DeviceUtilities.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;xl.beforeExport.invoke({exporter:this});const t=await this.export(this.objectToExport).finally(()=>{xl.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 – please report a bug!",n),null))):i}_currentExportTasks=new Map;_previousTimeScale=1;async internalExport(e){ie.start("export-usdz",{onProgress:O=>{this.dispatchEvent(new CustomEvent("export-progress",{detail:{progress:O}}))}}),ie.report("export-usdz",{message:"Starting export",totalSteps:40,currentStep:0}),ie.report("export-usdz",{message:"Load progressive textures",autoStep:5}),ie.start("export-usdz-textures","export-usdz");const t=S.getComponentsInChildren(e,Zt);for(const O of t)O&&O.enabled&&O.updateSprite(!0);const i=S.getComponentsInChildren(e,mi),n=new Array;let o=0;for(const O of i){for(const M of O.sharedMeshes)if(M){const E=ne.NEEDLE_progressive.assignMeshLOD(M,0);E instanceof Promise&&n.push(new Promise((j,L)=>{E.then(()=>{o++,ie.report("export-usdz-textures",{message:"Loaded progressive mesh",currentStep:o,totalSteps:n.length}),j()}).catch(z=>L(z))}))}for(const M of O.sharedMaterials)if(M){const E=ne.NEEDLE_progressive.assignTextureLOD(M,0);E instanceof Promise&&n.push(new Promise((j,L)=>{E.then(()=>{o++,ie.report("export-usdz-textures",{message:"Loaded progressive texture",currentStep:o,totalSteps:n.length}),j()}).catch(z=>L(z))}))}}ii&&Se("Progressive Loading: "+n.length),await Promise.all(n),ii&&Se("Progressive Loading: done"),ie.end("export-usdz-textures");const r=It.Global.Mask;It.Global.Set(wn.AR);const a=new V0,l=new fu(this.quickLookCompatible);let h;const d=[];this.interactive&&(d.push(new yg),d.push(new dr),globalThis.NEEDLE_USE_RAPIER&&S.getComponentsInChildren(e,Ne).length>0&&(this.physics?(h=new _g,d.push(h)):A()&&console.warn("USDZExporter: Physics export is disabled, but there are active Rigidbody components in the scene. They will not be exported.")),d.push(new vu),d.push(new Pg));const u=[l,...d,...this.extensions],p={self:this,exporter:a,extensions:u,object:e};ie.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,ie.report("export-usdz","auto export animations and audio sources");const m=new Array;this.autoExportAnimations&&m.push(..._M(e,l)),u.find(O=>O.extensionName==="Audio")&&this.autoExportAudioSources&&m.push(...bM(e)),a.debug=ii,a.pruneUnusedNodes=!xM;const b=Ko.instance.objs.map(O=>O.batchedMesh);a.keepObject=O=>{let M=!0;const E=S.getComponent(O,mi);return E&&!E.enabled&&(M=!1),M&&b.includes(O)&&(M=!1),M&&S.getComponentInParent(O,Pc)&&(M=!1),M&&S.getComponentInParent(O,In)&&(M=!1),ii&&!M&&console.log("USDZExporter: Discarding object",O),M},a.beforeWritingDocument=()=>{if(A()&&l&&h){const O=l.animatedRoots;for(const M of O){const E=S.getComponentsInChildren(M,Ne).filter(L=>L.enabled),j=S.getComponents(M,Kt).filter(L=>L.enabled&&!L.isTrigger);(E.length>0||j.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.",M)}}};const g=new Array;this.objectToExport&&this.quickLookCompatible&&this.interactive&&this.objectToExport.traverse(O=>{O.visible||g.push(O)});const v=u.find(O=>O.extensionName==="Behaviour");this.interactive&&v&&g.length>0&&v.addBehavior(vM(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"),ie.report("export-usdz","Invoking exporter.parse");const x=await a.parse(this.objectToExport,{ar:{anchoring:{type:this.anchoringType},planeAnchoring:{alignment:this.planeAnchoringAlignment}},extensions:u,quickLookCompatible:this.quickLookCompatible,maxTextureSize:this.maxTextureSize,exportInvisible:_}),T=new Blob([x],{type:"model/vnd.usdz+zip"});this.revertWebARSessionRoot(),this.context.time.timeScale=this._previousTimeScale,ie.report("export-usdz","Invoking after-export"),this.dispatchEvent(new CustomEvent("after-export",{detail:p}));for(const O of m)S.destroy(O);return It.Global.Set(r),ie.end("export-usdz"),T}openInQuickLook(e,t){const i=e instanceof Blob?URL.createObjectURL(e):e,n=this.buildQuicklookOverlay();ii&&console.log("QuickLook Overlay",n);const o=n.callToAction?encodeURIComponent(n.callToAction):"",r=n.checkoutTitle?encodeURIComponent(n.checkoutTitle):"",a=n.checkoutSubtitle?encodeURIComponent(n.checkoutSubtitle):"";this.link.href=i+`#callToAction=${o}&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){xl.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&&he("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&&Se("Quicklook url: "+n),n&&(En()?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),En()||(console.log("Custom Quicklook banner text requires pro license: https://needle.tools/pricing"),e.callToAction="Close",e.checkoutTitle="🌵 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 c.Matrix4().makeRotationY(Math.PI);static invertForwardQuaternion=new c.Quaternion().setFromEuler(new c.Euler(0,Math.PI,0));_rootSessionRootWasAppliedTo=null;_rootPositionBeforeExport=new c.Vector3;_rootRotationBeforeExport=new c.Quaternion;_rootScaleBeforeExport=new c.Vector3;getARScaleAndTarget(){if(!this.objectToExport)return{scale:1,_invertForward:!1,target:this.gameObject,sessionRoot:null};const e=S.findObjectOfType(bu);let t=S.getComponentInParent(this.objectToExport,hi);t||(t=S.getComponentInChildren(this.objectToExport,hi));let i=1,n=!1;const o=this.objectToExport;return e?i=e.arScale:t&&(i=t.arScale,n=t.invertForward),{scale:1/i,_invertForward:n,target:o,sessionRoot:t?.gameObject??null}}applyWebARSessionRoot(){if(!this.objectToExport)return;const{scale:e,_invertForward:t,target:i,sessionRoot:n}=this.getARScaleAndTarget(),o=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(xl.invertForwardQuaternion),i.updateMatrix(),i.updateMatrixWorld(!0),n&&o&&i.matrix.premultiply(o)}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 t=qs.getOrCreate().createQuicklookButton();return t.parentNode||this.context.menu.appendChild(t),t}};_t([f(c.Object3D)],Jt.prototype,"objectToExport");_t([f()],Jt.prototype,"autoExportAnimations");_t([f()],Jt.prototype,"autoExportAudioSources");_t([f()],Jt.prototype,"exportFileName");_t([f(URL)],Jt.prototype,"customUsdzFile");_t([f(pr)],Jt.prototype,"customBranding");_t([f()],Jt.prototype,"anchoringType");_t([f()],Jt.prototype,"maxTextureSize");_t([f()],Jt.prototype,"planeAnchoringAlignment");_t([f()],Jt.prototype,"interactive");_t([f()],Jt.prototype,"physics");_t([f()],Jt.prototype,"allowCreateQuicklookButton");_t([f()],Jt.prototype,"quickLookCompatible");let Tn=Jt;var SM=Object.defineProperty,CM=Object.getOwnPropertyDescriptor,Og=(s,e,t,i)=>{for(var n=CM(e,t),o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&SM(e,t,n),n};class Ta extends k{get fog(){return this._fog||(this._fog=new c.Fog(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)}}Og([f()],Ta.prototype,"near");Og([f()],Ta.prototype,"far");Og([f(c.Color)],Ta.prototype,"color");var PM=Object.defineProperty,Mg=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&PM(e,t,n),n};class mr extends k{objectBounds=!1;color;isGizmo=!0;_gizmoObject=null;_boxHelper=null;onEnable(){this.isGizmo&&!fc||(this._gizmoObject||(this.objectBounds?this._gizmoObject=new c.BoxHelper(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=ym(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),pe.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){for(;this._boxHelper;)this._boxHelper?.update(),yield}}Mg([f()],mr.prototype,"objectBounds");Mg([f(c.Color)],mr.prototype,"color");Mg([f()],mr.prototype,"isGizmo");var OM=Object.defineProperty,kg=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&OM(e,t,n),n};class Aa extends k{isGizmo=!1;color0;color1;gridHelper;size;divisions;offset;onEnable(){if(this.isGizmo&&!fc)return;const e=this.size,t=this.divisions;this.gridHelper||(this.gridHelper=new c.GridHelper(e,t,this.color0??new c.Color(.4,.4,.4),this.color1??new c.Color(.6,.6,.6)),this.offset!==void 0&&(this.gridHelper.position.y+=this.offset)),this.gridHelper&&this.gameObject.add(this.gridHelper)}onDisable(){this.gridHelper&&(this.gameObject.remove(this.gridHelper),this.gridHelper=null)}}kg([f()],Aa.prototype,"isGizmo");kg([f(c.Color)],Aa.prototype,"color0");kg([f(c.Color)],Aa.prototype,"color1");var MM=Object.defineProperty,Eg=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&MM(e,t,n),n};class Rg extends k{connectedBody;get rigidBody(){return this._rigidBody}_rigidBody=null;onEnable(){this._rigidBody||(this._rigidBody=this.gameObject.getComponent(Ne)),this.rigidBody&&this.connectedBody&&this.startCoroutine(this.create())}*create(){yield,this.rigidBody&&this.connectedBody&&this.activeAndEnabled&&this.createJoint(this.rigidBody,this.connectedBody)}}Eg([f(Ne)],Rg.prototype,"connectedBody");class Tg extends Rg{createJoint(e,t){this.context.physics.engine?.addFixedJoint(e,t)}}class jc extends Rg{anchor;axis;createJoint(e,t){this.axis&&this.anchor&&this.context.physics.engine?.addHingeJoint(e,t,this.anchor,this.axis)}}Eg([f(c.Vector3)],jc.prototype,"anchor");Eg([f(c.Vector3)],jc.prototype,"axis");var kM=Object.defineProperty,EM=Object.getOwnPropertyDescriptor,Un=(s,e,t,i)=>{for(var n=i>1?void 0:i?EM(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&kM(e,t,n),n};function Ff(s){return s*Math.PI/180}const D_=300,Rs=w("debuglights");class ei extends k{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 c.Color(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}Rs&&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 c.Color(this.color??16777215),Rs&&console.log(this.name,this)}onEnable(){Rs&&console.log("ENABLE LIGHT",this.name),this.createLight(),!this.isBaked&&(this.light&&(this.light.visible=!0,this.light.intensity=this._intensity,Rs&&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(),pe.LateUpdate))}onDisable(){Rs&&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=S.getComponentInParent(this.gameObject,hi)??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 c.DirectionalLight(this.color,this.intensity*Math.PI);if(t.position.set(0,0,-D_*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(t.target),Wo(t.target,0,0,0),this.light=t,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),Rs){const r=new c.DirectionalLightHelper(this.light,.2,this.color);this.context.scene.add(r)}break;case 0:const i=new c.SpotLight(this.color,this.intensity*Math.PI,this.range,Ff(this.spotAngle/2),1-Ff(this.innerSpotAngle/2)/Ff(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 o=new c.PointLight(this.color,this.intensity*Math.PI,this.range);this.light=o;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),Rs&&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=D_*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,Rs&&this.context.scene.add(new c.CameraHelper(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)}}Un([f()],ei.prototype,"type",2);Un([f(c.Color)],ei.prototype,"color",1);Un([f()],ei.prototype,"shadowNearPlane",1);Un([f()],ei.prototype,"shadowBias",1);Un([f()],ei.prototype,"shadowNormalBias",1);Un([f()],ei.prototype,"shadows",1);Un([f()],ei.prototype,"lightmapBakeType",2);Un([f()],ei.prototype,"intensity",1);Un([f()],ei.prototype,"shadowDistance",1);Un([f()],ei.prototype,"shadowResolution",1);new c.Vector3(0,0,0);var RM=Object.defineProperty,Bc=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&RM(e,t,n),n};const Uf=w("debuglods"),TM=w("nolods");class La{screenRelativeTransitionHeight;distance;renderers}Bc([f()],La.prototype,"screenRelativeTransitionHeight");Bc([f()],La.prototype,"distance");Bc([f(mi)],La.prototype,"renderers");class AM{model;get renderers(){return this.model.renderers}constructor(e){this.model=e}}class Fc extends k{fadeMode=0;localReferencePoint=void 0;lodCount=0;size=0;animateCrossFading=!1;lodModels;_lods=[];_settings=[];_lodsHandler;start(){if(Uf&&console.log("LODGROUP",this.name,this.lodModels,this),!TM&&!this._lodsHandler&&this.gameObject&&this.lodModels&&Array.isArray(this.lodModels)){const e=[];for(const i of this.lodModels){const n=new AM(i);this._lods.push(n);for(const o of n.renderers)e.includes(o)||e.push(o)}this._lodsHandler=new Array;for(let i=0;i<e.length;i++){const n=new c.LOD;this._lodsHandler.push(n),this.gameObject.add(n)}const t=new c.Object3D;t.name="Cull "+this.name;for(let i=0;i<e.length;i++){const n=e[i],o=this._lodsHandler[i],r=n.gameObject;Uf&&console.log(i,r.name);for(const a of this._lods){const l=a.model.distance;let h=null;if(a.renderers.includes(n)?h=r:h=t,h.type==="Group"){console.warn(`LODGroup ${this.name}: Group or MultiMaterial object's are not supported as LOD object: ${h.name}`);continue}Uf&&console.log("LEVEL",h.name,l),o.autoUpdate=!1,this.onAddLodLevel(o,h,a.model.distance)}}}}onAfterRender(){if(!this.gameObject||!this._lodsHandler)return;const e=this.context.mainCamera;if(e)for(const t of this._lodsHandler){t.update(e);const i=t.getCurrentLevel(),n=t.levels[i];t.layers.mask=n.object.layers.mask}}onAddLodLevel(e,t,i){if(t===this.gameObject){console.warn("LODGroup component must be on parent object and not mesh directly at the moment",t.name,t);return}e.addLevel(t,i*this._distanceFactor,.01);const n={lod:e,levelIndex:e.levels.length-1,distance:i};this._settings.push(n)}_distanceFactor=1;distanceFactor(e){if(e!==this._distanceFactor){this._distanceFactor=e;for(const t of this._settings){const i=t.lod.levels[t.levelIndex];i.distance=t.distance*e}}}}Bc([f(c.Vector3)],Fc.prototype,"localReferencePoint");Bc([f(La)],Fc.prototype,"lodModels");var LM=Object.defineProperty,lw=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&LM(e,t,n),n};const Lh=w("debugnestedgltf");class Uc extends k{filePath;loaded=new oe;loadAssetInParent=!0;_isLoadingOrDoneLoading=!1;listenToProgress(e){this.filePath?.beginListenDownload(e)}preload(){return this.filePath?.preload()||null}async start(){if(this._isLoadingOrDoneLoading)return;Lh&&console.log(this,this.guid);const e=this.gameObject.parent;if(e&&this.filePath){this._isLoadingOrDoneLoading=!0;const t=new on;t.idProvider=new mt(this.hash(this.guid)),t.parent=this.loadAssetInParent!==!1?e:this.gameObject,this.gameObject.updateMatrix();const i=this.gameObject.matrix;Lh&&console.log("Load nested:",this.filePath?.url??this.filePath,this.gameObject.position);const n=await this.filePath?.instantiate?.call(this.filePath,t);Lh&&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})),Lh&&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}}lw([f(Y)],Uc.prototype,"filePath");lw([f(oe)],Uc.prototype,"loaded");var DM=Object.defineProperty,Ag=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&DM(e,t,n),n};const IM=w("debugnet"),wu=class Ip extends k{url=null;urlParameterName=null;localhost=null;awake(){IM&&console.log(this),this.context.connection.registerProvider(this)}getWebsocketUrl(){let e=this.url?Ip.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){const o=w(this.urlParameterName);o&&typeof o=="string"&&(e=o)}if(!e)return null;const i=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(e);return i?.groups?i?.groups.socket_prefix?e:"wss://"+i?.groups.url:null}static GetUrl(e,t){let i=e;const n=Ip.IsLocalNetwork()&&t;if(n&&(i=t),e?.startsWith("/")){const o=n?i:window.location.origin;o?.endsWith("/")&&e.startsWith("/")&&(e=e.substring(1)),i=o+e}return i}static IsLocalNetwork(e=window.location.hostname){return Ii(e)}};Ag([f()],wu.prototype,"url");Ag([f()],wu.prototype,"urlParameterName");Ag([f()],wu.prototype,"localhost");let Lg=wu;var jM=Object.defineProperty,xu=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&jM(e,t,n),n};class gr extends k{referenceSpace;from;affectPosition=!1;affectRotation=!1;alignLookDirection=!1;levelLookDirection=!1;levelPosition=!1;positionOffset=new c.Vector3(0,0,0);rotationOffset=new c.Vector3(0,0,0);offset=new c.Vector3(0,0,0);update(){if(!this.from)return;var e=X(this.from),t=ue(this.from);this.offset.copy(this.positionOffset);const i=this.offset.length();if(this.referenceSpace&&this.offset.transformDirection(this.referenceSpace.matrixWorld).multiplyScalar(i),e.add(this.offset),this.levelPosition&&this.referenceSpace){const a=new c.Plane(this.gameObject.up,0),l=X(this.referenceSpace);a.setFromNormalAndCoplanarPoint(this.gameObject.up,l);const h=new c.Vector3(0,0,0);a.projectPoint(e,h),e.copy(h)}this.affectPosition&&ot(this.gameObject,e);const n=new c.Euler(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),o=new c.Quaternion().setFromEuler(n);this.affectRotation&&Ji(this.gameObject,t.multiply(o));const r=new c.Vector3;this.from.getWorldDirection(r).multiplyScalar(50),this.levelLookDirection&&(r.y=0),this.alignLookDirection&&this.gameObject.lookAt(r)}}xu([f(S)],gr.prototype,"referenceSpace");xu([f(S)],gr.prototype,"from");xu([f(c.Vector3)],gr.prototype,"positionOffset");xu([f(c.Vector3)],gr.prototype,"rotationOffset");var BM=Object.defineProperty,lo=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&BM(e,t,n),n};class Xt{time=0;value=0;inTangent=1/0;inWeight;outTangent=1/0;outWeight;weightedMode;constructor(e=0,t=0){this.time=e,this.value=t}}lo([f()],Xt.prototype,"time");lo([f()],Xt.prototype,"value");lo([f()],Xt.prototype,"inTangent");lo([f()],Xt.prototype,"inWeight");lo([f()],Xt.prototype,"outTangent");lo([f()],Xt.prototype,"outWeight");lo([f()],Xt.prototype,"weightedMode");const cw=class Sl{static linearFromTo(e,t,i){const n=new Sl,o=new Xt;o.time=0,o.value=e;const r=new Xt;return r.time=i,r.value=t,n.keys.push(o,r),n}static constant(e){const t=new Sl,i=new Xt;return i.time=0,i.value=e,t.keys.push(i),t}keys=[];clone(){const e=new Sl;return e.keys=this.keys?.map(t=>{const i=new Xt;return i.time=t.time,i.value=t.value,i.inTangent=t.inTangent,i.inWeight=t.inWeight,i.outTangent=t.outTangent,i.outWeight=t.outWeight,i.weightedMode=t.weightedMode,i})||[],e}get duration(){return!this.keys||this.keys.length==0?0:this.keys[this.keys.length-1].time}evaluate(e){if(!this.keys||this.keys.length==0)return 0;if(this.keys.length===1)return this.keys[0].value;if(this.keys[0].time>=e)return this.keys[0].value;for(let t=0;t<this.keys.length;t++){const i=this.keys[t];if(i.time<=e)if(t+1<this.keys.length){const o=this.keys[t+1];if(o.time<e)continue;return!isFinite(i.outTangent)||!isFinite(o.inTangent)?i.value:Sl.interpolateValue(e,i,o)}else return i.value}return this.keys[this.keys.length-1].value}static interpolateValue(e,t,i){const n=t.time,o=t.value,r=t.outTangent,a=i.time,l=i.value,h=i.inTangent,d=a-n,u=d*d,p=u*d,m=((r+h)*d-2*(l-o))/p,y=(3*(l-o)-(h+2*r)*d)/u,b=r,g=o,v=e-n,_=v*v,x=_*v;return m*x+y*_+b*v+g}};lo([f(Xt)],cw.prototype,"keys");let zc=cw;var FM=Object.defineProperty,C=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&FM(e,t,n),n};const Dh=w("debugparticles");var Zn=(s=>(s[s.Billboard=0]="Billboard",s[s.Stretch=1]="Stretch",s[s.HorizontalBillboard=2]="HorizontalBillboard",s[s.VerticalBillboard=3]="VerticalBillboard",s[s.Mesh=4]="Mesh",s))(Zn||{});class yr{alphaKeys=[];colorKeys=[];get duration(){return 1}evaluate(e,t){let i,n=0,o=null,r=0;for(let a=0;a<this.alphaKeys.length;a++){const l=this.alphaKeys[a];(l.time<e||!i)&&(i=l,n=a)}for(let a=0;a<this.colorKeys.length;a++){const l=this.colorKeys[a];(l.time<e||!o)&&(o=l,r=a)}if(o)if(r+1<this.colorKeys.length){const l=this.colorKeys[r+1],h=D.remap(e,o.time,l.time,0,1);t.r=D.lerp(o.color.r,l.color.r,h),t.g=D.lerp(o.color.g,l.color.g,h),t.b=D.lerp(o.color.b,l.color.b,h)}else t.r=o.color.r,t.g=o.color.g,t.b=o.color.b;if(i)if(n+1<this.alphaKeys.length){const l=this.alphaKeys[n+1],h=D.remap(e,i.time,l.time,0,1);t.alpha=D.lerp(i.alpha,l.alpha,h)}else t.alpha=i.alpha;return t}}C([f()],yr.prototype,"alphaKeys");C([f()],yr.prototype,"colorKeys");var tc=(s=>(s[s.Local=0]="Local",s[s.World=1]="World",s[s.Custom=2]="Custom",s))(tc||{}),Ld=(s=>(s[s.Sphere=0]="Sphere",s[s.SphereShell=1]="SphereShell",s[s.Hemisphere=2]="Hemisphere",s[s.HemisphereShell=3]="HemisphereShell",s[s.Cone=4]="Cone",s[s.Box=5]="Box",s[s.Mesh=6]="Mesh",s[s.ConeShell=7]="ConeShell",s[s.ConeVolume=8]="ConeVolume",s[s.ConeVolumeShell=9]="ConeVolumeShell",s[s.Circle=10]="Circle",s[s.CircleEdge=11]="CircleEdge",s[s.SingleSidedEdge=12]="SingleSidedEdge",s[s.MeshRenderer=13]="MeshRenderer",s[s.SkinnedMeshRenderer=14]="SkinnedMeshRenderer",s[s.BoxShell=15]="BoxShell",s[s.BoxEdge=16]="BoxEdge",s[s.Donut=17]="Donut",s[s.Rectangle=18]="Rectangle",s[s.Sprite=19]="Sprite",s[s.SpriteRenderer=20]="SpriteRenderer",s))(Ld||{});const ys=class Cl{static constant(e){const t=new Cl;return t.setConstant(e),t}static betweenTwoConstants(e,t){const i=new Cl;return i.setMinMaxConstant(e,t),i}static curve(e,t=1){const i=new Cl;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 Cl;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,o=e*this.curveMax.duration;return D.lerp(this.curveMin.evaluate(n),this.curveMax.evaluate(o),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}};C([f()],ys.prototype,"mode");C([f()],ys.prototype,"constant");C([f()],ys.prototype,"constantMin");C([f()],ys.prototype,"constantMax");C([f(zc)],ys.prototype,"curve");C([f(zc)],ys.prototype,"curveMin");C([f(zc)],ys.prototype,"curveMax");C([f()],ys.prototype,"curveMultiplier");let G=ys;const co=class ft{static constant(e){const t=new ft;return t.constant(e),t}static betweenTwoColors(e,t){const i=new ft;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 Z(0,0,0,1);static _temp2=new Z(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,ft._temp),ft._temp;case 2:case"TwoColors":return ft._temp.lerpColors(this.colorMin,this.colorMax,i);case 3:case"TwoGradients":return this.gradientMin.evaluate(e,ft._temp),this.gradientMax.evaluate(e,ft._temp2),ft._temp.lerp(ft._temp2,i);case 4:case"RandomColor":const o=Math.random();return this.gradientMin.evaluate(e,ft._temp),this.gradientMax.evaluate(e,ft._temp2),ft._temp.lerp(ft._temp2,o)}return ft._temp.set(16777215),ft._temp.alpha=1,ft._temp}};C([f()],co.prototype,"mode");C([f(Z)],co.prototype,"color");C([f(Z)],co.prototype,"colorMin");C([f(Z)],co.prototype,"colorMax");C([f(yr)],co.prototype,"gradient");C([f(yr)],co.prototype,"gradientMin");C([f(yr)],co.prototype,"gradientMax");let _r=co;var jp=(s=>(s[s.Hierarchy=0]="Hierarchy",s[s.Local=1]="Local",s[s.Shape=2]="Shape",s))(jp||{});class Ct{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}C([f(G)],Ct.prototype,"gravityModifier");C([f(_r)],Ct.prototype,"startColor");C([f(G)],Ct.prototype,"startDelay");C([f(G)],Ct.prototype,"startLifetime");C([f(G)],Ct.prototype,"startRotation");C([f(G)],Ct.prototype,"startRotationX");C([f(G)],Ct.prototype,"startRotationY");C([f(G)],Ct.prototype,"startRotationZ");C([f(G)],Ct.prototype,"startSize");C([f(G)],Ct.prototype,"startSizeX");C([f(G)],Ct.prototype,"startSizeY");C([f(G)],Ct.prototype,"startSizeZ");C([f(G)],Ct.prototype,"startSpeed");class Dd{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 _s{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}}C([f()],_s.prototype,"enabled");C([f()],_s.prototype,"bursts");C([f(G)],_s.prototype,"rateOverTime");C([f()],_s.prototype,"rateOverTimeMultiplier");C([f(G)],_s.prototype,"rateOverDistance");C([f()],_s.prototype,"rateOverDistanceMultiplier");class Su{enabled;color}C([f(_r)],Su.prototype,"color");class br{enabled;separateAxes;size;sizeMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;_time=0;_temp=new c.Vector3;evaluate(e,t,i){if(t||(t=this._temp),!this.enabled)return t.x=t.y=t.z=1,t;if(this.separateAxes)t.x=this.x.evaluate(e,i)*this.xMultiplier,t.y=this.y.evaluate(e,i)*this.yMultiplier,t.z=this.z.evaluate(e,i)*this.zMultiplier;else{const n=this.size.evaluate(e,i)*this.sizeMultiplier;t.x=n}return t}}C([f(G)],br.prototype,"size");C([f(G)],br.prototype,"x");C([f(G)],br.prototype,"y");C([f(G)],br.prototype,"z");const Ge=class Pl{get type(){return Ld[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 Pl}shapeType=5;enabled=!0;alignToDirection=!1;angle=0;arc=360;arcSpread;arcSpeedMultiplier;arcMode;boxThickness;position;rotation;_rotation=new c.Euler;scale;radius;radiusThickness;sphericalDirectionAmount;randomDirectionAmount;randomPositionAmount;meshShapeType;meshRenderer;_meshObj;_meshGeometry;setMesh(e){this.meshRenderer=e,e?(this._meshObj=e.sharedMeshes[Math.floor(Math.random()*e.sharedMeshes.length)],this._meshGeometry=this._meshObj.geometry):(this._meshObj=void 0,this._meshGeometry=void 0)}system;_space;_worldSpaceMatrix=new c.Matrix4;_worldSpaceMatrixInverse=new c.Matrix4;constructor(){Dh&&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 c.Vector3(0,0,0);_temp=new c.Vector3(0,0,0);_triangle=new c.Triangle;onInitialize(e){this._vector.set(0,0,0),e.mesh=void 0,e.mesh_geometry=void 0;const t=this._temp.copy(this.position),i=this._space===1;i&&t.applyQuaternion(this.system.worldQuaternion);let n=this.radius;if(i&&(n*=this.system.worldScale.x),this.enabled){switch(this.shapeType){case 5:Dh&&B.DrawWireBox(this.position,this.scale,14540253,1),this._vector.x=Math.random()*this.scale.x-this.scale.x/2,this._vector.y=Math.random()*this.scale.y-this.scale.y/2,this._vector.z=Math.random()*this.scale.z-this.scale.z/2,this._vector.add(t);break;case 4:this.randomConePoint(this.position,this.angle,n,this.radiusThickness,this.arc,this.arcMode,this._vector);break;case 0:this.randomSpherePoint(this.position,n,this.radiusThickness,this.arc,this._vector);break;case 10:this.randomCirclePoint(this.position,n,this.radiusThickness,this.arc,this._vector);break;case 13:const o=this.meshRenderer;o?.destroyed==!1&&this.setMesh(o);const r=e.mesh=this._meshObj,a=e.mesh_geometry=this._meshGeometry;if(r&&a)switch(this.meshShapeType){case 0:{const l=a.getAttribute("position"),h=Math.floor(Math.random()*l.count);this._vector.fromBufferAttribute(l,h),this._vector.applyMatrix4(r.matrixWorld),e.mesh_normal=h}break;case 1:break;case 2:{const l=a.index;if(l){let h=Math.random(),d=Math.random();h+d>1&&(h=1-h,d=1-d);const u=Math.floor(Math.random()*(l.count/3));let p=u*3,m=u*3+1,y=u*3+2;p=l.getX(p),m=l.getX(m),y=l.getX(y);const b=a.getAttribute("position");this._triangle.a.fromBufferAttribute(b,p),this._triangle.b.fromBufferAttribute(b,m),this._triangle.c.fromBufferAttribute(b,y),this._vector.set(0,0,0).addScaledVector(this._triangle.a,h).addScaledVector(this._triangle.b,d).addScaledVector(this._triangle.c,1-(h+d)),this._vector.applyMatrix4(r.matrixWorld),e.mesh_normal=u}}break}break;default:this._vector.set(0,0,0),A()&&!globalThis.__particlesystem_shapetype_unsupported&&(console.warn("ParticleSystem ShapeType is not supported:",Ld[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)),Dh&&B.DrawSphere(this._vector,.03,16711680,.5,!0)}_dir=new c.Vector3;getDirection(e,t){if(!this.enabled)return this._dir.set(0,0,1),this._dir;switch(this.shapeType){case 5:this._dir.set(0,0,1);break;case 4:this._dir.set(0,0,1);break;case 10:case 0:const i=t.x,n=t.y,o=t.z;this._dir.set(i,n,o),this.system?.worldspace?this._dir.sub(this.system.worldPos):this._dir.sub(this.position);break;case 13:const r=e.mesh,a=e.mesh_geometry;if(r&&a)switch(this.meshShapeType){case 0:{const l=a.getAttribute("normal"),h=e.mesh_normal;this._dir.fromBufferAttribute(l,h)}break;case 1:break;case 2:{const l=a.index;if(l){const h=e.mesh_normal,d=l.getX(h*3),u=l.getX(h*3+1),p=l.getX(h*3+2),m=a.getAttribute("position"),y=V(),b=V(),g=V();y.fromBufferAttribute(m,d),b.fromBufferAttribute(m,u),g.fromBufferAttribute(m,p),y.sub(b),g.sub(b),y.cross(g),this._dir.copy(y).multiplyScalar(-1);const v=ue(r);this._dir.applyQuaternion(v)}}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),Dh&&(B.DrawSphere(t,.01,8925952,.5,!0),B.DrawDirection(t,this._dir,8925952,.5,!0)),this._dir}static _randomQuat=new c.Quaternion;static _tempVec=new c.Vector3;randomizePosition(e,t){if(t<=0)return;const i=Pl._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=Pl._randomQuat,n=Pl._tempVec;n.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).normalize(),i.setFromAxisAngle(n,t*Math.random()*Math.PI),e.applyQuaternion(i)}spherizeDirection(e,t){if(t===0)return;const i=Math.random()*Math.PI*2,n=Math.acos(1-Math.random()*2),o=Math.sin(n)*Math.cos(i),r=Math.sin(n)*Math.sin(i),a=Math.cos(n),l=new c.Vector3(o,r,a);e.lerp(l,t)}randomSpherePoint(e,t,i,n,o){const r=Math.random(),a=Math.random(),l=2*Math.PI*r*(n/360),h=Math.acos(2*a-1),d=D.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,u=e.x+this.scale.x*(-d*Math.sin(h)*Math.cos(l)),p=e.y+this.scale.y*(d*Math.sin(h)*Math.sin(l)),m=e.z+this.scale.z*(d*Math.cos(h));o.x=u,o.y=p,o.z=m}randomCirclePoint(e,t,i,n,o){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,h=e.x+this.scale.x*l*Math.cos(a),d=e.y+this.scale.y*l*Math.sin(a),u=e.z;o.x=h,o.y=d,o.z=u}_loopTime=0;_loopDirection=1;randomConePoint(e,t,i,n,o,r,a){let l=0,h=0;switch(r){case 0:l=Math.random(),h=Math.random();break;case 2:this._loopTime>1&&(this._loopDirection=-1),this._loopTime<0&&(this._loopDirection=1);case 1:l=.5,h=Math.random(),this._loopTime+=this.system.deltaTime*this._loopDirection;break}let d=2*Math.PI*l*(o/360);switch(r){case 2:case 1:d+=Math.PI+.5,d+=this._loopTime*Math.PI*2,d%=D.toRadians(o);break}const u=Math.acos(2*h-1),p=D.lerp(1,1-Math.pow(1-Math.random(),Math.PI),n)*i,m=e.x+-p*Math.sin(u)*Math.cos(d),y=e.y+p*Math.sin(u)*Math.sin(d),b=e.z;a.x=m*this.scale.x,a.y=y*this.scale.y,a.z=b*this.scale.z}};C([f()],Ge.prototype,"shapeType");C([f()],Ge.prototype,"enabled");C([f()],Ge.prototype,"alignToDirection");C([f()],Ge.prototype,"angle");C([f()],Ge.prototype,"arc");C([f()],Ge.prototype,"arcSpread");C([f()],Ge.prototype,"arcSpeedMultiplier");C([f()],Ge.prototype,"arcMode");C([f(c.Vector3)],Ge.prototype,"boxThickness");C([f(c.Vector3)],Ge.prototype,"position");C([f(c.Vector3)],Ge.prototype,"rotation");C([f(c.Vector3)],Ge.prototype,"scale");C([f()],Ge.prototype,"radius");C([f()],Ge.prototype,"radiusThickness");C([f()],Ge.prototype,"sphericalDirectionAmount");C([f()],Ge.prototype,"randomDirectionAmount");C([f()],Ge.prototype,"randomPositionAmount");C([f()],Ge.prototype,"meshShapeType");C([f(Mc)],Ge.prototype,"meshRenderer");let Dg=Ge;class fe{damping;enabled;frequency;octaveCount;octaveMultiplier;octaveScale;positionAmount;quality;remap;remapEnabled;remapMultiplier;remapX;remapXMultiplier;remapY;remapYMultiplier;remapZ;remapZMultiplier;scrollSpeedMultiplier;separateAxes;strengthMultiplier;strengthX;strengthXMultiplier;strengthY;strengthYMultiplier;strengthZ;strengthZMultiplier;_noise;_time=0;update(e){this._time+=e.time.deltaTime*this.scrollSpeedMultiplier}_temp=new c.Vector3;apply(e,t,i,n,o,r){if(!this.enabled)return;this._noise||(this._noise=se.createNoise4D(()=>0));const a=this._temp.set(t.x,t.y,t.z).multiplyScalar(this.frequency),l=this._noise(a.x,a.y,a.z,this._time),h=this._noise(a.x,a.y,a.z,this._time+1e3*this.frequency),d=this._noise(a.x,a.y,a.z,this._time+2e3*this.frequency);this._temp.set(l,h,d).normalize();const u=o/r;let p=this.positionAmount.evaluate(u);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(u)*1.5),this._temp.multiplyScalar(p)),i.x+=this._temp.x,i.y+=this._temp.y,i.z+=this._temp.z}}C([f()],fe.prototype,"damping");C([f()],fe.prototype,"enabled");C([f()],fe.prototype,"frequency");C([f()],fe.prototype,"octaveCount");C([f()],fe.prototype,"octaveMultiplier");C([f()],fe.prototype,"octaveScale");C([f(G)],fe.prototype,"positionAmount");C([f()],fe.prototype,"quality");C([f(G)],fe.prototype,"remap");C([f()],fe.prototype,"remapEnabled");C([f()],fe.prototype,"remapMultiplier");C([f(G)],fe.prototype,"remapX");C([f()],fe.prototype,"remapXMultiplier");C([f(G)],fe.prototype,"remapY");C([f()],fe.prototype,"remapYMultiplier");C([f(G)],fe.prototype,"remapZ");C([f()],fe.prototype,"remapZMultiplier");C([f()],fe.prototype,"scrollSpeedMultiplier");C([f()],fe.prototype,"separateAxes");C([f()],fe.prototype,"strengthMultiplier");C([f(G)],fe.prototype,"strengthX");C([f()],fe.prototype,"strengthXMultiplier");C([f(G)],fe.prototype,"strengthY");C([f()],fe.prototype,"strengthYMultiplier");C([f(G)],fe.prototype,"strengthZ");C([f()],fe.prototype,"strengthZMultiplier");class Re{enabled;attachRibbonToTransform=!1;colorOverLifetime;colorOverTrail;dieWithParticles=!0;inheritParticleColor=!0;lifetime;lifetimeMultiplier;minVertexDistance=.2;mode=0;ratio=1;ribbonCount=1;shadowBias=0;sizeAffectsLifetime=!1;sizeAffectsWidth=!1;splitSubEmitterRibbons=!1;textureMode=0;widthOverTrail;widthOverTrailMultiplier;worldSpace=!1;getWidth(e,t,i,n){const o=this.widthOverTrail.evaluate(i,n);return e*=o,e}getColor(e,t,i){const n=this.colorOverTrail.evaluate(i),o=this.colorOverLifetime.evaluate(t);e.x*=n.r*o.r,e.y*=n.g*o.g,e.z*=n.b*o.b,"alpha"in n&&"alpha"in o&&(e.w*=n.alpha*o.alpha)}}C([f()],Re.prototype,"enabled");C([f()],Re.prototype,"attachRibbonToTransform");C([f(_r)],Re.prototype,"colorOverLifetime");C([f(_r)],Re.prototype,"colorOverTrail");C([f()],Re.prototype,"dieWithParticles");C([f()],Re.prototype,"inheritParticleColor");C([f(G)],Re.prototype,"lifetime");C([f()],Re.prototype,"lifetimeMultiplier");C([f()],Re.prototype,"minVertexDistance");C([f()],Re.prototype,"mode");C([f()],Re.prototype,"ratio");C([f()],Re.prototype,"ribbonCount");C([f()],Re.prototype,"shadowBias");C([f()],Re.prototype,"sizeAffectsLifetime");C([f()],Re.prototype,"sizeAffectsWidth");C([f()],Re.prototype,"splitSubEmitterRibbons");C([f()],Re.prototype,"textureMode");C([f(G)],Re.prototype,"widthOverTrail");C([f()],Re.prototype,"widthOverTrailMultiplier");C([f()],Re.prototype,"worldSpace");class Ae{enabled;space=0;orbitalX;orbitalY;orbitalZ;orbitalXMultiplier;orbitalYMultiplier;orbitalZMultiplier;orbitalOffsetX;orbitalOffsetY;orbitalOffsetZ;speedModifier;speedModifierMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;_system;update(e){this._system=e}_temp=new c.Vector3;_temp2=new c.Vector3;_temp3=new c.Vector3;_hasOrbital=!1;_index=0;_orbitalMatrix=new c.Matrix4;init(e){this._index==0&&(e.debug=!0),this._index+=1,e.orbitx=this.orbitalX.evaluate(Math.random()),e.orbity=this.orbitalY.evaluate(Math.random()),e.orbitz=this.orbitalZ.evaluate(Math.random()),this._hasOrbital=e.orbitx!=0||e.orbity!=0||e.orbitz!=0}apply(e,t,i,n,o,r,a){if(!this.enabled)return;const l=r/a,h=this.speedModifier.evaluate(l)*this.speedModifierMultiplier,d=this.x.evaluate(l),u=this.y.evaluate(l),p=this.z.evaluate(l);if(this._temp.set(-d,u,p),this._system&&this._system.main.simulationSpace===1&&this._temp.applyQuaternion(this._system.worldQuaternion),this._hasOrbital&&this._system?.worldPos){const y=this._temp2.set(i.x,i.y,i.z),b=this.orbitalXMultiplier,g=this.orbitalYMultiplier,v=this.orbitalZMultiplier,_=h*Math.PI*2*10,x=Math.cos(_*b),T=Math.sin(_*b),O=Math.cos(_*g),M=Math.sin(_*g),E=Math.cos(_*v),j=Math.sin(_*v),L=y.x*(O*E)+y.y*(O*j)+y.z*-M,z=y.x*(T*M*E-x*j)+y.y*(T*M*j+x*E)+y.z*(T*O),$=y.x*(x*M*E+T*j)+y.y*(x*M*j-T*E)+y.z*(x*O),R=this._temp3.set(y.x-L,y.y-z,y.z-$);R.normalize(),R.multiplyScalar(.2/o*Math.max(this.orbitalXMultiplier,this.orbitalYMultiplier,this.orbitalZMultiplier)),n.x+=R.x,n.y+=R.y,n.z+=R.z}n.x+=this._temp.x,n.y+=this._temp.y,n.z+=this._temp.z,n.x*=h,n.y*=h,n.z*=h}}C([f()],Ae.prototype,"enabled");C([f()],Ae.prototype,"space");C([f(G)],Ae.prototype,"orbitalX");C([f(G)],Ae.prototype,"orbitalY");C([f(G)],Ae.prototype,"orbitalZ");C([f()],Ae.prototype,"orbitalXMultiplier");C([f()],Ae.prototype,"orbitalYMultiplier");C([f()],Ae.prototype,"orbitalZMultiplier");C([f()],Ae.prototype,"orbitalOffsetX");C([f()],Ae.prototype,"orbitalOffsetY");C([f()],Ae.prototype,"orbitalOffsetZ");C([f(G)],Ae.prototype,"speedModifier");C([f()],Ae.prototype,"speedModifierMultiplier");C([f(G)],Ae.prototype,"x");C([f()],Ae.prototype,"xMultiplier");C([f(G)],Ae.prototype,"y");C([f()],Ae.prototype,"yMultiplier");C([f(G)],Ae.prototype,"z");C([f()],Ae.prototype,"zMultiplier");class Pt{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}}C([f()],Pt.prototype,"animation");C([f()],Pt.prototype,"enabled");C([f()],Pt.prototype,"cycleCount");C([f(G)],Pt.prototype,"frameOverTime");C([f()],Pt.prototype,"frameOverTimeMultiplier");C([f()],Pt.prototype,"numTilesX");C([f()],Pt.prototype,"numTilesY");C([f(G)],Pt.prototype,"startFrame");C([f()],Pt.prototype,"startFrameMultiplier");C([f()],Pt.prototype,"rowMode");C([f()],Pt.prototype,"rowIndex");C([f()],Pt.prototype,"spriteCount");C([f()],Pt.prototype,"timeMode");class an{enabled;separateAxes;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t){return this.enabled?this.separateAxes?0:this.z.evaluate(e,t)*-1:0}}C([f()],an.prototype,"enabled");C([f()],an.prototype,"separateAxes");C([f(G)],an.prototype,"x");C([f()],an.prototype,"xMultiplier");C([f(G)],an.prototype,"y");C([f()],an.prototype,"yMultiplier");C([f(G)],an.prototype,"z");C([f()],an.prototype,"zMultiplier");class Ni{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}}C([f()],Ni.prototype,"enabled");C([f()],Ni.prototype,"range");C([f()],Ni.prototype,"separateAxes");C([f(G)],Ni.prototype,"x");C([f()],Ni.prototype,"xMultiplier");C([f(G)],Ni.prototype,"y");C([f()],Ni.prototype,"yMultiplier");C([f(G)],Ni.prototype,"z");C([f()],Ni.prototype,"zMultiplier");class et{enabled;dampen;drag;dragMultiplier;limit;limitMultiplier;separateAxes;limitX;limitXMultiplier;limitY;limitYMultiplier;limitZ;limitZMultiplier;multiplyDragByParticleSize=!1;multiplyDragByParticleVelocity=!1;space;_temp=new c.Vector3;_temp2=new c.Vector3;apply(e,t,i,n,o,r,a){if(this.enabled){const l=this.limit.evaluate(o)*this.limitMultiplier;if(t.length()>l){this._temp.copy(t).normalize().multiplyScalar(l);const d=this.dampen*.5;t.x=D.lerp(t.x,this._temp.x,d),t.y=D.lerp(t.y,this._temp.y,d),t.z=D.lerp(t.z,this._temp.z,d),i.x=D.lerp(i.x,this._temp.x,d),i.y=D.lerp(i.y,this._temp.y,d),i.z=D.lerp(i.z,this._temp.z,d)}}}}C([f()],et.prototype,"enabled");C([f()],et.prototype,"dampen");C([f(G)],et.prototype,"drag");C([f()],et.prototype,"dragMultiplier");C([f(G)],et.prototype,"limit");C([f()],et.prototype,"limitMultiplier");C([f()],et.prototype,"separateAxes");C([f(G)],et.prototype,"limitX");C([f()],et.prototype,"limitXMultiplier");C([f(G)],et.prototype,"limitY");C([f()],et.prototype,"limitYMultiplier");C([f(G)],et.prototype,"limitZ");C([f()],et.prototype,"limitZMultiplier");C([f()],et.prototype,"multiplyDragByParticleSize");C([f()],et.prototype,"multiplyDragByParticleVelocity");C([f()],et.prototype,"space");const Nc=class hw{enabled;curve;curveMultiplier;mode;clone(){const e=new hw;return e.enabled=this.enabled,e.curve=this.curve?.clone(),e.curveMultiplier=this.curveMultiplier,e.mode=this.mode,e}system;get _lastWorldPosition(){return this.system._iv_lastWorldPosition||(this.system._iv_lastWorldPosition=new c.Vector3),this.system._iv_lastWorldPosition}get _velocity(){return this.system._iv_velocity||(this.system._iv_velocity=new c.Vector3),this.system._iv_velocity}_temp=new c.Vector3;_firstUpdate=!0;awake(e){this.system=e,this.reset()}reset(){this._firstUpdate=!0}update(e){this.enabled&&this.system.worldspace!==!1&&(this._firstUpdate?(this._firstUpdate=!1,this._velocity.set(0,0,0),this._lastWorldPosition.copy(this.system.worldPos)):this._lastWorldPosition&&(this._velocity.copy(this.system.worldPos).sub(this._lastWorldPosition).multiplyScalar(1/this.system.deltaTime),this._lastWorldPosition.copy(this.system.worldPos)))}applyInitial(e){if(this.enabled&&this.system.worldspace!==!1&&this.mode===0){const t=this.curve.evaluate(Math.random(),Math.random());this._temp.copy(this._velocity).multiplyScalar(t),e.x+=this._temp.x,e.y+=this._temp.y,e.z+=this._temp.z}}_frames=0;applyCurrent(e,t,i){if(this.enabled&&this.system&&this.system.worldspace!==!1&&this.mode===1){const n=this.curve.evaluate(t,i);this._temp.copy(this._velocity).multiplyScalar(n),e.x+=this._temp.x,e.y+=this._temp.y,e.z+=this._temp.z}}};C([f()],Nc.prototype,"enabled");C([f(G)],Nc.prototype,"curve");C([f()],Nc.prototype,"curveMultiplier");C([f()],Nc.prototype,"mode");let Ig=Nc;class ti{enabled;range;separateAxes;size;sizeMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t,i,n){const o=e.length(),r=D.remap(o,this.range.x,this.range.y,0,1),a=this.size.evaluate(r,i);return n.x*=a,n.y*=a,n.z*=a,n}}C([f()],ti.prototype,"enabled");C([f(c.Vector2)],ti.prototype,"range");C([f()],ti.prototype,"separateAxes");C([f(G)],ti.prototype,"size");C([f()],ti.prototype,"sizeMultiplier");C([f(G)],ti.prototype,"x");C([f()],ti.prototype,"xMultiplier");C([f(G)],ti.prototype,"y");C([f()],ti.prototype,"yMultiplier");C([f(G)],ti.prototype,"z");C([f()],ti.prototype,"zMultiplier");class Da{enabled;range;color;evaluate(e,t,i){const n=e.length(),o=D.remap(n,this.range.x,this.range.y,0,1),r=this.color.evaluate(o,t);i.x*=r.r,i.y*=r.g,i.z*=r.b,"alpha"in r&&(i.w*=r.alpha)}}C([f()],Da.prototype,"enabled");C([f(c.Vector2)],Da.prototype,"range");C([f(_r)],Da.prototype,"color");new c.Vector3(1,1,1);new c.Vector3(0,0,1);class jg{constructor(e,t,i,n){this.system=e,this.particleSystem=t,this.subSystem=i,this.subParticleSystem=n,this.subParticleSystem&&this.subParticleSystem&&(this.subParticleSystem.onlyUsedByOther=!0);const o=1e3;this._circularBuffer=new di(()=>new se.Matrix4,o)}type="NeedleParticleSubEmitter";emitterType;emitterProbability;q_=new c.Quaternion;v_=new c.Vector3;v2_=new c.Vector3;_emitterMatrix=new se.Matrix4;_circularBuffer;clone(){throw new Error("Method not implemented.")}initialize(e){e.emissionState={burstIndex:0,burstWaveIndex:0,time:0,waitEmiting:0},this._emitterMatrix.copy(this.subSystem.matrixWorld).invert().premultiply(this.system.matrixWorld),this._emitterMatrix.setPosition(0,0,0),this.emitterType===Bp.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===Bp.Death){let n=e.life;if(e[Kr]!==void 0&&(n=e[Kr]),!(e.age+t*1.2>=n))return;const r=this.subSystem.main.maxParticles-this.subSystem.currentParticles;e.emissionState.waitEmiting=r}const i=new se.Matrix4;i.set(1,0,0,e.position.x,0,1,0,e.position.y,0,0,1,e.position.z,0,0,0,1),this.particleSystem.worldSpace||i.multiplyMatrices(this._emitterMatrix,i),this.subParticleSystem.emit(t,e.emissionState,i)}}var UM=Object.defineProperty,Te=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&UM(e,t,n),n};const Fs=w("debugparticles"),zM=w("noprogressive"),NM=w("debugprogressive");var Bp=(s=>(s[s.Birth=0]="Birth",s[s.Collision=1]="Collision",s[s.Death=2]="Death",s[s.Trigger=3]="Trigger",s[s.Manual=4]="Manual",s))(Bp||{});class Vi extends k{renderMode;particleMaterial;trailMaterial;particleMesh;maxParticleSize;minParticleSize;velocityScale;cameraVelocityScale;lengthScale;start(){if(this.maxParticleSize!==.5&&this.minParticleSize!==0&&A()){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"){Fs&&console.debug("ParticleSystemRenderer.getMaterial: MeshStandardMaterial detected, converting to MeshBasicMaterial. See https://github.com/Alchemist0823/three.quarks/issues/101"),"map"in t&&t.map&&(t.map.colorSpace=c.LinearSRGBColorSpace,t.map.premultiplyAlpha=!1);const i=new c.MeshBasicMaterial;i.copy(t),e?this.trailMaterial=i:this.particleMaterial=i}t.map&&(t.map.colorSpace=c.LinearSRGBColorSpace,t.map.premultiplyAlpha=!1),e&&t.side===c.FrontSide&&(t=t.clone(),t.side=c.BackSide,e?this.trailMaterial=t:this.particleMaterial=t)}return t&&!zM&&t._didRequestTextureLOD===void 0&&(t._didRequestTextureLOD=0,NM&&console.log("Load material LOD",t.name),ne.NEEDLE_progressive.assignTextureLOD(t,0)),t}getMesh(e){let t=null;if(!t&&(this.particleMesh instanceof c.Mesh&&(t=this.particleMesh.geometry),t===null)){t=new c.PlaneGeometry(1,1);const n=t.attributes.uv;for(let o=0;o<n.count;o++)n.setX(o,1-n.getX(o))}return new c.Mesh(t,this.getMaterial())}}Te([f()],Vi.prototype,"renderMode");Te([f(c.Material)],Vi.prototype,"particleMaterial");Te([f(c.Material)],Vi.prototype,"trailMaterial");Te([f()],Vi.prototype,"maxParticleSize");Te([f()],Vi.prototype,"minParticleSize");Te([f()],Vi.prototype,"velocityScale");Te([f()],Vi.prototype,"cameraVelocityScale");Te([f()],Vi.prototype,"lengthScale");class Ih{_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 Bg{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 VM extends Bg{genValue(){return this.system.textureSheetAnimation.getStartIndex()}}class $M extends Bg{_lastPosition=new c.Vector3;_lastDistance=0;update(){const e=X(this.system.gameObject);this._lastDistance=this._lastPosition.distanceTo(e),this._lastPosition.copy(e)}genValue(){if(!this.system.isPlaying||!this.system.emission.enabled||this.system.currentParticles>=this.system.maxParticles)return 0;let e=this.system.emission.rateOverTime.evaluate(this.system.time/this.system.duration,Math.random());if(this.system.deltaTime>0){const n=this.system.emission.rateOverDistance.evaluate(this.system.time/this.system.duration,Math.random());let r=this._lastDistance/this.system.deltaTime*n;Number.isFinite(r)||(r=0),e+=r}const t=this.system.emission.getBurst();t>0&&(e+=t/this.system.deltaTime);const i=this.system.maxParticles-this.system.currentParticles;return D.clamp(e,0,i/this.system.deltaTime)}}class WM extends Bg{genValue(){return this.system.isPlaying,0}}class ho{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 GM extends ho{type="NeedleTextureSheet";update(e,t){const i=this.system.textureSheetAnimation;if(i.enabled){const n=e.age/e.life,o=i.evaluate(n);o!==void 0&&(e.uvTile=o)}}}const I_=Symbol("particleRotation");class HM extends ho{type="NeedleRotation";initialize(e){e[I_]=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[I_])*t:this.system.renderer.renderMode===Zn.Billboard&&(e.rotation=Math.PI),this.system.rotationBySpeed.enabled)){const n=e.velocity.length();e.rotation+=this.system.rotationBySpeed.evaluate(i,n)*t}}}const j_=Symbol("sizeLerpFactor"),qM=new c.Vector3;class XM extends ho{type="NeedleSize";_minSize=0;_maxSize=1;initialize(e){e[j_]=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[j_]).x);let o=1;this.system.renderer.renderMode!==Zn.Mesh&&(o=this.system.worldScale.x/this.system.cameraScale);const r=V(e.startSize).multiplyScalar(n*o);if(e.size.set(r.x,r.y,r.z),this.system.localspace){const a=dw(this.system,qM);e.size.x*=a.x,e.size.y*=a.y,e.size.z*=a.z}}}const Kr=Symbol("particleLife"),zf=Symbol("trailLifetime"),B_=Symbol("trailStartLength"),Nf=Symbol("trailWidthRandom");class QM extends ho{type="NeedleTrail";initialize(e){e instanceof se.TrailParticle&&(e[Kr]=e.life,this.system.trails.enabled&&this.system.trails.dieWithParticles===!1&&(e[zf]=this.system.trails.lifetime.evaluate(Math.random(),Math.random()),e.life+=e[zf]),e[B_]=e.length,e[Nf]=Math.random())}update(e){if(this.system.trails?.enabled&&e instanceof se.TrailParticle){const t=e,i=e.age/e[Kr],n=e.previous.values(),o=e.previous.length;for(let r=0;r<o;r++){const l=n.next().value,h=1-r/(o-1),d=e.size;if(d.x<=0&&!this.system.trails.sizeAffectsWidth){const u=20*this.system.trails.widthOverTrail.evaluate(.5,t[Nf]);d.x=u,d.y=u,d.z=u}l.size=this.system.trails.getWidth(d.x,i,h,t[Nf]),l.color.copy(e.color),this.system.trails.getColor(l.color,i,h)}if(e.age>e[Kr]){e.velocity.set(0,0,0);const r=(e.age-e[Kr])/e[zf];t.length=D.lerp(e[B_],0,r)}}}}const jh=Symbol("startVelocity"),F_=Symbol("gravityModifier"),Vf=Symbol("gravitySpeed"),Bh=Symbol("velocity lerp factor"),Fp=new c.Vector3;class YM extends ho{type="NeedleVelocity";_gravityDirection=new c.Vector3;initialize(e){const t=this.system.main.simulationSpeed;e.startSpeed=this.system.main.startSpeed.evaluate(Math.random(),Math.random());const i=this.system.shape.getDirection(e,e.position);e.velocity.x=i.x*e.startSpeed,e.velocity.y=i.y*e.startSpeed,e.velocity.z=i.z*e.startSpeed,this.system.inheritVelocity?.enabled&&this.system.inheritVelocity.applyInitial(e.velocity),e[jh]?e[jh].copy(e.velocity):e[jh]=e.velocity.clone();const n=this.system.main.gravityModifier.evaluate(Math.random(),Math.random());e[F_]=n*t,e[Vf]=n*t*.5,e[Bh]=Math.random(),this.system.velocityOverLifetime?.init(e),this._gravityDirection.set(0,-1,0),this.system.main.simulationSpace===tc.Local&&this._gravityDirection.applyQuaternion(this.system.worldQuaternionInverted).normalize()}update(e,t){const i=e[jh],n=e[F_];if(n!==0){const u=n*e[Vf];Fp.copy(this._gravityDirection).multiplyScalar(u),e[Vf]+=t*.05,i.add(Fp)}e.velocity.copy(i);const o=e.age/e.life;this.system.inheritVelocity?.enabled&&this.system.inheritVelocity.applyCurrent(e.velocity,o,e[Bh]);const r=this.system.noise;r.enabled&&r.apply(0,e.position,e.velocity,t,e.age,e.life);const a=this.system.sizeBySpeed;a?.enabled&&(e.size=a.evaluate(e.velocity,o,e[Bh],e.size));const l=this.system.colorBySpeed;l?.enabled&&l.evaluate(e.velocity,e[Bh],e.color);const h=this.system.velocityOverLifetime;h.enabled&&h.apply(e,0,e.position,e.velocity,t,e.age,e.life);const d=this.system.limitVelocityOverLifetime;if(d.enabled&&d.apply(e.position,i,e.velocity,e.size,o,t,1),this.system.worldspace){const u=this.system.worldScale;e.velocity.x*=u.x,e.velocity.y*=u.y,e.velocity.z*=u.z}}}const U_=Symbol("colorLerpFactor"),z_=new Z(1,1,1,1),vo=new Z(1,1,1,1);class KM extends ho{type="NeedleColor";initialize(e){}_init(e){const t=this.system.renderer.particleMaterial;vo.copy(this.system.main.startColor.evaluate(Math.random())),t?.color&&(z_.copy(t.color),vo.multiply(z_)),vo.convertLinearToSRGB(),e.startColor.set(vo.r,vo.g,vo.b,vo.alpha),e.color.copy(e.startColor),e[U_]=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[U_]);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 ZM{system;emission;get anim(){return this.system.textureSheetAnimation}constructor(e){this.system=e,this.emission=new $M(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 Ih(this.system.main.startLifetime)}get startSpeed(){return new Ih(this.system.main.startSpeed)}get startRotation(){return new Ih(this.system.main.startRotation)}get startSize(){return new Ih(this.system.main.startSize)}startLength;get startColor(){return new se.ConstantColor(new se.Vector4(1,1,1,1))}get emissionOverTime(){return this.emission}get emissionOverDistance(){return new WM(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 se.RenderMode.Trail;switch(this.system.renderer.renderMode){case Zn.Billboard:return se.RenderMode.BillBoard;case Zn.Stretch:return se.RenderMode.StretchedBillBoard;case Zn.HorizontalBillboard:return se.RenderMode.HorizontalBillBoard;case Zn.VerticalBillboard:return se.RenderMode.VerticalBillBoard;case Zn.Mesh:return se.RenderMode.Mesh}return se.RenderMode.BillBoard}rendererEmitterSettings={startLength:new se.ConstantValue(220),followLocalOrigin:!1};get speedFactor(){let e=this.system.main.simulationSpeed;return this.system.renderer?.renderMode===Zn.Stretch&&(e*=this.system.renderer.velocityScale??1),e}flatWhiteTexture;clonedTexture={original:void 0,clone:void 0};get texture(){const e=this.material;if(e&&e.map){const t=e.map;if(this.clonedTexture.original!==t||!this.clonedTexture.clone){const i=t.clone();i.premultiplyAlpha=!1,i.colorSpace=c.LinearSRGBColorSpace,this.clonedTexture.original=t,this.clonedTexture.clone=i}return this.clonedTexture.clone}return this.flatWhiteTexture||(this.flatWhiteTexture=Em(new Z(1,1,1,1),1)),this.flatWhiteTexture}get startTileIndex(){return new VM(this.system)}get uTileCount(){return this.anim.enabled?this.anim?.numTilesX:void 0}get vTileCount(){return this.anim.enabled?this.anim?.numTilesY:void 0}get renderOrder(){return 1}get blending(){return this.system.renderer.particleMaterial?.blending??c.NormalBlending}get transparent(){return this.system.renderer.transparent}get worldSpace(){return this.system.main.simulationSpace===tc.World}}class JM{burstParticleIndex=0;burstParticleCount=0;isBursting=!1;travelDistance=0;previousWorldPos;burstIndex=0;burstWaveIndex=0;time=0;waitEmiting=0}const Ot=class sd extends k{play(e=!1){e&&S.foreachComponent(this.gameObject,t=>{t instanceof sd&&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&&S.foreachComponent(this.gameObject,t=>{t instanceof sd&&t!==this&&t.pause(!1)},!0),this._isPlaying=!1}stop(e=!0,t=!1){e&&S.foreachComponent(this.gameObject,i=>{i instanceof sd&&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 JM),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===tc.World}get localspace(){return this.main.simulationSpace===tc.Local}__worldQuaternion=new c.Quaternion;get worldQuaternion(){return this.__worldQuaternion}_worldQuaternionInverted=new c.Quaternion;get worldQuaternionInverted(){return this._worldQuaternionInverted}_worldScale=new c.Vector3;get worldScale(){return this._worldScale}_worldPositionFrame=-1;_worldPos=new c.Vector3;get worldPos(){return this._worldPositionFrame!==this.context.time.frame&&(this._worldPositionFrame=this.context.time.frame,X(this.gameObject,this._worldPos)),this._worldPos}get matrixWorld(){return this._container.matrixWorld}get isSubsystem(){return this._isUsedAsSubsystem}addBehaviour(e){return this._particleSystem?(e instanceof ho&&(e.system=this),Fs&&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&&((A()||Fs)&&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 Dd)){const n=new Dd;ua(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 Id)){const n=new Id;ua(n,i),e[t]=n}}Fs&&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(Vi),!this.main)throw new Error("Not Supported: ParticleSystem needs a serialized MainModule. Creating new particle systems at runtime is currently not supported.");this._container=new c.Object3D,this._container.matrixAutoUpdate=!1,this.context.scene.add(this._container),this._batchSystem=new se.BatchedParticleRenderer,this._batchSystem.name=this.gameObject.name,this._container.add(this._batchSystem),this._interface=new ZM(this),this._particleSystem=new se.ParticleSystem(this._interface),this._particleSystem.addBehavior(new XM(this)),this._particleSystem.addBehavior(new KM(this)),this._particleSystem.addBehavior(new GM(this)),this._particleSystem.addBehavior(new HM(this)),this._particleSystem.addBehavior(new YM(this)),this._particleSystem.addBehavior(new QM(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),Fs&&(console.log(this),this.gameObject.add(new c.AxesHelper(1)))}start(){this.addSubParticleSystems(),this.updateLayers(),this.renderer.particleMesh instanceof c.Mesh&&this._interface.renderMode==se.RenderMode.Mesh&&ne.NEEDLE_progressive.assignMeshLOD(this.renderer.particleMesh,0).then(e=>{e&&this.particleSystem&&this._interface.renderMode==se.RenderMode.Mesh&&(this.particleSystem.instancingGeometry=e)})}onDestroy(){this._container?.removeFromParent(),this._batchSystem?.removeFromParent(),this._particleSystem?.emitter.removeFromParent(),this._particleSystem?.dispose()}onEnable(){this.main&&(this.inheritVelocity&&(this.inheritVelocity.system=this),this._batchSystem&&(this._batchSystem.visible=!0),this.playOnAwake&&this.play(),this._isPlaying=this.playOnAwake)}onDisable(){this._batchSystem&&(this._batchSystem.visible=!1)}onBeforeRender(){this.main&&(this._didPreWarm===!1&&this.main?.prewarm===!0&&(this._didPreWarm=!0,this.preWarm()),this.onUpdate(),this.onSimulate(this.deltaTime))}preWarm(){if(!this.emission?.enabled||this.emission.rateOverTime.getMax()<=0)return;const t=1/60,i=this.main.duration,n=this.main.startLifetime.getMax(),r=Math.min(Math.max(i,n)/Math.max(.01,this.main.simulationSpeed),1e3),a=Math.ceil(r/t),l=Date.now();Fs&&console.log(`Particles ${this.name} - Prewarm for ${a} frames (${r} sec). Duration: ${i}, Lifetime: ${n}`);for(let h=0;h<a&&!(this.currentParticles>=this.maxParticles);h++){const d=Date.now()-l;if(d>2e3){console.warn(`Particles ${this.name} - Prewarm took too long. Aborting: ${d}`);break}this.onUpdate(),this.onSimulate(t)}}_lastBatchesCount=-1;onSimulate(e){if(this._batchSystem){let t=this.context.time.frameCount%60===0;this._lastBatchesCount!==this._batchSystem.batches.length&&(this._lastBatchesCount=this._batchSystem.batches.length,t=!0),t&&this.updateLayers(),this._batchSystem.update(e)}this._time+=e,this._time>this.duration&&(this._time=0)}updateLayers(){if(this._batchSystem)for(let e=0;e<this._batchSystem.batches.length;e++){const t=this._batchSystem.batches[e];t.layers.disableAll();const i=this.layer;t.layers.mask=1<<i}}onUpdate(){if(this._bursts&&(this.emission.bursts=this._bursts,delete this._bursts),!this._isPlaying)return;const e=this.context.mainCamera;if(e){const n=Ie(e);this._cameraScale=n.x}const t=!this.worldspace,i=this.gameObject;if(ue(i,this.__worldQuaternion),this._worldQuaternionInverted.copy(this.__worldQuaternion).invert(),Ie(this.gameObject,this._worldScale),t&&this._container&&this.gameObject?.parent){const n=dw(this,Fp);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():A()&&console.warn("SubParticleSystem serialization issue(?)",e.particleSystem,e));const t=e.particleSystem?._particleSystem;if(t){e.particleSystem._isUsedAsSubsystem=!0;const i=new jg(this,this._particleSystem,e.particleSystem,t);i.emitterType=e.type,i.emitterProbability=e.emitProbability,this._particleSystem.addBehavior(i)}else Fs&&console.warn("Could not add SubParticleSystem",e,this)}}};Te([f(Su)],Ot.prototype,"colorOverLifetime");Te([f(Ct)],Ot.prototype,"main");Te([f(_s)],Ot.prototype,"emission");Te([f(br)],Ot.prototype,"sizeOverLifetime");Te([f(Dg)],Ot.prototype,"shape");Te([f(fe)],Ot.prototype,"noise");Te([f(Re)],Ot.prototype,"trails");Te([f(Ae)],Ot.prototype,"velocityOverLifetime");Te([f(et)],Ot.prototype,"limitVelocityOverLifetime");Te([f(Ig)],Ot.prototype,"inheritVelocity");Te([f(Da)],Ot.prototype,"colorBySpeed");Te([f(Pt)],Ot.prototype,"textureSheetAnimation");Te([f(an)],Ot.prototype,"rotationOverLifetime");Te([f(Ni)],Ot.prototype,"rotationBySpeed");Te([f(ti)],Ot.prototype,"sizeBySpeed");let ic=Ot;class Id{particleSystem;emitProbability=1;properties;type;_deserialize(e,t){const i=this.particleSystem;if(i instanceof ic)return;let n="";i&&typeof i.guid=="string"&&(n=i.guid,this.particleSystem=S.findByGuid(n,t)),Fs&&!(this.particleSystem instanceof ic)&&console.warn("Could not find particle system for sub emitter",n,t,this)}}function dw(s,e){if(e.set(1,1,1),s.gameObject.parent&&s.localspace)switch(s.main.scalingMode){case jp.Local:e=Ie(s.gameObject.parent,e),e.x=1/e.x,e.y=1/e.y,e.z=1/e.z;break;default:if(!s.unsupported_scaling_mode){s.unsupported_scaling_mode=!0;const t="ParticleSystem scale mode "+jp[s.main.scalingMode]+" is not supported";A()&&he(t),console.warn(t,s.name,s)}e=Ie(s.gameObject,e);break}return e}var ek=Object.defineProperty,Fg=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&ek(e,t,n),n};class Ia extends k{strength=1;radius=2;targets=[];update(){const e=this.gameObject.worldPosition,t=-this.strength*this.context.time.deltaTime;this.targets?.forEach(i=>{if(!i)return;const n=i.gameObject.worldPosition.sub(e),o=n.length();if(o>this.radius)return;let r=t;o>1?r/=o*o:r/=Math.max(.05,o),i.applyImpulse(n.multiplyScalar(r))})}}Fg([f()],Ia.prototype,"strength");Fg([f()],Ia.prototype,"radius");Fg([f(Ne)],Ia.prototype,"targets");class _a extends k{_didAssignPlayerColor=!1;onEnable(){this.context.connection.beginListen(Q.JoinedRoom,this.tryAssignColor),this._didAssignPlayerColor||this.startCoroutine(this.waitForConnection())}onDisable(){this.context.connection.stopListen(Q.JoinedRoom,this.tryAssignColor)}*waitForConnection(){for(;!this.destroyed&&this.activeAndEnabled&&(yield km(.2),!this.tryAssignColor()););}tryAssignColor=()=>{const e=S.getComponentInParent(this.gameObject,Yi);if(e&&e.owner)return this._didAssignPlayerColor=!0,this.assignUserColor(e.owner),!0;const t=S.getComponentInParent(this.gameObject,xe);return t?.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(t.connectionId),!0):!1};assignUserColor(e){const t=_a.hashCode(e),i=_a.colorFromHashCode(t);if(this.gameObject.type==="Mesh"){const n=this.gameObject;this.assignColor(i,e,n)}else if(this.gameObject.children)for(const n of this.gameObject.children){const o=n;o.material&&o.material.color&&this.assignColor(i,e,o)}}assignColor(e,t,i){let n=i.material;n&&(n._playerMaterial!==t&&(n=n.clone(),n._playerMaterial=t,i.material=n),n.color=e)}static hashCode(e){var t=0,i,n;if(e.length===0)return t;for(i=0;i<e.length;i++)n=e.charCodeAt(i),t=(t<<5)-t+n,t|=0;return t}static colorFromHashCode(e){const t=(e&16711680)>>16,i=(e&65280)>>8,n=e&255;return new c.Color(t/255,i/255,n/255)}}const Ol=w("debugpost");let Up=null;function tk(s){Up=s}function uw(s){let e=s.gameObject;for(;e;){for(const t of Kd(e))if(t.isPostProcessingManager===!0)return t;e=e.parent}return null}function ik(s){let e=uw(s);if(!e)if(Up){Ol&&console.warn("Adding postprocessing manager to the scene.");const t=s.scene;e=Zi(t,Up)}else A()&&console.warn("No post processing manager found");return e}const Ke={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 Be=null;function nk(s){Ol==="verbose"&&console.debug("Before ordering effects",[...s]),Be||(Be=new Map,Be.set(exports.MODULES.POSTPROCESSING.MODULE.NormalPass,Ke.NormalPass),Be.set(exports.MODULES.POSTPROCESSING.MODULE.DepthDownsamplingPass,Ke.DepthDownsamplingPass),Be.set(exports.MODULES.POSTPROCESSING.MODULE.SMAAEffect,Ke.SMAA),Be.set(exports.MODULES.POSTPROCESSING.MODULE.SSAOEffect,Ke.SSAO),Be.set(exports.MODULES.POSTPROCESSING_AO.MODULE.N8AOPostPass,Ke.SSAO),Be.set(exports.MODULES.POSTPROCESSING_AO.MODULE.N8AOPass,Ke.SSAO),Be.set(exports.MODULES.POSTPROCESSING.MODULE.TiltShiftEffect,Ke.TiltShift),Be.set(exports.MODULES.POSTPROCESSING.MODULE.DepthOfFieldEffect,Ke.DepthOfField),Be.set(exports.MODULES.POSTPROCESSING.MODULE.ChromaticAberrationEffect,Ke.ChromaticAberration),Be.set(exports.MODULES.POSTPROCESSING.MODULE.BloomEffect,Ke.Bloom),Be.set(exports.MODULES.POSTPROCESSING.MODULE.SelectiveBloomEffect,Ke.Bloom),Be.set(exports.MODULES.POSTPROCESSING.MODULE.VignetteEffect,Ke.Vignette),Be.set(exports.MODULES.POSTPROCESSING.MODULE.PixelationEffect,Ke.Pixelation),Be.set(exports.MODULES.POSTPROCESSING.MODULE.ToneMappingEffect,Ke.ToneMapping),Be.set(exports.MODULES.POSTPROCESSING.MODULE.HueSaturationEffect,Ke.HueSaturation),Be.set(exports.MODULES.POSTPROCESSING.MODULE.BrightnessContrastEffect,Ke.BrightnessContrast)),s.sort((e,t)=>{const i=typeof e.priority=="number"?e.priority:Be.get(e.effect.constructor)??Number.NEGATIVE_INFINITY,n=typeof t.priority=="number"?t.priority:Be.get(t.effect.constructor)??Number.NEGATIVE_INFINITY;return i===Number.NEGATIVE_INFINITY?(Ol&&console.warn("Unknown effect found: ",e.constructor.name,e),1):n===Number.NEGATIVE_INFINITY?(Ol&&console.warn("Unknown effect found: ",t.constructor.name,t),-1):i-n}),Ol==="verbose"&&console.debug("After ordering effects",[...s])}var sk=Object.defineProperty,ok=Object.getOwnPropertyDescriptor,fw=(s,e,t,i)=>{for(var n=ok(e,t),o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&sk(e,t,n),n};const rk=w("debugpost");class I{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;rk&&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}}fw([f()],I.prototype,"overrideState");fw([f()],I.prototype,"value");class ak extends Ui{constructor(){super([I])}onSerialize(e,t){}onDeserialize(e,t){const i=t.target,n=t.path;let o;if(i&&n&&(o=i[n]),(typeof o!="object"||typeof o=="object"&&o.isVolumeParameter!==!0)&&(o=new I),typeof e=="object"&&"value"in e){const r=e.value;o.initialize(r),o.overrideState=e.overrideState}else o.value=e;return o}}new ak;var lk=Object.defineProperty,ck=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&lk(e,t,n),n};const $f=w("debugpost");class Ve extends k{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 I?n.initialize(i):n!==void 0&&(this[t]=i)}}active=!0;_manager=null;onEnable(){super.onEnable(),$f&&console.warn("Enable",this.constructor.name+(this.__internalDidAwakeAndStart?"":" (awake)")),this.__internalDidAwakeAndStart&&(this.active=!0),this.onEffectEnabled()}onDisable(){super.onDisable(),$f&&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=ik(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(){$f&&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 I&&i.__init()}}onEditorModification(e){const t=e.propertyName;if(this[t]instanceof I){const i=e.value;return this[t].value=i,!0}}}ck([f()],Ve.prototype,"active");var hk=Object.defineProperty,dk=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&hk(e,t,n),n};const uk=w("debugpost"),zp={};function $i(s,e){zp[s]=e}function fk(s){return s.__type in zp?zp[s.__type]:(uk&&s.__type&&console.warn("Unknown postprocessing type",s.__type,s),Ve)}class Cu{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)}}dk([$e([s=>fk(s),Ve])],Cu.prototype,"components");var pk=Object.defineProperty,mk=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&pk(e,t,n),n};const gk=w("debugpost");class Vc extends Ve{get typeName(){return"Antialiasing"}preset=new I(2);onCreateEffect(){const e=new exports.MODULES.POSTPROCESSING.MODULE.SMAAEffect({preset:this.preset?.value??exports.MODULES.POSTPROCESSING.MODULE.SMAAPreset.HIGH,edgeDetectionMode:exports.MODULES.POSTPROCESSING.MODULE.EdgeDetectionMode.LUMA});return this.preset.onValueChanged=t=>{gk&&console.log("Antialiasing preset changed to",t),e.applyPreset(t)},e}}mk([f(I)],Vc.prototype,"preset");$i("Antialiasing",Vc);var yk=Object.defineProperty,Ug=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&yk(e,t,n),n};const Pu=class pw extends Ve{static useSelectiveBloom=!1;get typeName(){return"Bloom"}threshold=new I(.9);intensity=new I(1);scatter=new I(.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=pw.useSelectiveBloom),this.selectiveBloom){const t=e=new exports.MODULES.POSTPROCESSING.MODULE.SelectiveBloomEffect(this.context.scene,this.context.mainCamera,{blendFunction:exports.MODULES.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 exports.MODULES.POSTPROCESSING.MODULE.BloomEffect({blendFunction:exports.MODULES.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});return this.intensity.onValueChanged=t=>{e.intensity=t},this.threshold.onValueChanged=t=>{e.luminanceMaterial.threshold=Math.pow(t,2.2)},this.scatter.onValueChanged=t=>{e.luminancePass.enabled=!0,e.luminanceMaterial.smoothing=t,e.mipmapBlurPass&&(e.mipmapBlurPass.radius=c.MathUtils.lerp(.1,.9,t))},e}};Ug([f(I)],Pu.prototype,"threshold");Ug([f(I)],Pu.prototype,"intensity");Ug([f(I)],Pu.prototype,"scatter");let Ou=Pu;$i("Bloom",Ou);var _k=Object.defineProperty,bk=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&_k(e,t,n),n};class $c extends Ve{get typeName(){return"ChromaticAberration"}intensity=new I(0);onCreateEffect(){const e=new exports.MODULES.POSTPROCESSING.MODULE.ChromaticAberrationEffect;return e.offset=new c.Vector2(0,0),e.radialModulation=!0,e.modulationOffset=.15,this.intensity.valueProcessor=t=>t*.02,this.intensity.onValueChanged=t=>{e.offset.x=-t,e.offset.y=t},e}}bk([f(I)],$c.prototype,"intensity");$i("ChromaticAberration",$c);var Ml=(s=>(s[s.None=0]="None",s[s.Neutral=1]="Neutral",s[s.ACES=2]="ACES",s[s.AgX=3]="AgX",s[s.KhronosNeutral=4]="KhronosNeutral",s))(Ml||{});const N_=new Map;function Wf(s){switch(s){case 0:return c.LinearToneMapping;case 1:return c.ReinhardToneMapping;case 2:return c.ACESFilmicToneMapping;case 3:return c.AgXToneMapping;case 4:return c.NeutralToneMapping;default:return N_.has(s)||(N_.set(s,!0),console.warn("[Postprocessing] Unknown tone mapping mode",s)),c.NeutralToneMapping}}function vk(s){switch(s){case c.LinearToneMapping:return 0;case c.ACESFilmicToneMapping:return 2;case c.AgXToneMapping:return 3;case c.NeutralToneMapping:return 1;case c.ReinhardToneMapping:return 1;default:return 0}}function od(s){switch(s){case c.LinearToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR;case c.ACESFilmicToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.ACES_FILMIC;case c.AgXToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.AGX;case c.NeutralToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.NEUTRAL;case c.ReinhardToneMapping:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.REINHARD;default:return exports.MODULES.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR}}var wk=Object.defineProperty,mw=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&wk(e,t,n),n};const Gf=w("debugpost");class Zs extends Ve{get typeName(){return"ToneMapping"}mode=new I(void 0);exposure=new I(1);setMode(e){const t=Ml[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=uw(this);e&&super.onEffectEnabled(e)}_tonemappingEffect=null;onCreateEffect(){if(this.mode.isInitialized==!1){const i=vk(this.context.renderer.toneMapping);Gf&&console.log("[PostProcessing] Initializing ToneMapping mode to renderer.toneMapping",this.context.renderer.toneMapping+" → "+i),this.mode.initialize(i)}this._tonemappingEffect?.dispose();const e=Wf(this.mode.value),t=this._tonemappingEffect=new exports.MODULES.POSTPROCESSING.MODULE.ToneMappingEffect({mode:od(e)});return this.mode.onValueChanged=i=>{if(typeof i=="string")i=Wv(i),t.mode=od(i);else{const n=Wf(i);t.mode=od(n)}t.name="ToneMapping ("+Ml[i]+")",Gf&&console.log("[PostProcessing] ToneMapping mode changed to",Ml[i],e,t.mode)},Gf&&console.log("[PostProcessing] Use ToneMapping",Ml[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=Wf(this.mode.value)),this.exposure.overrideState&&this.exposure.value!==void 0)){const e=Math.max(0,this.exposure.value);this.context.renderer.toneMappingExposure=e}}}mw([f(I)],Zs.prototype,"mode");mw([f(I)],Zs.prototype,"exposure");$i("Tonemapping",Zs);var xk=Object.defineProperty,Mu=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&xk(e,t,n),n};class uo extends Ve{get typeName(){return"ColorAdjustments"}remap=!0;postExposure=new I(1);contrast=new I(0);hueShift=new I(0);saturation=new I(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(o=>o instanceof Zs);t||(t=new Zs,this.postprocessingContext?.components.push(t)),this.postExposure.onValueChanged=o=>{this.postExposure.overrideState&&t?t.exposure.value=o: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 exports.MODULES.POSTPROCESSING.MODULE.BrightnessContrastEffect;this.contrast.onValueChanged=o=>i.contrast=o;const n=new exports.MODULES.POSTPROCESSING.MODULE.HueSaturationEffect;return this.hueShift.onValueChanged=o=>n.hue=o,this.saturation.onValueChanged=o=>n.saturation=o,e.push(i),e.push(n),e}}Mu([f(I)],uo.prototype,"postExposure");Mu([f(I)],uo.prototype,"contrast");Mu([f(I)],uo.prototype,"hueShift");Mu([f(I)],uo.prototype,"saturation");$i("ColorAdjustments",uo);var Sk=Object.defineProperty,vr=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&Sk(e,t,n),n};const Ck=w("debugpost");class ln extends Ve{get typeName(){return"DepthOfField"}mode;focusDistance=new I(1);focalLength=new I(.2);aperture=new I(20);gaussianMaxRadius=new I;resolutionScale=new I(1/window.devicePixelRatio);bokehScale=new I;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){Ck&&console.warn("DepthOfField: Mode is set to Off");return}const e=new exports.MODULES.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(){}}vr([f()],ln.prototype,"mode");vr([f(I)],ln.prototype,"focusDistance");vr([f(I)],ln.prototype,"focalLength");vr([f(I)],ln.prototype,"aperture");vr([f(I)],ln.prototype,"gaussianMaxRadius");vr([f(I)],ln.prototype,"resolutionScale");vr([f(I)],ln.prototype,"bokehScale");$i("DepthOfField",ln);class nc extends Ve{effect;constructor(e){super(),this.effect=e}get typeName(){return this.effect.constructor.name}onCreateEffect(){return this.effect}}var Pk=Object.defineProperty,Ok=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&Pk(e,t,n),n};class Wc extends Ve{get typeName(){return"PixelationEffect"}granularity=new I(10);onCreateEffect(){const e=new exports.MODULES.POSTPROCESSING.MODULE.PixelationEffect;return this.granularity.onValueChanged=t=>{e.granularity=t},e}}Ok([f(I)],Wc.prototype,"granularity");$i("PixelationEffect",Wc);var Mk=Object.defineProperty,Gc=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&Mk(e,t,n),n};class bs extends Ve{get typeName(){return"ScreenSpaceAmbientOcclusion"}intensity=new I(2);falloff=new I(1);samples=new I(9);color=new I(new c.Color(0,0,0));luminanceInfluence=new I(.7);onBeforeRender(){if(this._ssao&&this.context.mainCamera instanceof c.PerspectiveCamera){const e=this.context.mainCamera.far-this.context.mainCamera.near;this._ssao.ssaoMaterial.worldDistanceFalloff=e*.01,this._ssao.ssaoMaterial.worldDistanceThreshold=this.context.mainCamera.far}}_ssao;onCreateEffect(){const e=this.context.mainCamera,t=new exports.MODULES.POSTPROCESSING.MODULE.NormalPass(this.context.scene,e),i=new exports.MODULES.POSTPROCESSING.MODULE.DepthDownsamplingPass({normalBuffer:t.texture,resolutionScale:.5}),n=this._ssao=new exports.MODULES.POSTPROCESSING.MODULE.SSAOEffect(e,t.texture,{normalDepthBuffer:i.texture,worldDistanceThreshold:1,worldDistanceFalloff:1,worldProximityThreshold:.1,worldProximityFalloff:2,intensity:1,blendFunction:exports.MODULES.POSTPROCESSING.MODULE.BlendFunction.MULTIPLY,luminanceInfluence:.5});this.intensity.onValueChanged=r=>{n.intensity=r},this.falloff.onValueChanged=r=>{n.ssaoMaterial.radius=r*.1},this.samples.onValueChanged=r=>{n.ssaoMaterial.samples=r},this.color.onValueChanged=r=>{n.color||(n.color=new c.Color),n.color.copy(r)},this.luminanceInfluence.onValueChanged=r=>{n.luminanceInfluence=r};const o=new Array;return o.push(t),o.push(i),o.push(n),o}}Gc([f(I)],bs.prototype,"intensity");Gc([f(I)],bs.prototype,"falloff");Gc([f(I)],bs.prototype,"samples");Gc([f(I)],bs.prototype,"color");Gc([f(I)],bs.prototype,"luminanceInfluence");$i("ScreenSpaceAmbientOcclusion",bs);var kk=Object.defineProperty,wr=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&kk(e,t,n),n};const Ek=w("debugN8AO");var Np=(s=>(s[s.Performance=0]="Performance",s[s.Low=1]="Low",s[s.Medium=2]="Medium",s[s.High=3]="High",s[s.Ultra=4]="Ultra",s))(Np||{});class cn extends Ve{get typeName(){return"ScreenSpaceAmbientOcclusionN8"}get pass(){return this._ssao}gammaCorrection=!0;aoRadius=new I(1);falloff=new I(1);intensity=new I(1);color=new I(new c.Color(0,0,0));screenspaceRadius=!1;quality=2;_ssao;onValidate(){this._ssao&&(this._ssao.setQualityMode(Np[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 exports.MODULES.POSTPROCESSING_AO.MODULE.N8AOPostPass(this.context.scene,e,t,i);n.name="SSAO_N8";const o=Np[this.quality];n.setQualityMode(o),n.configuration.transparencyAware=!1;const r=new c.WebGLRenderTarget(t,i);return n.configuration.beautyRenderTarget=r,n.configuration.autoRenderBeauty=!1,n.configuration.gammaCorrection=this.gammaCorrection,n.configuration.screenSpaceRadius=this.screenspaceRadius,Ek&&(n.enableDebugMode(),console.log(n),setInterval(()=>{console.log("SSAO",n.lastTime)},1e3),setInterval(()=>{console.log("SSAO",n.enabled,{ssao:n,autoRenderBeauty:n.configuration.autoRenderBeauty})},4e3)),this.intensity.onValueChanged=a=>{n.configuration.intensity=a},this.falloff.onValueChanged=a=>{n.configuration.distanceFalloff=a},this.aoRadius.onValueChanged=a=>{n.configuration.aoRadius=a},this.color.onValueChanged=a=>{n.color||(n.color=new c.Color),n.configuration.color.copy(a)},n}}wr([yt(),f()],cn.prototype,"gammaCorrection");wr([f(I)],cn.prototype,"aoRadius");wr([f(I)],cn.prototype,"falloff");wr([f(I)],cn.prototype,"intensity");wr([f(I)],cn.prototype,"color");wr([yt(),f()],cn.prototype,"screenspaceRadius");wr([yt(),f()],cn.prototype,"quality");$i("ScreenSpaceAmbientOcclusionN8",cn);var Rk=Object.defineProperty,Tk=Object.getOwnPropertyDescriptor,gw=(s,e,t,i)=>{for(var n=Tk(e,t),o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&Rk(e,t,n),n};class Hc extends Ve{get typeName(){return"Sharpening"}order=Ke.Sharpening;_effect;onCreateEffect(){return this._effect??=new(Ak()),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}gw([f()],Hc.prototype,"amount");gw([f()],Hc.prototype,"radius");function Ak(){const s=`
|
|
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 exports.MODULES.POSTPROCESSING.MODULE.Effect{constructor(){super("Sharpening",e,{vertexShader:s,blendFunction:exports.MODULES.POSTPROCESSING.MODULE.BlendFunction.NORMAL,uniforms:new Map([["amount",new c.Uniform$1(1)],["radius",new c.Uniform$1(1)]]),attributes:qw.EffectAttribute.CONVOLUTION})}}return t}var Lk=Object.defineProperty,ja=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&Lk(e,t,n),n};class zn extends Ve{get typeName(){return"TiltShiftEffect"}offset=new I(0);rotation=new I(0);focusArea=new I(.4);feather=new I(.3);kernelSize=new I(2);resolutionScale=new I(1/window.devicePixelRatio);init(){this.offset.defaultValue=0,this.rotation.defaultValue=0,this.focusArea.defaultValue=.4,this.feather.defaultValue=.3,this.kernelSize.defaultValue=exports.MODULES.POSTPROCESSING.MODULE.KernelSize.MEDIUM,this.resolutionScale.defaultValue=1/window.devicePixelRatio}onCreateEffect(){const e=new exports.MODULES.POSTPROCESSING.MODULE.TiltShiftEffect({kernelSize:exports.MODULES.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}}ja([f(I)],zn.prototype,"offset");ja([f(I)],zn.prototype,"rotation");ja([f(I)],zn.prototype,"focusArea");ja([f(I)],zn.prototype,"feather");ja([f(I)],zn.prototype,"kernelSize");ja([f(I)],zn.prototype,"resolutionScale");$i("TiltShiftEffect",zn);var Dk=Object.defineProperty,zg=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&Dk(e,t,n),n};class xr extends Ve{get typeName(){return"Vignette"}color=new I({r:0,g:0,b:0,a:1});intensity=new I(0);center=new I({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 exports.MODULES.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}}zg([f(I)],xr.prototype,"color");zg([f(I)],xr.prototype,"intensity");zg([f(I)],xr.prototype,"center");$i("Vignette",xr);globalThis.NEEDLE_USE_POSTPROCESSING=globalThis.NEEDLE_USE_POSTPROCESSING!==void 0?globalThis.NEEDLE_USE_POSTPROCESSING:!0;const Gn=w("debugpost"),Hf=Symbol("needle:postprocessing-handler"),il=Symbol("needle:previous-autoclear-state"),nl=Symbol("needle:previous-tone-mapping");class Ng{_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(Gn&&console.log("Unapplying postprocessing effects"),this._isActive=!1,this._lastVolumeComponents){for(const n of this._lastVolumeComponents)n.unapply();this._lastVolumeComponents.length=0}const t=this.context;t[Hf]===this&&(delete t[Hf],typeof t.renderer[il]=="boolean"&&(t.renderer.autoClear=t.renderer[il]),typeof t.renderer[nl]=="number"&&(t.renderer.toneMapping=t.renderer[nl])),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([exports.MODULES.POSTPROCESSING.load(),exports.MODULES.POSTPROCESSING_AO.load()]),e[Hf]=this,Gn&&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 o=this._lastVolumeComponents[n];if(o.context=e,o.apply){if(o.active){let r=function(h,d){return d?(d instanceof exports.MODULES.POSTPROCESSING.MODULE.Effect||d instanceof exports.MODULES.POSTPROCESSING.MODULE.Pass||console.warn(`PostprocessingEffect ${h} 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=o.apply(i);if(!a)continue;const l=o.typeName||o.constructor.name;if(Array.isArray(a))for(const h of a)r(l,h)&&this._effects.push({effect:h,typeName:o.typeName,priority:o.order});else{if(!r(l,a))continue;this._effects.push({effect:a,typeName:o.typeName,priority:o.order})}}}else o.active&&he("Volume component is not a VolumeComponent: "+o.__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,o=t.threeCamera;if(typeof i[il]=="boolean"&&(i.autoClear=i[il]),i[il]=i.autoClear,typeof i[nl]=="number"&&(i.toneMapping=i[nl]),i[nl]=i.toneMapping,i.toneMapping!=c.NoToneMapping&&!this._effects.find(d=>d instanceof exports.MODULES.POSTPROCESSING.MODULE.ToneMappingEffect)){const d=new exports.MODULES.POSTPROCESSING.MODULE.ToneMappingEffect;d.name=`ToneMapping (${i.toneMapping})`,d.mode=od(i.toneMapping),this._effects.push({typeName:"ToneMapping",effect:d,priority:Ke.ToneMapping})}this._composer||(this._composer=new exports.MODULES.POSTPROCESSING.MODULE.EffectComposer(i,{frameBufferType:c.HalfFloatType,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(o),r.setRenderer(i),r.setMainScene(n),r.autoRenderToScreen=!0,r.multisampling=0;for(const d of r.passes)d.dispose();r.removeAllPasses();const a=new exports.MODULES.POSTPROCESSING.MODULE.RenderPass(n,o);a.name="RenderPass",a.mainScene=n,r.addPass(a);const l=a.render;this._customInputBuffer?.dispose(),this._customInputBuffer=null,a.render=(d,u,p,m,y)=>{u&&(u.samples=0,p&&(p.samples=0),(!this._customInputBuffer||this._customInputBuffer.width!==u.width||this._customInputBuffer.height!==u.height||this._customInputBuffer.samples!==this._multisampling||this._customInputBuffer.texture.format!==u.texture.format||this._customInputBuffer.texture.type!==c.HalfFloatType)&&(this._customInputBuffer?.dispose(),this._customInputBuffer=new c.WebGLRenderTarget(u.width,u.height,{format:u.texture.format,type:c.HalfFloatType,depthBuffer:u.depthBuffer,depthTexture:u.depthTexture?new c.DepthTexture(u.width,u.height):void 0,stencilBuffer:u.stencilBuffer,samples:Math.max(0,this._multisampling),minFilter:u.texture.minFilter??c.LinearFilter,magFilter:u.texture.magFilter??c.LinearFilter,generateMipmaps:u.texture.generateMipmaps}),this._customInputBufferId++,this._customInputBuffer.texture.name=`CustomInputBuffer-${this._customInputBufferId}`,this._customInputBuffer.depthTexture&&u.depthTexture&&(this._customInputBuffer.depthTexture.format=u.depthTexture.format,this._customInputBuffer.depthTexture.type=u.depthTexture.type),this._customInputBuffer.samples>0&&(this._customInputBuffer.ignoreDepthForMultisampleCopy=!1),Gn&&console.warn(`[PostProcessing] Input buffer created with size ${this._customInputBuffer.width}x${this._customInputBuffer.height} and samples ${this._customInputBuffer.samples}`)),l.call(a,d,this._customInputBuffer,p,m,y),Xs.blit(this._customInputBuffer.texture,u,{renderer:d,depthTexture:this._customInputBuffer.depthTexture,depthWrite:!0,depthTest:!0}))};try{nk(this._effects);let d=!1,u=null;for(let y=this._effects.length-1;y>=0;y--){const
|
|
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=o.apply(i);if(!a)continue;const l=o.typeName||o.constructor.name;if(Array.isArray(a))for(const h of a)r(l,h)&&this._effects.push({effect:h,typeName:o.typeName,priority:o.order});else{if(!r(l,a))continue;this._effects.push({effect:a,typeName:o.typeName,priority:o.order})}}}else o.active&&he("Volume component is not a VolumeComponent: "+o.__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,o=t.threeCamera;if(typeof i[il]=="boolean"&&(i.autoClear=i[il]),i[il]=i.autoClear,typeof i[nl]=="number"&&(i.toneMapping=i[nl]),i[nl]=i.toneMapping,i.toneMapping!=c.NoToneMapping&&!this._effects.find(d=>d instanceof exports.MODULES.POSTPROCESSING.MODULE.ToneMappingEffect)){const d=new exports.MODULES.POSTPROCESSING.MODULE.ToneMappingEffect;d.name=`ToneMapping (${i.toneMapping})`,d.mode=od(i.toneMapping),this._effects.push({typeName:"ToneMapping",effect:d,priority:Ke.ToneMapping})}this._composer||(this._composer=new exports.MODULES.POSTPROCESSING.MODULE.EffectComposer(i,{frameBufferType:c.HalfFloatType,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(o),r.setRenderer(i),r.setMainScene(n),r.autoRenderToScreen=!0,r.multisampling=0;for(const d of r.passes)d.dispose();r.removeAllPasses();const a=new exports.MODULES.POSTPROCESSING.MODULE.RenderPass(n,o);a.name="RenderPass",a.mainScene=n,r.addPass(a);const l=a.render;this._customInputBuffer?.dispose(),this._customInputBuffer=null,a.render=(d,u,p,m,y)=>{u&&(u.samples=0,p&&(p.samples=0),(!this._customInputBuffer||this._customInputBuffer.width!==u.width||this._customInputBuffer.height!==u.height||this._customInputBuffer.samples!==this._multisampling||this._customInputBuffer.texture.format!==u.texture.format||this._customInputBuffer.texture.type!==c.HalfFloatType)&&(this._customInputBuffer?.dispose(),this._customInputBuffer=new c.WebGLRenderTarget(u.width,u.height,{format:u.texture.format,type:c.HalfFloatType,depthBuffer:u.depthBuffer,depthTexture:u.depthTexture?new c.DepthTexture(u.width,u.height):void 0,stencilBuffer:u.stencilBuffer,samples:Math.max(0,this._multisampling),minFilter:u.texture.minFilter??c.LinearFilter,magFilter:u.texture.magFilter??c.LinearFilter,generateMipmaps:u.texture.generateMipmaps}),this._customInputBufferId++,this._customInputBuffer.texture.name=`CustomInputBuffer-${this._customInputBufferId}`,this._customInputBuffer.depthTexture&&u.depthTexture&&(this._customInputBuffer.depthTexture.format=u.depthTexture.format,this._customInputBuffer.depthTexture.type=u.depthTexture.type),this._customInputBuffer.samples>0&&(this._customInputBuffer.ignoreDepthForMultisampleCopy=!1),Gn&&console.warn(`[PostProcessing] Input buffer created with size ${this._customInputBuffer.width}x${this._customInputBuffer.height} and samples ${this._customInputBuffer.samples}`)),l.call(a,d,this._customInputBuffer,p,m,y),Xs.blit(this._customInputBuffer.texture,u,{renderer:d,depthTexture:this._customInputBuffer.depthTexture,depthWrite:!0,depthTest:!0}))};try{nk(this._effects);let d=!1,u=null;for(let y=this._effects.length-1;y>=0;y--){const b=this._effects[y].effect;if(b instanceof exports.MODULES.POSTPROCESSING.MODULE.ToneMappingEffect){if(d){Gn&&console.warn(`[PostProcessing] Found multiple tonemapping effects in the scene: ${b.name} and ${u?.name}. Only the last one added will be used.`),this._effects.splice(y,1);continue}u=b,d=!0}}const p=[];let m=!1;for(let y=0;y<this._effects.length;y++){const g=this._effects[y].effect;if(g instanceof exports.MODULES.POSTPROCESSING.MODULE.SMAAEffect?this._hasSmaaEffect=!0:g instanceof exports.MODULES.POSTPROCESSING.MODULE.NormalPass&&(this._anyPassHasNormal=!0),!(g instanceof exports.MODULES.POSTPROCESSING.MODULE.ToneMappingEffect&&u!==g))if(g instanceof exports.MODULES.POSTPROCESSING.MODULE.Effect){const v=g.getAttributes(),_=exports.MODULES.POSTPROCESSING.MODULE.EffectAttribute.CONVOLUTION;v&_&&(Gn&&console.log("[PostProcessing] Convolution effect: "+g.name),m&&(Gn&&console.log("[PostProcessing] → Merging effects ["+p.map(x=>x.name).join(", ")+"]"),this.createPassForMergeableEffects(p,r,o,n)),m=!0),p.push(g)}else g instanceof exports.MODULES.POSTPROCESSING.MODULE.Pass?(m=!1,this.createPassForMergeableEffects(p,r,o,n),g.renderToScreen=!1,r.addPass(g)):(m=!1,this.createPassForMergeableEffects(p,r,o,n),r.addPass(g))}this.createPassForMergeableEffects(p,r,o,n)}catch(d){console.error("Error while applying postprocessing effects",d),r.passes.forEach(u=>u.dispose()),r.removeAllPasses()}let h=!1;for(let d=r.passes.length-1;d>=0;d--){const u=r.passes[d];let p=!1,m=!1;u.enabled&&(h||(p=!0,m=!0),h=!0),u.renderToScreen=m,u?.configuration!==void 0?u.configuration.gammaCorrection=p:"autosetGamma"in u&&(u.autosetGamma=p),this._anyPassHasDepth||=u.needsDepthTexture}this.handleDevicePixelRatio(),Gn&&console.log("[PostProcessing] Passes →",[...r.passes],`
|
|
1329
1329
|
---------------------------------
|
|
1330
1330
|
• `+r.passes.map(d=>d.name||d.constructor.name+"*").join(`
|
|
1331
1331
|
• `)+`
|
|
@@ -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):(Xf&&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()):A()&&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(qf,this.context.connection.currentRoomViewId),window.location.origin+window.location.pathname+"?"+t.toString()}return null}setRandomRoomUrlParameter(){const e=rc(),t=this.generateRoomName();w(this.urlParameterName)?e.set(this.urlParameterName,t):e.append(this.urlParameterName,t),Qp(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&&Wl(this.urlParameterName,null),this.context.connection.leaveRoom(),this._userWantsToBeInARoom=!1;else{if(this.urlParameterName){const t=w(this.urlParameterName);(!t||t===!0)&&(this._lastJoinedRoom?Wl(this.urlParameterName,this._lastJoinedRoom):this.setRandomRoomUrlParameter())}this.tryJoinRoom()}},this._roomButtonIconJoin=pt("group"),this._roomButtonIconLeave=pt("group_off"),this.updateRoomButtonState(),this.context.connection.beginListen(Q.JoinedRoom,this.updateRoomButtonState),this.context.connection.beginListen(Q.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(Q.JoinedRoom,this.updateRoomButtonState),this.context.connection.stopListen(Q.LeftRoom,this.updateRoomButtonState)}_viewOnlyButton;onEnableViewOnlyButton(){this.context.connection.isConnected?this.onCreateViewOnlyButton():(this.context.connection.stopListen(Q.JoinedRoom,this.onCreateViewOnlyButton),this.context.connection.beginListen(Q.JoinedRoom,this.onCreateViewOnlyButton))}onDisableViewOnlyButton(){this.context.connection.stopListen(Q.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),Se("View only URL copied to clipboard")):he("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(pt("visibility"))}this.context.menu.appendChild(this._viewOnlyButton)}}po([f()],dn.prototype,"roomName",2);po([f()],dn.prototype,"urlParameterName",2);po([f()],dn.prototype,"joinRandomRoom",2);po([f()],dn.prototype,"requireRoomParameter",2);po([f()],dn.prototype,"autoRejoin",2);po([f()],dn.prototype,"createJoinButton",2);po([f()],dn.prototype,"createViewOnlyButton",2);po([f()],dn.prototype,"roomPrefix",1);function vE(){const s=w("testwindowcount")||0;s&&s>0&&wE(s)}function wE(s){if(w("testwindow"))return null;const e=new URL(window.location.href);ep(e.searchParams,yP,1),ep(e.searchParams,"testwindow",1);const t=e.toString(),i=[];window.onbeforeunload=()=>{for(const l of i)l.close()};const n=.05,o=128;let r=0,a=0;for(let l=0;l<s;l++){r*o+o*.01>=window.innerWidth&&(a+=1,r=0);const h=r*(o*(1+n))+window.screenLeft,d=a*(o*(1+n))+window.screenTop+90+60*a;r+=1;const u=window.open(t,"test window "+l,`popup=yes width=${o} height=${o} top=${d} left=${h}`);if(!u){console.warn("Failed to open window");continue}i.push(u),u.onload=()=>{u.onbeforeunload=()=>{for(let p=0;p<i.length;p++){const m=i[p];m!==u&&m.close()}i.length=0}}}return i}class Wg extends k{awake(){vE()}}class Gg extends k{transformsPerFrame=10;interval=0;useFlatbuffers=!0;awake(){if(this.useFlatbuffers)this.context.connection.beginListenBinary(Yl,e=>{});else{this.models=[];for(let e=0;e<this.transformsPerFrame;e++)this.models.push(new xE(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 se.Builder(1024));const e=this.builder;for(let t=0;t<this.transformsPerFrame;t++){e.clear();const i=o0(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 xE{guid;fast=!1;position;rotation;velocity=void 0;dontSave;isValid(){return this.fast!==void 0||this.position!==void 0||this.rotation!==void 0||this.velocity!==void 0}constructor(e,t){this.guid=e,this.position={x:0,y:0,z:0},this.rotation={x:0,y:0,z:0,w:0},this.update(t,null)}static temp=new c.Vector3;update(e,t){const i=e.worldPosition;this.position.x=i.x,this.position.y=i.y,this.position.z=i.z;const n=e.worldQuaternion;if(this.rotation.x=n.x,this.rotation.y=n.y,this.rotation.z=n.z,this.rotation.w=n.w,this.fast=!1,t){const o=t.getVelocity();this.velocity===void 0&&(this.velocity={x:0,y:0,z:0}),this.velocity.x=o.x,this.velocity.y=o.y,this.velocity.z=o.z}}}var SE=Object.defineProperty,Lu=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&SE(e,t,n),n};const CE=w("debugsignals");class Du{guid}Lu([f()],Du.prototype,"guid");class Zc{signal;reaction}Lu([f(Du)],Zc.prototype,"signal");Lu([f(oe)],Zc.prototype,"reaction");const Mw=class Yn extends k{static receivers={};static invoke(e){if(Yn.receivers[e]){const t=Yn.receivers[e];if(!t)return;for(const i of t)i.invoke(e)}}events;awake(){CE&&console.log("SignalReceiver awake",this)}onEnable(){if(this.events)for(const e of this.events)Yn.receivers[e.signal.guid]||(Yn.receivers[e.signal.guid]=[]),Yn.receivers[e.signal.guid].push(this)}onDisable(){if(this.events){for(const e of this.events)if(Yn.receivers[e.signal.guid]){const t=Yn.receivers[e.signal.guid].indexOf(this);t>=0&&Yn.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)}}};Lu([f(Zc)],Mw.prototype,"events");let Jc=Mw;var si=(s=>(s.Activation="ActivationTrack",s.Animation="AnimationTrack",s.Audio="AudioTrack",s.Control="ControlTrack",s.Marker="MarkerTrack",s.Signal="SignalTrack",s))(si||{}),gn=(s=>(s[s.None=0]="None",s[s.Hold=1]="Hold",s[s.Loop=2]="Loop",s[s.PingPong=3]="PingPong",s[s.Continue=4]="Continue",s))(gn||{}),Hg=(s=>(s.Signal="SignalEmitter",s))(Hg||{});const Mn=w("debugtimeline");class eh{director;track;get muted(){return this.track.muted}set muted(e){e!==this.track.muted&&(this.track.muted=e,this.onMuteChanged?.call(this))}*forEachClip(e=!1){if(this.track?.clips)if(e)for(let t=this.track.clips.length-1;t>=0;t--)yield this.track.clips[t];else for(const t of this.track.clips)yield t}getClipTime(e,t){return t.clipIn+(e-t.start)*t.timeScale}getClipTimeNormalized(e,t){return(e-t.start)/t.duration}evaluateWeight(e,t,i,n=!0){if(t<0||t>=i.length)return 0;const o=i[t];if(n||e>=o.start&&e<=o.end){let r=1;if(o.easeInDuration>0){const a=Math.min((e-o.start)/o.easeInDuration,1);r*=a}if(o.easeOutDuration>0){const a=Math.min((o.end-e)/o.easeOutDuration,1);r*=a}return r}return 0}}class PE{clip;rootPositionOffset;rootQuaternionOffset;get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}rootStartPosition;rootEndPosition;rootStartQuaternion;rootEndQuaternion;constructor(e){const t=e.getClip();this.clip=t;const i=e.getRoot(),n=i.name+".position",o=i.name+".quaternion";Mn&&console.log(t.name,t.tracks,n);for(const r of t.tracks)if(!(r.times.length<=0)){if(r.name.endsWith(n))this.rootStartPosition=new c.Vector3().fromArray(r.values,0),this.rootEndPosition=new c.Vector3().fromArray(r.values,r.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),Mn&&console.log(this.rootPositionOffset);else if(r.name.endsWith(o)&&(this.rootStartQuaternion=new c.Quaternion().fromArray(r.values,0),this.rootEndQuaternion=new c.Quaternion().fromArray(r.values,r.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),Mn)){const a=new c.Euler().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",a)}}}}class Iu extends eh{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&&r_(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],o=n+".position",r=n+".quaternion";let a=!1,l=!1;for(const h of t.tracks)h.name.endsWith(o)?(a=!0,this.createPositionInterpolant(t,e,h)):h.name.endsWith(r)&&(l=!0,this.createRotationInterpolant(t,e,h));if(!a||!l){const h=this.mixer?.getRoot(),d=t.tracks[0],u=d.name.lastIndexOf("."),p=d.name.substring(0,u),m=p.substring(p.lastIndexOf(".")+1),y=h.getObjectByName(m);if(y)if(a){if(!l){const _=t.tracks[0].name.substring(0,u)+".quaternion";Mn&&console.warn("Create quaternion track",m,y);const g=y.quaternion,v=new c.QuaternionKeyframeTrack(_,[0,t.duration],[g.x,g.y,g.z,g.w,g.x,g.y,g.z,g.w]);t.tracks.push(v),this.createRotationInterpolant(t,e,v)}}else{const _=p+".position";Mn&&console.warn("Create position track",m,y);const g=y.position,v=new c.VectorKeyframeTrack(_,[0,t.duration],[g.x,g.y,g.z,g.x,g.y,g.z]);t.tracks.push(v),this.createPositionInterpolant(t,e,v)}}}bind(){if(!this._didBind){this._didBind=!0,Mn&&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 PE(e);this._actionOffsets.push(t)}this.target&&(this._animator=S.getComponent(this.target,rt)??null,this._animator&&r_(this._animator.gameObject,this,!0));for(const e of this.models){const t=e.asset,i=t.position,n=t.rotation;i&&i.x!==void 0&&(i.isVector3||(t.position=new c.Vector3(i.x,i.y,i.z)),n.isQuaternion||(t.rotation=new c.Quaternion(n.x,n.y,n.z,n.w)))}this.ensureTrackOffsets()}}ensureTrackOffsets(){if(this.trackOffset){const e=this.trackOffset.position;e&&(e.isVector3||(this.trackOffset.position=new c.Vector3(e.x,e.y,e.z)));const t=this.trackOffset.rotation;t&&(t.isQuaternion||(this.trackOffset.rotation=new c.Quaternion(t.x,t.y,t.z,t.w)))}}_useclipOffsets=!0;_totalOffsetPosition=new c.Vector3;_totalOffsetRotation=new c.Quaternion;_totalOffsetPosition2=new c.Vector3;_totalOffsetRotation2=new c.Quaternion;_summedPos=new c.Vector3;_tempPos=new c.Vector3;_summedRot=new c.Quaternion;_tempRot=new c.Quaternion;_clipRotQuat=new c.Quaternion;evaluate(e){if(this.track.muted||!this.mixer)return;this.bind(),this._totalOffsetPosition.set(0,0,0),this._totalOffsetRotation.set(0,0,0,1),this._totalOffsetPosition2.set(0,0,0),this._totalOffsetRotation2.set(0,0,0,1);let t=0,i=0,n=!1,o=!1,r=0;for(let a=0;a<this.clips.length;a++){const l=this.models[a],h=this.actions[a],d=l.asset;h.weight=0;const u=e>=l.start&&e<=l.end,p=l.preExtrapolationMode,m=l.postExtrapolationMode,y=a<this.clips.length-1?this.models[a+1]:null;let _=u,g=!1;if(!_&&!n&&l.end<e&&m!==gn.None?(!y||y.start>e)&&(_=!0,n=!0):a==0&&!_&&!o&&l.start>e&&p!==gn.None&&(!y||y.start<e)&&(_=!0,g=!0,o=!0),_){let v=this.weight;v*=this.evaluateWeight(e,a,this.models,_),v*=this.director.weight;let b=u;if(g)switch(p){case gn.Hold:break;case gn.Loop:e+=l.start,b=!0;break;default:e+=l.start,b=!0;break}let x=this.getClipTime(e,l),T=0;const O=d.duration;if(g&&p===gn.Hold&&(x=0),b){if(d.loop)for(T+=Math.floor(x/(O+1e-6));x>O;)x-=O}else if(!u&&n)switch(m){case gn.Hold:x=this.getClipTime(l.end,l);break;case gn.Loop:x%=O;break;case gn.PingPong:const j=Math.floor(x/O)%2!==0;x%=O,j&&(x=O-x);break}l.reversed===!0?h.time=h.getClip().duration-x:h.time=x,h.timeScale=0;const M=Math.max(0,v);if(h.weight=M,r+=M,h.clampWhenFinished=!1,h.isRunning()||h.play(),this._useclipOffsets){const E=t==0?this._totalOffsetPosition:this._totalOffsetPosition2,j=t==0?this._totalOffsetRotation:this._totalOffsetRotation2;t<1&&(i=1-v),t+=1;const L=this._summedPos.set(0,0,0),z=this._tempPos.set(0,0,0),$=this._summedRot.identity(),R=this._tempRot.identity(),U=d.rotation;U&&(this._clipRotQuat.identity(),this._clipRotQuat.slerp(U,v));const N=this._actionOffsets[a];if(N.hasOffsets)for(let K=0;K<T;K++)N.rootPositionOffset?z.copy(N.rootPositionOffset):z.set(0,0,0),z.applyQuaternion($),this._clipRotQuat&&z.applyQuaternion(this._clipRotQuat),N.rootQuaternionOffset&&(R.copy(N.rootQuaternionOffset),$.multiply(R)),L.add(z);this._clipRotQuat&&j.multiply(this._clipRotQuat),j.multiply($),d.position&&L.add(d.position),E.add(L)}}}if(this._useclipOffsets&&(this._totalOffsetPosition.lerp(this._totalOffsetPosition2,i),this._totalOffsetRotation.slerp(this._totalOffsetRotation2,i)),this.__mixerError===void 0&&(Mn||A())&&this._animator?.runtimeAnimatorController?.mixer&&this.mixer!==this._animator?.runtimeAnimatorController?.mixer&&(this.__mixerError=!0,console.error("AnimationTrack mixer is not shared with the animator controller - this might result in the timeline to not animate properly. Please report a bug to the Needle Engine team!",this)),this._animator?.runtimeAnimatorController){const a=Math.max(0,1-r);this._animator?.runtimeAnimatorController?.update(a)}else this.mixer.update(e)}createRotationInterpolant(e,t,i){const n=i.createInterpolant.bind(i),o=new c.Quaternion;this.ensureTrackOffsets();const r=this.trackOffset?.rotation;i.createInterpolant=()=>{const a=n(),l=a.evaluate.bind(a);return a.evaluate=h=>{const d=l(h);if(o.set(d[0],d[1],d[2],d[3]),o.premultiply(this._totalOffsetRotation),r&&o.premultiply(r),this.director.animationCallbackReceivers)for(const u of this.director.animationCallbackReceivers)u?.onTimelineRotation?.call(u,this.director,this.target,h,o);return d[0]=o.x,d[1]=o.y,d[2]=o.z,d[3]=o.w,d},a}}createPositionInterpolant(e,t,i){const n=i.createInterpolant.bind(i),o=new c.Vector3;this.ensureTrackOffsets();const r=this.trackOffset?.rotation,a=this.trackOffset?.position;let l;i.createInterpolant=()=>{const h=n(),d=h.evaluate.bind(h);return h.evaluate=u=>{const p=d(u);if(o.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&&o.sub(l)),o.applyQuaternion(this._totalOffsetRotation),o.add(this._totalOffsetPosition),r&&o.applyQuaternion(r),a&&(o.x-=a.x,o.y+=a.y,o.z+=a.z),this.director.animationCallbackReceivers)for(const m of this.director.animationCallbackReceivers)m?.onTimelinePosition?.call(m,this.director,this.target,u,o);return p[0]=o.x,p[1]=o.y,p[2]=o.z,p},h}}}const OE=w("mutetimeline");class os extends eh{models=[];listener;audio=[];audioContextTimeOffset=[];lastTime=0;audioSource;_audioLoader=null;getAudioFilePath(e){const t=this.director.sourceId;return Js(t,e)}onAllowAudioChanged(e){for(let t=0;t<this.models.length;t++){const i=this.models[t];this.audio[t].setVolume(e?i.asset.volume:0)}}addModel(e){const t=new c.Audio(this.listener);this.audio.push(t);const i=e;i._didTriggerPlay=!1,this.models.push(i)}onDisable(){for(const e of this.audio)e.isPlaying&&e.stop();for(const e of this.models)e._didTriggerPlay=!1}onDestroy(){for(const e of this.audio)e.source&&e?.disconnect();this.audio.length=0}onMuteChanged(){if(this.muted)for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t?.isPlaying&&t.stop()}}stop(){for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t?.isPlaying&&t.stop()}for(const e of this.models)e._didTriggerPlay=!1}_playableDirectorResumed=!1;onPauseChanged(){for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t?.isPlaying&&t.stop()}this._playableDirectorResumed=this.director.isPlaying}evaluate(e){if(OE||this.track.muted||this.director.speed<0)return;const t=this.director.context.application.muted,i=this._playableDirectorResumed;this._playableDirectorResumed=!1;const n=t?.1:0;for(let o=0;o<this.models.length;o++){const r=this.models[o],a=this.audio[o],l=r.asset;if((!a||!a.buffer)&&this.isInTimeRange(r,e-1,e+1)&&this.handleAudioLoading(r,a),pi.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,Mn&&console.log("Timeline Audio ("+this.track.name+") play with offset "+a.offset+" - "+r.asset.clip),a.play(n),r._didTriggerPlay=!0);else{const d=r.clipIn+(e-r.start)*r.timeScale,u=a.context.currentTime-a._startedAt+a.offset;Math.abs(d-u)>.3&&(a.offset=d,a.stop(),a.play(n))}let h=l.volume;if(this.track.volume!==void 0&&(h*=this.track.volume),t&&(h=0),r.easeInDuration>0){const d=Math.min((e-r.start)/r.easeInDuration,1);h*=d}if(r.easeOutDuration>0){const d=Math.min((r.end-e)/r.easeOutDuration,1);h*=d}a.setVolume(h*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 o=e-i,r=e+t;for(const a of this.models)if(this.isInTimeRange(a,o,r)){const l=this.audio[this.models.indexOf(a)],h=this.handleAudioLoading(a,l);h!==null&&(n===null&&(n=[]),n.push(h))}return n!==null?Promise.all(n):null}isInTimeRange(e,t,i){return t<=e.start&&i>=e.end||t>=e.start&&t<=e.end||i>=e.start&&i<=e.end}static _audioBuffers=new Map;static dispose(){os._audioBuffers.clear()}handleAudioLoading(e,t){this._audioLoader||(this._audioLoader=new c.AudioLoader);const i=this.getAudioFilePath(e.asset.clip);if(os._audioBuffers.get(i)){const o=os._audioBuffers.get(i);return o.then(r=>{r&&t.setBuffer(r)}),o}Mn&&console.warn("LOAD audio track",i,this.director.sourceId);const n=new Promise((o,r)=>{this._audioLoader.load(i,a=>{t.setBuffer(a),o(a)},void 0,a=>{console.error("Error loading audio",a),o(null)})});return os._audioBuffers.set(i,n),n}}class sc extends eh{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],o=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(!o)if(Mn&&console.log("Trigger signal",e,n.time,n),this.didTrigger[i]=!0,this.receivers?.length<=0)Jc.invoke(n.asset);else for(const l of this.receivers)l&&l.invoke(n.asset)}else n.emitOnce||(this.didTrigger[i]=!1)}}}class ju extends eh{models=[];timelines=[];resolveSourceObjects(e){for(let t=this.models.length-1;t>=0;t--){const n=this.models[t].asset;if(!n.sourceObject||typeof n.sourceObject!="object"){console.log("no source object, removing model",t,n),this.models.splice(t,1);continue}else{const o=S.getComponent(n.sourceObject,er);this.timelines.push(o),o&&n.updateDirector&&(o.playOnAwake=!1)}}}_previousActiveModel=null;evaluate(e){this._previousActiveModel=null;for(let t=0;t<this.models.length;t++){const i=this.models[t],n=i.asset;if(e>=i.start&&e<=i.end){this._previousActiveModel=i;const o=this.getClipTime(e,i);if(n.controlActivation){const r=n.sourceObject;r.visible=!0}if(n.updateDirector){const r=this.timelines[t];r&&(r.isPlaying&&r.pause(),r.time=o,r.evaluate())}}else{const o=this._previousActiveModel?.asset;if(n.controlActivation){const r=n.sourceObject;o?.sourceObject!==r&&(r.visible=!1)}}}}}var ME=Object.defineProperty,kw=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&ME(e,t,n),n};const Hn=w("debugtimeline"),qg=class $p extends k{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:(Hn||Ii())&&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(){Hn&&console.log(this,this.playableAsset?.tracks),this.rebuildGraph(),!this.isValid()&&(Hn||A())&&(Hn?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&&!pi.userInteractionRegistered&&this.waitForAudio;)await Ln(200)}this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine=this.startCoroutine(this.internalUpdate(),pe.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 si.Activation:if(!e&&!this._isPlaying)continue;for(let o=0;o<n.outputs.length;o++){const r=n.outputs[o];if(typeof r=="object"){let a=!1;if(n.clips)for(const h of n.clips)h.start<=i&&i<=h.end&&(a=!0);const l=r;l.visible!==void 0&&l.visible!==a&&(l.visible=a,Hn&&console.warn(this.name,"set ActivationTrack-"+o,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=ac(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 o=S.findByGuid(n,e);o===null||typeof o!="object"?(t.outputs.splice(i,1),console.warn("Failed to resolve binding",n,t.name,t.type)):(Hn&&console.log("Resolved binding",n,"to",o),t.outputs[i]=o)}else if(n===null){if(t.outputs.splice(i,1),$p.createTrackFunctions[t.type])continue;t.type!==si.Audio&&t.type!==si.Control&&t.type!==si.Marker&&t.type!==si.Signal&&console.warn("Missing binding",n,t.name,t.type,this.name,this.playableAsset.name)}}if(t.type===si.Control&&t.clips)for(let i=0;i<t.clips.length;i++){const n=t.clips[i];let o=n.asset.sourceObject;if(typeof o=="string"){this._guidsMap&&this._guidsMap[o]&&(o=this._guidsMap[o]);const r=S.findByGuid(o,e);r===null||typeof r!="object"?console.warn("Failed to resolve sourceObject binding",o,t.name,n):(Hn&&console.log("Resolved binding",o,"to",r),n.asset.sourceObject=r)}}}}findRoot(e){return e.parent?this.findRoot(e.parent):e}updateTimelineDuration(){if(this._duration=0,!(!this.playableAsset||!this.playableAsset.tracks)){for(const e of this.playableAsset.tracks)if(e.muted!==!0){if(e.clips)for(const t of e.clips)t.end>this._duration&&(this._duration=t.end);if(e.markers)for(const t of e.markers)t.time>this._duration&&(this._duration=t.time+.001)}}}setupAndCreateTrackHandlers(){if(this._animationTracks.length=0,this._audioTracks.length=0,this._signalTracks.length=0,!this.playableAsset)return;let e=S.findObjectOfType(ns,this.context);for(const t of this.playableAsset.tracks){const i=t.type,n=$p.createTrackFunctions[i];if(n!=null){const o=n(this,t);if(typeof o.evaluate=="function"){o.director=this,o.track=t,this._customTracks.push(o);continue}}if(t.type===si.Animation){if(!t.clips||t.clips.length<=0){Hn&&console.warn("Animation track has no clips",t);continue}for(let o=t.outputs.length-1;o>=0;o--){let r=t.outputs[o];if(r instanceof c.Object3D){const l=S.getOrAddComponent(r,rt);l&&(r=l)}const a=r?.gameObject?.animations;if(a){const l=new Iu;l.trackOffset=t.trackOffset,l.director=this,l.track=t;for(let h=0;h<t.clips.length;h++){const d=t.clips[h],u=d.asset;if(!u){console.error(`Timeline ${this.name}: clip #${h} on track "${t.name}" has no animation data`);continue}const p=u.clip;let m=p;if((typeof m=="string"||typeof m=="number")&&(m=a.find(_=>_.name===p)),Hn&&console.log(u,p,"→",m),!m){console.warn("Could not find animationClip for model",d,t.name,this.name,this.playableAsset?.name,a,r);continue}r instanceof rt&&r.runtimeAnimatorController&&(r.__internalDidAwakeAndStart||r.initializeRuntimeAnimatorController(),r.runtimeAnimatorController.mixer||r.runtimeAnimatorController.bind(r),l.mixer=r.runtimeAnimatorController.mixer),l.mixer||(l.mixer=new c.AnimationMixer(r.gameObject),this.context.animations.registerAnimationMixer(l.mixer)),l.clips.push(m),l.mixer.uncacheAction(m),l.createHooks(d.asset,m);const y=l.mixer.clipAction(m);l.actions.push(y),l.models.push(d)}this._animationTracks.push(l)}}}else if(t.type===si.Audio){if(!t.clips||t.clips.length<=0)continue;const o=new os;o.director=this,o.track=t,o.audioSource=t.outputs.find(r=>r instanceof pi),this._audioTracks.push(o),e||(e=this.context.mainCameraComponent?.gameObject.addComponent(ns)),o.listener=e.listener;for(let r=0;r<t.clips.length;r++){const a=t.clips[r];o.addModel(a)}}else if(t.type===si.Marker){const o=new sc;if(o.director=this,o.track=t,t.markers)for(const r of t.markers)switch(r.type){case Hg.Signal:o.models.push(r),o.didTrigger.push(!1);break}if(o!==null&&o.models.length>0){const r=S.getComponent(this.gameObject,Jc);r&&(o.receivers.push(r),this._signalTracks.push(o))}}else if(t.type===si.Signal){const o=new sc;if(o.director=this,o.track=t,t.markers)for(const r of t.markers)o.models.push(r),o.didTrigger.push(!1);for(const r of t.outputs)o.receivers.push(r);this._signalTracks.push(o)}else if(t.type===si.Control){const o=new ju;if(o.director=this,o.track=t,t.clips)for(const r of t.clips)o.models.push(r);o.resolveSourceObjects(this.context),this._controlTracks.push(o)}}}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)}};kw([f()],qg.prototype,"playOnAwake");kw([f()],qg.prototype,"extrapolationMode");let er=qg;var kE=Object.defineProperty,Bu=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&kE(e,t,n),n};class Pr extends k{isGizmo=!1;translationSnap=1;rotationSnapAngle=15;scaleSnap=.25;get control(){return this._control}_control;orbit;onEnable(){if(!(this.isGizmo&&!fc)&&this.context.mainCamera&&(this._control||(this._control=new q.TransformControls(this.context.mainCamera,this.context.renderer.domElement),this._control.enabled=!0,this._control.getRaycaster().layers.set(2),this._control.size=1,("_root"in this._control?this._control._root:this._control).traverse(t=>{const i=t;if(i.layers.set(2),i){const n=i.material;n&&(n.opacity=.3)}}),this.orbit=S.getComponentInParent(this.context.mainCamera,de)??void 0),this._control)){const e=this._control.getHelper();this.context.scene.add(e),this._control.attach(this.gameObject),this._control?.addEventListener("dragging-changed",this.onControlChangedEvent),window.addEventListener("keydown",this.windowKeyDownListener),window.addEventListener("keyup",this.windowKeyUpListener)}}onDisable(){this._control?.getHelper()?.removeFromParent(),this._control?.removeEventListener("dragging-changed",this.onControlChangedEvent),window.removeEventListener("keydown",this.windowKeyDownListener),window.removeEventListener("keyup",this.windowKeyUpListener)}enableSnapping(){this._control&&(this._control.setTranslationSnap(this.translationSnap),this._control.setRotationSnap(c.MathUtils.degToRad(this.rotationSnapAngle)),this._control.setScaleSnap(this.scaleSnap))}disableSnapping(){this._control&&(this._control.setTranslationSnap(null),this._control.setRotationSnap(null),this._control.setScaleSnap(null))}onControlChangedEvent=e=>{const t=this.orbit;if(t&&(t.enabled=!e.value),e.value){const i=this.gameObject.getComponentInParent(nn);i&&(i.fastMode=!0,i.requestOwnership())}else{const i=this.gameObject.getComponentInParent(nn);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}}}Bu([f()],Pr.prototype,"isGizmo");Bu([f()],Pr.prototype,"translationSnap");Bu([f()],Pr.prototype,"rotationSnapAngle");Bu([f()],Pr.prototype,"scaleSnap");var EE=Object.defineProperty,RE=Object.getOwnPropertyDescriptor,Fu=(s,e,t,i)=>{for(var n=i>1?void 0:i?RE(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&EE(e,t,n),n};class Xg{texture=null;rect}Fu([f(c.Texture)],Xg.prototype,"texture",2);let Ua=class extends Ic{set image(e){this.sprite||(this.sprite=new Xg),this.sprite.texture=e,this.onAfterCreated()}get image(){return this.sprite?this.sprite.texture:null}get sprite(){return this._sprite}set sprite(e){this._sprite!==e&&(this._sprite=e,this.onAfterCreated())}_sprite;pixelsPerUnitMultiplier=1;isBuiltinSprite(){const e=this.sprite;switch(e?.texture?.name){case"InputFieldBackground":case"UISprite":case"Background":case"Knob":return!0}return!e?.texture?.name?.length&&e?.texture?.image?.width===32&&e?.texture?.image?.height===32}onBeforeCreate(e){super.onBeforeCreate(e),this.isBuiltinSprite()&&(e.borderRadius=5/this.pixelsPerUnitMultiplier,this.sprite?.texture?.name==="Knob"&&(e.borderRadius=999))}onAfterCreated(){this.__didAwake&&(super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture(this.sprite?.texture))}};Fu([f(Xg)],Ua.prototype,"sprite",1);Fu([f()],Ua.prototype,"pixelsPerUnitMultiplier",2);class Uu extends Ic{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))}}Fu([f(c.Texture)],Uu.prototype,"mainTexture",1);var TE=Object.defineProperty,AE=Object.getOwnPropertyDescriptor,vi=(s,e,t,i)=>{for(var n=i>1?void 0:i?AE(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&TE(e,t,n),n};const xo=w("debugbutton");class mo{colorMultiplier;disabledColor;fadeDuration;highlightedColor;normalColor;pressedColor;selectedColor}vi([f()],mo.prototype,"colorMultiplier",2);vi([f(Z)],mo.prototype,"disabledColor",2);vi([f()],mo.prototype,"fadeDuration",2);vi([f(Z)],mo.prototype,"highlightedColor",2);vi([f(Z)],mo.prototype,"normalColor",2);vi([f(Z)],mo.prototype,"pressedColor",2);vi([f(Z)],mo.prototype,"selectedColor",2);class LE{disabledTrigger;highlightedTrigger;normalTrigger;pressedTrigger;selectedTrigger}class vs extends k{click(){this.onClick?.invoke()}onClick=new oe;_isHovered=0;onPointerEnter(e){const t=e.event.pointerType==="mouse"&&e.button===0;t&&(this._isHovered+=1),xo&&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),xo&&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){xo&&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){xo&&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===Gd.Mouse)&&(xo&&(console.warn("Button Click",this.onClick),Se("CLICKED button "+this.name+" at "+this.context.time.frameCount)),this.onClick&&this.onClick.listenerCount>0&&(this.onClick.invoke(),e.use(),xo))){const t=this.gameObject.worldPosition;t.add(this.gameObject.worldUp.multiplyScalar(1+Math.random()*.5)),B.DrawLabel(t,"CLICK:"+Date.now(),.1,1+Math.random()*.5)}}colors;transition;animationTriggers;animator;set interactable(e){this._interactable=e,this._image&&(this._image.setInteractable(e),e?this._image.setState("normal"):this._image.setState("disabled"))}get interactable(){return this._interactable}_interactable=!0;set_interactable(e){this.interactable=e}awake(){super.awake(),xo&&console.log(this),this._isInit=!1,this.init()}start(){this._image?.setInteractable(this.interactable),this.gameObject.getComponentInParent(ma)||this.gameObject.addComponent(su)}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=S.getComponent(this.gameObject,Ua),this._image&&(this.stateSetup(this._image),this.interactable?this._image.setState("normal"):this._image.setState("disabled")))}stateSetup(e){e.setInteractable(this.interactable);const t=this.getFinalColor(e.color,this.colors?.normalColor),i={state:"normal",attributes:{backgroundColor:t,backgroundOpacity:t.alpha}};e.setupState(i);const n=this.getFinalColor(e.color,this.colors?.highlightedColor),o={state:"hovered",attributes:{backgroundColor:n,backgroundOpacity:n.alpha}};e.setupState(o);const r=this.getFinalColor(e.color,this.colors?.pressedColor),a={state:"pressed",attributes:{backgroundColor:r,backgroundOpacity:r.alpha}};e.setupState(a);const l=this.getFinalColor(e.color,this.colors?.selectedColor),h={state:"selected",attributes:{backgroundColor:l,backgroundOpacity:l.alpha}};e.setupState(h);const d=this.getFinalColor(e.color,this.colors?.disabledColor),u={state:"disabled",attributes:{backgroundColor:d,backgroundOpacity:d.alpha}};e.setupState(u)}getFinalColor(e,t){return t?e.clone().multiply(t).convertLinearToSRGB():e.clone().convertLinearToSRGB()}}vi([f(oe)],vs.prototype,"onClick",2);vi([f(mo)],vs.prototype,"colors",2);vi([f()],vs.prototype,"transition",2);vi([f(LE)],vs.prototype,"animationTriggers",2);vi([f(rt)],vs.prototype,"animator",2);vi([f()],vs.prototype,"interactable",1);var DE=Object.defineProperty,zu=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&DE(e,t,n),n};const As=w("debuginputfield"),th=class W extends k{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 W.active===this}textComponent;placeholder;onValueChanged;onEndEdit;static active=null;static activeTime=-1;static htmlField=null;static htmlFieldFocused=!1;inputEventFn;_iosEventFn;start(){As&&console.log(this.name,this)}onEnable(){W.htmlField||(W.htmlField=document.createElement("input"),W.htmlField.style.width="0px",W.htmlField.style.height="0px",W.htmlField.style.padding="0px",W.htmlField.style.border="none",W.htmlField.style.overflow="hidden",W.htmlField.style.caretColor="transparent",W.htmlField.style.outline="none",W.htmlField.classList.add("ar"),W.htmlField.onfocus=()=>W.htmlFieldFocused=!0,W.htmlField.onblur=()=>W.htmlFieldFocused=!1,document.body.append(W.htmlField)),this.inputEventFn||(this.inputEventFn=this.onInput.bind(this)),W.htmlField.addEventListener("keyup",this.inputEventFn),this.placeholder&&this.textComponent?.text.length&&S.setActive(this.placeholder.gameObject,!1),exports.DeviceUtilities.isiOS()&&(this._iosEventFn=this.processInputOniOS.bind(this),window.addEventListener("click",this._iosEventFn))}onDisable(){W.htmlField?.removeEventListener("keyup",this.inputEventFn),this.onDeselected(),this._iosEventFn&&window.removeEventListener("click",this._iosEventFn)}clear(){W.active===this&&W.htmlField?(W.htmlField.value="",this.setTextFromInputField()):(this.textComponent&&(this.textComponent.text=""),this.placeholder&&S.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){As&&console.log("CLICK",e,W.active),W.activeTime=this.context.time.time,W.active!==this&&this.startCoroutine(this.activeLoop(),pe.LateUpdate),this.selectInputField()}*activeLoop(){for(this.onSelected();W.active===this&&!(this.context.input.getPointerClicked(0)&&this.context.time.time-W.activeTime>.2);)this.setTextFromInputField(),yield;this.onDeselected()}onSelected(){if(W.active!==this&&(As&&console.log("Select",this.name,this,W.htmlField,this.context.isInXR,this.context.arOverlayElement,this.textComponent?.text,W.htmlField?.value),W.active?.onDeselected(),W.active=this,this.placeholder&&S.setActive(this.placeholder.gameObject,!1),W.htmlField)){if(W.htmlField.value=this.textComponent?.text||"",As&&console.log("set input field value",W.htmlField.value),this.context.isInXR){const e=this.context.arOverlayElement;e&&e.append(W.htmlField)}this.selectInputField()}}onDeselected(){W.active===this&&(W.active=null,As&&console.log("Deselect",this.name,this),W.htmlField&&(W.htmlField.blur(),document.body.append(W.htmlField)),this.placeholder&&(!this.textComponent||this.textComponent.text.length<=0)&&S.setActive(this.placeholder.gameObject,!0),W.htmlField&&this.onEndEdit?.invoke(W.htmlField.value))}update(){W.active===this&&this.textComponent?.markDirty()}onInput(e){if(W.active===this){if(As&&console.log(e.code,e,W.htmlField?.value,this.textComponent?.text),e.code==="Escape"||e.code==="Enter"){this.onDeselected();return}W.htmlField&&(this.textComponent&&(this.setTextFromInputField(),this.placeholder&&S.setActive(this.placeholder.gameObject,this.textComponent.text.length<=0)),this.selectInputField())}}setTextFromInputField(){if(this.textComponent&&W.htmlField){const e=this.textComponent.text,t=W.htmlField.value,i=this.textComponent.text!==W.htmlField.value;this.textComponent.text=W.htmlField.value,i&&(As&&console.log("[InputField] value changed:",t,e),this.onValueChanged?.invoke(t,e))}}selectInputField(){W.htmlField&&(As&&console.log("Focus Inputfield",W.htmlFieldFocused),W.htmlField.setSelectionRange(W.htmlField.value.length,W.htmlField.value.length),exports.DeviceUtilities.isiOS()?W.htmlField.focus({preventScroll:!0}):setTimeout(()=>W.htmlField?.focus(),1))}processInputOniOS(){const e=this.context.physics.raycast();if(!e.length)return;const i=e[0].object,n=Im(i);(n?.gameObject===this.gameObject||n?.gameObject.parent===this.gameObject)&&this.selectInputField()}};zu([f(St)],th.prototype,"textComponent");zu([f(St)],th.prototype,"placeholder");zu([f(oe)],th.prototype,"onValueChanged");zu([f(oe)],th.prototype,"onEndEdit");let Qg=th;var IE=Object.defineProperty,Ew=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&IE(e,t,n),n};class ih extends k{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 q.InteractiveGroup;t.listenToPointerEvents(this.context.renderer,this.context.mainCamera),this.gameObject.add(t);const i=new q.HTMLMesh(e);t.add(i),i.visible=!1;const n=i.material;n.transparent=!0,setTimeout(()=>{i.visible=!0;const o=Nd(this.gameObject).clone();hc(this.gameObject,0,0,0),this.gameObject.updateMatrixWorld();const r=new c.Box3;r.setFromObject(t),this.setWorldRotation(o.x,o.y,o.z);const a=r.max.x-r.min.x,l=r.max.y-r.min.y;if(this.keepAspect){const d=a/l;a>l?i.scale.set(1/a,1/l/d,1):i.scale.set(1/a*d,1/l,1)}else i.scale.set(1/a,1/l,1);const h=this.gameObject.scale;i.scale.multiply(h)},1)}onDisable(){this._object?.removeFromParent()}}Ew([f()],ih.prototype,"id");Ew([f()],ih.prototype,"keepAspect");/* @license
|
|
1403
|
+
C) Set "joinRandomRoom" to true`),!1):(Xf&&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()):A()&&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(qf,this.context.connection.currentRoomViewId),window.location.origin+window.location.pathname+"?"+t.toString()}return null}setRandomRoomUrlParameter(){const e=rc(),t=this.generateRoomName();w(this.urlParameterName)?e.set(this.urlParameterName,t):e.append(this.urlParameterName,t),Qp(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&&Wl(this.urlParameterName,null),this.context.connection.leaveRoom(),this._userWantsToBeInARoom=!1;else{if(this.urlParameterName){const t=w(this.urlParameterName);(!t||t===!0)&&(this._lastJoinedRoom?Wl(this.urlParameterName,this._lastJoinedRoom):this.setRandomRoomUrlParameter())}this.tryJoinRoom()}},this._roomButtonIconJoin=pt("group"),this._roomButtonIconLeave=pt("group_off"),this.updateRoomButtonState(),this.context.connection.beginListen(Q.JoinedRoom,this.updateRoomButtonState),this.context.connection.beginListen(Q.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(Q.JoinedRoom,this.updateRoomButtonState),this.context.connection.stopListen(Q.LeftRoom,this.updateRoomButtonState)}_viewOnlyButton;onEnableViewOnlyButton(){this.context.connection.isConnected?this.onCreateViewOnlyButton():(this.context.connection.stopListen(Q.JoinedRoom,this.onCreateViewOnlyButton),this.context.connection.beginListen(Q.JoinedRoom,this.onCreateViewOnlyButton))}onDisableViewOnlyButton(){this.context.connection.stopListen(Q.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),Se("View only URL copied to clipboard")):he("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(pt("visibility"))}this.context.menu.appendChild(this._viewOnlyButton)}}po([f()],dn.prototype,"roomName",2);po([f()],dn.prototype,"urlParameterName",2);po([f()],dn.prototype,"joinRandomRoom",2);po([f()],dn.prototype,"requireRoomParameter",2);po([f()],dn.prototype,"autoRejoin",2);po([f()],dn.prototype,"createJoinButton",2);po([f()],dn.prototype,"createViewOnlyButton",2);po([f()],dn.prototype,"roomPrefix",1);function vE(){const s=w("testwindowcount")||0;s&&s>0&&wE(s)}function wE(s){if(w("testwindow"))return null;const e=new URL(window.location.href);ep(e.searchParams,yP,1),ep(e.searchParams,"testwindow",1);const t=e.toString(),i=[];window.onbeforeunload=()=>{for(const l of i)l.close()};const n=.05,o=128;let r=0,a=0;for(let l=0;l<s;l++){r*o+o*.01>=window.innerWidth&&(a+=1,r=0);const h=r*(o*(1+n))+window.screenLeft,d=a*(o*(1+n))+window.screenTop+90+60*a;r+=1;const u=window.open(t,"test window "+l,`popup=yes width=${o} height=${o} top=${d} left=${h}`);if(!u){console.warn("Failed to open window");continue}i.push(u),u.onload=()=>{u.onbeforeunload=()=>{for(let p=0;p<i.length;p++){const m=i[p];m!==u&&m.close()}i.length=0}}}return i}class Wg extends k{awake(){vE()}}class Gg extends k{transformsPerFrame=10;interval=0;useFlatbuffers=!0;awake(){if(this.useFlatbuffers)this.context.connection.beginListenBinary(Yl,e=>{});else{this.models=[];for(let e=0;e<this.transformsPerFrame;e++)this.models.push(new xE(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 se.Builder(1024));const e=this.builder;for(let t=0;t<this.transformsPerFrame;t++){e.clear();const i=o0(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 xE{guid;fast=!1;position;rotation;velocity=void 0;dontSave;isValid(){return this.fast!==void 0||this.position!==void 0||this.rotation!==void 0||this.velocity!==void 0}constructor(e,t){this.guid=e,this.position={x:0,y:0,z:0},this.rotation={x:0,y:0,z:0,w:0},this.update(t,null)}static temp=new c.Vector3;update(e,t){const i=e.worldPosition;this.position.x=i.x,this.position.y=i.y,this.position.z=i.z;const n=e.worldQuaternion;if(this.rotation.x=n.x,this.rotation.y=n.y,this.rotation.z=n.z,this.rotation.w=n.w,this.fast=!1,t){const o=t.getVelocity();this.velocity===void 0&&(this.velocity={x:0,y:0,z:0}),this.velocity.x=o.x,this.velocity.y=o.y,this.velocity.z=o.z}}}var SE=Object.defineProperty,Lu=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&SE(e,t,n),n};const CE=w("debugsignals");class Du{guid}Lu([f()],Du.prototype,"guid");class Zc{signal;reaction}Lu([f(Du)],Zc.prototype,"signal");Lu([f(oe)],Zc.prototype,"reaction");const Mw=class Yn extends k{static receivers={};static invoke(e){if(Yn.receivers[e]){const t=Yn.receivers[e];if(!t)return;for(const i of t)i.invoke(e)}}events;awake(){CE&&console.log("SignalReceiver awake",this)}onEnable(){if(this.events)for(const e of this.events)Yn.receivers[e.signal.guid]||(Yn.receivers[e.signal.guid]=[]),Yn.receivers[e.signal.guid].push(this)}onDisable(){if(this.events){for(const e of this.events)if(Yn.receivers[e.signal.guid]){const t=Yn.receivers[e.signal.guid].indexOf(this);t>=0&&Yn.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)}}};Lu([f(Zc)],Mw.prototype,"events");let Jc=Mw;var si=(s=>(s.Activation="ActivationTrack",s.Animation="AnimationTrack",s.Audio="AudioTrack",s.Control="ControlTrack",s.Marker="MarkerTrack",s.Signal="SignalTrack",s))(si||{}),gn=(s=>(s[s.None=0]="None",s[s.Hold=1]="Hold",s[s.Loop=2]="Loop",s[s.PingPong=3]="PingPong",s[s.Continue=4]="Continue",s))(gn||{}),Hg=(s=>(s.Signal="SignalEmitter",s))(Hg||{});const Mn=w("debugtimeline");class eh{director;track;get muted(){return this.track.muted}set muted(e){e!==this.track.muted&&(this.track.muted=e,this.onMuteChanged?.call(this))}*forEachClip(e=!1){if(this.track?.clips)if(e)for(let t=this.track.clips.length-1;t>=0;t--)yield this.track.clips[t];else for(const t of this.track.clips)yield t}getClipTime(e,t){return t.clipIn+(e-t.start)*t.timeScale}getClipTimeNormalized(e,t){return(e-t.start)/t.duration}evaluateWeight(e,t,i,n=!0){if(t<0||t>=i.length)return 0;const o=i[t];if(n||e>=o.start&&e<=o.end){let r=1;if(o.easeInDuration>0){const a=Math.min((e-o.start)/o.easeInDuration,1);r*=a}if(o.easeOutDuration>0){const a=Math.min((o.end-e)/o.easeOutDuration,1);r*=a}return r}return 0}}class PE{clip;rootPositionOffset;rootQuaternionOffset;get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}rootStartPosition;rootEndPosition;rootStartQuaternion;rootEndQuaternion;constructor(e){const t=e.getClip();this.clip=t;const i=e.getRoot(),n=i.name+".position",o=i.name+".quaternion";Mn&&console.log(t.name,t.tracks,n);for(const r of t.tracks)if(!(r.times.length<=0)){if(r.name.endsWith(n))this.rootStartPosition=new c.Vector3().fromArray(r.values,0),this.rootEndPosition=new c.Vector3().fromArray(r.values,r.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),Mn&&console.log(this.rootPositionOffset);else if(r.name.endsWith(o)&&(this.rootStartQuaternion=new c.Quaternion().fromArray(r.values,0),this.rootEndQuaternion=new c.Quaternion().fromArray(r.values,r.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),Mn)){const a=new c.Euler().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",a)}}}}class Iu extends eh{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&&r_(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],o=n+".position",r=n+".quaternion";let a=!1,l=!1;for(const h of t.tracks)h.name.endsWith(o)?(a=!0,this.createPositionInterpolant(t,e,h)):h.name.endsWith(r)&&(l=!0,this.createRotationInterpolant(t,e,h));if(!a||!l){const h=this.mixer?.getRoot(),d=t.tracks[0],u=d.name.lastIndexOf("."),p=d.name.substring(0,u),m=p.substring(p.lastIndexOf(".")+1),y=h.getObjectByName(m);if(y)if(a){if(!l){const b=t.tracks[0].name.substring(0,u)+".quaternion";Mn&&console.warn("Create quaternion track",m,y);const g=y.quaternion,v=new c.QuaternionKeyframeTrack(b,[0,t.duration],[g.x,g.y,g.z,g.w,g.x,g.y,g.z,g.w]);t.tracks.push(v),this.createRotationInterpolant(t,e,v)}}else{const b=p+".position";Mn&&console.warn("Create position track",m,y);const g=y.position,v=new c.VectorKeyframeTrack(b,[0,t.duration],[g.x,g.y,g.z,g.x,g.y,g.z]);t.tracks.push(v),this.createPositionInterpolant(t,e,v)}}}bind(){if(!this._didBind){this._didBind=!0,Mn&&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 PE(e);this._actionOffsets.push(t)}this.target&&(this._animator=S.getComponent(this.target,rt)??null,this._animator&&r_(this._animator.gameObject,this,!0));for(const e of this.models){const t=e.asset,i=t.position,n=t.rotation;i&&i.x!==void 0&&(i.isVector3||(t.position=new c.Vector3(i.x,i.y,i.z)),n.isQuaternion||(t.rotation=new c.Quaternion(n.x,n.y,n.z,n.w)))}this.ensureTrackOffsets()}}ensureTrackOffsets(){if(this.trackOffset){const e=this.trackOffset.position;e&&(e.isVector3||(this.trackOffset.position=new c.Vector3(e.x,e.y,e.z)));const t=this.trackOffset.rotation;t&&(t.isQuaternion||(this.trackOffset.rotation=new c.Quaternion(t.x,t.y,t.z,t.w)))}}_useclipOffsets=!0;_totalOffsetPosition=new c.Vector3;_totalOffsetRotation=new c.Quaternion;_totalOffsetPosition2=new c.Vector3;_totalOffsetRotation2=new c.Quaternion;_summedPos=new c.Vector3;_tempPos=new c.Vector3;_summedRot=new c.Quaternion;_tempRot=new c.Quaternion;_clipRotQuat=new c.Quaternion;evaluate(e){if(this.track.muted||!this.mixer)return;this.bind(),this._totalOffsetPosition.set(0,0,0),this._totalOffsetRotation.set(0,0,0,1),this._totalOffsetPosition2.set(0,0,0),this._totalOffsetRotation2.set(0,0,0,1);let t=0,i=0,n=!1,o=!1,r=0;for(let a=0;a<this.clips.length;a++){const l=this.models[a],h=this.actions[a],d=l.asset;h.weight=0;const u=e>=l.start&&e<=l.end,p=l.preExtrapolationMode,m=l.postExtrapolationMode,y=a<this.clips.length-1?this.models[a+1]:null;let b=u,g=!1;if(!b&&!n&&l.end<e&&m!==gn.None?(!y||y.start>e)&&(b=!0,n=!0):a==0&&!b&&!o&&l.start>e&&p!==gn.None&&(!y||y.start<e)&&(b=!0,g=!0,o=!0),b){let v=this.weight;v*=this.evaluateWeight(e,a,this.models,b),v*=this.director.weight;let _=u;if(g)switch(p){case gn.Hold:break;case gn.Loop:e+=l.start,_=!0;break;default:e+=l.start,_=!0;break}let x=this.getClipTime(e,l),T=0;const O=d.duration;if(g&&p===gn.Hold&&(x=0),_){if(d.loop)for(T+=Math.floor(x/(O+1e-6));x>O;)x-=O}else if(!u&&n)switch(m){case gn.Hold:x=this.getClipTime(l.end,l);break;case gn.Loop:x%=O;break;case gn.PingPong:const j=Math.floor(x/O)%2!==0;x%=O,j&&(x=O-x);break}l.reversed===!0?h.time=h.getClip().duration-x:h.time=x,h.timeScale=0;const M=Math.max(0,v);if(h.weight=M,r+=M,h.clampWhenFinished=!1,h.isRunning()||h.play(),this._useclipOffsets){const E=t==0?this._totalOffsetPosition:this._totalOffsetPosition2,j=t==0?this._totalOffsetRotation:this._totalOffsetRotation2;t<1&&(i=1-v),t+=1;const L=this._summedPos.set(0,0,0),z=this._tempPos.set(0,0,0),$=this._summedRot.identity(),R=this._tempRot.identity(),U=d.rotation;U&&(this._clipRotQuat.identity(),this._clipRotQuat.slerp(U,v));const N=this._actionOffsets[a];if(N.hasOffsets)for(let K=0;K<T;K++)N.rootPositionOffset?z.copy(N.rootPositionOffset):z.set(0,0,0),z.applyQuaternion($),this._clipRotQuat&&z.applyQuaternion(this._clipRotQuat),N.rootQuaternionOffset&&(R.copy(N.rootQuaternionOffset),$.multiply(R)),L.add(z);this._clipRotQuat&&j.multiply(this._clipRotQuat),j.multiply($),d.position&&L.add(d.position),E.add(L)}}}if(this._useclipOffsets&&(this._totalOffsetPosition.lerp(this._totalOffsetPosition2,i),this._totalOffsetRotation.slerp(this._totalOffsetRotation2,i)),this.__mixerError===void 0&&(Mn||A())&&this._animator?.runtimeAnimatorController?.mixer&&this.mixer!==this._animator?.runtimeAnimatorController?.mixer&&(this.__mixerError=!0,console.error("AnimationTrack mixer is not shared with the animator controller - this might result in the timeline to not animate properly. Please report a bug to the Needle Engine team!",this)),this._animator?.runtimeAnimatorController){const a=Math.max(0,1-r);this._animator?.runtimeAnimatorController?.update(a)}else this.mixer.update(e)}createRotationInterpolant(e,t,i){const n=i.createInterpolant.bind(i),o=new c.Quaternion;this.ensureTrackOffsets();const r=this.trackOffset?.rotation;i.createInterpolant=()=>{const a=n(),l=a.evaluate.bind(a);return a.evaluate=h=>{const d=l(h);if(o.set(d[0],d[1],d[2],d[3]),o.premultiply(this._totalOffsetRotation),r&&o.premultiply(r),this.director.animationCallbackReceivers)for(const u of this.director.animationCallbackReceivers)u?.onTimelineRotation?.call(u,this.director,this.target,h,o);return d[0]=o.x,d[1]=o.y,d[2]=o.z,d[3]=o.w,d},a}}createPositionInterpolant(e,t,i){const n=i.createInterpolant.bind(i),o=new c.Vector3;this.ensureTrackOffsets();const r=this.trackOffset?.rotation,a=this.trackOffset?.position;let l;i.createInterpolant=()=>{const h=n(),d=h.evaluate.bind(h);return h.evaluate=u=>{const p=d(u);if(o.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&&o.sub(l)),o.applyQuaternion(this._totalOffsetRotation),o.add(this._totalOffsetPosition),r&&o.applyQuaternion(r),a&&(o.x-=a.x,o.y+=a.y,o.z+=a.z),this.director.animationCallbackReceivers)for(const m of this.director.animationCallbackReceivers)m?.onTimelinePosition?.call(m,this.director,this.target,u,o);return p[0]=o.x,p[1]=o.y,p[2]=o.z,p},h}}}const OE=w("mutetimeline");class os extends eh{models=[];listener;audio=[];audioContextTimeOffset=[];lastTime=0;audioSource;_audioLoader=null;getAudioFilePath(e){const t=this.director.sourceId;return Js(t,e)}onAllowAudioChanged(e){for(let t=0;t<this.models.length;t++){const i=this.models[t];this.audio[t].setVolume(e?i.asset.volume:0)}}addModel(e){const t=new c.Audio(this.listener);this.audio.push(t);const i=e;i._didTriggerPlay=!1,this.models.push(i)}onDisable(){for(const e of this.audio)e.isPlaying&&e.stop();for(const e of this.models)e._didTriggerPlay=!1}onDestroy(){for(const e of this.audio)e.source&&e?.disconnect();this.audio.length=0}onMuteChanged(){if(this.muted)for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t?.isPlaying&&t.stop()}}stop(){for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t?.isPlaying&&t.stop()}for(const e of this.models)e._didTriggerPlay=!1}_playableDirectorResumed=!1;onPauseChanged(){for(let e=0;e<this.audio.length;e++){const t=this.audio[e];t?.isPlaying&&t.stop()}this._playableDirectorResumed=this.director.isPlaying}evaluate(e){if(OE||this.track.muted||this.director.speed<0)return;const t=this.director.context.application.muted,i=this._playableDirectorResumed;this._playableDirectorResumed=!1;const n=t?.1:0;for(let o=0;o<this.models.length;o++){const r=this.models[o],a=this.audio[o],l=r.asset;if((!a||!a.buffer)&&this.isInTimeRange(r,e-1,e+1)&&this.handleAudioLoading(r,a),pi.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,Mn&&console.log("Timeline Audio ("+this.track.name+") play with offset "+a.offset+" - "+r.asset.clip),a.play(n),r._didTriggerPlay=!0);else{const d=r.clipIn+(e-r.start)*r.timeScale,u=a.context.currentTime-a._startedAt+a.offset;Math.abs(d-u)>.3&&(a.offset=d,a.stop(),a.play(n))}let h=l.volume;if(this.track.volume!==void 0&&(h*=this.track.volume),t&&(h=0),r.easeInDuration>0){const d=Math.min((e-r.start)/r.easeInDuration,1);h*=d}if(r.easeOutDuration>0){const d=Math.min((r.end-e)/r.easeOutDuration,1);h*=d}a.setVolume(h*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 o=e-i,r=e+t;for(const a of this.models)if(this.isInTimeRange(a,o,r)){const l=this.audio[this.models.indexOf(a)],h=this.handleAudioLoading(a,l);h!==null&&(n===null&&(n=[]),n.push(h))}return n!==null?Promise.all(n):null}isInTimeRange(e,t,i){return t<=e.start&&i>=e.end||t>=e.start&&t<=e.end||i>=e.start&&i<=e.end}static _audioBuffers=new Map;static dispose(){os._audioBuffers.clear()}handleAudioLoading(e,t){this._audioLoader||(this._audioLoader=new c.AudioLoader);const i=this.getAudioFilePath(e.asset.clip);if(os._audioBuffers.get(i)){const o=os._audioBuffers.get(i);return o.then(r=>{r&&t.setBuffer(r)}),o}Mn&&console.warn("LOAD audio track",i,this.director.sourceId);const n=new Promise((o,r)=>{this._audioLoader.load(i,a=>{t.setBuffer(a),o(a)},void 0,a=>{console.error("Error loading audio",a),o(null)})});return os._audioBuffers.set(i,n),n}}class sc extends eh{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],o=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(!o)if(Mn&&console.log("Trigger signal",e,n.time,n),this.didTrigger[i]=!0,this.receivers?.length<=0)Jc.invoke(n.asset);else for(const l of this.receivers)l&&l.invoke(n.asset)}else n.emitOnce||(this.didTrigger[i]=!1)}}}class ju extends eh{models=[];timelines=[];resolveSourceObjects(e){for(let t=this.models.length-1;t>=0;t--){const n=this.models[t].asset;if(!n.sourceObject||typeof n.sourceObject!="object"){console.log("no source object, removing model",t,n),this.models.splice(t,1);continue}else{const o=S.getComponent(n.sourceObject,er);this.timelines.push(o),o&&n.updateDirector&&(o.playOnAwake=!1)}}}_previousActiveModel=null;evaluate(e){this._previousActiveModel=null;for(let t=0;t<this.models.length;t++){const i=this.models[t],n=i.asset;if(e>=i.start&&e<=i.end){this._previousActiveModel=i;const o=this.getClipTime(e,i);if(n.controlActivation){const r=n.sourceObject;r.visible=!0}if(n.updateDirector){const r=this.timelines[t];r&&(r.isPlaying&&r.pause(),r.time=o,r.evaluate())}}else{const o=this._previousActiveModel?.asset;if(n.controlActivation){const r=n.sourceObject;o?.sourceObject!==r&&(r.visible=!1)}}}}}var ME=Object.defineProperty,kw=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&ME(e,t,n),n};const Hn=w("debugtimeline"),qg=class $p extends k{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:(Hn||Ii())&&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(){Hn&&console.log(this,this.playableAsset?.tracks),this.rebuildGraph(),!this.isValid()&&(Hn||A())&&(Hn?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&&!pi.userInteractionRegistered&&this.waitForAudio;)await Ln(200)}this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine=this.startCoroutine(this.internalUpdate(),pe.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 si.Activation:if(!e&&!this._isPlaying)continue;for(let o=0;o<n.outputs.length;o++){const r=n.outputs[o];if(typeof r=="object"){let a=!1;if(n.clips)for(const h of n.clips)h.start<=i&&i<=h.end&&(a=!0);const l=r;l.visible!==void 0&&l.visible!==a&&(l.visible=a,Hn&&console.warn(this.name,"set ActivationTrack-"+o,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=ac(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 o=S.findByGuid(n,e);o===null||typeof o!="object"?(t.outputs.splice(i,1),console.warn("Failed to resolve binding",n,t.name,t.type)):(Hn&&console.log("Resolved binding",n,"to",o),t.outputs[i]=o)}else if(n===null){if(t.outputs.splice(i,1),$p.createTrackFunctions[t.type])continue;t.type!==si.Audio&&t.type!==si.Control&&t.type!==si.Marker&&t.type!==si.Signal&&console.warn("Missing binding",n,t.name,t.type,this.name,this.playableAsset.name)}}if(t.type===si.Control&&t.clips)for(let i=0;i<t.clips.length;i++){const n=t.clips[i];let o=n.asset.sourceObject;if(typeof o=="string"){this._guidsMap&&this._guidsMap[o]&&(o=this._guidsMap[o]);const r=S.findByGuid(o,e);r===null||typeof r!="object"?console.warn("Failed to resolve sourceObject binding",o,t.name,n):(Hn&&console.log("Resolved binding",o,"to",r),n.asset.sourceObject=r)}}}}findRoot(e){return e.parent?this.findRoot(e.parent):e}updateTimelineDuration(){if(this._duration=0,!(!this.playableAsset||!this.playableAsset.tracks)){for(const e of this.playableAsset.tracks)if(e.muted!==!0){if(e.clips)for(const t of e.clips)t.end>this._duration&&(this._duration=t.end);if(e.markers)for(const t of e.markers)t.time>this._duration&&(this._duration=t.time+.001)}}}setupAndCreateTrackHandlers(){if(this._animationTracks.length=0,this._audioTracks.length=0,this._signalTracks.length=0,!this.playableAsset)return;let e=S.findObjectOfType(ns,this.context);for(const t of this.playableAsset.tracks){const i=t.type,n=$p.createTrackFunctions[i];if(n!=null){const o=n(this,t);if(typeof o.evaluate=="function"){o.director=this,o.track=t,this._customTracks.push(o);continue}}if(t.type===si.Animation){if(!t.clips||t.clips.length<=0){Hn&&console.warn("Animation track has no clips",t);continue}for(let o=t.outputs.length-1;o>=0;o--){let r=t.outputs[o];if(r instanceof c.Object3D){const l=S.getOrAddComponent(r,rt);l&&(r=l)}const a=r?.gameObject?.animations;if(a){const l=new Iu;l.trackOffset=t.trackOffset,l.director=this,l.track=t;for(let h=0;h<t.clips.length;h++){const d=t.clips[h],u=d.asset;if(!u){console.error(`Timeline ${this.name}: clip #${h} on track "${t.name}" has no animation data`);continue}const p=u.clip;let m=p;if((typeof m=="string"||typeof m=="number")&&(m=a.find(b=>b.name===p)),Hn&&console.log(u,p,"→",m),!m){console.warn("Could not find animationClip for model",d,t.name,this.name,this.playableAsset?.name,a,r);continue}r instanceof rt&&r.runtimeAnimatorController&&(r.__internalDidAwakeAndStart||r.initializeRuntimeAnimatorController(),r.runtimeAnimatorController.mixer||r.runtimeAnimatorController.bind(r),l.mixer=r.runtimeAnimatorController.mixer),l.mixer||(l.mixer=new c.AnimationMixer(r.gameObject),this.context.animations.registerAnimationMixer(l.mixer)),l.clips.push(m),l.mixer.uncacheAction(m),l.createHooks(d.asset,m);const y=l.mixer.clipAction(m);l.actions.push(y),l.models.push(d)}this._animationTracks.push(l)}}}else if(t.type===si.Audio){if(!t.clips||t.clips.length<=0)continue;const o=new os;o.director=this,o.track=t,o.audioSource=t.outputs.find(r=>r instanceof pi),this._audioTracks.push(o),e||(e=this.context.mainCameraComponent?.gameObject.addComponent(ns)),o.listener=e.listener;for(let r=0;r<t.clips.length;r++){const a=t.clips[r];o.addModel(a)}}else if(t.type===si.Marker){const o=new sc;if(o.director=this,o.track=t,t.markers)for(const r of t.markers)switch(r.type){case Hg.Signal:o.models.push(r),o.didTrigger.push(!1);break}if(o!==null&&o.models.length>0){const r=S.getComponent(this.gameObject,Jc);r&&(o.receivers.push(r),this._signalTracks.push(o))}}else if(t.type===si.Signal){const o=new sc;if(o.director=this,o.track=t,t.markers)for(const r of t.markers)o.models.push(r),o.didTrigger.push(!1);for(const r of t.outputs)o.receivers.push(r);this._signalTracks.push(o)}else if(t.type===si.Control){const o=new ju;if(o.director=this,o.track=t,t.clips)for(const r of t.clips)o.models.push(r);o.resolveSourceObjects(this.context),this._controlTracks.push(o)}}}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)}};kw([f()],qg.prototype,"playOnAwake");kw([f()],qg.prototype,"extrapolationMode");let er=qg;var kE=Object.defineProperty,Bu=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&kE(e,t,n),n};class Pr extends k{isGizmo=!1;translationSnap=1;rotationSnapAngle=15;scaleSnap=.25;get control(){return this._control}_control;orbit;onEnable(){if(!(this.isGizmo&&!fc)&&this.context.mainCamera&&(this._control||(this._control=new q.TransformControls(this.context.mainCamera,this.context.renderer.domElement),this._control.enabled=!0,this._control.getRaycaster().layers.set(2),this._control.size=1,("_root"in this._control?this._control._root:this._control).traverse(t=>{const i=t;if(i.layers.set(2),i){const n=i.material;n&&(n.opacity=.3)}}),this.orbit=S.getComponentInParent(this.context.mainCamera,de)??void 0),this._control)){const e=this._control.getHelper();this.context.scene.add(e),this._control.attach(this.gameObject),this._control?.addEventListener("dragging-changed",this.onControlChangedEvent),window.addEventListener("keydown",this.windowKeyDownListener),window.addEventListener("keyup",this.windowKeyUpListener)}}onDisable(){this._control?.getHelper()?.removeFromParent(),this._control?.removeEventListener("dragging-changed",this.onControlChangedEvent),window.removeEventListener("keydown",this.windowKeyDownListener),window.removeEventListener("keyup",this.windowKeyUpListener)}enableSnapping(){this._control&&(this._control.setTranslationSnap(this.translationSnap),this._control.setRotationSnap(c.MathUtils.degToRad(this.rotationSnapAngle)),this._control.setScaleSnap(this.scaleSnap))}disableSnapping(){this._control&&(this._control.setTranslationSnap(null),this._control.setRotationSnap(null),this._control.setScaleSnap(null))}onControlChangedEvent=e=>{const t=this.orbit;if(t&&(t.enabled=!e.value),e.value){const i=this.gameObject.getComponentInParent(nn);i&&(i.fastMode=!0,i.requestOwnership())}else{const i=this.gameObject.getComponentInParent(nn);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}}}Bu([f()],Pr.prototype,"isGizmo");Bu([f()],Pr.prototype,"translationSnap");Bu([f()],Pr.prototype,"rotationSnapAngle");Bu([f()],Pr.prototype,"scaleSnap");var EE=Object.defineProperty,RE=Object.getOwnPropertyDescriptor,Fu=(s,e,t,i)=>{for(var n=i>1?void 0:i?RE(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&EE(e,t,n),n};class Xg{texture=null;rect}Fu([f(c.Texture)],Xg.prototype,"texture",2);let Ua=class extends Ic{set image(e){this.sprite||(this.sprite=new Xg),this.sprite.texture=e,this.onAfterCreated()}get image(){return this.sprite?this.sprite.texture:null}get sprite(){return this._sprite}set sprite(e){this._sprite!==e&&(this._sprite=e,this.onAfterCreated())}_sprite;pixelsPerUnitMultiplier=1;isBuiltinSprite(){const e=this.sprite;switch(e?.texture?.name){case"InputFieldBackground":case"UISprite":case"Background":case"Knob":return!0}return!e?.texture?.name?.length&&e?.texture?.image?.width===32&&e?.texture?.image?.height===32}onBeforeCreate(e){super.onBeforeCreate(e),this.isBuiltinSprite()&&(e.borderRadius=5/this.pixelsPerUnitMultiplier,this.sprite?.texture?.name==="Knob"&&(e.borderRadius=999))}onAfterCreated(){this.__didAwake&&(super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture(this.sprite?.texture))}};Fu([f(Xg)],Ua.prototype,"sprite",1);Fu([f()],Ua.prototype,"pixelsPerUnitMultiplier",2);class Uu extends Ic{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))}}Fu([f(c.Texture)],Uu.prototype,"mainTexture",1);var TE=Object.defineProperty,AE=Object.getOwnPropertyDescriptor,vi=(s,e,t,i)=>{for(var n=i>1?void 0:i?AE(e,t):e,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&TE(e,t,n),n};const xo=w("debugbutton");class mo{colorMultiplier;disabledColor;fadeDuration;highlightedColor;normalColor;pressedColor;selectedColor}vi([f()],mo.prototype,"colorMultiplier",2);vi([f(Z)],mo.prototype,"disabledColor",2);vi([f()],mo.prototype,"fadeDuration",2);vi([f(Z)],mo.prototype,"highlightedColor",2);vi([f(Z)],mo.prototype,"normalColor",2);vi([f(Z)],mo.prototype,"pressedColor",2);vi([f(Z)],mo.prototype,"selectedColor",2);class LE{disabledTrigger;highlightedTrigger;normalTrigger;pressedTrigger;selectedTrigger}class vs extends k{click(){this.onClick?.invoke()}onClick=new oe;_isHovered=0;onPointerEnter(e){const t=e.event.pointerType==="mouse"&&e.button===0;t&&(this._isHovered+=1),xo&&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),xo&&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){xo&&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){xo&&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===Gd.Mouse)&&(xo&&(console.warn("Button Click",this.onClick),Se("CLICKED button "+this.name+" at "+this.context.time.frameCount)),this.onClick&&this.onClick.listenerCount>0&&(this.onClick.invoke(),e.use(),xo))){const t=this.gameObject.worldPosition;t.add(this.gameObject.worldUp.multiplyScalar(1+Math.random()*.5)),B.DrawLabel(t,"CLICK:"+Date.now(),.1,1+Math.random()*.5)}}colors;transition;animationTriggers;animator;set interactable(e){this._interactable=e,this._image&&(this._image.setInteractable(e),e?this._image.setState("normal"):this._image.setState("disabled"))}get interactable(){return this._interactable}_interactable=!0;set_interactable(e){this.interactable=e}awake(){super.awake(),xo&&console.log(this),this._isInit=!1,this.init()}start(){this._image?.setInteractable(this.interactable),this.gameObject.getComponentInParent(ma)||this.gameObject.addComponent(su)}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=S.getComponent(this.gameObject,Ua),this._image&&(this.stateSetup(this._image),this.interactable?this._image.setState("normal"):this._image.setState("disabled")))}stateSetup(e){e.setInteractable(this.interactable);const t=this.getFinalColor(e.color,this.colors?.normalColor),i={state:"normal",attributes:{backgroundColor:t,backgroundOpacity:t.alpha}};e.setupState(i);const n=this.getFinalColor(e.color,this.colors?.highlightedColor),o={state:"hovered",attributes:{backgroundColor:n,backgroundOpacity:n.alpha}};e.setupState(o);const r=this.getFinalColor(e.color,this.colors?.pressedColor),a={state:"pressed",attributes:{backgroundColor:r,backgroundOpacity:r.alpha}};e.setupState(a);const l=this.getFinalColor(e.color,this.colors?.selectedColor),h={state:"selected",attributes:{backgroundColor:l,backgroundOpacity:l.alpha}};e.setupState(h);const d=this.getFinalColor(e.color,this.colors?.disabledColor),u={state:"disabled",attributes:{backgroundColor:d,backgroundOpacity:d.alpha}};e.setupState(u)}getFinalColor(e,t){return t?e.clone().multiply(t).convertLinearToSRGB():e.clone().convertLinearToSRGB()}}vi([f(oe)],vs.prototype,"onClick",2);vi([f(mo)],vs.prototype,"colors",2);vi([f()],vs.prototype,"transition",2);vi([f(LE)],vs.prototype,"animationTriggers",2);vi([f(rt)],vs.prototype,"animator",2);vi([f()],vs.prototype,"interactable",1);var DE=Object.defineProperty,zu=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&DE(e,t,n),n};const As=w("debuginputfield"),th=class W extends k{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 W.active===this}textComponent;placeholder;onValueChanged;onEndEdit;static active=null;static activeTime=-1;static htmlField=null;static htmlFieldFocused=!1;inputEventFn;_iosEventFn;start(){As&&console.log(this.name,this)}onEnable(){W.htmlField||(W.htmlField=document.createElement("input"),W.htmlField.style.width="0px",W.htmlField.style.height="0px",W.htmlField.style.padding="0px",W.htmlField.style.border="none",W.htmlField.style.overflow="hidden",W.htmlField.style.caretColor="transparent",W.htmlField.style.outline="none",W.htmlField.classList.add("ar"),W.htmlField.onfocus=()=>W.htmlFieldFocused=!0,W.htmlField.onblur=()=>W.htmlFieldFocused=!1,document.body.append(W.htmlField)),this.inputEventFn||(this.inputEventFn=this.onInput.bind(this)),W.htmlField.addEventListener("keyup",this.inputEventFn),this.placeholder&&this.textComponent?.text.length&&S.setActive(this.placeholder.gameObject,!1),exports.DeviceUtilities.isiOS()&&(this._iosEventFn=this.processInputOniOS.bind(this),window.addEventListener("click",this._iosEventFn))}onDisable(){W.htmlField?.removeEventListener("keyup",this.inputEventFn),this.onDeselected(),this._iosEventFn&&window.removeEventListener("click",this._iosEventFn)}clear(){W.active===this&&W.htmlField?(W.htmlField.value="",this.setTextFromInputField()):(this.textComponent&&(this.textComponent.text=""),this.placeholder&&S.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){As&&console.log("CLICK",e,W.active),W.activeTime=this.context.time.time,W.active!==this&&this.startCoroutine(this.activeLoop(),pe.LateUpdate),this.selectInputField()}*activeLoop(){for(this.onSelected();W.active===this&&!(this.context.input.getPointerClicked(0)&&this.context.time.time-W.activeTime>.2);)this.setTextFromInputField(),yield;this.onDeselected()}onSelected(){if(W.active!==this&&(As&&console.log("Select",this.name,this,W.htmlField,this.context.isInXR,this.context.arOverlayElement,this.textComponent?.text,W.htmlField?.value),W.active?.onDeselected(),W.active=this,this.placeholder&&S.setActive(this.placeholder.gameObject,!1),W.htmlField)){if(W.htmlField.value=this.textComponent?.text||"",As&&console.log("set input field value",W.htmlField.value),this.context.isInXR){const e=this.context.arOverlayElement;e&&e.append(W.htmlField)}this.selectInputField()}}onDeselected(){W.active===this&&(W.active=null,As&&console.log("Deselect",this.name,this),W.htmlField&&(W.htmlField.blur(),document.body.append(W.htmlField)),this.placeholder&&(!this.textComponent||this.textComponent.text.length<=0)&&S.setActive(this.placeholder.gameObject,!0),W.htmlField&&this.onEndEdit?.invoke(W.htmlField.value))}update(){W.active===this&&this.textComponent?.markDirty()}onInput(e){if(W.active===this){if(As&&console.log(e.code,e,W.htmlField?.value,this.textComponent?.text),e.code==="Escape"||e.code==="Enter"){this.onDeselected();return}W.htmlField&&(this.textComponent&&(this.setTextFromInputField(),this.placeholder&&S.setActive(this.placeholder.gameObject,this.textComponent.text.length<=0)),this.selectInputField())}}setTextFromInputField(){if(this.textComponent&&W.htmlField){const e=this.textComponent.text,t=W.htmlField.value,i=this.textComponent.text!==W.htmlField.value;this.textComponent.text=W.htmlField.value,i&&(As&&console.log("[InputField] value changed:",t,e),this.onValueChanged?.invoke(t,e))}}selectInputField(){W.htmlField&&(As&&console.log("Focus Inputfield",W.htmlFieldFocused),W.htmlField.setSelectionRange(W.htmlField.value.length,W.htmlField.value.length),exports.DeviceUtilities.isiOS()?W.htmlField.focus({preventScroll:!0}):setTimeout(()=>W.htmlField?.focus(),1))}processInputOniOS(){const e=this.context.physics.raycast();if(!e.length)return;const i=e[0].object,n=Im(i);(n?.gameObject===this.gameObject||n?.gameObject.parent===this.gameObject)&&this.selectInputField()}};zu([f(St)],th.prototype,"textComponent");zu([f(St)],th.prototype,"placeholder");zu([f(oe)],th.prototype,"onValueChanged");zu([f(oe)],th.prototype,"onEndEdit");let Qg=th;var IE=Object.defineProperty,Ew=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&IE(e,t,n),n};class ih extends k{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 q.InteractiveGroup;t.listenToPointerEvents(this.context.renderer,this.context.mainCamera),this.gameObject.add(t);const i=new q.HTMLMesh(e);t.add(i),i.visible=!1;const n=i.material;n.transparent=!0,setTimeout(()=>{i.visible=!0;const o=Nd(this.gameObject).clone();hc(this.gameObject,0,0,0),this.gameObject.updateMatrixWorld();const r=new c.Box3;r.setFromObject(t),this.setWorldRotation(o.x,o.y,o.z);const a=r.max.x-r.min.x,l=r.max.y-r.min.y;if(this.keepAspect){const d=a/l;a>l?i.scale.set(1/a,1/l/d,1):i.scale.set(1/a*d,1/l,1)}else i.scale.set(1/a,1/l,1);const h=this.gameObject.scale;i.scale.multiply(h)},1)}onDisable(){this._object?.removeFromParent()}}Ew([f()],ih.prototype,"id");Ew([f()],ih.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
|
-
`),A()&&dc("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(s.xr.getReferenceSpace());if(n)for(const o of n.views)if("camera"in o&&o.camera){let r=s.xr.getBinding();if(r||(r=new XRWebGLBinding(t.session,s.getContext())),r){let a=null;if("getCameraImage"in r){$E(s,e);const l=s.properties.get(e);if(l)return a=r.getCameraImage(o.camera),l.__webglTexture=a,!0;console.warn("No texture properties found for target texture")}}else console.error(o.camera,s.xr)}else console.error("NO CAMERA IN VIEW");else console.error(s.xr.getReferenceSpace(),t);return!1}const q_=new WeakMap;function $E(s,e){const t=q_.get(e)||new WeakSet;if(t.has(s))return;t.add(s),q_.set(e,t),console.debug("Initialize texture for camera feed");const i=new c.MeshBasicMaterial,n=new c.PlaneGeometry,o=new c.Scene;o.add(new c.Mesh(n,i));const r=new c.PerspectiveCamera;i.map=e,s.render(o,r)}function WE(s,e,t,i="image/webp",n){return Jg({context:s,width:e,height:t,mimeType:i,camera:n})}function Jg(s){s||(s={});const{transparent:e=!1}=s;let{mimeType:t,context:i,width:n,height:o,camera:r}=s;if(!i&&(i=ae.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!=pe.EarlyUpdate)return console.warn("Screenshot: defer to access XR frame"),new Promise(E=>{hs(j=>{const L=Jg(s);E(L)},pe.EarlyUpdate,{once:!0})});const h=a.domElement,d=h.width,u=h.height;n||(n=d),o||(o=u);const p=n,m=o;let y=window.devicePixelRatio||1,
|
|
1423
|
+
`),A()&&dc("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(s.xr.getReferenceSpace());if(n)for(const o of n.views)if("camera"in o&&o.camera){let r=s.xr.getBinding();if(r||(r=new XRWebGLBinding(t.session,s.getContext())),r){let a=null;if("getCameraImage"in r){$E(s,e);const l=s.properties.get(e);if(l)return a=r.getCameraImage(o.camera),l.__webglTexture=a,!0;console.warn("No texture properties found for target texture")}}else console.error(o.camera,s.xr)}else console.error("NO CAMERA IN VIEW");else console.error(s.xr.getReferenceSpace(),t);return!1}const q_=new WeakMap;function $E(s,e){const t=q_.get(e)||new WeakSet;if(t.has(s))return;t.add(s),q_.set(e,t),console.debug("Initialize texture for camera feed");const i=new c.MeshBasicMaterial,n=new c.PlaneGeometry,o=new c.Scene;o.add(new c.Mesh(n,i));const r=new c.PerspectiveCamera;i.map=e,s.render(o,r)}function WE(s,e,t,i="image/webp",n){return Jg({context:s,width:e,height:t,mimeType:i,camera:n})}function Jg(s){s||(s={});const{transparent:e=!1}=s;let{mimeType:t,context:i,width:n,height:o,camera:r}=s;if(!i&&(i=ae.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!=pe.EarlyUpdate)return console.warn("Screenshot: defer to access XR frame"),new Promise(E=>{hs(j=>{const L=Jg(s);E(L)},pe.EarlyUpdate,{once:!0})});const h=a.domElement,d=h.width,u=h.height;n||(n=d),o||(o=u);const p=n,m=o;let y=window.devicePixelRatio||1,b=1;i.devicePixelRatio==="auto"||i.devicePixelRatio==="manual"?b=1:b=i.devicePixelRatio/window.devicePixelRatio,y*=b,n/=y,o/=y,n=Math.floor(n),o=Math.floor(o),a.xr.isPresenting&&a.xr.getFrame();const g=a.xr.enabled;a.xr.enabled=!1,a.xr.isPresenting=!1,h.style.width=`${n}px`,h.style.height=`${o}px`;const v=a.getRenderTarget(),_=a.getClearColor(new c.Color),x=a.getClearAlpha(),T=i.scene.background,O="aspect"in r?r.aspect:null;try{const M=s.render_events!==!1,E=new Array;M&&(va(i.scene,mi,E),E.forEach(R=>{if(R?.onBeforeRender(),R.isInstancingActive&&R.instances)for(let U=0;U<R.instances?.length;U++){const N=R.instances[U];es(N.object,!0)}})),e&&(i.scene.background=null,a.setClearColor(0,0)),s.background&&(i.scene.background=null,a.setClearColor(s.background),s.background instanceof Z&&a.setClearAlpha(s.background.a)),e&&a.setClearAlpha(0),a.setSize(n,o,!1),"cam"in r&&(r=r.threeCamera),r instanceof c.PerspectiveCamera&&(r.aspect=n/o,r.updateProjectionMatrix());const j="type"in s&&s.type==="texture";let L=null;j&&(L=new c.WebGLRenderTarget(n,o,{wrapS:c.MirroredRepeatWrapping,wrapT:c.MirroredRepeatWrapping,format:1023}),a.setRenderTarget(L));let z=h;if(l?(L&&console.error('Taking XR screenshots with { type: "texture" } is currently not supported.'),z=exports.InternalScreenshotUtils.compositeWithCameraImage({width:p,height:m,scene:i.scene,camera:r,renderer:a})):i.renderNow(r||null),r instanceof c.PerspectiveCamera&&O!=null&&(r.aspect=O,r.updateProjectionMatrix()),M&&E.forEach(R=>R.onAfterRender()),!t&&"download_filename"in s&&s.download_filename)switch(s.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&&s.trim===!0){const R=GE(z);R&&(z=R)}if("type"in s){if(s.type==="texture")return L?(s.target&&(s.target.image=L?.texture.image,s.target.needsUpdate=!0),L.texture.offset.set(0,-1),L.texture.needsUpdate=!0,L.texture):(console.error("No target texture found"),null);if(s.type==="blob")return new Promise((U,N)=>{z.toBlob(K=>{U(K)},t)});if(s.type==="share")return new Promise((U,N)=>{z.toBlob(K=>{if(K&&"share"in navigator){let ee="file_type"in s&&s.file_type||t;t||(ee="image/png");const ce=ee?.split("/")[1]||"png",me=new File([K],"filename"in s?s.filename||`screenshot.${ce}`:`screenshot.${ce}`,{type:ee});return navigator.share({title:"title"in s?s.title:void 0,text:"text"in s?s.text:void 0,url:"url"in s?s.url:void 0,files:[me]}).catch(He=>{console.warn("User cancelled share",He.message)}).finally(()=>{U({blob:K,shared:!0})})}return{blob:K,shared:!1}},t)})}const $=z.toDataURL(t);if("download_filename"in s&&s.download_filename){let R=s.download_filename;if(exports.DeviceUtilities.isMobileDevice()&&typeof window<"u"){const U=R+"_screenshots",N=R.split("."),K=N.pop()?.toLowerCase();let ee=0;localStorage.getItem(U)&&(ee=parseInt(sessionStorage.getItem(U)||"0")),ee>0&&(R=`${N.join()}-${ee}.${K}`),ee+=1,sessionStorage.setItem(U,ee.toString())}Lw($,R)}return $}finally{a.setRenderTarget(v),i.scene.background=T,a.setSize(d,u,!1),a.setClearColor(_,x),O!=null&&r instanceof c.PerspectiveCamera&&(r.aspect=O,r.updateProjectionMatrix()),a.xr.enabled=g,a.xr.isPresenting=l,l||i.updateSize(!0)}return null}function GE(s){if(!("document"in globalThis))return null;const e=document.createElement("canvas");e.width=s.width,e.height=s.height;const t=e.getContext("2d");if(!t)return null;t.drawImage(s,0,0);const i=e.width,n=e.height,r=t.getImageData(0,0,i,n).data;let a=n,l=i,h=0,d=0;for(let b=0;b<n;b++)for(let g=0;g<i;g++){const v=(b*i+g)*4;r[v+3]!==0&&(g<l&&(l=g),g>d&&(d=g),b<a&&(a=b),b>h&&(h=b))}const u=d-l+1,p=h-a+1,m=document.createElement("canvas"),y=m.getContext("2d");return y?(m.width=u,m.height=p,y.drawImage(e,l,a,u,p,0,0,u,p),m):null}let sl=null;function Lw(s,e){if(s){if(!s.startsWith("data:image")){console.error("Can not save image: Data url is not an image",s);return}sl||(sl=document.createElement("a")),sl.href=s,sl.download=e,sl.click()}}exports.InternalScreenshotUtils=void 0;(s=>{let e=null,t=null,i=null,n=null,o=null;function r(h){const{renderer:d,width:u,height:p}=h,m=d.xr.enabled,y=d.getRenderTarget(),b=d.autoClear,g=u,v=p,_=u/p;(!i||i.width!==g||i.height!==v)&&(i??=new c.WebGLRenderTarget(g,v,{colorSpace:c.SRGBColorSpace}),i.width=g,i.height=v,i.samples=4,i.texture.repeat.y=-1,i.texture.offset.y=1),(!o||o.width!==g||o.height!==v)&&(o=document.createElement("canvas"),o.width=g,o.height=v,o.style.position="fixed",o.style.top="0px",o.style.right="0px",o.style.width="300px",o.style.height=`${300/_}px`,o.style.zIndex="1000",o.style.pointerEvents="none",o.style.opacity="1.0",o.style.willChange="contents"),e||(e=l({defines:{DECODE_VIDEO_TEXTURE:!0}})),t||(t=l()),n||(n=new c.Texture),d.xr.updateCamera(h.camera),d.xr.enabled=!1,d.autoClear=!1,d.clear(),d.setSize(g,v),d.setRenderTarget(i),Aw(h.renderer,n)||console.error("Could not update texture from XR frame");const T=S.findObjectOfType(oh);return T?T.setTexture(n):(e.setTexture(n),d.render(e,h.camera)),d.clearDepth(),d.setSize(g,v),d.render(h.scene,h.camera),d.setRenderTarget(null),t.setTexture(i.texture),d.render(t,h.camera),o.getContext("2d",{alpha:!1}).drawImage(d.domElement,0,0,o.width,o.height),d.setRenderTarget(y),d.xr.enabled=m,d.autoClear=b,o}s.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 QE=Object.defineProperty,go=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&QE(e,t,n),n};const Fd=w("debugimagetracking");class ba{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 di(()=>new c.Vector3,20);static _rotationBuffer=new di(()=>new c.Quaternion,20);_position;_rotation;ensureTransformData(){if(!this._position){this._position=ba._positionBuffer.get(),this._rotation=ba._rotationBuffer.get();const e=this._pose.transform,t=H.active.convertSpace(e);this._position.copy(t?.position),this._rotation.copy(t?.quaternion)}}_trackingComponent;_trackedImage;_bitmap;_pose;constructor(e,t,i,n,o,r){this._trackingComponent=e,this._trackedImage=t,this._bitmap=i,this.measuredSize=n,this.state=o,this._pose=r}}class xs{constructor(e){this.image=e.url,this.widthInMeters=e.widthInMeters,e.object instanceof c.Object3D?this.object=new Y({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}}go([f(URL)],xs.prototype,"image");go([f()],xs.prototype,"widthInMeters");go([f(Y)],xs.prototype,"object");go([f()],xs.prototype,"createObjectInstance");go([f()],xs.prototype,"imageDoesNotMove");go([f()],xs.prototype,"hideWhenTrackingIsLost");class YE{constructor(e,t){this.exporter=e,this.component=t,Fd&&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&&(Fd||A())&&(he("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=exports.DeviceUtilities.getiOSVersion(),r=(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*r).toFixed(8)),t.closeBlock()}async onAfterSerialize(e){if(!this.shouldExport)return;const t=this.imageModel,i=Nl.get(t.image),r=await(await(await q0(i)).convertToBlob({type:"image/png"})).arrayBuffer();e.files["image_tracking/"+this.filename]=new Uint8Array(r)}onExportObject(e,t,i){if(!this.shouldExport)return;const n=this.component;if(!n||!n.trackedImages?.length||!n.activeAndEnabled)return;const o=n.trackedImages[0];if(o.object?.asset===e){this.imageModel=o,this.filename=o.getNameFromUrl()||"marker.png";const{scale:r,target:a}=this.exporter.getARScaleAndTarget();let l=e;const h=new c.Matrix4;if(e!==a)for(;l&&l.parent&&l.parent!==a;)l=l.parent,h.premultiply(l.matrix);const d=h.clone().invert();t.setMatrix(d.scale(new c.Vector3(r,r,r)))}}}class rh extends k{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),Q_(e.image)),t&&this.setPrimaryImage(e)}trackedImages=[];smooth=!0;trackedImageIndexMap=new Map;get supported(){return this._supported}_supported=!0;awake(){if(Fd&&console.log(this),!!this.trackedImages)for(const e of this.trackedImages)e.image&&Q_(e.image)}onEnable(){Tn.beforeExport.addEventListener(this.onBeforeUSDZExport)}onDisable(){Tn.beforeExport.removeEventListener(this.onBeforeUSDZExport)}onBeforeUSDZExport=e=>{this.activeAndEnabled&&this.trackedImages?.length&&e.exporter.extensions.push(new YE(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=Nl.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&&exports.DeviceUtilities.isAndroidDevice()&&he(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 o=this.context.renderer.xr.getReferenceSpace();if(o){for(const r of n){const a=r.trackingState,l=r.index,h=this.trackedImageIndexMap.get(l);if(h){const d=t.getPose(r.imageSpace,o),u=new ba(this,h,r.image,r.measuredSize,a,d);this.currentImages.push(u)}else Fd&&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,he(this.webXRIncubationsWarning);return}const i=1e3;for(const[n,o]of this.imageToObjectMap){if(!o.object||!n||n.hideWhenTrackingIsLost===!1)continue;let r=!1;for(const a of this.currentImages)if(a.model===n){const l=Date.now()-o.lastTrackingTime;if(n.imageDoesNotMove||a.state==="tracked"||l<=i){r=!0;break}}r||S.setActive(o.object,!1)}}onImageTrackingUpdate=e=>{const t=H.active;if(t)for(const i of e){const n=i.model,o=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=S.instantiate(a)),a){r.object=a;for(const l of a.getComponentsInChildren(mi))l.setInstancingEnabled(!1);t.rig?(t.rig.gameObject.add(a),i.applyToObject(a),a.activeSelf||S.setActive(a,!0)):console.warn("XRImageTracking: missing XRRig")}});else{if(r.frames++,o&&(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||S.setActive(r.object,!0))}}}}go([f(xs)],rh.prototype,"trackedImages");go([f()],rh.prototype,"smooth");const Nl=new Map,zh=new Map;async function Q_(s){if(Nl.has(s))return zh.has(s)?zh.get(s):Promise.resolve(!0);const e=new Promise(t=>{Nl.set(s,null);const i=document.createElement("img");i.src=s,i.addEventListener("load",async()=>{const n=await createImageBitmap(i);Nl.set(s,n),t(!0)})});return zh.set(s,e),e.finally(()=>{zh.delete(s)}),e}var KE=Object.defineProperty,$a=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&KE(e,t,n),n};const So=w("debugplanetracking");class Ss extends k{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 r=i.detectedPlanes,a=i.detectedMeshes,l=r!==void 0&&r.size>0,h=a!==void 0&&a.size>0;if(this.initiateRoomCaptureIfNoData&&(!l&&!h&&this.firstTimeNoPlanesDetected<-10&&(this.firstTimeNoPlanesDetected=Date.now()),(l||h)&&(this.firstTimeNoPlanesDetected=-1),this.firstTimeNoPlanesDetected>0&&Date.now()-this.firstTimeNoPlanesDetected>2500&&"initiateRoomCapture"in i.session&&(i.session.initiateRoomCapture(),this.firstTimeNoPlanesDetected=-1)),r!==void 0&&this.processFrameData(e.xr,t.gameObject,i,r,this._allPlanes),a!==void 0&&this.processFrameData(e.xr,t.gameObject,i,a,this._allMeshes),So){const d=this.context.mainCameraComponent.gameObject.worldPosition;for(const u of this._allPlanes.values())!u.mesh||!u.mesh.visible||(this.bounds.makeEmpty(),u.mesh.traverse(p=>{p instanceof c.Mesh&&this.bounds.expandByObject(p)}),this.bounds.getCenter(this.center),this.labelOffset.copy(d).sub(this.center).normalize().multiplyScalar(.1),B.DrawLabel(this.center.add(this.labelOffset),(u.xrData.semanticLabel||"plane").toUpperCase()+`
|
|
1462
|
-
`+u.xrData.lastChangedTime.toFixed(2),.02))}}bounds=new c.Box3;center=new c.Vector3;labelOffset=new c.Vector3;removeData(e,t){const i=t.get(e);if(!i)return;t.delete(e),So&&console.log("Plane no longer tracked, id="+i.id),i.mesh&&(i.mesh.removeFromParent(),i.mesh.traverse(o=>{const r=o.userData.normalsHelper;r?(r.dispose(),r.removeFromParent()):So&&console.warn("No normals helper found for mesh",i.mesh)}),ui(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,o){const a=this.context.renderer.xr.getReferenceSpace();if(a){for(const l of o.keys())n.has(l)||this.removeData(l,o);for(const l of n){const h="planeSpace"in l?l.planeSpace:"meshSpace"in l?l.meshSpace:void 0;if(!h)continue;const d=i.getPose(h,a);let u;if(o.has(l)){const p=o.get(l);if(u=p.mesh,p.timestamp<l.lastChangedTime){if(p.timestamp=l.lastChangedTime,p.mesh){const y=this.createGeometry(l);if(p.mesh instanceof c.Mesh)p.mesh.geometry.dispose(),p.mesh.geometry=y,this.makeOccluder(p.mesh,p.mesh.material);else if(p.mesh instanceof c.Group)for(const _ of p.mesh.children)_ instanceof c.Mesh&&(_.geometry.dispose(),_.geometry=y,this.makeOccluder(_,_.material));if(p.collider){const _=p.mesh;p.collider.sharedMesh=_,p.collider.convex=this.checkIfContextShouldBeConvex(_,p.xrData),p.collider.onDisable(),p.collider.onEnable()}So&&(console.log("Plane updated, id="+p.id,p),p.mesh.traverse(_=>{if(!(_ instanceof c.Mesh))return;const g=_.userData.normalsHelper;g&&g.update()}))}const m=new CustomEvent("plane-tracking",{detail:{type:"plane-updated",context:p}});this.dispatchEvent(m)}}else{if(!this.dataTemplate){const p=new c.Mesh;So?p.material=new c.MeshNormalMaterial:this.occluder?(p.material=new c.MeshBasicMaterial,this.makeOccluder(p,p.material,!0)):p.material=new c.MeshBasicMaterial({wireframe:!0,opacity:.5,transparent:!0,color:3355443}),this.dataTemplate=new Y("","",p)}if(!this.dataTemplate.asset)this.dataTemplate.loadAssetAsync();else{const p=S.instantiate(this.dataTemplate.asset);if(p.name="xr-tracked-plane",u=p,sm(p,!1),p instanceof c.Mesh)_e(p.geometry),p.geometry=this.createGeometry(l),this.makeOccluder(p,p.material,this.occluder&&!this.dataTemplate);else if(p instanceof c.Group)for(const _ of p.children)_ instanceof c.Mesh&&(_e(_.geometry),_.geometry=this.createGeometry(l),this.makeOccluder(_,_.material,this.occluder&&!this.dataTemplate));const m=p.getComponent(so);if(m){const _=p;m.sharedMesh=_,m.convex=this.checkIfContextShouldBeConvex(_,l),m.onDisable(),m.onEnable()}p.matrixAutoUpdate=!1,p.matrixWorldNeedsUpdate=!0,t.add(p);const y={id:this._dataId++,xrData:l,timestamp:l.lastChangedTime,mesh:p,collider:m};o.set(l,y),So&&console.log("New plane detected, id="+y.id,y,{hasCollider:!!m,isGroup:p instanceof c.Group});try{const _=new CustomEvent("plane-tracking",{detail:{type:"plane-added",context:y}});this.dispatchEvent(_)}catch(_){console.error(_)}}}u&&(d?(u.visible=!0,u.matrix.fromArray(d.transform.matrix),u.matrix.premultiply(this._flipForwardMatrix)):u.visible=!1,So&&u.traverse(p=>{if(p instanceof c.Mesh)if(p.userData.normalsHelper)p.userData.normalsHelper.update();else{const m=new q.VertexNormalsHelper(p,.05,255);m.layers.disableAll(),m.layers.set(2),this.context.scene.add(m),p.userData.normalsHelper=m}}))}}}_flipForwardMatrix=new c.Matrix4().makeRotationY(Math.PI);checkIfContextShouldBeConvex(e,t){if(!e)return!0;if(e){const i=new c.Box3;i.expandByObject(e);const n=new c.Vector3;i.getSize(n);let o=!0;return n.x>2&&n.y>2&&n.z>1.5&&(o=!1),o&&"semanticLabel"in t&&t.semanticLabel==="wall"&&(o=!0),o}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 c.BufferGeometry}_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 c.BufferGeometry;n.setIndex(new c.BufferAttribute(t,1)),n.setAttribute("position",new c.BufferAttribute(e,3));const o=Array();for(let r=0;r<e.length;r+=3)o.push(e[r],e[r+2]);return n.setAttribute("uv",new c.BufferAttribute(e,3)),n.computeVertexNormals(),this._verticesCache.set(i,n),n}createPlaneGeometry(e){const t=new c.BufferGeometry,i=[],n=[];e.forEach(p=>{i.push(p.x,p.y,p.z),n.push(p.x,p.z)});const o=new c.Vector3(i[0],i[1],i[2]),r=new c.Vector3(i[3],i[4],i[5]),a=new c.Vector3(i[6],i[7],i[8]),l=new c.Vector3,h=new c.Vector3;l.subVectors(r,o),h.subVectors(a,o),l.cross(h),l.normalize();const d=[];for(let p=0;p<i.length/3;p++)d.push(l.x,l.y,l.z);const u=[];for(let p=2;p<e.length;++p)u.push(0,p-1,p);return t.setAttribute("position",new c.BufferAttribute(new Float32Array(i),3)),t.setAttribute("uv",new c.BufferAttribute(new Float32Array(n),2)),t.setAttribute("normal",new c.BufferAttribute(new Float32Array(d),3)),t.setIndex(u),t.computeBoundingBox(),t.computeBoundingSphere(),t}}$a([f(Y)],Ss.prototype,"dataTemplate");$a([f()],Ss.prototype,"occluder");$a([f()],Ss.prototype,"initiateRoomCaptureIfNoData");$a([f()],Ss.prototype,"usePlaneData");$a([f()],Ss.prototype,"useMeshData");$a([f()],Ss.prototype,"runInVR");var ZE=Object.defineProperty,JE=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&ZE(e,t,n),n};const Y_=w("debugwebxr");class Wu extends k{priority=0;get isActive(){return this.activeAndEnabled&&this.gameObject.visible}setAsActiveXRRig(){H.active?.setRigActive(this)}setPriority(e){this.priority=e}awake(){if(Y_){const e=new c.Object3D;e.position.y+=.5,this.gameObject.add(e);const t=e.addNewComponent(mr);t&&(t.isGizmo=!1);const i=new c.AxesHelper(.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),Y_&&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)}}JE([f()],Wu.prototype,"priority");class eR extends k{toggleKey="KeyP";update(){this.context.input.isKeyDown(this.toggleKey)&&this.context.domElement.classList.toggle("presentation-mode")}}P.add("AlignmentConstraint",vc);P.add("Animation",Ft);P.add("Animator",rt);P.add("AudioListener",ns);P.add("AudioSource",pi);P.add("Avatar_Brain_LookAt",Zl);P.add("Avatar_MouthShapes",Cc);P.add("Avatar_MustacheShake",Fm);P.add("AvatarBlink_Simple",ar);P.add("AvatarEyeLook_Rotation",zm);P.add("AxesHelper",xa);P.add("BasicIKConstraint",Vm);P.add("BoxHelperComponent",nt);P.add("Camera",qt);P.add("CharacterController",lr);P.add("CharacterControllerInput",us);P.add("Collider",Kt);P.add("SphereCollider",Sa);P.add("BoxCollider",lu);P.add("MeshCollider",so);P.add("CapsuleCollider",ls);P.add("ContactShadows",Pc);P.add("LogStats",Wm);P.add("DeleteBox",Gs);P.add("Deletable",Hm);P.add("DeviceFlag",cu);P.add("DragControls",Ro);P.add("DropListener",fs);P.add("Duplicatable",Qm);P.add("EventListEvent",nu);P.add("EventTrigger",du);P.add("GltfExportBox",ig);P.add("GltfExport",sg);P.add("VariantAction",ag);P.add("ChangeTransformOnClick",ur);P.add("ChangeMaterialOnClick",lg);P.add("SetActiveOnClick",cg);P.add("HideOnStart",Ei);P.add("EmphasizeOnClick",Oa);P.add("PlayAudioOnClick",Qs);P.add("PlayAnimationOnClick",ec);P.add("PreliminaryAction",Ma);P.add("PreliminaryTrigger",Rc);P.add("VisibilityAction",Tc);P.add("TapGestureTrigger",dg);P.add("USDZExporter",Tn);P.add("Fog",Ta);P.add("BoxGizmo",mr);P.add("GridHelper",Aa);P.add("GroundProjectedEnv",In);P.add("UsageMarker",Oc);P.add("Interactable",Gm);P.add("FixedJoint",Tg);P.add("HingeJoint",jc);P.add("Light",ei);P.add("LODGroup",Fc);P.add("LookAtConstraint",rr);P.add("NeedleMenu",Bn);P.add("NestedGltf",Uc);P.add("Networking",Lg);P.add("OffsetConstraint",gr);P.add("CameraTargetReachedEvent",Kl);P.add("OrbitControls",de);P.add("ParticleSystemRenderer",Vi);P.add("ParticleSystem",ic);P.add("Attractor",Ia);P.add("PlayerColor",_a);P.add("Antialiasing",Vc);P.add("BloomEffect",Ou);P.add("ChromaticAberration",$c);P.add("ColorAdjustments",uo);P.add("DepthOfField",ln);P.add("EffectWrapper",nc);P.add("PixelationEffect",Wc);P.add("ScreenSpaceAmbientOcclusion",bs);P.add("ScreenSpaceAmbientOcclusionN8",cn);P.add("SharpeningEffect",Hc);P.add("TiltShiftEffect",zn);P.add("ToneMappingEffect",Zs);P.add("Vignette",xr);P.add("Volume",Ba);P.add("ReflectionProbe",Jl);P.add("Renderer",mi);P.add("MeshRenderer",Mc);P.add("SkinnedMeshRenderer",tg);P.add("Rigidbody",Ne);P.add("SceneSwitcher",je);P.add("ScreenCapture",fo);P.add("ShadowCatcher",Xc);P.add("RemoteSkybox",ku);P.add("SmoothFollow",Ru);P.add("SpatialTriggerReceiver",An);P.add("SpatialTrigger",Tu);P.add("SpectatorCamera",Au);P.add("SplineContainer",Sr);P.add("SplineWalker",hn);P.add("SpriteRenderer",Zt);P.add("SyncedCamera",$g);P.add("SyncedRoom",dn);P.add("SyncedTransform",nn);P.add("TestRunner",Wg);P.add("TestSimulateUserData",Gg);P.add("PlayableDirector",er);P.add("SignalReceiver",Jc);P.add("AnimationTrackHandler",Iu);P.add("AudioTrackHandler",os);P.add("SignalTrackHandler",sc);P.add("ControlTrackHandler",ju);P.add("TransformGizmo",Pr);P.add("BaseUIComponent",Bi);P.add("UIRootComponent",Ac);P.add("Button",vs);P.add("Canvas",ya);P.add("CanvasGroup",Ks);P.add("EventSystem",jt);P.add("Graphic",Dc);P.add("MaskableGraphic",Ic);P.add("Image",Ua);P.add("RawImage",Uu);P.add("InputField",Qg);P.add("VerticalLayoutGroup",wg);P.add("HorizontalLayoutGroup",xg);P.add("GridLayoutGroup",Sg);P.add("Outline",Ra);P.add("ObjectRaycaster",fi);P.add("GraphicRaycaster",su);P.add("SpatialGrabRaycaster",Qo);P.add("RectTransform",sn);P.add("SpatialHtml",ih);P.add("Text",St);P.add("EnvironmentScene",Nu);P.add("LookAt",Yg);P.add("OpenURL",za);P.add("VideoPlayer",Ze);P.add("Voip",no);P.add("ClickThrough",$u);P.add("CursorFollow",sh);P.add("ScrollFollow",Zg);P.add("Avatar",Ys);P.add("XRControllerFollow",ws);P.add("XRControllerModel",cs);P.add("XRControllerMovement",gi);P.add("TeleportTarget",_u);P.add("WebARCameraBackground",oh);P.add("WebARSessionRoot",hi);P.add("WebXR",bu);P.add("AvatarMarker",xe);P.add("WebXRImageTracking",rh);P.add("WebXRPlaneTracking",Ss);P.add("XRRig",Wu);P.add("XRFlag",Ti);P.add("PlayerSync",mg);P.add("PlayerState",Yi);P.add("PresentationMode",eR);const Vl=st,tR=w("debugtypestore");tR&&console.log(P);function iR(s,e){const i=_v(s,e);return i!==void 0?i:null}const nR=new bC,Qf=Symbol("deserialize-queue");async function sR(s,e,t,i=null,n){if(!t){console.debug("Can not create component instances: gltf is null");return}const o=[];let r=i;typeof r=="number"&&(r=new mt(i));const a=e.indexOf("?");e=a===-1?e:e.substring(0,a);const l=new Pm(t.scene);l.gltfId=e,l.context=s,l.gltf=t,l.nodeToObject=n?.nodeToObjectMap,l.implementationInformation=nR;let h=s[Qf];if(h||(h=s[Qf]=[]),t.scenes)for(const d of t.scenes)await qp(l,d,h,o,0);if(t.children)for(const d of t.children)await qp(l,d,h,o,0);s.new_scripts_pre_setup_callbacks.push(()=>{const d=s[Qf];if(d){for(const u of d)oR(u,l);d.length=0}if(r){const u={},p=[];Hp(t,r,u,p);for(const m of t.scenes)Hp(m,r,u,p);for(const m of p)m.resolveGuids(u)}})}const Gp=Symbol("original-component-name"),Ir=new Map;function Hp(s,e,t,i){if(e===null||!s)return;const n=s.guid,o=s.guid;o?.length&&(Ir.has(o)||(Vl&&console.log('Creating InstanceIdProvider with key "'+o+'" for object '+s.name),Ir.set(o,new mt(o))));const r=o&&Ir.get(o)||e;if(s.guid=r.generateUUID(),n&&n!=="invalid"&&(t[n]=s.guid),s&&s.userData&&s.userData.components)for(const a of s.userData.components){if(a===null)continue;const l=a.guid;l?Ir.has(l)||(Vl&&console.log('Creating InstanceIdProvider with key "'+l+'" for component '+a[Gp]),Ir.set(l,new mt(l))):Vl&&console.warn("Can not create IdProvider: component "+a[Gp]+" has no guid",a.guid);const h=Ir.get(l)||e,d=a.guid;a.guid=h.generateUUID(),d&&d!=="invalid"&&(t[d]=a.guid),a.resolveGuids&&i.push(a)}if(s.children)for(const a of s.children)Hp(a,e,t,i)}const ol=[];async function qp(s,e,t,i,n){if(!e)return;const o=e.userData;if(o){const r=o.builtin_components;if(r&&r.length>0)for(const a of r)try{if(a===null)continue;const l=P.get(a.name);if(l!=null){const h=new l;h.sourceId=s.gltfId,ua(h,a,s.implementationInformation),h.context=s.context,"guid"in a&&(h[Rl]=a.guid),h[Gp]=a.name,jo(e,h,!1),t.push({instance:h,compData:a,obj:e}),h.isCamera&&s.context&&s.context.mainCamera===null&&h.tag==="MainCamera"&&s.context.setCurrentCamera(h),s.context?.physics?.engine?.isInitialized===!1&&(h.isCollider||h.isRigidbody)&&s.context?.physics.engine?.initialize()}else Vl&&console.debug("unknown component: "+a.name),ol.includes(a.name)||ol.push(a.name)}catch(l){console.error(a.name+" - "+l.message,l)}}if(e.children)for(const r of e.children)await qp(s,r,t,i,n+1);if(ol.length>0&&n===0){const r=ol.join(", ");console.warn(`Unknown components in scene: ${r}`),ol.length=0,Ii()&&Se(`<strong>Unknown components in scene</strong>:
|
|
1462
|
+
`+u.xrData.lastChangedTime.toFixed(2),.02))}}bounds=new c.Box3;center=new c.Vector3;labelOffset=new c.Vector3;removeData(e,t){const i=t.get(e);if(!i)return;t.delete(e),So&&console.log("Plane no longer tracked, id="+i.id),i.mesh&&(i.mesh.removeFromParent(),i.mesh.traverse(o=>{const r=o.userData.normalsHelper;r?(r.dispose(),r.removeFromParent()):So&&console.warn("No normals helper found for mesh",i.mesh)}),ui(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,o){const a=this.context.renderer.xr.getReferenceSpace();if(a){for(const l of o.keys())n.has(l)||this.removeData(l,o);for(const l of n){const h="planeSpace"in l?l.planeSpace:"meshSpace"in l?l.meshSpace:void 0;if(!h)continue;const d=i.getPose(h,a);let u;if(o.has(l)){const p=o.get(l);if(u=p.mesh,p.timestamp<l.lastChangedTime){if(p.timestamp=l.lastChangedTime,p.mesh){const y=this.createGeometry(l);if(p.mesh instanceof c.Mesh)p.mesh.geometry.dispose(),p.mesh.geometry=y,this.makeOccluder(p.mesh,p.mesh.material);else if(p.mesh instanceof c.Group)for(const b of p.mesh.children)b instanceof c.Mesh&&(b.geometry.dispose(),b.geometry=y,this.makeOccluder(b,b.material));if(p.collider){const b=p.mesh;p.collider.sharedMesh=b,p.collider.convex=this.checkIfContextShouldBeConvex(b,p.xrData),p.collider.onDisable(),p.collider.onEnable()}So&&(console.log("Plane updated, id="+p.id,p),p.mesh.traverse(b=>{if(!(b instanceof c.Mesh))return;const g=b.userData.normalsHelper;g&&g.update()}))}const m=new CustomEvent("plane-tracking",{detail:{type:"plane-updated",context:p}});this.dispatchEvent(m)}}else{if(!this.dataTemplate){const p=new c.Mesh;So?p.material=new c.MeshNormalMaterial:this.occluder?(p.material=new c.MeshBasicMaterial,this.makeOccluder(p,p.material,!0)):p.material=new c.MeshBasicMaterial({wireframe:!0,opacity:.5,transparent:!0,color:3355443}),this.dataTemplate=new Y("","",p)}if(!this.dataTemplate.asset)this.dataTemplate.loadAssetAsync();else{const p=S.instantiate(this.dataTemplate.asset);if(p.name="xr-tracked-plane",u=p,sm(p,!1),p instanceof c.Mesh)_e(p.geometry),p.geometry=this.createGeometry(l),this.makeOccluder(p,p.material,this.occluder&&!this.dataTemplate);else if(p instanceof c.Group)for(const b of p.children)b instanceof c.Mesh&&(_e(b.geometry),b.geometry=this.createGeometry(l),this.makeOccluder(b,b.material,this.occluder&&!this.dataTemplate));const m=p.getComponent(so);if(m){const b=p;m.sharedMesh=b,m.convex=this.checkIfContextShouldBeConvex(b,l),m.onDisable(),m.onEnable()}p.matrixAutoUpdate=!1,p.matrixWorldNeedsUpdate=!0,t.add(p);const y={id:this._dataId++,xrData:l,timestamp:l.lastChangedTime,mesh:p,collider:m};o.set(l,y),So&&console.log("New plane detected, id="+y.id,y,{hasCollider:!!m,isGroup:p instanceof c.Group});try{const b=new CustomEvent("plane-tracking",{detail:{type:"plane-added",context:y}});this.dispatchEvent(b)}catch(b){console.error(b)}}}u&&(d?(u.visible=!0,u.matrix.fromArray(d.transform.matrix),u.matrix.premultiply(this._flipForwardMatrix)):u.visible=!1,So&&u.traverse(p=>{if(p instanceof c.Mesh)if(p.userData.normalsHelper)p.userData.normalsHelper.update();else{const m=new q.VertexNormalsHelper(p,.05,255);m.layers.disableAll(),m.layers.set(2),this.context.scene.add(m),p.userData.normalsHelper=m}}))}}}_flipForwardMatrix=new c.Matrix4().makeRotationY(Math.PI);checkIfContextShouldBeConvex(e,t){if(!e)return!0;if(e){const i=new c.Box3;i.expandByObject(e);const n=new c.Vector3;i.getSize(n);let o=!0;return n.x>2&&n.y>2&&n.z>1.5&&(o=!1),o&&"semanticLabel"in t&&t.semanticLabel==="wall"&&(o=!0),o}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 c.BufferGeometry}_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 c.BufferGeometry;n.setIndex(new c.BufferAttribute(t,1)),n.setAttribute("position",new c.BufferAttribute(e,3));const o=Array();for(let r=0;r<e.length;r+=3)o.push(e[r],e[r+2]);return n.setAttribute("uv",new c.BufferAttribute(e,3)),n.computeVertexNormals(),this._verticesCache.set(i,n),n}createPlaneGeometry(e){const t=new c.BufferGeometry,i=[],n=[];e.forEach(p=>{i.push(p.x,p.y,p.z),n.push(p.x,p.z)});const o=new c.Vector3(i[0],i[1],i[2]),r=new c.Vector3(i[3],i[4],i[5]),a=new c.Vector3(i[6],i[7],i[8]),l=new c.Vector3,h=new c.Vector3;l.subVectors(r,o),h.subVectors(a,o),l.cross(h),l.normalize();const d=[];for(let p=0;p<i.length/3;p++)d.push(l.x,l.y,l.z);const u=[];for(let p=2;p<e.length;++p)u.push(0,p-1,p);return t.setAttribute("position",new c.BufferAttribute(new Float32Array(i),3)),t.setAttribute("uv",new c.BufferAttribute(new Float32Array(n),2)),t.setAttribute("normal",new c.BufferAttribute(new Float32Array(d),3)),t.setIndex(u),t.computeBoundingBox(),t.computeBoundingSphere(),t}}$a([f(Y)],Ss.prototype,"dataTemplate");$a([f()],Ss.prototype,"occluder");$a([f()],Ss.prototype,"initiateRoomCaptureIfNoData");$a([f()],Ss.prototype,"usePlaneData");$a([f()],Ss.prototype,"useMeshData");$a([f()],Ss.prototype,"runInVR");var ZE=Object.defineProperty,JE=(s,e,t,i)=>{for(var n=void 0,o=s.length-1,r;o>=0;o--)(r=s[o])&&(n=r(e,t,n)||n);return n&&ZE(e,t,n),n};const Y_=w("debugwebxr");class Wu extends k{priority=0;get isActive(){return this.activeAndEnabled&&this.gameObject.visible}setAsActiveXRRig(){H.active?.setRigActive(this)}setPriority(e){this.priority=e}awake(){if(Y_){const e=new c.Object3D;e.position.y+=.5,this.gameObject.add(e);const t=e.addNewComponent(mr);t&&(t.isGizmo=!1);const i=new c.AxesHelper(.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),Y_&&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)}}JE([f()],Wu.prototype,"priority");class eR extends k{toggleKey="KeyP";update(){this.context.input.isKeyDown(this.toggleKey)&&this.context.domElement.classList.toggle("presentation-mode")}}P.add("AlignmentConstraint",vc);P.add("Animation",Ft);P.add("Animator",rt);P.add("AudioListener",ns);P.add("AudioSource",pi);P.add("Avatar_Brain_LookAt",Zl);P.add("Avatar_MouthShapes",Cc);P.add("Avatar_MustacheShake",Fm);P.add("AvatarBlink_Simple",ar);P.add("AvatarEyeLook_Rotation",zm);P.add("AxesHelper",xa);P.add("BasicIKConstraint",Vm);P.add("BoxHelperComponent",nt);P.add("Camera",qt);P.add("CharacterController",lr);P.add("CharacterControllerInput",us);P.add("Collider",Kt);P.add("SphereCollider",Sa);P.add("BoxCollider",lu);P.add("MeshCollider",so);P.add("CapsuleCollider",ls);P.add("ContactShadows",Pc);P.add("LogStats",Wm);P.add("DeleteBox",Gs);P.add("Deletable",Hm);P.add("DeviceFlag",cu);P.add("DragControls",Ro);P.add("DropListener",fs);P.add("Duplicatable",Qm);P.add("EventListEvent",nu);P.add("EventTrigger",du);P.add("GltfExportBox",ig);P.add("GltfExport",sg);P.add("VariantAction",ag);P.add("ChangeTransformOnClick",ur);P.add("ChangeMaterialOnClick",lg);P.add("SetActiveOnClick",cg);P.add("HideOnStart",Ei);P.add("EmphasizeOnClick",Oa);P.add("PlayAudioOnClick",Qs);P.add("PlayAnimationOnClick",ec);P.add("PreliminaryAction",Ma);P.add("PreliminaryTrigger",Rc);P.add("VisibilityAction",Tc);P.add("TapGestureTrigger",dg);P.add("USDZExporter",Tn);P.add("Fog",Ta);P.add("BoxGizmo",mr);P.add("GridHelper",Aa);P.add("GroundProjectedEnv",In);P.add("UsageMarker",Oc);P.add("Interactable",Gm);P.add("FixedJoint",Tg);P.add("HingeJoint",jc);P.add("Light",ei);P.add("LODGroup",Fc);P.add("LookAtConstraint",rr);P.add("NeedleMenu",Bn);P.add("NestedGltf",Uc);P.add("Networking",Lg);P.add("OffsetConstraint",gr);P.add("CameraTargetReachedEvent",Kl);P.add("OrbitControls",de);P.add("ParticleSystemRenderer",Vi);P.add("ParticleSystem",ic);P.add("Attractor",Ia);P.add("PlayerColor",_a);P.add("Antialiasing",Vc);P.add("BloomEffect",Ou);P.add("ChromaticAberration",$c);P.add("ColorAdjustments",uo);P.add("DepthOfField",ln);P.add("EffectWrapper",nc);P.add("PixelationEffect",Wc);P.add("ScreenSpaceAmbientOcclusion",bs);P.add("ScreenSpaceAmbientOcclusionN8",cn);P.add("SharpeningEffect",Hc);P.add("TiltShiftEffect",zn);P.add("ToneMappingEffect",Zs);P.add("Vignette",xr);P.add("Volume",Ba);P.add("ReflectionProbe",Jl);P.add("Renderer",mi);P.add("MeshRenderer",Mc);P.add("SkinnedMeshRenderer",tg);P.add("Rigidbody",Ne);P.add("SceneSwitcher",je);P.add("ScreenCapture",fo);P.add("ShadowCatcher",Xc);P.add("RemoteSkybox",ku);P.add("SmoothFollow",Ru);P.add("SpatialTriggerReceiver",An);P.add("SpatialTrigger",Tu);P.add("SpectatorCamera",Au);P.add("SplineContainer",Sr);P.add("SplineWalker",hn);P.add("SpriteRenderer",Zt);P.add("SyncedCamera",$g);P.add("SyncedRoom",dn);P.add("SyncedTransform",nn);P.add("TestRunner",Wg);P.add("TestSimulateUserData",Gg);P.add("PlayableDirector",er);P.add("SignalReceiver",Jc);P.add("AnimationTrackHandler",Iu);P.add("AudioTrackHandler",os);P.add("SignalTrackHandler",sc);P.add("ControlTrackHandler",ju);P.add("TransformGizmo",Pr);P.add("BaseUIComponent",Bi);P.add("UIRootComponent",Ac);P.add("Button",vs);P.add("Canvas",ya);P.add("CanvasGroup",Ks);P.add("EventSystem",jt);P.add("Graphic",Dc);P.add("MaskableGraphic",Ic);P.add("Image",Ua);P.add("RawImage",Uu);P.add("InputField",Qg);P.add("VerticalLayoutGroup",wg);P.add("HorizontalLayoutGroup",xg);P.add("GridLayoutGroup",Sg);P.add("Outline",Ra);P.add("ObjectRaycaster",fi);P.add("GraphicRaycaster",su);P.add("SpatialGrabRaycaster",Qo);P.add("RectTransform",sn);P.add("SpatialHtml",ih);P.add("Text",St);P.add("EnvironmentScene",Nu);P.add("LookAt",Yg);P.add("OpenURL",za);P.add("VideoPlayer",Ze);P.add("Voip",no);P.add("ClickThrough",$u);P.add("CursorFollow",sh);P.add("ScrollFollow",Zg);P.add("Avatar",Ys);P.add("XRControllerFollow",ws);P.add("XRControllerModel",cs);P.add("XRControllerMovement",gi);P.add("TeleportTarget",_u);P.add("WebARCameraBackground",oh);P.add("WebARSessionRoot",hi);P.add("WebXR",bu);P.add("AvatarMarker",xe);P.add("WebXRImageTracking",rh);P.add("WebXRPlaneTracking",Ss);P.add("XRRig",Wu);P.add("XRFlag",Ti);P.add("PlayerSync",mg);P.add("PlayerState",Yi);P.add("PresentationMode",eR);const Vl=st,tR=w("debugtypestore");tR&&console.log(P);function iR(s,e){const i=_v(s,e);return i!==void 0?i:null}const nR=new bC,Qf=Symbol("deserialize-queue");async function sR(s,e,t,i=null,n){if(!t){console.debug("Can not create component instances: gltf is null");return}const o=[];let r=i;typeof r=="number"&&(r=new mt(i));const a=e.indexOf("?");e=a===-1?e:e.substring(0,a);const l=new Pm(t.scene);l.gltfId=e,l.context=s,l.gltf=t,l.nodeToObject=n?.nodeToObjectMap,l.implementationInformation=nR;let h=s[Qf];if(h||(h=s[Qf]=[]),t.scenes)for(const d of t.scenes)await qp(l,d,h,o,0);if(t.children)for(const d of t.children)await qp(l,d,h,o,0);s.new_scripts_pre_setup_callbacks.push(()=>{const d=s[Qf];if(d){for(const u of d)oR(u,l);d.length=0}if(r){const u={},p=[];Hp(t,r,u,p);for(const m of t.scenes)Hp(m,r,u,p);for(const m of p)m.resolveGuids(u)}})}const Gp=Symbol("original-component-name"),Ir=new Map;function Hp(s,e,t,i){if(e===null||!s)return;const n=s.guid,o=s.guid;o?.length&&(Ir.has(o)||(Vl&&console.log('Creating InstanceIdProvider with key "'+o+'" for object '+s.name),Ir.set(o,new mt(o))));const r=o&&Ir.get(o)||e;if(s.guid=r.generateUUID(),n&&n!=="invalid"&&(t[n]=s.guid),s&&s.userData&&s.userData.components)for(const a of s.userData.components){if(a===null)continue;const l=a.guid;l?Ir.has(l)||(Vl&&console.log('Creating InstanceIdProvider with key "'+l+'" for component '+a[Gp]),Ir.set(l,new mt(l))):Vl&&console.warn("Can not create IdProvider: component "+a[Gp]+" has no guid",a.guid);const h=Ir.get(l)||e,d=a.guid;a.guid=h.generateUUID(),d&&d!=="invalid"&&(t[d]=a.guid),a.resolveGuids&&i.push(a)}if(s.children)for(const a of s.children)Hp(a,e,t,i)}const ol=[];async function qp(s,e,t,i,n){if(!e)return;const o=e.userData;if(o){const r=o.builtin_components;if(r&&r.length>0)for(const a of r)try{if(a===null)continue;const l=P.get(a.name);if(l!=null){const h=new l;h.sourceId=s.gltfId,ua(h,a,s.implementationInformation),h.context=s.context,"guid"in a&&(h[Rl]=a.guid),h[Gp]=a.name,jo(e,h,!1),t.push({instance:h,compData:a,obj:e}),h.isCamera&&s.context&&s.context.mainCamera===null&&h.tag==="MainCamera"&&s.context.setCurrentCamera(h),s.context?.physics?.engine?.isInitialized===!1&&(h.isCollider||h.isRigidbody)&&s.context?.physics.engine?.initialize()}else Vl&&console.debug("unknown component: "+a.name),ol.includes(a.name)||ol.push(a.name)}catch(l){console.error(a.name+" - "+l.message,l)}}if(e.children)for(const r of e.children)await qp(s,r,t,i,n+1);if(ol.length>0&&n===0){const r=ol.join(", ");console.warn(`Unknown components in scene: ${r}`),ol.length=0,Ii()&&Se(`<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(o);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
|
-
`,o.appendChild(r),rl&&console.log("Created fallback close button",o,e)}appendElement(e,t){return t.shadowRoot?t.shadowRoot.appendChild(e):t.appendChild(e)}}const ko=w("debugloading"),al=w("debugloadingrendering"),K_=w("debuglicense");class fR{className;additionalClasses}let ll=0,Z_;function ty(s){ko&&console.log(s.progress.loaded.toFixed(0)+"/"+s.progress.total.toFixed(0),s);const e=s.count,t=s.progress.total;t===0||t===void 0?(Z_!==s.name&&(ll=0),Z_=s.name,ll+=(1-ll)*.001,ko&&he("Loading "+s.name+" did not report total size")):ll=s.progress.loaded/t;const i=s.index/e+ll/e;return D.clamp01(i)}class oc{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(ko&&console.warn("Begin Loading"),!this._loadingElement){for(let i=0;i<t.children.length;i++){const n=t.children[i];if(n.classList.contains(oc.LoadingContainerClassName)){if(!this._allowCustomLoadingElement){ko&&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=ty(e)),!t&&"name"in e&&this.setMessage("loading "+e.name)),this.loadingProgress=i,t&&this.setMessage(t),this.updateDisplay()}onLoadingFinished(){ko&&console.warn("Finished Loading"),al||(this.loadingProgress=1,this.onDoneLoading())}setMessage(e){this._messageContainer&&(this._messageContainer.innerText=e)}_progressLoop;smoothProgressLoop(){if(this._progressLoop)return;let e=1/12;al&&(e=1/500,typeof al=="number"&&(e*=al)),this._progressLoop=setInterval(()=>{this.loadingProgress>=.95&&!al&&(e=.9),this._progress=D.lerp(this._progress,this.loadingProgress,e*this.loadingProgress),this.updateDisplay()},e)}onDoneLoading(){
|
|
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(o);const r=this._element.getAttribute("poster");if(r!==null&&r!=="0"){const _=document.createElement("div"),g=r?.length?"0px":"50px";_.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: -${g};
|
|
1508
|
-
background: url('${r?.length?r:"/include/poster.webp"}') center center no-repeat;
|
|
1509
|
-
background-size: cover;
|
|
1510
|
-
filter: blur(${g});
|
|
1511
|
-
`,this._loadingElement.appendChild(_)}const a=document.createElement("img"),l="80%",h="15%",d=".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 ${d}, opacity .3s ease-in-out ${d}`,a.src=ob,i&&this._element){const _=this._element.getAttribute("loading-logo-src");_&&(a.src=_,setTimeout(()=>{a.style.opacity="1",a.style.transform="translateY(0px)"},1))}a.style.width=`${l}`,a.style.height=`min(1000px, max(${h}, 50px))`,o.appendChild(a);const u=document.createElement("div");u.style.cssText=`
|
|
1489
|
+
`,o.appendChild(r),rl&&console.log("Created fallback close button",o,e)}appendElement(e,t){return t.shadowRoot?t.shadowRoot.appendChild(e):t.appendChild(e)}}const ko=w("debugloading"),al=w("debugloadingrendering"),K_=w("debuglicense");class fR{className;additionalClasses}let ll=0,Z_;function ty(s){ko&&console.log(s.progress.loaded.toFixed(0)+"/"+s.progress.total.toFixed(0),s);const e=s.count,t=s.progress.total;t===0||t===void 0?(Z_!==s.name&&(ll=0),Z_=s.name,ll+=(1-ll)*.001,ko&&he("Loading "+s.name+" did not report total size")):ll=s.progress.loaded/t;const i=s.index/e+ll/e;return D.clamp01(i)}class oc{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(ko&&console.warn("Begin Loading"),!this._loadingElement){for(let i=0;i<t.children.length;i++){const n=t.children[i];if(n.classList.contains(oc.LoadingContainerClassName)){if(!this._allowCustomLoadingElement){ko&&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=ty(e)),!t&&"name"in e&&this.setMessage("loading "+e.name)),this.loadingProgress=i,t&&this.setMessage(t),this.updateDisplay()}onLoadingFinished(){ko&&console.warn("Finished Loading"),al||(this.loadingProgress=1,this.onDoneLoading())}setMessage(e){this._messageContainer&&(this._messageContainer.innerText=e)}_progressLoop;smoothProgressLoop(){if(this._progressLoop)return;let e=1/12;al&&(e=1/500,typeof al=="number"&&(e*=al)),this._progressLoop=setInterval(()=>{this.loadingProgress>=.95&&!al&&(e=.9),this._progress=D.lerp(this._progress,this.loadingProgress,e*this.loadingProgress),this.updateDisplay()},e)}onDoneLoading(){this._loadingElement&&(ko&&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){ko&&!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=En();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??oc.LoadingContainerClassName;if(this._loadingElement.classList.add(n),this._loadingElementOptions?.additionalClasses)for(const p of this._loadingElementOptions.additionalClasses)this._loadingElement.classList.add(p);const o=document.createElement("div");this._loadingElement.appendChild(o);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=ob,i&&this._element){const p=this._element.getAttribute("loading-logo-src");p&&(r.src=p)}o.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(()=>{
|
|
1497
|
+
`,setTimeout(()=>{l.style.opacity="1"},1),this._loadingElement.appendChild(l);const h=document.createElement("div"),d=100;h.style.display="flex",h.style.width=d+"%",h.style.height="3px",h.style.position="absolute",h.style.left="0",h.style.bottom="0px",h.style.opacity="0",h.style.transition="opacity 1s ease-in-out 2s",setTimeout(()=>{h.style.opacity="1"},1),t==="light"?h.style.backgroundColor="rgba(0,0,0,.2)":h.style.backgroundColor="rgba(255,255,255,.2)",this._loadingElement.appendChild(h),this._loadingBar=document.createElement("div"),h.appendChild(this._loadingBar);const u=function(p){return D.lerp(0,d,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} ${u(0)}, ${m} ${u(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=Rn();if(t)return;K_&&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),!A()&&pa&&(K_&&console.log("Waiting for runtime license check"),await pa,t=Rn()),!t&&(i.style.transition="opacity .5s ease-in-out",i.style.opacity="1")}}lm(Dw);const ge=w("debugwebcomponent"),J_="needle-engine",zw="vr",Nw="desktop",pR=[Uw,zw,Nw],cl="ar-session-active",hl="desktop-session-active",mR=["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 iy extends HTMLElement{static get observedAttributes(){return mR}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 uR,this.addEventListener("ready",this.onReady),Hv(),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 F({domElement:this}),this.addEventListener("error",this.onError)}async connectedCallback(){if(ge&&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"];ge&&console.log('src is null, trying to load from globalThis["needle:codegen_files"]',t),t&&(ge&&console.log('globalThis["needle:codegen_files"]',t),this.setAttribute("src",t))}ge&&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";ge&&console.warn('<needle-engine> disconnected, keep-alive: "'+e+'"',typeof e,"Dispose=",t),t?(ge&&console.warn("<needle-engine> dispose"),this._context?.dispose(),this._context=null,this._lastSourceFiles=null,this._loadId+=1):ge&&console.warn("<needle-engine> is not disposed because keep-alive is set")}attributeChangedCallback(e,t,i){switch(ge&&console.log("attributeChangedCallback",e,t,i),e){case"src":ge&&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&&(ge&&console.log(e+" attribute changed",i),this.registerEventFromAttribute(e,i));break;case"dracoDecoderPath":ge&&console.log("dracoDecoderPath",i),t_(i);break;case"dracoDecoderType":i==="wasm"||i==="js"?(ge&&console.log("dracoDecoderType",i),i_(i)):console.error("Invalid dracoDecoderType",i,"expected js or wasm");break;case"ktx2DecoderPath":ge&&console.log("ktx2DecoderPath",i),n_(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!=Gr&&this.setPublicKey();break}case"version":{i!=Ki&&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||(ge&&console.warn("Create new context"),this._context=new F({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&&(ge&&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)&&(ge&&console.warn("Clear scene",e),this._context.clear(),t!==this._loadId))return;const i=this.getAttribute("alias");this.classList.add("loading");const n=Rn();this.ensureLoadStartIsRegistered();let o=this.dispatchEvent(new CustomEvent("loadstart",{detail:{context:this._context,alias:i},cancelable:!0}));if(n){const y=this.getAttribute("hide-loading-overlay");y!=null&&y!=="0"&&(o=!1)}o===!1&&!n&&(A()||(o=!0),console.warn("Needle Engine: You need a commercial license to override the default loading view. Visit https://needle.tools/pricing"),A()&&he('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&&o&&(this._loadingView=new oc(this)),o&&(this._didFullyLoad!==!0?this._loadingView?.onLoadingBegin("begin load"):setTimeout(()=>{this._loadingView&&this._loadingProgress01<.3&&this._loadId===t&&this._loadingView.onLoadingBegin("begin load")},300)),ge&&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}),h=new Array,d=new AbortController;this._abortController=d;const u={files:e,abortSignal:d.signal,onLoadingProgress:y=>{if(ge&&console.debug("Loading progress: ",y),d.signal.aborted)return;const
|
|
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}),h=new Array,d=new AbortController;this._abortController=d;const u={files:e,abortSignal:d.signal,onLoadingProgress:y=>{if(ge&&console.debug("Loading progress: ",y),d.signal.aborted)return;const b=y.index;!h[b]&&y.name&&(h[b]=gR(y.name)),y.name=h[b],o&&this._loadingView?.onLoadingUpdate(y),a.name=y.name,a.progress=y.progress,this._loadingProgress01=ty(y),a.totalProgress01=this._loadingProgress01,this.dispatchEvent(l)},onLoadingFinished:(y,b,g)=>{ge&&console.debug(`Finished loading "${b}" (aborted? ${d.signal.aborted})`),!d.signal.aborted&&g&&r.push({src:b,file:g})}};yR(this);const p=this.getAttribute("hash");p!=null&&(this._context.hash=p),this._context.alias=i,this._createContextPromise=this._context.create(u);const m=await this._createContextPromise;if(this.applyAttributes(),ge&&console.warn(`--------------
|
|
1601
1579
|
Needle Engine: finished loading `+t+`
|
|
1602
1580
|
`,e,`Aborted? ${d.signal.aborted}`),d.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,o&&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 o=this.getAttribute("tone-mapping-exposure");if(o!=null){const r=parseFloat(o);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=Z.fromColorRepresentation(i);ge&&console.debug("<needle-engine> background-color changed, str:",i,"→",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,o=>n?.call(globalThis,this._context,o)))}catch(n){console.error("Error registering event "+e+'="'+t+`" failed with the following error:
|
|
1603
|
-
`,n)}}setPublicKey(){Gr&&Gr.length>0&&this.setAttribute("public-key",Gr)}setVersion(){Ki.length>0&&this.setAttribute("version",Ki)}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(cl),this.classList.remove(hl);const e=this.getAROverlayContainer();ge&&console.warn("onSetupAR:",e),e&&(e.classList.add(cl),e.classList.remove(hl)),this.foreachHtmlElement(t=>this.setupElementsForMode(t,Uw))}onSetupVR(){this.classList.remove(cl),this.classList.remove(hl),this.foreachHtmlElement(e=>this.setupElementsForMode(e,zw))}onSetupDesktop(){this.classList.remove(cl),this.classList.add(hl);const e=this.getAROverlayContainer();e&&(e.classList.remove(cl),e.classList.add(hl)),this.foreachHtmlElement(t=>this.setupElementsForMode(t,Nw))}setupElementsForMode(e,t,i=null){if(e===this._context?.renderer?.domElement||e.id==="VRButton"||e.id==="ARButton")return;if(e.classList.contains(t))e.style.visibility="visible",e.style.display==="none"&&(e.style.display="block");else for(const o of pR)e.classList.contains(o)&&(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&&(ge&&console.log("using custom draco decoder path",e),t_(e));const t=this.getAttribute("dracoDecoderType");t&&(ge&&console.log("using custom draco decoder type",t),i_(t));const i=this.getAttribute("ktx2DecoderPath");i&&(ge&&console.log("using custom ktx2 decoder path",i),n_(i))}}typeof window<"u"&&!window.customElements.get(J_)&&window.customElements.define(J_,iy);function gR(s){if(s.startsWith("blob:"))return"blob";const e=s.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 o=t.split(".").pop(),a=o?["glb","gltf","usdz","usd","fbx","obj","mtl"].indexOf(o.toLowerCase()):-1;if(o&&a>=0&&(t=t.substring(0,t.length-o.length-1)),t=decodeURIComponent(t),t.length>3){let l="",h=!1;const d=["(",")","[","]","{","}",":",";",",",".","!","?"];for(let u=0;u<t.length;u++){let p=t[u];(p==="_"||p==="-")&&(p=" "),!(p===" "&&l.length<=0||d.includes(p)||(l.length===0&&(p=p.toUpperCase()),h&&p===" "))&&(h&&(p=p.toUpperCase()),h=!1,l+=p,p===" "&&(h=!0))}return A()&&t!==l&&console.debug('Generated display name: "'+t+'" → "'+l+'"'),l.trim()}return A()&&console.debug("Loading: use default name",t),t}function yR(s){eu(e=>{const t=s.getAttribute("loading-blur");if(t!==null&&t!=="0"&&e.domElement===s){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 o=170;if(e.scene.background===null){const r=s,a=e.renderer.domElement,l=a.style.filter,h=a.style.overflow;a.style.filter+=`blur(${n})`,r.style.overflow="hidden",i?.then(()=>{const d=a.animate([{filter:"blur(0px)"}],{duration:o,easing:"ease-in"});d.onfinish=()=>{a.style.filter=l,r.style.overflow=h}})}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:o,easing:"ease-in"});a.onfinish=()=>{r.remove()}})}}},{once:!0})}const _R=Object.freeze(Object.defineProperty({__proto__:null,NeedleEngineWebComponent:iy},Symbol.toStringTag,{value:"Module"}));function bR(){tn.registerWaitForInteraction(()=>{const s=c.AudioContext.getContext();s.addEventListener("statechange",()=>{setTimeout(()=>{const e=s.state;(e==="suspended"||e==="interrupted")&&s.resume().then(()=>{console.log("AudioContext resumed successfully")}).catch(t=>{console.log("Failed to resume AudioContext: "+t)})},500)})})}setTimeout(bR,1e3);const Ue=w("debugphysics"),Yf=w("debugcolliderplacement"),Kf=w("debugcollisions"),vR=w("showcolliders"),Nh=w("debugraycasts"),Vt=Symbol("needle component"),Rt=Symbol("physics body"),eb=Symbol("rigidbody");globalThis.NEEDLE_USE_RAPIER=globalThis.NEEDLE_USE_RAPIER!==void 0?globalThis.NEEDLE_USE_RAPIER:!0;Ue&&console.log("Use Rapier",!0,globalThis.NEEDLE_USE_RAPIER);ae.registerCallback(re.ContextCreationStart,s=>{Ue&&console.log("Register rapier physics backend"),s.context.physics.engine=new oa(s.context)});class oa{debugRenderColliders=!1;debugRenderRaycasts=!1;removeBody(e){if(!e)return;this.validate();const t=e[Rt];if(e[Rt]=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 exports.MODULES.RAPIER_PHYSICS.MODULE.Collider){const o=n;this.world?.removeCollider(o,!0);const r=o.parent();r&&r.numColliders()<=0&&(r[Vt]||this.world?.removeRigidBody(r))}else n instanceof exports.MODULES.RAPIER_PHYSICS.MODULE.RigidBody&&(n.numColliders()<=0?this.world?.removeRigidBody(n):A()&&(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,o=n[Rt];o&&this.syncPhysicsBody(n.gameObject,o,t,i)}}updateProperties(e){if(this.validate(),e.isCollider){const t=e,i=t[Rt];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):(Ue&&console.log("Initialize rapier physics engine"),this._hasCreatedWorld?(console.error("Invalid call to create physics world: world is already created"),!0):(this._hasCreatedWorld=!0,exports.MODULES.RAPIER_PHYSICS.MAYBEMODULE==null&&(Ue&&console.trace("Loading rapier physics engine"),await(await exports.MODULES.RAPIER_PHYSICS.load()).init()),Ue&&console.log("Physics engine initialized, creating world..."),this._world=new exports.MODULES.RAPIER_PHYSICS.MODULE.World(this._gravity),this.rapierRay=new exports.MODULES.RAPIER_PHYSICS.MODULE.Ray({x:0,y:0,z:0},{x:0,y:0,z:1}),this.enabled=!0,this._isInitialized=!0,Ue&&console.log("Physics world created"),!0))}validate(){this._isInitialized||Ue&&(this._lastWarnTime=this._lastWarnTime??0,Date.now()-this._lastWarnTime>1e3&&(this._lastWarnTime=Date.now(),console.warn("Physics engine is not initialized")))}rapierRay;raycastVectorsBuffer=new di(()=>new c.Vector3,10);raycast(e,t,i){if(!this._isInitialized)return console.log("Physics engine is not initialized"),null;let n=i?.maxDistance,o=i?.solid;n===void 0&&(n=1/0),o===void 0&&(o=!0);const r=this.getPhysicsRay(this.rapierRay,e,t);if(!r)return null;(this.debugRenderRaycasts||Nh)&&B.DrawRay(r.origin,r.dir,255,1);const a=this.world?.castRay(r,n,o,i?.queryFilterFlags,i?.filterGroups,void 0,void 0,l=>{const h=l[Vt];return i?.filterPredicate?i.filterPredicate(h):i?.useIgnoreRaycastLayer!==!1?!h?.gameObject.layers.isEnabled(2):!0});if(a){const l=r.pointAt(a.timeOfImpact),h=this.raycastVectorsBuffer.get();return h.set(l.x,l.y,l.z),{point:h,collider:a.collider[Vt]}}return null}raycastAndGetNormal(e,t,i){if(!this._isInitialized)return null;let n=i?.maxDistance,o=i?.solid;n===void 0&&(n=1/0),o===void 0&&(o=!0);const r=this.getPhysicsRay(this.rapierRay,e,t);if(!r)return null;(this.debugRenderRaycasts||Nh)&&B.DrawRay(r.origin,r.dir,255,1);const a=this.world?.castRayAndGetNormal(r,n,o,i?.queryFilterFlags,i?.filterGroups,void 0,void 0,l=>{const h=l[Vt];return i?.filterPredicate?i.filterPredicate(h):i?.useIgnoreRaycastLayer!==!1?!h?.gameObject.layers.isEnabled(2):!0});if(a){const l=r.pointAt(a.timeOfImpact),h=a.normal,d=this.raycastVectorsBuffer.get(),u=this.raycastVectorsBuffer.get();return d.set(l.x,l.y,l.z),u.set(h.x,h.y,h.z),{point:d,normal:u,collider:a.collider[Vt]}}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)&&(Ue&&console.warn("Converting screenspace to raycast space",a),this.context?.input.convertScreenspaceToRaycastSpace(a)),a.unproject(n),t=a}const o=t;e.origin.x=o.x,e.origin.y=o.y,e.origin.z=o.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=X(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 exports.MODULES.RAPIER_PHYSICS.MODULE.Ball(t),this.rapierSphere.radius=t,(this.debugRenderRaycasts||Nh)&&B.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 exports.MODULES.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||Nh)&&B.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 o=n[Vt],r=new f0(o.gameObject,o);return this.rapierColliderArray.push(r),!0},void 0,void 0,void 0,void 0,n=>n.isSensor()?!1:n[Vt].gameObject.layers.isEnabled(2)==!1),this.rapierColliderArray):this.rapierColliderArray:this.rapierColliderArray}enabled=!1;get world(){return this._world}_tempPosition=new c.Vector3;_tempQuaternion=new c.Quaternion;_tempScale=new c.Vector3;_tempMatrix=new c.Matrix4;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){Ue&&console.warn("Physics are disabled");return}const i=e.gameObject,n=Ie(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 o=1e-7;n.x<o&&(n.x=o),n.y<o&&(n.y=o),n.z<o&&(n.z=o);const r=exports.MODULES.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){Ue&&console.warn("Physics are disabled");return}const t=exports.MODULES.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){Ue&&console.warn("Physics are disabled");return}const o=e.gameObject.worldScale;o.x=Math.abs(o.x),o.y=Math.abs(o.y);const r=i*o.x;t=Math.max(t,r);const a=D.clamp(t*.5*o.y-i*o.x,0,Number.MAX_SAFE_INTEGER),l=exports.MODULES.RAPIER_PHYSICS.MODULE.ColliderDesc.capsule(a,r);this.createCollider(e,l)}async addMeshCollider(e,t,i,n){let o=t.geometry;if(!o){Ue&&console.warn("Missing mesh geometry",t.name);return}o.index?.array?.length||(console.warn(`Your MeshCollider is missing vertices or indices in the assined mesh "${t.name}". Consider providing an indexed geometry.`),o=q.mergeVertices(o));let r=null;const a=o.getAttribute("position");if(a instanceof c.InterleavedBufferAttribute){const u=a.count;r=new Float32Array(u*3);for(let p=0;p<u;p++){const m=a.getX(p),y=a.getY(p),_=a.getZ(p);r[p*3]=m,r[p*3+1]=y,r[p*3+2]=_}}else r=a.array;if(await this.initialize(),!this.enabled){Ue&&console.warn("Physics are disabled");return}if(!e.activeAndEnabled)return;const l=o.index?.array,h=e.gameObject.worldScale.clone();if(n&&h.multiply(n),Math.abs(h.x-1)>1e-4||Math.abs(h.y-1)>1e-4||Math.abs(h.z-1)>1e-4){const u=`${o.uuid}_${h.x}_${h.y}_${h.z}_${i}`;if(this._meshCache.has(u))Ue&&console.warn("Use cached mesh collider"),r=this._meshCache.get(u);else{(Ue||A())&&console.debug(`[Performance] Your MeshCollider "${e.name}" is scaled: consider applying the scale to the collider mesh instead (${h.x}, ${h.y}, ${h.z})`);const p=new Float32Array(r.length);for(let m=0;m<r.length;m+=3)p[m]=r[m]*h.x,p[m+1]=r[m+1]*h.y,p[m+2]=r[m+2]*h.z;r=p,this._meshCache.set(u,p)}}const d=i?exports.MODULES.RAPIER_PHYSICS.MODULE.ColliderDesc.convexHull(r):exports.MODULES.RAPIER_PHYSICS.MODULE.ColliderDesc.trimesh(r,l);d&&this.createCollider(e,d)}updatePhysicsMaterial(e){if(!e)return;const t=e.sharedMaterial,i=e[Rt];if(i&&t){if(t.bounciness!==void 0&&i.setRestitution(t.bounciness),t.bounceCombine!==void 0)switch(t.bounceCombine){case it.Average:i.setRestitutionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case it.Maximum:i.setRestitutionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case it.Minimum:i.setRestitutionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case it.Multiply:i.setRestitutionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}if(t.dynamicFriction!==void 0&&i.setFriction(t.dynamicFriction),t.frictionCombine!==void 0)switch(t.frictionCombine){case it.Average:i.setFrictionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case it.Maximum:i.setFrictionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case it.Minimum:i.setFrictionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case it.Multiply:i.setFrictionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}}}getBody(e){return e?e[Rt]:null}getComponent(e){return e?e[Vt]: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):(Ue&&console.log("Create collider without rigidbody",e.name),i.makeRotationFromQuaternion(ue(e.gameObject)),i.setPosition(X(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 o=e.sharedMaterial;if(o){if(o.bounciness!==void 0&&t.setRestitution(o.bounciness),o.bounceCombine!==void 0)switch(o.bounceCombine){case it.Average:t.setRestitutionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case it.Maximum:t.setRestitutionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case it.Minimum:t.setRestitutionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case it.Multiply:t.setRestitutionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}if(o.dynamicFriction!==void 0&&t.setFriction(o.dynamicFriction),o.frictionCombine!==void 0)switch(o.frictionCombine){case it.Average:t.setFrictionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case it.Maximum:t.setFrictionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case it.Minimum:t.setFrictionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case it.Multiply:t.setFrictionCombineRule(exports.MODULES.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[Vt]=e,e[Rt]=r,r.setActiveEvents(exports.MODULES.RAPIER_PHYSICS.MODULE.ActiveEvents.COLLISION_EVENTS),r.setActiveCollisionTypes(exports.MODULES.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[Rt],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 o=e.filter;let r=0;if(o==null)r=65535;else for(let a=0;a<o.length;a++){const l=o[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[Rt],!i){const o=n.isKinematic&&!Yf;Ue&&console.log("Create rigidbody",o);const r=o?exports.MODULES.RAPIER_PHYSICS.MODULE.RigidBodyDesc.kinematicPositionBased():exports.MODULES.RAPIER_PHYSICS.MODULE.RigidBodyDesc.dynamic(),a=X(e.attachedRigidbody.gameObject);r.setTranslation(a.x,a.y,a.z),r.setRotation(ue(e.attachedRigidbody.gameObject)),r.centerOfMass=new exports.MODULES.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[Vt]=n,n[Rt]=i,this.internalUpdateRigidbodyProperties(n,i),this.getRigidbodyRelativeMatrix(e.gameObject,n.gameObject,t),e[eb]=i}else{const n=exports.MODULES.RAPIER_PHYSICS.MODULE.RigidBodyDesc.kinematicPositionBased(),o=X(e.gameObject);n.setTranslation(o.x,o.y,o.z),n.setRotation(ue(e.gameObject)),i=this.world.createRigidBody(n),t.identity(),i[Vt]=null}return i}internal_getRigidbody(e){return e.isCollider===!0?e[eb]:e[Rt]}internalUpdateColliderProperties(e,t){const i=t.shape;let n=!1;switch(i.type){case exports.MODULES.RAPIER_PHYSICS.MODULE.ShapeType.Ball:{const p=i,m=e,y=e.gameObject,_=Ie(y,this._tempPosition),g=Math.abs(m.radius*_.x);n=p.radius!==g,p.radius=g,n&&t.setShape(p);break}case exports.MODULES.RAPIER_PHYSICS.MODULE.ShapeType.Cuboid:const o=i,r=e,a=e.gameObject,l=Ie(a,this._tempPosition),h=Math.abs(r.size.x*.5*l.x),d=Math.abs(r.size.y*.5*l.y),u=Math.abs(r.size.z*.5*l.z);n=o.halfExtents.x!==h||o.halfExtents.y!==d||o.halfExtents.z!==u,o.halfExtents.x=h,o.halfExtents.y=d,o.halfExtents.z=u,n&&t.setShape(o);break}if(n){const o=e.attachedRigidbody;o?.autoMass&&this.getBody(o)?.recomputeMassPropertiesFromColliders()}this.updateColliderCollisionGroups(e),e.isTrigger!==t.isSensor()&&t.setSensor(e.isTrigger)}internalUpdateRigidbodyProperties(e,t){if(t.enableCcd(e.collisionDetectionMode!==iu.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(exports.MODULES.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicPositionBased,!1):t.setBodyType(exports.MODULES.RAPIER_PHYSICS.MODULE.RigidBodyType.Dynamic,!1)}lines;step(e){if(this.world&&this.enabled){if(this._isUpdatingPhysicsWorld=!0,this.eventQueue||(this.eventQueue=new exports.MODULES.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 wR(this.world,this.eventQueue)),this.collisionHandler&&(this.collisionHandler.handleCollisionEvents(),this.collisionHandler.update()),this.updateDebugRendering(this.world))}updateDebugRendering(e){if(Ue||Yf||vR||this.debugRenderColliders===!0){if(!this.lines){const i=new c.LineBasicMaterial({color:7855479,fog:!1}),n=new c.BufferGeometry;this.lines=new c.LineSegments(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 c.BufferAttribute(t.vertices,3)),this.lines.geometry.setAttribute("color",new c.BufferAttribute(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(!Yf)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 o=i.translation(),r=i.rotation();if(Number.isNaN(o.x)||Number.isNaN(r.x)){!n.__COLLIDER_NAN&&A()&&(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),h=Ie(t.gameObject);l.multiply(h),o.x-=l.x,o.y-=l.y,o.z-=l.z}Wo(t.gameObject,o.x,o.y,o.z),tm(t.gameObject,r.x,r.y,r.z,r.w)}}syncPhysicsBody(e,t,i,n){if(t instanceof exports.MODULES.RAPIER_PHYSICS.MODULE.RigidBody){const o=X(e,this._tempPosition),r=ue(e,this._tempQuaternion);switch(t.bodyType()){case exports.MODULES.RAPIER_PHYSICS.MODULE.RigidBodyType.Fixed:case exports.MODULES.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicPositionBased:case exports.MODULES.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicVelocityBased:i&&t.setNextKinematicTranslation(o),n&&t.setNextKinematicRotation(r);break;default:i&&t.setTranslation(o,!1),n&&t.setRotation(r,!1);break}}else if(t instanceof exports.MODULES.RAPIER_PHYSICS.MODULE.Collider){e.matrixWorldNeedsUpdate&&e.updateWorldMatrix(!0,!1),e.matrixWorld.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const o=this._tempPosition,r=this._tempQuaternion,a=t[Vt];if(this.tryApplyCenter(a,o),i){const l=t.translation();(l.x!==o.x||l.y!==o.y||l.z!==o.z)&&t.setTranslation(o)}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 c.Vector3;_tempCenterVec=new c.Vector3;_tempCenterQuaternion=new c.Quaternion;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,Ie(e.gameObject,this._tempCenterVec),this._tempCenterPos.multiply(this._tempCenterVec),e.attachedRigidbody?this._tempCenterPos.applyQuaternion(e.gameObject.quaternion):(ue(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=oa._matricesBuffer,n.length=0),e===t){const o=Ie(e,this._tempPosition);i.makeScale(o.x,o.y,o.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[Rt],n=t[Rt];this.calculateJointRelativeMatrices(e.gameObject,t.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const o=exports.MODULES.RAPIER_PHYSICS.MODULE.JointData.fixed(oa.centerConnectionPos,oa.centerConnectionRot,this._tempPosition,this._tempQuaternion),r=this.world.createImpulseJoint(o,i,n,!0);Ue&&console.log("ADD FIXED JOINT",r)}addHingeJoint(e,t,i,n){if(!this.world){console.error("Physics world not initialized");return}const o=e[Rt],r=t[Rt];this.calculateJointRelativeMatrices(e.gameObject,t.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const a=exports.MODULES.RAPIER_PHYSICS.MODULE.JointData.revolute(i,this._tempPosition,n),l=this.world.createImpulseJoint(a,o,r,!0);Ue&&console.log("ADD HINGE JOINT",l)}calculateJointRelativeMatrices(e,t,i){e.updateWorldMatrix(!0,!1),t.updateWorldMatrix(!0,!1);const n=e.matrixWorld,o=t.matrixWorld;n.elements[0]=1,n.elements[5]=1,n.elements[10]=1,o.elements[0]=1,o.elements[5]=1,o.elements[10]=1,i.copy(o).premultiply(n.invert()).invert()}}class wR{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),o=this.world.getCollider(t);if(!n||!o)return;const r=n[Vt],a=o[Vt];Kf&&console.log("EVT",r.name,a.name,i,n,o),r&&a&&(i?(this.onCollisionStarted(r,n,a,o),this.onCollisionStarted(a,o,r,n)):(this.onCollisionEnded(r,a),this.onCollisionEnded(a,r)))})}update(){this.onHandleCollisionStay()}onCollisionStarted(e,t,i,n){let o=null;if(e.isTrigger||i.isTrigger)qo(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)=>{qo(r,h=>{if(h.destroyed)return;const d=h.onCollisionEnter||h.onCollisionStay||h.onCollisionExit;if(d||Kf){if(!o){const u=[],p=a.normal();i instanceof so&&i.convex&&(p.x=-p.x,p.y=-p.y,p.z=-p.z);for(let m=0;m<a.numSolverContacts();m++){const y=a.solverContactPoint(m),_=a.contactImpulse(m);if(y){const g=a.contactDist(m),v=a.solverContactFriction(m),b=a.solverContactTangentVelocity(m),x=new d0(y,g,p,_,v,b);u.push(x),Kf&&B.DrawDirection(y,p,16711680,3,!0)}}o=new u0(r,i,u)}if(d){const u={collider:e,component:h,collision:o};this.activeCollisions.push(u),h.onCollisionStay&&this.activeCollisionsStay.push(u),h.onCollisionEnter?.call(h,o)}}})})}}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],o=n.collider;if(o.destroyed||n.collision.collider.destroyed){this.activeCollisions.splice(i,1),i--;continue}if(o===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],o=n.collider;if(o.destroyed||n.collision.collider.destroyed){this.activeCollisionsStay.splice(i,1),i--;continue}if(o===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],o=n.collider;if(o.destroyed||n.otherCollider.destroyed){this.activeTriggers.splice(i,1),i--;continue}if(o===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 xR{static async createComparisonScene(e){const{files:t}=e,n=await Promise.all(t.map(g=>new Y(g).loadAssetAsync())),o=new c.Scene;let r=0;for(const g of n)if(g instanceof c.Object3D){g.position.y=r,o.add(g);const v=Bt([g]);r+=v.getSize(new c.Vector3).y,r+=.1}const a=new c.PerspectiveCamera(20);o.add(a);const l=e.environment||"https://dl.polyhaven.org/file/ph-assets/HDRIs/exr/1k/studio_small_09_1k.exr";{let g=null;if(l.endsWith(".hdr")){const v=(await Promise.resolve().then(()=>require("./three-examples-C9WfZu-X.umd.cjs")).then(b=>b.RGBELoader$1)).RGBELoader;g=new v}else if(l.endsWith(".exr")){const v=(await Promise.resolve().then(()=>require("./three-examples-C9WfZu-X.umd.cjs")).then(b=>b.EXRLoader$1)).EXRLoader;g=new v}if(g){const v=await g.loadAsync(l).catch(b=>(console.error(b),null));v&&(v.mapping=c.EquirectangularReflectionMapping,v.needsUpdate=!0,o.background=v,o.environment=v,o.backgroundBlurriness=.75)}else console.warn("Unsupported environment map format",l)}const h=Bt(o.children),d=h.getCenter(new c.Vector3),u=h.getSize(new c.Vector3),m=Math.max(u.x,u.y,u.z)/(2*Math.tan(Math.PI*a.fov/360));a.position.set(d.x,d.y,m),a.lookAt(d);const y=new q.OrbitControls(a,e.domElement||document.body);y.target=d,y.update();const _=(e.domElement||document.body).getBoundingClientRect();return a.aspect=_.width/_.height,a.updateProjectionMatrix(),{scene:o,camera:a}}}let Xp=0;function tb(s){s?Xp++:Xp--}function SR(){return Xp>0}const CR={binary:!0,animations:!0};async function PR(s){if(!s.context)throw new Error("No context provided to exportAsGLTF");s.scene||(s.scene=s.context.scene);const e={...CR,...s},{context:t}=e,i=new q.GLTFExporter;i.register(a=>new L0(a)),i.register(a=>new $P(a)),i.register(a=>new k0(a)),Jm(i,e.context);const n={binary:e.binary,animations:MR(t,e.scene,[])},o=new OR;console.debug("Exporting GLTF",n),o.onBeforeExport(e),tb(!0);const r=await i.parseAsync(e.scene,n).catch(a=>(console.error(a),null));if(tb(!1),o.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),h=document.createElement("a");h.href=l;let d=e.downloadAs;!d.endsWith(".glb")&&!d.endsWith(".gltf")&&(d+=e.binary?".glb":".gltf"),h.download=d,h.click()}}return r}const ib=Symbol("needle:weight");class OR{_undo=[];onBeforeExport(e){e.context.animations.mixers.forEach(t=>{const i=fa.tryGetActionsFromMixer(t);if(i)for(let n=0;n<i.length;n++){const o=i[n];o[ib]=o.weight,o.weight=0,this._undo.push(()=>{o.weight=o[ib]})}t.update(0)}),e.context.scene.traverse(t=>{if(!Ep(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 MR(s,e,t){s.animations.mixers.forEach(n=>{const o=fa.tryGetActionsFromMixer(n);if(o)for(let r=0;r<o.length;r++){const l=o[r].getClip();t.push(l)}}),Array.isArray(e)||(e=[e]);for(const n of e)fa.tryGetAnimationClipsFromObjectHierarchy(n,t);const i=new Set(t);return Array.from(i)}const nb="needle-button",Zf=A();class Vw 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;#s;#e;#i;#o;#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{Zf?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.#s??=document.createElement("style"),this.#s.innerHTML=`
|
|
1581
|
+
`,n)}}setPublicKey(){Gr&&Gr.length>0&&this.setAttribute("public-key",Gr)}setVersion(){Ki.length>0&&this.setAttribute("version",Ki)}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(cl),this.classList.remove(hl);const e=this.getAROverlayContainer();ge&&console.warn("onSetupAR:",e),e&&(e.classList.add(cl),e.classList.remove(hl)),this.foreachHtmlElement(t=>this.setupElementsForMode(t,Uw))}onSetupVR(){this.classList.remove(cl),this.classList.remove(hl),this.foreachHtmlElement(e=>this.setupElementsForMode(e,zw))}onSetupDesktop(){this.classList.remove(cl),this.classList.add(hl);const e=this.getAROverlayContainer();e&&(e.classList.remove(cl),e.classList.add(hl)),this.foreachHtmlElement(t=>this.setupElementsForMode(t,Nw))}setupElementsForMode(e,t,i=null){if(e===this._context?.renderer?.domElement||e.id==="VRButton"||e.id==="ARButton")return;if(e.classList.contains(t))e.style.visibility="visible",e.style.display==="none"&&(e.style.display="block");else for(const o of pR)e.classList.contains(o)&&(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&&(ge&&console.log("using custom draco decoder path",e),t_(e));const t=this.getAttribute("dracoDecoderType");t&&(ge&&console.log("using custom draco decoder type",t),i_(t));const i=this.getAttribute("ktx2DecoderPath");i&&(ge&&console.log("using custom ktx2 decoder path",i),n_(i))}}typeof window<"u"&&!window.customElements.get(J_)&&window.customElements.define(J_,iy);function gR(s){if(s.startsWith("blob:"))return"blob";const e=s.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 o=t.split(".").pop(),a=o?["glb","gltf","usdz","usd","fbx","obj","mtl"].indexOf(o.toLowerCase()):-1;if(o&&a>=0&&(t=t.substring(0,t.length-o.length-1)),t=decodeURIComponent(t),t.length>3){let l="",h=!1;const d=["(",")","[","]","{","}",":",";",",",".","!","?"];for(let u=0;u<t.length;u++){let p=t[u];(p==="_"||p==="-")&&(p=" "),!(p===" "&&l.length<=0||d.includes(p)||(l.length===0&&(p=p.toUpperCase()),h&&p===" "))&&(h&&(p=p.toUpperCase()),h=!1,l+=p,p===" "&&(h=!0))}return A()&&t!==l&&console.debug('Generated display name: "'+t+'" → "'+l+'"'),l.trim()}return A()&&console.debug("Loading: use default name",t),t}function yR(s){eu(e=>{const t=s.getAttribute("loading-blur");if(t!==null&&t!=="0"&&e.domElement===s){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 o=170;if(e.scene.background===null){const r=s,a=e.renderer.domElement,l=a.style.filter,h=a.style.overflow;a.style.filter+=`blur(${n})`,r.style.overflow="hidden",i?.then(()=>{const d=a.animate([{filter:"blur(0px)"}],{duration:o,easing:"ease-in"});d.onfinish=()=>{a.style.filter=l,r.style.overflow=h}})}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:o,easing:"ease-in"});a.onfinish=()=>{r.remove()}})}}},{once:!0})}const _R=Object.freeze(Object.defineProperty({__proto__:null,NeedleEngineWebComponent:iy},Symbol.toStringTag,{value:"Module"}));function bR(){tn.registerWaitForInteraction(()=>{const s=c.AudioContext.getContext();s.addEventListener("statechange",()=>{setTimeout(()=>{const e=s.state;(e==="suspended"||e==="interrupted")&&s.resume().then(()=>{console.log("AudioContext resumed successfully")}).catch(t=>{console.log("Failed to resume AudioContext: "+t)})},500)})})}setTimeout(bR,1e3);const Ue=w("debugphysics"),Yf=w("debugcolliderplacement"),Kf=w("debugcollisions"),vR=w("showcolliders"),Nh=w("debugraycasts"),Vt=Symbol("needle component"),Rt=Symbol("physics body"),eb=Symbol("rigidbody");globalThis.NEEDLE_USE_RAPIER=globalThis.NEEDLE_USE_RAPIER!==void 0?globalThis.NEEDLE_USE_RAPIER:!0;Ue&&console.log("Use Rapier",!0,globalThis.NEEDLE_USE_RAPIER);ae.registerCallback(re.ContextCreationStart,s=>{Ue&&console.log("Register rapier physics backend"),s.context.physics.engine=new oa(s.context)});class oa{debugRenderColliders=!1;debugRenderRaycasts=!1;removeBody(e){if(!e)return;this.validate();const t=e[Rt];if(e[Rt]=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 exports.MODULES.RAPIER_PHYSICS.MODULE.Collider){const o=n;this.world?.removeCollider(o,!0);const r=o.parent();r&&r.numColliders()<=0&&(r[Vt]||this.world?.removeRigidBody(r))}else n instanceof exports.MODULES.RAPIER_PHYSICS.MODULE.RigidBody&&(n.numColliders()<=0?this.world?.removeRigidBody(n):A()&&(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,o=n[Rt];o&&this.syncPhysicsBody(n.gameObject,o,t,i)}}updateProperties(e){if(this.validate(),e.isCollider){const t=e,i=t[Rt];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):(Ue&&console.log("Initialize rapier physics engine"),this._hasCreatedWorld?(console.error("Invalid call to create physics world: world is already created"),!0):(this._hasCreatedWorld=!0,exports.MODULES.RAPIER_PHYSICS.MAYBEMODULE==null&&(Ue&&console.trace("Loading rapier physics engine"),await(await exports.MODULES.RAPIER_PHYSICS.load()).init()),Ue&&console.log("Physics engine initialized, creating world..."),this._world=new exports.MODULES.RAPIER_PHYSICS.MODULE.World(this._gravity),this.rapierRay=new exports.MODULES.RAPIER_PHYSICS.MODULE.Ray({x:0,y:0,z:0},{x:0,y:0,z:1}),this.enabled=!0,this._isInitialized=!0,Ue&&console.log("Physics world created"),!0))}validate(){this._isInitialized||Ue&&(this._lastWarnTime=this._lastWarnTime??0,Date.now()-this._lastWarnTime>1e3&&(this._lastWarnTime=Date.now(),console.warn("Physics engine is not initialized")))}rapierRay;raycastVectorsBuffer=new di(()=>new c.Vector3,10);raycast(e,t,i){if(!this._isInitialized)return console.log("Physics engine is not initialized"),null;let n=i?.maxDistance,o=i?.solid;n===void 0&&(n=1/0),o===void 0&&(o=!0);const r=this.getPhysicsRay(this.rapierRay,e,t);if(!r)return null;(this.debugRenderRaycasts||Nh)&&B.DrawRay(r.origin,r.dir,255,1);const a=this.world?.castRay(r,n,o,i?.queryFilterFlags,i?.filterGroups,void 0,void 0,l=>{const h=l[Vt];return i?.filterPredicate?i.filterPredicate(h):i?.useIgnoreRaycastLayer!==!1?!h?.gameObject.layers.isEnabled(2):!0});if(a){const l=r.pointAt(a.timeOfImpact),h=this.raycastVectorsBuffer.get();return h.set(l.x,l.y,l.z),{point:h,collider:a.collider[Vt]}}return null}raycastAndGetNormal(e,t,i){if(!this._isInitialized)return null;let n=i?.maxDistance,o=i?.solid;n===void 0&&(n=1/0),o===void 0&&(o=!0);const r=this.getPhysicsRay(this.rapierRay,e,t);if(!r)return null;(this.debugRenderRaycasts||Nh)&&B.DrawRay(r.origin,r.dir,255,1);const a=this.world?.castRayAndGetNormal(r,n,o,i?.queryFilterFlags,i?.filterGroups,void 0,void 0,l=>{const h=l[Vt];return i?.filterPredicate?i.filterPredicate(h):i?.useIgnoreRaycastLayer!==!1?!h?.gameObject.layers.isEnabled(2):!0});if(a){const l=r.pointAt(a.timeOfImpact),h=a.normal,d=this.raycastVectorsBuffer.get(),u=this.raycastVectorsBuffer.get();return d.set(l.x,l.y,l.z),u.set(h.x,h.y,h.z),{point:d,normal:u,collider:a.collider[Vt]}}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)&&(Ue&&console.warn("Converting screenspace to raycast space",a),this.context?.input.convertScreenspaceToRaycastSpace(a)),a.unproject(n),t=a}const o=t;e.origin.x=o.x,e.origin.y=o.y,e.origin.z=o.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=X(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 exports.MODULES.RAPIER_PHYSICS.MODULE.Ball(t),this.rapierSphere.radius=t,(this.debugRenderRaycasts||Nh)&&B.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 exports.MODULES.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||Nh)&&B.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 o=n[Vt],r=new f0(o.gameObject,o);return this.rapierColliderArray.push(r),!0},void 0,void 0,void 0,void 0,n=>n.isSensor()?!1:n[Vt].gameObject.layers.isEnabled(2)==!1),this.rapierColliderArray):this.rapierColliderArray:this.rapierColliderArray}enabled=!1;get world(){return this._world}_tempPosition=new c.Vector3;_tempQuaternion=new c.Quaternion;_tempScale=new c.Vector3;_tempMatrix=new c.Matrix4;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){Ue&&console.warn("Physics are disabled");return}const i=e.gameObject,n=Ie(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 o=1e-7;n.x<o&&(n.x=o),n.y<o&&(n.y=o),n.z<o&&(n.z=o);const r=exports.MODULES.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){Ue&&console.warn("Physics are disabled");return}const t=exports.MODULES.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){Ue&&console.warn("Physics are disabled");return}const o=e.gameObject.worldScale;o.x=Math.abs(o.x),o.y=Math.abs(o.y);const r=i*o.x;t=Math.max(t,r);const a=D.clamp(t*.5*o.y-i*o.x,0,Number.MAX_SAFE_INTEGER),l=exports.MODULES.RAPIER_PHYSICS.MODULE.ColliderDesc.capsule(a,r);this.createCollider(e,l)}async addMeshCollider(e,t,i,n){let o=t.geometry;if(!o){Ue&&console.warn("Missing mesh geometry",t.name);return}o.index?.array?.length||(console.warn(`Your MeshCollider is missing vertices or indices in the assined mesh "${t.name}". Consider providing an indexed geometry.`),o=q.mergeVertices(o));let r=null;const a=o.getAttribute("position");if(a instanceof c.InterleavedBufferAttribute){const u=a.count;r=new Float32Array(u*3);for(let p=0;p<u;p++){const m=a.getX(p),y=a.getY(p),b=a.getZ(p);r[p*3]=m,r[p*3+1]=y,r[p*3+2]=b}}else r=a.array;if(await this.initialize(),!this.enabled){Ue&&console.warn("Physics are disabled");return}if(!e.activeAndEnabled)return;const l=o.index?.array,h=e.gameObject.worldScale.clone();if(n&&h.multiply(n),Math.abs(h.x-1)>1e-4||Math.abs(h.y-1)>1e-4||Math.abs(h.z-1)>1e-4){const u=`${o.uuid}_${h.x}_${h.y}_${h.z}_${i}`;if(this._meshCache.has(u))Ue&&console.warn("Use cached mesh collider"),r=this._meshCache.get(u);else{(Ue||A())&&console.debug(`[Performance] Your MeshCollider "${e.name}" is scaled: consider applying the scale to the collider mesh instead (${h.x}, ${h.y}, ${h.z})`);const p=new Float32Array(r.length);for(let m=0;m<r.length;m+=3)p[m]=r[m]*h.x,p[m+1]=r[m+1]*h.y,p[m+2]=r[m+2]*h.z;r=p,this._meshCache.set(u,p)}}const d=i?exports.MODULES.RAPIER_PHYSICS.MODULE.ColliderDesc.convexHull(r):exports.MODULES.RAPIER_PHYSICS.MODULE.ColliderDesc.trimesh(r,l);d&&this.createCollider(e,d)}updatePhysicsMaterial(e){if(!e)return;const t=e.sharedMaterial,i=e[Rt];if(i&&t){if(t.bounciness!==void 0&&i.setRestitution(t.bounciness),t.bounceCombine!==void 0)switch(t.bounceCombine){case it.Average:i.setRestitutionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case it.Maximum:i.setRestitutionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case it.Minimum:i.setRestitutionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case it.Multiply:i.setRestitutionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}if(t.dynamicFriction!==void 0&&i.setFriction(t.dynamicFriction),t.frictionCombine!==void 0)switch(t.frictionCombine){case it.Average:i.setFrictionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case it.Maximum:i.setFrictionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case it.Minimum:i.setFrictionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case it.Multiply:i.setFrictionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}}}getBody(e){return e?e[Rt]:null}getComponent(e){return e?e[Vt]: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):(Ue&&console.log("Create collider without rigidbody",e.name),i.makeRotationFromQuaternion(ue(e.gameObject)),i.setPosition(X(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 o=e.sharedMaterial;if(o){if(o.bounciness!==void 0&&t.setRestitution(o.bounciness),o.bounceCombine!==void 0)switch(o.bounceCombine){case it.Average:t.setRestitutionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case it.Maximum:t.setRestitutionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case it.Minimum:t.setRestitutionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case it.Multiply:t.setRestitutionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}if(o.dynamicFriction!==void 0&&t.setFriction(o.dynamicFriction),o.frictionCombine!==void 0)switch(o.frictionCombine){case it.Average:t.setFrictionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case it.Maximum:t.setFrictionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case it.Minimum:t.setFrictionCombineRule(exports.MODULES.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case it.Multiply:t.setFrictionCombineRule(exports.MODULES.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[Vt]=e,e[Rt]=r,r.setActiveEvents(exports.MODULES.RAPIER_PHYSICS.MODULE.ActiveEvents.COLLISION_EVENTS),r.setActiveCollisionTypes(exports.MODULES.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[Rt],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 o=e.filter;let r=0;if(o==null)r=65535;else for(let a=0;a<o.length;a++){const l=o[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[Rt],!i){const o=n.isKinematic&&!Yf;Ue&&console.log("Create rigidbody",o);const r=o?exports.MODULES.RAPIER_PHYSICS.MODULE.RigidBodyDesc.kinematicPositionBased():exports.MODULES.RAPIER_PHYSICS.MODULE.RigidBodyDesc.dynamic(),a=X(e.attachedRigidbody.gameObject);r.setTranslation(a.x,a.y,a.z),r.setRotation(ue(e.attachedRigidbody.gameObject)),r.centerOfMass=new exports.MODULES.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[Vt]=n,n[Rt]=i,this.internalUpdateRigidbodyProperties(n,i),this.getRigidbodyRelativeMatrix(e.gameObject,n.gameObject,t),e[eb]=i}else{const n=exports.MODULES.RAPIER_PHYSICS.MODULE.RigidBodyDesc.kinematicPositionBased(),o=X(e.gameObject);n.setTranslation(o.x,o.y,o.z),n.setRotation(ue(e.gameObject)),i=this.world.createRigidBody(n),t.identity(),i[Vt]=null}return i}internal_getRigidbody(e){return e.isCollider===!0?e[eb]:e[Rt]}internalUpdateColliderProperties(e,t){const i=t.shape;let n=!1;switch(i.type){case exports.MODULES.RAPIER_PHYSICS.MODULE.ShapeType.Ball:{const p=i,m=e,y=e.gameObject,b=Ie(y,this._tempPosition),g=Math.abs(m.radius*b.x);n=p.radius!==g,p.radius=g,n&&t.setShape(p);break}case exports.MODULES.RAPIER_PHYSICS.MODULE.ShapeType.Cuboid:const o=i,r=e,a=e.gameObject,l=Ie(a,this._tempPosition),h=Math.abs(r.size.x*.5*l.x),d=Math.abs(r.size.y*.5*l.y),u=Math.abs(r.size.z*.5*l.z);n=o.halfExtents.x!==h||o.halfExtents.y!==d||o.halfExtents.z!==u,o.halfExtents.x=h,o.halfExtents.y=d,o.halfExtents.z=u,n&&t.setShape(o);break}if(n){const o=e.attachedRigidbody;o?.autoMass&&this.getBody(o)?.recomputeMassPropertiesFromColliders()}this.updateColliderCollisionGroups(e),e.isTrigger!==t.isSensor()&&t.setSensor(e.isTrigger)}internalUpdateRigidbodyProperties(e,t){if(t.enableCcd(e.collisionDetectionMode!==iu.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(exports.MODULES.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicPositionBased,!1):t.setBodyType(exports.MODULES.RAPIER_PHYSICS.MODULE.RigidBodyType.Dynamic,!1)}lines;step(e){if(this.world&&this.enabled){if(this._isUpdatingPhysicsWorld=!0,this.eventQueue||(this.eventQueue=new exports.MODULES.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 wR(this.world,this.eventQueue)),this.collisionHandler&&(this.collisionHandler.handleCollisionEvents(),this.collisionHandler.update()),this.updateDebugRendering(this.world))}updateDebugRendering(e){if(Ue||Yf||vR||this.debugRenderColliders===!0){if(!this.lines){const i=new c.LineBasicMaterial({color:7855479,fog:!1}),n=new c.BufferGeometry;this.lines=new c.LineSegments(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 c.BufferAttribute(t.vertices,3)),this.lines.geometry.setAttribute("color",new c.BufferAttribute(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(!Yf)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 o=i.translation(),r=i.rotation();if(Number.isNaN(o.x)||Number.isNaN(r.x)){!n.__COLLIDER_NAN&&A()&&(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),h=Ie(t.gameObject);l.multiply(h),o.x-=l.x,o.y-=l.y,o.z-=l.z}Wo(t.gameObject,o.x,o.y,o.z),tm(t.gameObject,r.x,r.y,r.z,r.w)}}syncPhysicsBody(e,t,i,n){if(t instanceof exports.MODULES.RAPIER_PHYSICS.MODULE.RigidBody){const o=X(e,this._tempPosition),r=ue(e,this._tempQuaternion);switch(t.bodyType()){case exports.MODULES.RAPIER_PHYSICS.MODULE.RigidBodyType.Fixed:case exports.MODULES.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicPositionBased:case exports.MODULES.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicVelocityBased:i&&t.setNextKinematicTranslation(o),n&&t.setNextKinematicRotation(r);break;default:i&&t.setTranslation(o,!1),n&&t.setRotation(r,!1);break}}else if(t instanceof exports.MODULES.RAPIER_PHYSICS.MODULE.Collider){e.matrixWorldNeedsUpdate&&e.updateWorldMatrix(!0,!1),e.matrixWorld.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const o=this._tempPosition,r=this._tempQuaternion,a=t[Vt];if(this.tryApplyCenter(a,o),i){const l=t.translation();(l.x!==o.x||l.y!==o.y||l.z!==o.z)&&t.setTranslation(o)}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 c.Vector3;_tempCenterVec=new c.Vector3;_tempCenterQuaternion=new c.Quaternion;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,Ie(e.gameObject,this._tempCenterVec),this._tempCenterPos.multiply(this._tempCenterVec),e.attachedRigidbody?this._tempCenterPos.applyQuaternion(e.gameObject.quaternion):(ue(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=oa._matricesBuffer,n.length=0),e===t){const o=Ie(e,this._tempPosition);i.makeScale(o.x,o.y,o.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[Rt],n=t[Rt];this.calculateJointRelativeMatrices(e.gameObject,t.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const o=exports.MODULES.RAPIER_PHYSICS.MODULE.JointData.fixed(oa.centerConnectionPos,oa.centerConnectionRot,this._tempPosition,this._tempQuaternion),r=this.world.createImpulseJoint(o,i,n,!0);Ue&&console.log("ADD FIXED JOINT",r)}addHingeJoint(e,t,i,n){if(!this.world){console.error("Physics world not initialized");return}const o=e[Rt],r=t[Rt];this.calculateJointRelativeMatrices(e.gameObject,t.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const a=exports.MODULES.RAPIER_PHYSICS.MODULE.JointData.revolute(i,this._tempPosition,n),l=this.world.createImpulseJoint(a,o,r,!0);Ue&&console.log("ADD HINGE JOINT",l)}calculateJointRelativeMatrices(e,t,i){e.updateWorldMatrix(!0,!1),t.updateWorldMatrix(!0,!1);const n=e.matrixWorld,o=t.matrixWorld;n.elements[0]=1,n.elements[5]=1,n.elements[10]=1,o.elements[0]=1,o.elements[5]=1,o.elements[10]=1,i.copy(o).premultiply(n.invert()).invert()}}class wR{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),o=this.world.getCollider(t);if(!n||!o)return;const r=n[Vt],a=o[Vt];Kf&&console.log("EVT",r.name,a.name,i,n,o),r&&a&&(i?(this.onCollisionStarted(r,n,a,o),this.onCollisionStarted(a,o,r,n)):(this.onCollisionEnded(r,a),this.onCollisionEnded(a,r)))})}update(){this.onHandleCollisionStay()}onCollisionStarted(e,t,i,n){let o=null;if(e.isTrigger||i.isTrigger)qo(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)=>{qo(r,h=>{if(h.destroyed)return;const d=h.onCollisionEnter||h.onCollisionStay||h.onCollisionExit;if(d||Kf){if(!o){const u=[],p=a.normal();i instanceof so&&i.convex&&(p.x=-p.x,p.y=-p.y,p.z=-p.z);for(let m=0;m<a.numSolverContacts();m++){const y=a.solverContactPoint(m),b=a.contactImpulse(m);if(y){const g=a.contactDist(m),v=a.solverContactFriction(m),_=a.solverContactTangentVelocity(m),x=new d0(y,g,p,b,v,_);u.push(x),Kf&&B.DrawDirection(y,p,16711680,3,!0)}}o=new u0(r,i,u)}if(d){const u={collider:e,component:h,collision:o};this.activeCollisions.push(u),h.onCollisionStay&&this.activeCollisionsStay.push(u),h.onCollisionEnter?.call(h,o)}}})})}}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],o=n.collider;if(o.destroyed||n.collision.collider.destroyed){this.activeCollisions.splice(i,1),i--;continue}if(o===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],o=n.collider;if(o.destroyed||n.collision.collider.destroyed){this.activeCollisionsStay.splice(i,1),i--;continue}if(o===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],o=n.collider;if(o.destroyed||n.otherCollider.destroyed){this.activeTriggers.splice(i,1),i--;continue}if(o===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 xR{static async createComparisonScene(e){const{files:t}=e,n=await Promise.all(t.map(g=>new Y(g).loadAssetAsync())),o=new c.Scene;let r=0;for(const g of n)if(g instanceof c.Object3D){g.position.y=r,o.add(g);const v=Bt([g]);r+=v.getSize(new c.Vector3).y,r+=.1}const a=new c.PerspectiveCamera(20);o.add(a);const l=e.environment||"https://dl.polyhaven.org/file/ph-assets/HDRIs/exr/1k/studio_small_09_1k.exr";{let g=null;if(l.endsWith(".hdr")){const v=(await Promise.resolve().then(()=>require("./three-examples-C9WfZu-X.umd.cjs")).then(_=>_.RGBELoader$1)).RGBELoader;g=new v}else if(l.endsWith(".exr")){const v=(await Promise.resolve().then(()=>require("./three-examples-C9WfZu-X.umd.cjs")).then(_=>_.EXRLoader$1)).EXRLoader;g=new v}if(g){const v=await g.loadAsync(l).catch(_=>(console.error(_),null));v&&(v.mapping=c.EquirectangularReflectionMapping,v.needsUpdate=!0,o.background=v,o.environment=v,o.backgroundBlurriness=.75)}else console.warn("Unsupported environment map format",l)}const h=Bt(o.children),d=h.getCenter(new c.Vector3),u=h.getSize(new c.Vector3),m=Math.max(u.x,u.y,u.z)/(2*Math.tan(Math.PI*a.fov/360));a.position.set(d.x,d.y,m),a.lookAt(d);const y=new q.OrbitControls(a,e.domElement||document.body);y.target=d,y.update();const b=(e.domElement||document.body).getBoundingClientRect();return a.aspect=b.width/b.height,a.updateProjectionMatrix(),{scene:o,camera:a}}}let Xp=0;function tb(s){s?Xp++:Xp--}function SR(){return Xp>0}const CR={binary:!0,animations:!0};async function PR(s){if(!s.context)throw new Error("No context provided to exportAsGLTF");s.scene||(s.scene=s.context.scene);const e={...CR,...s},{context:t}=e,i=new q.GLTFExporter;i.register(a=>new L0(a)),i.register(a=>new $P(a)),i.register(a=>new k0(a)),Jm(i,e.context);const n={binary:e.binary,animations:MR(t,e.scene,[])},o=new OR;console.debug("Exporting GLTF",n),o.onBeforeExport(e),tb(!0);const r=await i.parseAsync(e.scene,n).catch(a=>(console.error(a),null));if(tb(!1),o.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),h=document.createElement("a");h.href=l;let d=e.downloadAs;!d.endsWith(".glb")&&!d.endsWith(".gltf")&&(d+=e.binary?".glb":".gltf"),h.download=d,h.click()}}return r}const ib=Symbol("needle:weight");class OR{_undo=[];onBeforeExport(e){e.context.animations.mixers.forEach(t=>{const i=fa.tryGetActionsFromMixer(t);if(i)for(let n=0;n<i.length;n++){const o=i[n];o[ib]=o.weight,o.weight=0,this._undo.push(()=>{o.weight=o[ib]})}t.update(0)}),e.context.scene.traverse(t=>{if(!Ep(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 MR(s,e,t){s.animations.mixers.forEach(n=>{const o=fa.tryGetActionsFromMixer(n);if(o)for(let r=0;r<o.length;r++){const l=o[r].getClip();t.push(l)}}),Array.isArray(e)||(e=[e]);for(const n of e)fa.tryGetAnimationClipsFromObjectHierarchy(n,t);const i=new Set(t);return Array.from(i)}const nb="needle-button",Zf=A();class Vw 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;#s;#e;#i;#o;#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{Zf?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.#s??=document.createElement("style"),this.#s.innerHTML=`
|
|
1605
1583
|
button {
|
|
1606
1584
|
all: initial;
|
|
1607
1585
|
cursor: inherit;
|
|
@@ -1635,4 +1613,4 @@ Error:`,r),null}}updateColliderCollisionGroups(e){const t=e[Rt],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.#s),xd(xp,{element:this.#t}),this.#o?.disconnect(),this.#o??=new MutationObserver(()=>this.#l()),this.#o.observe(this.#e,{attributes:!0}),Zf&&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=>{Zf&&console.log("Needle Button clicked"),!e.defaultPrevented&&this.#e&&this.#e.click()}}typeof window<"u"&&!window.customElements.get(nb)&&window.customElements.define(nb,Vw);const dl=w("debugavatar");class ny{root;head;leftHand;rigthHand;get isValid(){return this.head!==null&&this.head!==void 0}constructor(e,t,i,n){this.root=e,this.head=t,this.leftHand=i,this.rigthHand=n,this.root?.traverse(o=>o.layers.set(2))}}class $w{avatarRegistryUrl=null;async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let i=null;if(typeof t=="string"){if(i=await this.loadAvatar(e,t),!i){const o=new on;i=S.instantiate(ra(t,e.scene),o)}}else i=t;if(!i)return null;const n=this.findAvatar(i);return n.isValid?(dl&&console.log("[Custom Avatar] valid config",t,dl?n:""),n):(console.warn("[Custom Avatar] config isn't valid",t,dl?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(dl&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){const n=await fetch("./"+t);let o=null;if(n.ok){const a=await n.blob();a&&(o=await a.arrayBuffer())}return o?(await en().parseSync(e,o,null,0))?.scene??null:null}const i=new q.GLTFLoader;return Tm(i,e),new Promise((n,o)=>{const r=this.avatarRegistryUrl+"/"+t;i.load(r,async a=>{await en().createBuiltinComponents(e,r,a,null,void 0),n(a.scene)},a=>{dl&&console.log("[Custom Avatar] "+a.loaded/a.total*100+"% loaded of "+a.total/1024+"kB")},a=>{console.error("[Custom Avatar] Error when loading: "+a),n(null)})})}cacheModel(e,t){}findAvatar(e){const t=e;let i=t;i.children.length==1&&(i=e.children[0]);let n=this.findAvatarPart(i,["head"]);const o=this.findAvatarPart(i,["left","hand"]),r=this.findAvatarPart(i,["right","hand"]);if(!n){n=t;const l=new c.Vector3;new c.Box3().setFromObject(n).getSize(l);const h=Math.max(l.x,l.y,l.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+h+" meters! Should be < 0.3m"),h>.3&&n.scale.multiplyScalar(1/h*.3)}return new ny(t,n,o,r)}findAvatarPart(e,t){const i=e.name.toLowerCase();let n=!0;for(const o of t){if(!n)break;i.indexOf(o)===-1&&(n=!1)}if(n)return e;if(e.children)for(const o of e.children){const r=this.findAvatarPart(o,t);if(r)return r}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}}class Ww{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(e){}}class Gw{}const kR=Object.freeze(Object.defineProperty({__proto__:null,ActionBuilder:le,ActionCollection:Y0,ActionModel:Wt,AlignmentConstraint:vc,Animation:Ft,AnimationCurve:zc,AnimationExtension:fu,AnimationTrackHandler:Iu,Animator:rt,AnimatorController:Di,Antialiasing:Vc,Attractor:Ia,AudioExtension:dr,AudioListener:ns,AudioSource:pi,AudioTrackHandler:os,Avatar:Ys,AvatarBlink_Simple:ar,AvatarEyeLook_Rotation:zm,AvatarLoader:$w,AvatarMarker:xe,AvatarModel:ny,Avatar_Brain_LookAt:Zl,Avatar_MouthShapes:Cc,Avatar_MustacheShake:Fm,Avatar_POI:Vo,AxesHelper:xa,BaseUIComponent:Bi,BasicIKConstraint:Vm,BehaviorExtension:yg,BehaviorModel:gt,BloomEffect:Ou,BoxCollider:lu,BoxGizmo:mr,BoxHelperComponent:nt,Button:vs,CallInfo:is,Camera:qt,CameraTargetReachedEvent:Kl,Canvas:ya,CanvasGroup:Ks,CapsuleCollider:ls,ChangeMaterialOnClick:lg,ChangeTransformOnClick:ur,CharacterController:lr,CharacterControllerInput:us,ChromaticAberration:$c,ClickThrough:$u,Collider:Kt,ColorAdjustments:uo,ColorBySpeedModule:Da,ColorOverLifetimeModule:Su,ContactShadows:Pc,ControlTrackHandler:ju,CursorFollow:sh,CustomBranding:pr,Deletable:Hm,DeleteBox:Gs,DepthOfField:ln,DeviceFlag:cu,DocumentExtension:Ww,DragControls:Ro,DropListener:fs,Duplicatable:Qm,EffectWrapper:nc,EmissionModule:_s,EmphasizeOnClick:Oa,EnvironmentScene:Nu,EventList:oe,EventListEvent:nu,EventSystem:jt,EventTrigger:du,FieldWithDefault:I0,FixedJoint:Tg,Fog:Ta,GltfExport:sg,GltfExportBox:ig,Gradient:yr,Graphic:Dc,GraphicRaycaster:su,GridHelper:Aa,GridLayoutGroup:Sg,GroundProjectedEnv:In,GroupActionModel:To,HideOnStart:Ei,HingeJoint:jc,HorizontalLayoutGroup:xg,Image:Ua,InheritVelocityModule:Ig,InputField:Qg,InstanceHandle:$o,InstancingHandler:Ko,Interactable:Gm,Keyframe:Xt,LODGroup:Fc,LODModel:La,Light:ei,LimitVelocityOverLifetimeModule:et,LogStats:Wm,LookAt:Yg,LookAtConstraint:rr,MainModule:Ct,MaskableGraphic:Ic,MeshCollider:so,MeshRenderer:Mc,MinMaxCurve:G,MinMaxGradient:_r,NeedleMenu:Bn,NestedGltf:Uc,Networking:Lg,NoiseModule:fe,ObjectRaycaster:fi,OffsetConstraint:gr,OpenURL:za,OrbitControls:de,Outline:Ra,Padding:fr,ParticleBurst:Dd,ParticleSubEmitter:jg,ParticleSystem:ic,ParticleSystemRenderer:Vi,PhysicsExtension:_g,PixelationEffect:Wc,PlayAnimationOnClick:ec,PlayAudioOnClick:Qs,PlayableDirector:er,PlayerColor:_a,PointerEventData:xc,PostProcessingHandler:Ng,PreliminaryAction:Ma,PreliminaryTrigger:Rc,RawImage:Uu,Rect:tw,RectTransform:sn,ReflectionProbe:Jl,RegisteredAnimationInfo:Vs,RemoteSkybox:ku,Renderer:mi,RendererLightmap:Td,Rigidbody:Ne,RotationBySpeedModule:Ni,RotationOverLifetimeModule:an,SceneSwitcher:je,ScreenCapture:fo,ScreenSpaceAmbientOcclusion:bs,ScreenSpaceAmbientOcclusionN8:cn,ScrollFollow:Zg,SetActiveOnClick:cg,ShadowCatcher:Xc,ShapeModule:Dg,SharpeningEffect:Hc,SignalAsset:Du,SignalReceiver:Jc,SignalReceiverEvent:Zc,SignalTrackHandler:sc,Size:ew,SizeBySpeedModule:ti,SizeOverLifetimeModule:br,SkinnedMeshRenderer:tg,SmoothFollow:Ru,SpatialGrabRaycaster:Qo,SpatialHtml:ih,SpatialTrigger:Tu,SpatialTriggerReceiver:An,SpectatorCamera:Au,SphereCollider:Sa,SplineContainer:Sr,SplineData:Dn,SplineWalker:hn,Sprite:ms,SpriteData:sa,SpriteRenderer:Zt,SpriteSheet:ga,SubEmitterSystem:Id,SyncedCamera:$g,SyncedRoom:dn,SyncedTransform:nn,TapGestureTrigger:dg,TeleportTarget:_u,TestRunner:Wg,TestSimulateUserData:Gg,Text:St,TextBuilder:vg,TextExtension:vu,TextureSheetAnimationModule:Pt,TiltShiftEffect:zn,ToneMappingEffect:Zs,TrailModule:Re,TransformData:ke,TransformGizmo:Pr,TriggerBuilder:wt,TriggerModel:Hs,UIRaycastUtils:Dm,UIRootComponent:Ac,USDZExporter:Tn,USDZText:Yr,USDZUIExtension:Pg,UsageMarker:Oc,VariantAction:ag,VelocityOverLifetimeModule:Ae,VerticalLayoutGroup:wg,VideoPlayer:Ze,Vignette:xr,VisibilityAction:Tc,Voip:no,Volume:Ba,VolumeParameter:I,VolumeProfile:Cu,WebARCameraBackground:oh,WebARSessionRoot:hi,WebXR:bu,WebXRImageTracking:rh,WebXRImageTrackingModel:xs,WebXRPlaneTracking:Ss,WebXRTrackedImage:ba,XRControllerFollow:ws,XRControllerModel:cs,XRControllerMovement:gi,XRFlag:Ti,XRRig:Wu,XRState:It,__Ignore:Gw},Symbol.toStringTag,{value:"Module"})),Ud=w("debugmissingcamera");ae.registerCallback(re.MissingCamera,s=>{Ud&&console.warn("Creating missing camera");const e=s.context.scene,t=new c.PerspectiveCamera;t.name="Default Fallback Camera",e.add(t);const i=new qt;if(i.sourceId=s.files?.[0]?.src??"unknown",i.fieldOfView=35,s.context.domElement.getAttribute("transparent")!=null)i.clearFlags=No.Uninitialized;else if(s.context.domElement.getAttribute("background-image")?.length||s.context.lightmaps.tryGetSkybox(i.sourceId))i.clearFlags=No.Skybox;else{if(i.clearFlags=No.SolidColor,!s.context.domElement.getAttribute("background-color")){let a="#efefef";typeof window!==void 0&&window.matchMedia("(prefers-color-scheme: dark)").matches&&(a="#1f1f1f"),e.background=new c.Color(a)}if(!e.environment){const a=new c.PMREMGenerator$1(s.context.renderer),l=new Nu("neutral");e.environment=a.fromScene(l,.025).texture}}const o=jo(t,i,!0);return t.position.x=0,t.position.y=1,t.position.z=2,s.context.domElement?.cameraControls!=!1&&Hw(s.context,o),o});ae.registerCallback(re.ContextCreated,s=>{if(!s.context.mainCamera){Ud&&console.log("Will not auto-fit because a default camera exists");return}if(s.context.domElement?.cameraControls==!0){if(bb(s.context.mainCamera)?.isCameraController==!0){Ud&&console.log("Will not auto-fit because a camera controller exists");return}Hw(s.context)}});function Hw(s,e){e=e??s.mainCameraComponent;const t=e?.gameObject;if(Ud&&console.log("Creating default camera controls",e?.name),t){const i=pc(t,de);i.sourceId=e?.sourceId??"unknown";const n=s.domElement.getAttribute("auto-rotate");if(i.autoRotate=n!=null&&n!="0"&&n?.toLowerCase()!="false",i.autoRotateSpeed=.5,i.autoFit=!0,i.autoRotate&&n){const o=parseFloat(n);isNaN(o)||(i.autoRotateSpeed=o)}}else console.warn("Missing camera object, can not add orbit controls")}ae.registerCallback(re.ContextCreated,s=>{const e=s.context.domElement.getAttribute("autoplay");if(e!==void 0&&(e===""||e==="true"||e==="1")&&s.files)for(const t of s.files)S.foreachComponent(t.file.scene,n=>{if(n.enabled!==!1){if(n instanceof Ft&&n.playAutomatically||n instanceof rt||n instanceof er&&n.playOnAwake===!0)return!0;if(n instanceof Ft)return n.playAutomatically=!0,!0;if(n instanceof er)return n.playOnAwake=!0,!0}},!0)!==!0&&fa.autoplayAnimations(t.file)});exports.SplineUtils=void 0;(s=>{function e(t,i=!1,n=.75){const o=new Sr,r=1-D.clamp(n,0,1);return t.forEach((a,l)=>{const h=new c.Vector3;l<t.length-1?h.subVectors(t[l+1],a).normalize().multiplyScalar(r):i&&t.length>1&&h.subVectors(t[0],a).normalize().multiplyScalar(r);const d=new Dn;d.position.copy(a),d.tangentIn.copy(h),d.tangentOut.copy(h),o.addKnot(d)}),o.closed=i,o}s.createFromPoints=e})(exports.SplineUtils||(exports.SplineUtils={}));class ER extends se.WorkerBase{constructor(){super(new Worker(new URL("/generateMeshBVH.worker-2qGLkQjg.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:Hu&&Hu.tagName.toUpperCase()==="SCRIPT"&&Hu.src||new URL("needle-engine.bundle-BcceMKjs.umd.cjs",document.baseURI).href),{type:"module"})),this.name="GenerateMeshBVHWorker"}runTask(e,t,i={}){return new Promise((n,o)=>{if(t.getAttribute("position").isInterleavedBufferAttribute||t.index&&t.index.isInterleavedBufferAttribute)throw new Error("GenerateMeshBVHWorker: InterleavedBufferAttribute are not supported for the geometry attributes.");e.onerror=h=>{o(new Error(`[GenerateMeshBVHWorker] ${h.message||"Unknown error. Please check the server console. If you're using vite try adding 'three-mesh-bvh' to 'optimizeDeps.exclude' in your vite.config.js"}`))},e.onmessage=h=>{const{data:d}=h;if(d.error)o(new Error(d.error)),e.onmessage=null;else if(d.serialized){const{serialized:u,position:p}=d,m=se.MeshBVH.deserialize(u,t,{setIndex:!1}),y=Object.assign({setBoundingBox:!0},i);if(t.attributes.position.array=p,u.index)if(t.index)t.index.array=u.index;else{const _=new c.BufferAttribute(u.index,1,!1);t.setIndex(_)}y.setBoundingBox&&(t.boundingBox=m.getBoundingBox(new c.Box3)),i.onProgress&&i.onProgress(d.progress),n(m),e.onmessage=null}else i.onProgress&&i.onProgress(d.progress)};const r=t.index?t.index.array:null,a=t.attributes.position.array,l=[a];r&&l.push(r),e.postMessage({index:r,position:a,options:{...i,onProgress:null,includedProgressCallback:!!i.onProgress,groups:[...t.groups]}},l.map(h=>h.buffer).filter(h=>typeof SharedArrayBuffer>"u"||!(h instanceof SharedArrayBuffer)))})}}const RR=Object.freeze(Object.defineProperty({__proto__:null,GenerateMeshBVHWorker:ER},Symbol.toStringTag,{value:"Module"}));exports.$physicsKey=fP;exports.ActionBuilder=le;exports.ActionCollection=Y0;exports.ActionModel=Wt;exports.Addressables=Dv;exports.AlignmentConstraint=vc;exports.AmbientMode=ia;exports.Animation=Ft;exports.AnimationCurve=zc;exports.AnimationExtension=fu;exports.AnimationTrackHandler=Iu;exports.AnimationUtils=fa;exports.Animator=rt;exports.AnimatorConditionMode=Bs;exports.AnimatorController=Di;exports.AnimatorControllerParameterType=Am;exports.AnimatorStateInfo=gl;exports.Antialiasing=Vc;exports.Application=tn;exports.AssetDatabase=Kb;exports.AssetReference=Y;exports.Attractor=Ia;exports.AudioExtension=dr;exports.AudioListener=ns;exports.AudioSource=pi;exports.AudioTrackHandler=os;exports.Avatar=Ys;exports.AvatarBlink_Simple=ar;exports.AvatarEyeLook_Rotation=zm;exports.AvatarLoader=$w;exports.AvatarMarker=xe;exports.AvatarModel=ny;exports.Avatar_Brain_LookAt=Zl;exports.Avatar_MouthShapes=Cc;exports.Avatar_MustacheShake=Fm;exports.Avatar_POI=Vo;exports.Axes=Xr;exports.AxesHelper=xa;exports.BUILD_TIME=am;exports.BaseUIComponent=Bi;exports.BasicIKConstraint=Vm;exports.BehaviorExtension=yg;exports.BehaviorModel=gt;exports.BloomEffect=Ou;exports.BoxCollider=lu;exports.BoxGizmo=mr;exports.BoxHelperComponent=nt;exports.Button=vs;exports.ButtonsFactory=Qi;exports.CallDirection=m0;exports.CallInfo=is;exports.Camera=qt;exports.CameraTargetReachedEvent=Kl;exports.Canvas=ya;exports.CanvasGroup=Ks;exports.CapsuleCollider=ls;exports.ChangeMaterialOnClick=lg;exports.ChangeTransformOnClick=ur;exports.CharacterController=lr;exports.CharacterControllerInput=us;exports.ChromaticAberration=$c;exports.CircularBuffer=di;exports.ClearFlags=No;exports.ClickThrough=$u;exports.ClipExtrapolation=gn;exports.Collider=Kt;exports.Collision=u0;exports.CollisionDetectionMode=iu;exports.ColorAdjustments=uo;exports.ColorBySpeedModule=Da;exports.ColorOverLifetimeModule=Su;exports.Component=x1;exports.Component$1=k;exports.ComponentLifecycleEvents=qd;exports.Components=kR;exports.ConnectionEvents=Gb;exports.ContactPoint=d0;exports.ContactShadows=Pc;exports.Context=F;exports.ContextArgs=a1;exports.ContextEvent=re;exports.ContextRegistry=ae;exports.ControlTrackHandler=ju;exports.CursorFollow=sh;exports.CustomBranding=pr;exports.CustomShader=ye;exports.DefaultReflectionMode=wd;exports.Deletable=Hm;exports.DeleteBox=Gs;exports.DepthOfField=ln;exports.DeviceFlag=cu;exports.DocumentExtension=Ww;exports.DragControls=Ro;exports.DragMode=qm;exports.DropListener=fs;exports.Duplicatable=Qm;exports.EffectWrapper=nc;exports.EmissionModule=_s;exports.EmphasizeOnClick=Oa;exports.EngineLoadingView=oc;exports.EnvironmentScene=Nu;exports.EventList=oe;exports.EventListEvent=nu;exports.EventSystem=jt;exports.EventTrigger=du;exports.FieldWithDefault=I0;exports.FileReference=Uo;exports.FileReferenceSerializer=jv;exports.FileSpawnModel=jP;exports.File_Event=x0;exports.FixedJoint=Tg;exports.Fog=Ta;exports.FrameEvent=pe;exports.GENERATOR=Vd;exports.GameObject=S;exports.Gizmos=B;exports.GltfExport=sg;exports.GltfExportBox=ig;exports.Gradient=yr;exports.Graphic=Dc;exports.GraphicRaycaster=su;exports.Graphics=Xs;exports.GridHelper=Aa;exports.GridLayoutGroup=Sg;exports.GroundProjectedEnv=In;exports.GroupActionModel=To;exports.HideFlags=ou;exports.HideOnStart=Ei;exports.HingeJoint=jc;exports.HorizontalLayoutGroup=xg;exports.HostData=aC;exports.Image=Ua;exports.ImageReference=Fo;exports.ImageReferenceSerializer=Iv;exports.InheritVelocityModule=Ig;exports.Input=Ub;exports.InputEventQueue=Ht;exports.InputEvents=we;exports.InputField=Qg;exports.InstanceHandle=$o;exports.InstancingHandler=Ko;exports.InstancingUtil=Li;exports.InstantiateEvent=lv;exports.InstantiateIdProvider=mt;exports.InstantiateOptions=on;exports.Interactable=Gm;exports.JoinedRoomResponse=TS;exports.KeyEventArgs=vS;exports.Keyframe=Xt;exports.LODGroup=Fc;exports.LODModel=La;exports.LeftRoomResponse=AS;exports.Light=ei;exports.LightData=Nv;exports.LimitVelocityOverLifetimeModule=et;exports.LoadingElementOptions=fR;exports.LogStats=Wm;exports.LogType=ci;exports.LookAt=Yg;exports.LookAtConstraint=rr;exports.MainModule=Ct;exports.MarkerType=Hg;exports.MaskableGraphic=Ic;exports.Mathf=D;exports.MeshCollider=so;exports.MeshRenderer=Mc;exports.MinMaxCurve=G;exports.MinMaxGradient=_r;exports.NEKeyboardEvent=ul;exports.NEPointerEvent=Kn;exports.NeedleButtonElement=Vw;exports.NeedleEngineWebComponent=iy;exports.NeedleMenu=Bn;exports.NeedlePatchesKey=Wh;exports.NeedleXRController=dm;exports.NeedleXRSession=H;exports.NeedleXRSync=Xb;exports.NeedleXRUtils=Yb;exports.NestedGltf=Uc;exports.NetworkConnection=qb;exports.NetworkedStreamEvents=Cn;exports.NetworkedStreams=Sc;exports.Networking=Lg;exports.NewInstanceModel=hv;exports.NoiseModule=fe;exports.ObjectRaycaster=fi;exports.ObjectUtils=ir;exports.OffsetConstraint=gr;exports.OneEuroFilter=Vh;exports.OneEuroFilterXYZ=Jp;exports.OpenURL=za;exports.OrbitControls=de;exports.Outline=Ra;exports.OwnershipEvent=Hb;exports.OwnershipModel=mm;exports.PUBLIC_KEY=Gr;exports.Padding=fr;exports.ParticleBurst=Dd;exports.ParticleSubEmitter=jg;exports.ParticleSystem=ic;exports.ParticleSystemBaseBehaviour=ho;exports.ParticleSystemRenderer=Vi;exports.ParticleSystemShapeType=Ld;exports.PeerHandle=ss;exports.PeerNetworking=Wb;exports.Physics=da;exports.PhysicsExtension=_g;exports.PhysicsMaterialCombine=it;exports.PixelationEffect=Wc;exports.PlayAnimationOnClick=ec;exports.PlayAudioOnClick=Qs;exports.PlayableDirector=er;exports.PlayerColor=_a;exports.PlayerState=Yi;exports.PlayerStateEvent=J0;exports.PlayerSync=mg;exports.PlayerView=Fv;exports.PlayerViewManager=Uv;exports.PointerEventData=xc;exports.PointerType=Gd;exports.PostProcessingEffect=Ve;exports.PostProcessingEffectOrder=Ke;exports.PostProcessingHandler=Ng;exports.PreliminaryAction=Ma;exports.PreliminaryTrigger=Rc;exports.PrimitiveType=Go;exports.Progress=ie;exports.PromiseAllWithErrors=Kp;exports.PromiseErrorResult=tp;exports.RGBAColor=Z;exports.RapierPhysics=oa;exports.RawImage=Uu;exports.RaycastOptions=io;exports.Rect=tw;exports.RectTransform=sn;exports.ReflectionProbe=Jl;exports.RegisteredAnimationInfo=Vs;exports.RemoteSkybox=ku;exports.RenderTexture=Sn;exports.RenderTextureSerializer=a0;exports.Renderer=mi;exports.RendererData=zv;exports.RendererLightmap=Td;exports.Rigidbody=Ne;exports.RigidbodyConstraints=De;exports.RoomEvents=Q;exports.RotationBySpeedModule=Ni;exports.RotationOverLifetimeModule=an;exports.SceneLightSettings=kd;exports.SceneSwitcher=je;exports.ScreenCapture=fo;exports.ScreenSpaceAmbientOcclusion=bs;exports.ScreenSpaceAmbientOcclusionN8=cn;exports.ScrollFollow=Zg;exports.SendQueue=Xi;exports.SerializationContext=Pm;exports.SetActiveOnClick=cg;exports.ShadowCatcher=Xc;exports.ShapeModule=Dg;exports.ShapeOverlapResult=f0;exports.SharpeningEffect=Hc;exports.SignalAsset=Du;exports.SignalReceiver=Jc;exports.SignalReceiverEvent=Zc;exports.SignalTrackHandler=sc;exports.Size=ew;exports.SizeBySpeedModule=ti;exports.SizeOverLifetimeModule=br;exports.SkinnedMeshRenderer=tg;exports.SmoothFollow=Ru;exports.SpatialGrabRaycaster=Qo;exports.SpatialHtml=ih;exports.SpatialTrigger=Tu;exports.SpatialTriggerReceiver=An;exports.SpectatorCamera=Au;exports.SphereCollider=Sa;exports.SphereIntersection=_m;exports.SplineContainer=Sr;exports.SplineData=Dn;exports.SplineWalker=hn;exports.Sprite=ms;exports.SpriteData=sa;exports.SpriteRenderer=Zt;exports.SpriteSheet=ga;exports.StateMachineBehaviour=k1;exports.StreamEndedEvent=jm;exports.StreamReceivedEvent=p0;exports.SubEmitterSystem=Id;exports.SyncedCamera=$g;exports.SyncedRoom=dn;exports.SyncedTransform=nn;exports.TapGestureTrigger=dg;exports.TeleportTarget=_u;exports.TestRunner=Wg;exports.TestSceneUtils=xR;exports.TestSimulateUserData=Gg;exports.Text=St;exports.TextBuilder=vg;exports.TextExtension=vu;exports.TextureSheetAnimationModule=Pt;exports.TiltShiftEffect=zn;exports.Time=Vv;exports.ToneMappingEffect=Zs;exports.TrackHandler=eh;exports.TrackType=si;exports.TrailModule=Re;exports.TransformData=ke;exports.TransformGizmo=Pr;exports.TriggerBuilder=wt;exports.TriggerModel=Hs;exports.TypeStore=P;exports.UIRaycastUtils=Dm;exports.UIRootComponent=Ac;exports.USDDocument=og;exports.USDObject=ze;exports.USDWriter=N0;exports.USDZExporter=Tn;exports.USDZExporter$1=V0;exports.USDZText=Yr;exports.USDZUIExtension=Pg;exports.UriSerializer=l0;exports.UsageMarker=Oc;exports.UserJoinedOrLeftRoomModel=LS;exports.VERSION=Ki;exports.VariantAction=ag;exports.VelocityOverLifetimeModule=Ae;exports.VerticalLayoutGroup=wg;exports.VideoPlayer=Ze;exports.ViewDevice=$s;exports.Vignette=xr;exports.VisibilityAction=Tc;exports.Voip=no;exports.Volume=Ba;exports.VolumeParameter=I;exports.VolumeProfile=Cu;exports.WaitForFrames=zC;exports.WaitForPromise=Bv;exports.WaitForSeconds=km;exports.Watch=rs;exports.WebARCameraBackground=oh;exports.WebARSessionRoot=hi;exports.WebXR=bu;exports.WebXRButtonFactory=qs;exports.WebXRImageTracking=rh;exports.WebXRImageTrackingModel=xs;exports.WebXRPlaneTracking=Ss;exports.WebXRTrackedImage=ba;exports.XRControllerFollow=ws;exports.XRControllerModel=cs;exports.XRControllerMovement=gi;exports.XRFlag=Ti;exports.XRRig=Wu;exports.XRState=It;exports.XRStateFlag=wn;exports.__Ignore=Gw;exports.__internalNotifyObjectDestroyed=YS;exports.activeInHierarchyFieldName=as;exports.addAttributeChangeCallback=db;exports.addComponent=Zi;exports.addCustomExtensionPlugin=sO;exports.addNewComponent=jo;exports.addPatch=$d;exports.apply=Qd;exports.applyHMRChanges=w1;exports.applyPrototypeExtensions=xv;exports.beginListenDestroy=cv;exports.beginListenInstantiate=uv;exports.binaryIdentifierCasts=um;exports.build_scene_functions=r1;exports.builtinComponentKeyName=Po;exports.calculateProgress01=ty;exports.clearMessages=Rx;exports.colorSerializer=G1;exports.compareAssociation=gv;exports.componentSerializer=Jh;exports.copyTexture=Ob;exports.createMotion=n0;exports.debugNet=zt;exports.debugOwner=fl;exports.decompressGpuTexture=H0;exports.deepClone=ac;exports.delay=Ln;exports.delayForFrames=lc;exports.deserializeObject=bd;exports.destroy=ui;exports.destroyComponentInstance=Pv;exports.determineMimeTypeFromExtension=S0;exports.disposeObjectResources=_e;exports.disposeStream=Pn;exports.editorGuidKeyName=Rl;exports.enableSpatialConsole=Lo;exports.euler=q1;exports.eventListSerializer=K1;exports.exportAsGLTF=PR;exports.findByGuid=Mm;exports.findObjectOfType=yc;exports.findObjectsOfType=Mv;exports.findResourceUsers=bm;exports.fitObjectIntoVolume=kb;exports.foreachComponent=qo;exports.foreachComponentEnumerator=Kd;exports.forward=qx;exports.generateQRCode=fb;exports.generateSeed=dv;exports.getBoundingBox=Bt;exports.getCameraController=bb;exports.getComponent=sr;exports.getComponentInChildren=gc;exports.getComponentInParent=Xl;exports.getComponents=mc;exports.getComponentsInChildren=va;exports.getComponentsInParent=Xd;exports.getFormattedDate=B0;exports.getIconElement=pt;exports.getIconTexture=wp;exports.getLoader=en;exports.getOrAddComponent=pc;exports.getParam=w;exports.getParentHierarchyPath=Yx;exports.getPath=ax;exports.getPeerOptions=MS;exports.getPeerjsInstance=$b;exports.getResourceUserCount=ZS;exports.getTempColor=xb;exports.getTempQuaternion=Gt;exports.getTempVector=V;exports.getUrlParams=rc;exports.getVisibleInCustomShadowRendering=Mb;exports.getWorldDirection=Sb;exports.getWorldEuler=im;exports.getWorldPosition=X;exports.getWorldQuaternion=ue;exports.getWorldRotation=Nd;exports.getWorldScale=Ie;exports.hasCommercialLicense=Rn;exports.hasIndieLicense=bc;exports.hasPointerEventComponent=Cd;exports.hasProLicense=En;exports.hideDebugConsole=Ab;exports.imageToCanvas=q0;exports.instantiate=Xo;exports.invokeLoadedImportPluginHooks=A0;exports.invokeXRSessionEnd=Fb;exports.invokeXRSessionStart=Bb;exports.isActiveInHierarchy=kv;exports.isActiveSelf=wa;exports.isAndroidDevice=fx;exports.isAnimationAction=Pb;exports.isComponent=h0;exports.isDebugMode=nx;exports.isDesktop=cx;exports.isDestroyed=Ho;exports.isDevEnvironment=A;exports.isDisposed=QS;exports.isExporting=SR;exports.isGLTFModel=c0;exports.isHostedOnGlitch=sb;exports.isHotReloadEnabled=Op;exports.isHotReloading=b1;exports.isIPad=dx;exports.isIconElement=Gv;exports.isLocalNetwork=Ii;exports.isMacOS=mx;exports.isMobileDevice=hx;exports.isMozillaXR=px;exports.isQuest=_x;exports.isResourceTrackingEnabled=Jb;exports.isSafari=yx;exports.isUsingInstancing=Yd;exports.isiOS=gx;exports.isiPad=ux;exports.loadAsset=aR;exports.loadPMREM=Sw;exports.loadSync=ey;exports.logHierarchy=dd;exports.lookAtInverse=Ux;exports.lookAtObject=cc;exports.lookAtScreenPoint=zx;exports.makeId=ox;exports.makeIdFromRandomWords=lb;exports.makeNameSafe=ji;exports.markAsInstancedRendered=Ev;exports.microphonePermissionsGranted=bx;exports.nameof=ix;exports.nameofFactory=rb;exports.objectSerializer=r0;exports.offXRSessionEnd=bS;exports.offXRSessionStart=_S;exports.onAfterRender=y1;exports.onBeforeRender=g1;exports.onClear=p1;exports.onDestroy=m1;exports.onInitialized=Yv;exports.onStart=eu;exports.onUpdate=Kv;exports.onXRSessionEnd=hm;exports.onXRSessionStart=Wd;exports.parseSync=Bw;exports.placeOnSurface=Eb;exports.postprocessFBXMaterials=om;exports.prefix=U1;exports.pushState=ab;exports.randomNumber=rx;exports.registerBinaryType=fm;exports.registerComponent=Jd;exports.registerComponentExtension=Zm;exports.registerCustomEffectType=$i;exports.registerExportExtensions=Jm;exports.registerExtensions=Rd;exports.registerHotReloadType=Jv;exports.registerLoader=lm;exports.registerPrefabProvider=pv;exports.registerPrototypeExtensions=Sv;exports.registerType=uC;exports.relativePathPrefix=hb;exports.removeAttributeChangeCallback=ub;exports.removeComponent=Om;exports.removeCustomImportExtensionType=oO;exports.removePatch=gS;exports.resolveUrl=Js;exports.sanitizeString=cb;exports.saveImage=Lw;exports.screenshot=WE;exports.screenshot2=Jg;exports.sendDestroyed=wm;exports.serializable=f;exports.serializeObject=_v;exports.serializeable=$e;exports.setActive=Ll;exports.setAllowBalloonMessages=gb;exports.setAllowOverlayMessages=Ox;exports.setAutoFitEnabled=cd;exports.setCameraController=np;exports.setDestroyed=Tv;exports.setDevEnvironment=sS;exports.setDisposable=tv;exports.setDontDestroy=Fr;exports.setOrAddParamsToUrl=ep;exports.setParam=sx;exports.setParamWithoutReload=Wl;exports.setPeerOptions=kS;exports.setResourceTrackingEnabled=XS;exports.setState=Qp;exports.setVisibleInCustomShadowRendering=sm;exports.setWorldEuler=nm;exports.setWorldPosition=ot;exports.setWorldPositionXYZ=Wo;exports.setWorldQuaternion=Ji;exports.setWorldQuaternionXYZW=tm;exports.setWorldRotation=Cb;exports.setWorldRotationXYZ=hc;exports.setWorldScale=aa;exports.showBalloonError=dc;exports.showBalloonMessage=Se;exports.showBalloonWarning=he;exports.showDebugConsole=rm;exports.slerp=Fx;exports.syncDestroy=uc;exports.syncField=pg;exports.syncInstantiate=xm;exports.textureToCanvas=Kx;exports.tryCastBinary=Nb;exports.tryDetermineMimetypeFromBinary=P0;exports.tryDetermineMimetypeFromURL=C0;exports.tryFindObject=ra;exports.tryGetGuid=Vb;exports.unregisterHotReloadType=e0;exports.unwatchWrite=Yp;exports.useForAutoFit=vb;exports.validate=yt;exports.watchWrite=zd;
|
|
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.#s),xd(xp,{element:this.#t}),this.#o?.disconnect(),this.#o??=new MutationObserver(()=>this.#l()),this.#o.observe(this.#e,{attributes:!0}),Zf&&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=>{Zf&&console.log("Needle Button clicked"),!e.defaultPrevented&&this.#e&&this.#e.click()}}typeof window<"u"&&!window.customElements.get(nb)&&window.customElements.define(nb,Vw);const dl=w("debugavatar");class ny{root;head;leftHand;rigthHand;get isValid(){return this.head!==null&&this.head!==void 0}constructor(e,t,i,n){this.root=e,this.head=t,this.leftHand=i,this.rigthHand=n,this.root?.traverse(o=>o.layers.set(2))}}class $w{avatarRegistryUrl=null;async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let i=null;if(typeof t=="string"){if(i=await this.loadAvatar(e,t),!i){const o=new on;i=S.instantiate(ra(t,e.scene),o)}}else i=t;if(!i)return null;const n=this.findAvatar(i);return n.isValid?(dl&&console.log("[Custom Avatar] valid config",t,dl?n:""),n):(console.warn("[Custom Avatar] config isn't valid",t,dl?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(dl&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){const n=await fetch("./"+t);let o=null;if(n.ok){const a=await n.blob();a&&(o=await a.arrayBuffer())}return o?(await en().parseSync(e,o,null,0))?.scene??null:null}const i=new q.GLTFLoader;return Tm(i,e),new Promise((n,o)=>{const r=this.avatarRegistryUrl+"/"+t;i.load(r,async a=>{await en().createBuiltinComponents(e,r,a,null,void 0),n(a.scene)},a=>{dl&&console.log("[Custom Avatar] "+a.loaded/a.total*100+"% loaded of "+a.total/1024+"kB")},a=>{console.error("[Custom Avatar] Error when loading: "+a),n(null)})})}cacheModel(e,t){}findAvatar(e){const t=e;let i=t;i.children.length==1&&(i=e.children[0]);let n=this.findAvatarPart(i,["head"]);const o=this.findAvatarPart(i,["left","hand"]),r=this.findAvatarPart(i,["right","hand"]);if(!n){n=t;const l=new c.Vector3;new c.Box3().setFromObject(n).getSize(l);const h=Math.max(l.x,l.y,l.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+h+" meters! Should be < 0.3m"),h>.3&&n.scale.multiplyScalar(1/h*.3)}return new ny(t,n,o,r)}findAvatarPart(e,t){const i=e.name.toLowerCase();let n=!0;for(const o of t){if(!n)break;i.indexOf(o)===-1&&(n=!1)}if(n)return e;if(e.children)for(const o of e.children){const r=this.findAvatarPart(o,t);if(r)return r}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}}class Ww{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(e){}}class Gw{}const kR=Object.freeze(Object.defineProperty({__proto__:null,ActionBuilder:le,ActionCollection:Y0,ActionModel:Wt,AlignmentConstraint:vc,Animation:Ft,AnimationCurve:zc,AnimationExtension:fu,AnimationTrackHandler:Iu,Animator:rt,AnimatorController:Di,Antialiasing:Vc,Attractor:Ia,AudioExtension:dr,AudioListener:ns,AudioSource:pi,AudioTrackHandler:os,Avatar:Ys,AvatarBlink_Simple:ar,AvatarEyeLook_Rotation:zm,AvatarLoader:$w,AvatarMarker:xe,AvatarModel:ny,Avatar_Brain_LookAt:Zl,Avatar_MouthShapes:Cc,Avatar_MustacheShake:Fm,Avatar_POI:Vo,AxesHelper:xa,BaseUIComponent:Bi,BasicIKConstraint:Vm,BehaviorExtension:yg,BehaviorModel:gt,BloomEffect:Ou,BoxCollider:lu,BoxGizmo:mr,BoxHelperComponent:nt,Button:vs,CallInfo:is,Camera:qt,CameraTargetReachedEvent:Kl,Canvas:ya,CanvasGroup:Ks,CapsuleCollider:ls,ChangeMaterialOnClick:lg,ChangeTransformOnClick:ur,CharacterController:lr,CharacterControllerInput:us,ChromaticAberration:$c,ClickThrough:$u,Collider:Kt,ColorAdjustments:uo,ColorBySpeedModule:Da,ColorOverLifetimeModule:Su,ContactShadows:Pc,ControlTrackHandler:ju,CursorFollow:sh,CustomBranding:pr,Deletable:Hm,DeleteBox:Gs,DepthOfField:ln,DeviceFlag:cu,DocumentExtension:Ww,DragControls:Ro,DropListener:fs,Duplicatable:Qm,EffectWrapper:nc,EmissionModule:_s,EmphasizeOnClick:Oa,EnvironmentScene:Nu,EventList:oe,EventListEvent:nu,EventSystem:jt,EventTrigger:du,FieldWithDefault:I0,FixedJoint:Tg,Fog:Ta,GltfExport:sg,GltfExportBox:ig,Gradient:yr,Graphic:Dc,GraphicRaycaster:su,GridHelper:Aa,GridLayoutGroup:Sg,GroundProjectedEnv:In,GroupActionModel:To,HideOnStart:Ei,HingeJoint:jc,HorizontalLayoutGroup:xg,Image:Ua,InheritVelocityModule:Ig,InputField:Qg,InstanceHandle:$o,InstancingHandler:Ko,Interactable:Gm,Keyframe:Xt,LODGroup:Fc,LODModel:La,Light:ei,LimitVelocityOverLifetimeModule:et,LogStats:Wm,LookAt:Yg,LookAtConstraint:rr,MainModule:Ct,MaskableGraphic:Ic,MeshCollider:so,MeshRenderer:Mc,MinMaxCurve:G,MinMaxGradient:_r,NeedleMenu:Bn,NestedGltf:Uc,Networking:Lg,NoiseModule:fe,ObjectRaycaster:fi,OffsetConstraint:gr,OpenURL:za,OrbitControls:de,Outline:Ra,Padding:fr,ParticleBurst:Dd,ParticleSubEmitter:jg,ParticleSystem:ic,ParticleSystemRenderer:Vi,PhysicsExtension:_g,PixelationEffect:Wc,PlayAnimationOnClick:ec,PlayAudioOnClick:Qs,PlayableDirector:er,PlayerColor:_a,PointerEventData:xc,PostProcessingHandler:Ng,PreliminaryAction:Ma,PreliminaryTrigger:Rc,RawImage:Uu,Rect:tw,RectTransform:sn,ReflectionProbe:Jl,RegisteredAnimationInfo:Vs,RemoteSkybox:ku,Renderer:mi,RendererLightmap:Td,Rigidbody:Ne,RotationBySpeedModule:Ni,RotationOverLifetimeModule:an,SceneSwitcher:je,ScreenCapture:fo,ScreenSpaceAmbientOcclusion:bs,ScreenSpaceAmbientOcclusionN8:cn,ScrollFollow:Zg,SetActiveOnClick:cg,ShadowCatcher:Xc,ShapeModule:Dg,SharpeningEffect:Hc,SignalAsset:Du,SignalReceiver:Jc,SignalReceiverEvent:Zc,SignalTrackHandler:sc,Size:ew,SizeBySpeedModule:ti,SizeOverLifetimeModule:br,SkinnedMeshRenderer:tg,SmoothFollow:Ru,SpatialGrabRaycaster:Qo,SpatialHtml:ih,SpatialTrigger:Tu,SpatialTriggerReceiver:An,SpectatorCamera:Au,SphereCollider:Sa,SplineContainer:Sr,SplineData:Dn,SplineWalker:hn,Sprite:ms,SpriteData:sa,SpriteRenderer:Zt,SpriteSheet:ga,SubEmitterSystem:Id,SyncedCamera:$g,SyncedRoom:dn,SyncedTransform:nn,TapGestureTrigger:dg,TeleportTarget:_u,TestRunner:Wg,TestSimulateUserData:Gg,Text:St,TextBuilder:vg,TextExtension:vu,TextureSheetAnimationModule:Pt,TiltShiftEffect:zn,ToneMappingEffect:Zs,TrailModule:Re,TransformData:ke,TransformGizmo:Pr,TriggerBuilder:wt,TriggerModel:Hs,UIRaycastUtils:Dm,UIRootComponent:Ac,USDZExporter:Tn,USDZText:Yr,USDZUIExtension:Pg,UsageMarker:Oc,VariantAction:ag,VelocityOverLifetimeModule:Ae,VerticalLayoutGroup:wg,VideoPlayer:Ze,Vignette:xr,VisibilityAction:Tc,Voip:no,Volume:Ba,VolumeParameter:I,VolumeProfile:Cu,WebARCameraBackground:oh,WebARSessionRoot:hi,WebXR:bu,WebXRImageTracking:rh,WebXRImageTrackingModel:xs,WebXRPlaneTracking:Ss,WebXRTrackedImage:ba,XRControllerFollow:ws,XRControllerModel:cs,XRControllerMovement:gi,XRFlag:Ti,XRRig:Wu,XRState:It,__Ignore:Gw},Symbol.toStringTag,{value:"Module"})),Ud=w("debugmissingcamera");ae.registerCallback(re.MissingCamera,s=>{Ud&&console.warn("Creating missing camera");const e=s.context.scene,t=new c.PerspectiveCamera;t.name="Default Fallback Camera",e.add(t);const i=new qt;if(i.sourceId=s.files?.[0]?.src??"unknown",i.fieldOfView=35,s.context.domElement.getAttribute("transparent")!=null)i.clearFlags=No.Uninitialized;else if(s.context.domElement.getAttribute("background-image")?.length||s.context.lightmaps.tryGetSkybox(i.sourceId))i.clearFlags=No.Skybox;else{if(i.clearFlags=No.SolidColor,!s.context.domElement.getAttribute("background-color")){let a="#efefef";typeof window!==void 0&&window.matchMedia("(prefers-color-scheme: dark)").matches&&(a="#1f1f1f"),e.background=new c.Color(a)}if(!e.environment){const a=new c.PMREMGenerator$1(s.context.renderer),l=new Nu("neutral");e.environment=a.fromScene(l,.025).texture}}const o=jo(t,i,!0);return t.position.x=0,t.position.y=1,t.position.z=2,s.context.domElement?.cameraControls!=!1&&Hw(s.context,o),o});ae.registerCallback(re.ContextCreated,s=>{if(!s.context.mainCamera){Ud&&console.log("Will not auto-fit because a default camera exists");return}if(s.context.domElement?.cameraControls==!0){if(bb(s.context.mainCamera)?.isCameraController==!0){Ud&&console.log("Will not auto-fit because a camera controller exists");return}Hw(s.context)}});function Hw(s,e){e=e??s.mainCameraComponent;const t=e?.gameObject;if(Ud&&console.log("Creating default camera controls",e?.name),t){const i=pc(t,de);i.sourceId=e?.sourceId??"unknown";const n=s.domElement.getAttribute("auto-rotate");if(i.autoRotate=n!=null&&n!="0"&&n?.toLowerCase()!="false",i.autoRotateSpeed=.5,i.autoFit=!0,i.autoRotate&&n){const o=parseFloat(n);isNaN(o)||(i.autoRotateSpeed=o)}}else console.warn("Missing camera object, can not add orbit controls")}ae.registerCallback(re.ContextCreated,s=>{const e=s.context.domElement.getAttribute("autoplay");if(e!==void 0&&(e===""||e==="true"||e==="1")&&s.files)for(const t of s.files)S.foreachComponent(t.file.scene,n=>{if(n.enabled!==!1){if(n instanceof Ft&&n.playAutomatically||n instanceof rt||n instanceof er&&n.playOnAwake===!0)return!0;if(n instanceof Ft)return n.playAutomatically=!0,!0;if(n instanceof er)return n.playOnAwake=!0,!0}},!0)!==!0&&fa.autoplayAnimations(t.file)});exports.SplineUtils=void 0;(s=>{function e(t,i=!1,n=.75){const o=new Sr,r=1-D.clamp(n,0,1);return t.forEach((a,l)=>{const h=new c.Vector3;l<t.length-1?h.subVectors(t[l+1],a).normalize().multiplyScalar(r):i&&t.length>1&&h.subVectors(t[0],a).normalize().multiplyScalar(r);const d=new Dn;d.position.copy(a),d.tangentIn.copy(h),d.tangentOut.copy(h),o.addKnot(d)}),o.closed=i,o}s.createFromPoints=e})(exports.SplineUtils||(exports.SplineUtils={}));class ER extends se.WorkerBase{constructor(){super(new Worker(new URL("/generateMeshBVH.worker-2qGLkQjg.js",typeof document>"u"?require("url").pathToFileURL(__filename).href:Hu&&Hu.tagName.toUpperCase()==="SCRIPT"&&Hu.src||new URL("needle-engine.bundle-C7LSzO5L.umd.cjs",document.baseURI).href),{type:"module"})),this.name="GenerateMeshBVHWorker"}runTask(e,t,i={}){return new Promise((n,o)=>{if(t.getAttribute("position").isInterleavedBufferAttribute||t.index&&t.index.isInterleavedBufferAttribute)throw new Error("GenerateMeshBVHWorker: InterleavedBufferAttribute are not supported for the geometry attributes.");e.onerror=h=>{o(new Error(`[GenerateMeshBVHWorker] ${h.message||"Unknown error. Please check the server console. If you're using vite try adding 'three-mesh-bvh' to 'optimizeDeps.exclude' in your vite.config.js"}`))},e.onmessage=h=>{const{data:d}=h;if(d.error)o(new Error(d.error)),e.onmessage=null;else if(d.serialized){const{serialized:u,position:p}=d,m=se.MeshBVH.deserialize(u,t,{setIndex:!1}),y=Object.assign({setBoundingBox:!0},i);if(t.attributes.position.array=p,u.index)if(t.index)t.index.array=u.index;else{const b=new c.BufferAttribute(u.index,1,!1);t.setIndex(b)}y.setBoundingBox&&(t.boundingBox=m.getBoundingBox(new c.Box3)),i.onProgress&&i.onProgress(d.progress),n(m),e.onmessage=null}else i.onProgress&&i.onProgress(d.progress)};const r=t.index?t.index.array:null,a=t.attributes.position.array,l=[a];r&&l.push(r),e.postMessage({index:r,position:a,options:{...i,onProgress:null,includedProgressCallback:!!i.onProgress,groups:[...t.groups]}},l.map(h=>h.buffer).filter(h=>typeof SharedArrayBuffer>"u"||!(h instanceof SharedArrayBuffer)))})}}const RR=Object.freeze(Object.defineProperty({__proto__:null,GenerateMeshBVHWorker:ER},Symbol.toStringTag,{value:"Module"}));exports.$physicsKey=fP;exports.ActionBuilder=le;exports.ActionCollection=Y0;exports.ActionModel=Wt;exports.Addressables=Dv;exports.AlignmentConstraint=vc;exports.AmbientMode=ia;exports.Animation=Ft;exports.AnimationCurve=zc;exports.AnimationExtension=fu;exports.AnimationTrackHandler=Iu;exports.AnimationUtils=fa;exports.Animator=rt;exports.AnimatorConditionMode=Bs;exports.AnimatorController=Di;exports.AnimatorControllerParameterType=Am;exports.AnimatorStateInfo=gl;exports.Antialiasing=Vc;exports.Application=tn;exports.AssetDatabase=Kb;exports.AssetReference=Y;exports.Attractor=Ia;exports.AudioExtension=dr;exports.AudioListener=ns;exports.AudioSource=pi;exports.AudioTrackHandler=os;exports.Avatar=Ys;exports.AvatarBlink_Simple=ar;exports.AvatarEyeLook_Rotation=zm;exports.AvatarLoader=$w;exports.AvatarMarker=xe;exports.AvatarModel=ny;exports.Avatar_Brain_LookAt=Zl;exports.Avatar_MouthShapes=Cc;exports.Avatar_MustacheShake=Fm;exports.Avatar_POI=Vo;exports.Axes=Xr;exports.AxesHelper=xa;exports.BUILD_TIME=am;exports.BaseUIComponent=Bi;exports.BasicIKConstraint=Vm;exports.BehaviorExtension=yg;exports.BehaviorModel=gt;exports.BloomEffect=Ou;exports.BoxCollider=lu;exports.BoxGizmo=mr;exports.BoxHelperComponent=nt;exports.Button=vs;exports.ButtonsFactory=Qi;exports.CallDirection=m0;exports.CallInfo=is;exports.Camera=qt;exports.CameraTargetReachedEvent=Kl;exports.Canvas=ya;exports.CanvasGroup=Ks;exports.CapsuleCollider=ls;exports.ChangeMaterialOnClick=lg;exports.ChangeTransformOnClick=ur;exports.CharacterController=lr;exports.CharacterControllerInput=us;exports.ChromaticAberration=$c;exports.CircularBuffer=di;exports.ClearFlags=No;exports.ClickThrough=$u;exports.ClipExtrapolation=gn;exports.Collider=Kt;exports.Collision=u0;exports.CollisionDetectionMode=iu;exports.ColorAdjustments=uo;exports.ColorBySpeedModule=Da;exports.ColorOverLifetimeModule=Su;exports.Component=x1;exports.Component$1=k;exports.ComponentLifecycleEvents=qd;exports.Components=kR;exports.ConnectionEvents=Gb;exports.ContactPoint=d0;exports.ContactShadows=Pc;exports.Context=F;exports.ContextArgs=a1;exports.ContextEvent=re;exports.ContextRegistry=ae;exports.ControlTrackHandler=ju;exports.CursorFollow=sh;exports.CustomBranding=pr;exports.CustomShader=ye;exports.DefaultReflectionMode=wd;exports.Deletable=Hm;exports.DeleteBox=Gs;exports.DepthOfField=ln;exports.DeviceFlag=cu;exports.DocumentExtension=Ww;exports.DragControls=Ro;exports.DragMode=qm;exports.DropListener=fs;exports.Duplicatable=Qm;exports.EffectWrapper=nc;exports.EmissionModule=_s;exports.EmphasizeOnClick=Oa;exports.EngineLoadingView=oc;exports.EnvironmentScene=Nu;exports.EventList=oe;exports.EventListEvent=nu;exports.EventSystem=jt;exports.EventTrigger=du;exports.FieldWithDefault=I0;exports.FileReference=Uo;exports.FileReferenceSerializer=jv;exports.FileSpawnModel=jP;exports.File_Event=x0;exports.FixedJoint=Tg;exports.Fog=Ta;exports.FrameEvent=pe;exports.GENERATOR=Vd;exports.GameObject=S;exports.Gizmos=B;exports.GltfExport=sg;exports.GltfExportBox=ig;exports.Gradient=yr;exports.Graphic=Dc;exports.GraphicRaycaster=su;exports.Graphics=Xs;exports.GridHelper=Aa;exports.GridLayoutGroup=Sg;exports.GroundProjectedEnv=In;exports.GroupActionModel=To;exports.HideFlags=ou;exports.HideOnStart=Ei;exports.HingeJoint=jc;exports.HorizontalLayoutGroup=xg;exports.HostData=aC;exports.Image=Ua;exports.ImageReference=Fo;exports.ImageReferenceSerializer=Iv;exports.InheritVelocityModule=Ig;exports.Input=Ub;exports.InputEventQueue=Ht;exports.InputEvents=we;exports.InputField=Qg;exports.InstanceHandle=$o;exports.InstancingHandler=Ko;exports.InstancingUtil=Li;exports.InstantiateEvent=lv;exports.InstantiateIdProvider=mt;exports.InstantiateOptions=on;exports.Interactable=Gm;exports.JoinedRoomResponse=TS;exports.KeyEventArgs=vS;exports.Keyframe=Xt;exports.LODGroup=Fc;exports.LODModel=La;exports.LeftRoomResponse=AS;exports.Light=ei;exports.LightData=Nv;exports.LimitVelocityOverLifetimeModule=et;exports.LoadingElementOptions=fR;exports.LogStats=Wm;exports.LogType=ci;exports.LookAt=Yg;exports.LookAtConstraint=rr;exports.MainModule=Ct;exports.MarkerType=Hg;exports.MaskableGraphic=Ic;exports.Mathf=D;exports.MeshCollider=so;exports.MeshRenderer=Mc;exports.MinMaxCurve=G;exports.MinMaxGradient=_r;exports.NEKeyboardEvent=ul;exports.NEPointerEvent=Kn;exports.NeedleButtonElement=Vw;exports.NeedleEngineWebComponent=iy;exports.NeedleMenu=Bn;exports.NeedlePatchesKey=Wh;exports.NeedleXRController=dm;exports.NeedleXRSession=H;exports.NeedleXRSync=Xb;exports.NeedleXRUtils=Yb;exports.NestedGltf=Uc;exports.NetworkConnection=qb;exports.NetworkedStreamEvents=Cn;exports.NetworkedStreams=Sc;exports.Networking=Lg;exports.NewInstanceModel=hv;exports.NoiseModule=fe;exports.ObjectRaycaster=fi;exports.ObjectUtils=ir;exports.OffsetConstraint=gr;exports.OneEuroFilter=Vh;exports.OneEuroFilterXYZ=Jp;exports.OpenURL=za;exports.OrbitControls=de;exports.Outline=Ra;exports.OwnershipEvent=Hb;exports.OwnershipModel=mm;exports.PUBLIC_KEY=Gr;exports.Padding=fr;exports.ParticleBurst=Dd;exports.ParticleSubEmitter=jg;exports.ParticleSystem=ic;exports.ParticleSystemBaseBehaviour=ho;exports.ParticleSystemRenderer=Vi;exports.ParticleSystemShapeType=Ld;exports.PeerHandle=ss;exports.PeerNetworking=Wb;exports.Physics=da;exports.PhysicsExtension=_g;exports.PhysicsMaterialCombine=it;exports.PixelationEffect=Wc;exports.PlayAnimationOnClick=ec;exports.PlayAudioOnClick=Qs;exports.PlayableDirector=er;exports.PlayerColor=_a;exports.PlayerState=Yi;exports.PlayerStateEvent=J0;exports.PlayerSync=mg;exports.PlayerView=Fv;exports.PlayerViewManager=Uv;exports.PointerEventData=xc;exports.PointerType=Gd;exports.PostProcessingEffect=Ve;exports.PostProcessingEffectOrder=Ke;exports.PostProcessingHandler=Ng;exports.PreliminaryAction=Ma;exports.PreliminaryTrigger=Rc;exports.PrimitiveType=Go;exports.Progress=ie;exports.PromiseAllWithErrors=Kp;exports.PromiseErrorResult=tp;exports.RGBAColor=Z;exports.RapierPhysics=oa;exports.RawImage=Uu;exports.RaycastOptions=io;exports.Rect=tw;exports.RectTransform=sn;exports.ReflectionProbe=Jl;exports.RegisteredAnimationInfo=Vs;exports.RemoteSkybox=ku;exports.RenderTexture=Sn;exports.RenderTextureSerializer=a0;exports.Renderer=mi;exports.RendererData=zv;exports.RendererLightmap=Td;exports.Rigidbody=Ne;exports.RigidbodyConstraints=De;exports.RoomEvents=Q;exports.RotationBySpeedModule=Ni;exports.RotationOverLifetimeModule=an;exports.SceneLightSettings=kd;exports.SceneSwitcher=je;exports.ScreenCapture=fo;exports.ScreenSpaceAmbientOcclusion=bs;exports.ScreenSpaceAmbientOcclusionN8=cn;exports.ScrollFollow=Zg;exports.SendQueue=Xi;exports.SerializationContext=Pm;exports.SetActiveOnClick=cg;exports.ShadowCatcher=Xc;exports.ShapeModule=Dg;exports.ShapeOverlapResult=f0;exports.SharpeningEffect=Hc;exports.SignalAsset=Du;exports.SignalReceiver=Jc;exports.SignalReceiverEvent=Zc;exports.SignalTrackHandler=sc;exports.Size=ew;exports.SizeBySpeedModule=ti;exports.SizeOverLifetimeModule=br;exports.SkinnedMeshRenderer=tg;exports.SmoothFollow=Ru;exports.SpatialGrabRaycaster=Qo;exports.SpatialHtml=ih;exports.SpatialTrigger=Tu;exports.SpatialTriggerReceiver=An;exports.SpectatorCamera=Au;exports.SphereCollider=Sa;exports.SphereIntersection=_m;exports.SplineContainer=Sr;exports.SplineData=Dn;exports.SplineWalker=hn;exports.Sprite=ms;exports.SpriteData=sa;exports.SpriteRenderer=Zt;exports.SpriteSheet=ga;exports.StateMachineBehaviour=k1;exports.StreamEndedEvent=jm;exports.StreamReceivedEvent=p0;exports.SubEmitterSystem=Id;exports.SyncedCamera=$g;exports.SyncedRoom=dn;exports.SyncedTransform=nn;exports.TapGestureTrigger=dg;exports.TeleportTarget=_u;exports.TestRunner=Wg;exports.TestSceneUtils=xR;exports.TestSimulateUserData=Gg;exports.Text=St;exports.TextBuilder=vg;exports.TextExtension=vu;exports.TextureSheetAnimationModule=Pt;exports.TiltShiftEffect=zn;exports.Time=Vv;exports.ToneMappingEffect=Zs;exports.TrackHandler=eh;exports.TrackType=si;exports.TrailModule=Re;exports.TransformData=ke;exports.TransformGizmo=Pr;exports.TriggerBuilder=wt;exports.TriggerModel=Hs;exports.TypeStore=P;exports.UIRaycastUtils=Dm;exports.UIRootComponent=Ac;exports.USDDocument=og;exports.USDObject=ze;exports.USDWriter=N0;exports.USDZExporter=Tn;exports.USDZExporter$1=V0;exports.USDZText=Yr;exports.USDZUIExtension=Pg;exports.UriSerializer=l0;exports.UsageMarker=Oc;exports.UserJoinedOrLeftRoomModel=LS;exports.VERSION=Ki;exports.VariantAction=ag;exports.VelocityOverLifetimeModule=Ae;exports.VerticalLayoutGroup=wg;exports.VideoPlayer=Ze;exports.ViewDevice=$s;exports.Vignette=xr;exports.VisibilityAction=Tc;exports.Voip=no;exports.Volume=Ba;exports.VolumeParameter=I;exports.VolumeProfile=Cu;exports.WaitForFrames=zC;exports.WaitForPromise=Bv;exports.WaitForSeconds=km;exports.Watch=rs;exports.WebARCameraBackground=oh;exports.WebARSessionRoot=hi;exports.WebXR=bu;exports.WebXRButtonFactory=qs;exports.WebXRImageTracking=rh;exports.WebXRImageTrackingModel=xs;exports.WebXRPlaneTracking=Ss;exports.WebXRTrackedImage=ba;exports.XRControllerFollow=ws;exports.XRControllerModel=cs;exports.XRControllerMovement=gi;exports.XRFlag=Ti;exports.XRRig=Wu;exports.XRState=It;exports.XRStateFlag=wn;exports.__Ignore=Gw;exports.__internalNotifyObjectDestroyed=YS;exports.activeInHierarchyFieldName=as;exports.addAttributeChangeCallback=db;exports.addComponent=Zi;exports.addCustomExtensionPlugin=sO;exports.addNewComponent=jo;exports.addPatch=$d;exports.apply=Qd;exports.applyHMRChanges=w1;exports.applyPrototypeExtensions=xv;exports.beginListenDestroy=cv;exports.beginListenInstantiate=uv;exports.binaryIdentifierCasts=um;exports.build_scene_functions=r1;exports.builtinComponentKeyName=Po;exports.calculateProgress01=ty;exports.clearMessages=Rx;exports.colorSerializer=G1;exports.compareAssociation=gv;exports.componentSerializer=Jh;exports.copyTexture=Ob;exports.createMotion=n0;exports.debugNet=zt;exports.debugOwner=fl;exports.decompressGpuTexture=H0;exports.deepClone=ac;exports.delay=Ln;exports.delayForFrames=lc;exports.deserializeObject=bd;exports.destroy=ui;exports.destroyComponentInstance=Pv;exports.determineMimeTypeFromExtension=S0;exports.disposeObjectResources=_e;exports.disposeStream=Pn;exports.editorGuidKeyName=Rl;exports.enableSpatialConsole=Lo;exports.euler=q1;exports.eventListSerializer=K1;exports.exportAsGLTF=PR;exports.findByGuid=Mm;exports.findObjectOfType=yc;exports.findObjectsOfType=Mv;exports.findResourceUsers=bm;exports.fitObjectIntoVolume=kb;exports.foreachComponent=qo;exports.foreachComponentEnumerator=Kd;exports.forward=qx;exports.generateQRCode=fb;exports.generateSeed=dv;exports.getBoundingBox=Bt;exports.getCameraController=bb;exports.getComponent=sr;exports.getComponentInChildren=gc;exports.getComponentInParent=Xl;exports.getComponents=mc;exports.getComponentsInChildren=va;exports.getComponentsInParent=Xd;exports.getFormattedDate=B0;exports.getIconElement=pt;exports.getIconTexture=wp;exports.getLoader=en;exports.getOrAddComponent=pc;exports.getParam=w;exports.getParentHierarchyPath=Yx;exports.getPath=ax;exports.getPeerOptions=MS;exports.getPeerjsInstance=$b;exports.getResourceUserCount=ZS;exports.getTempColor=xb;exports.getTempQuaternion=Gt;exports.getTempVector=V;exports.getUrlParams=rc;exports.getVisibleInCustomShadowRendering=Mb;exports.getWorldDirection=Sb;exports.getWorldEuler=im;exports.getWorldPosition=X;exports.getWorldQuaternion=ue;exports.getWorldRotation=Nd;exports.getWorldScale=Ie;exports.hasCommercialLicense=Rn;exports.hasIndieLicense=bc;exports.hasPointerEventComponent=Cd;exports.hasProLicense=En;exports.hideDebugConsole=Ab;exports.imageToCanvas=q0;exports.instantiate=Xo;exports.invokeLoadedImportPluginHooks=A0;exports.invokeXRSessionEnd=Fb;exports.invokeXRSessionStart=Bb;exports.isActiveInHierarchy=kv;exports.isActiveSelf=wa;exports.isAndroidDevice=fx;exports.isAnimationAction=Pb;exports.isComponent=h0;exports.isDebugMode=nx;exports.isDesktop=cx;exports.isDestroyed=Ho;exports.isDevEnvironment=A;exports.isDisposed=QS;exports.isExporting=SR;exports.isGLTFModel=c0;exports.isHostedOnGlitch=sb;exports.isHotReloadEnabled=Op;exports.isHotReloading=b1;exports.isIPad=dx;exports.isIconElement=Gv;exports.isLocalNetwork=Ii;exports.isMacOS=mx;exports.isMobileDevice=hx;exports.isMozillaXR=px;exports.isQuest=_x;exports.isResourceTrackingEnabled=Jb;exports.isSafari=yx;exports.isUsingInstancing=Yd;exports.isiOS=gx;exports.isiPad=ux;exports.loadAsset=aR;exports.loadPMREM=Sw;exports.loadSync=ey;exports.logHierarchy=dd;exports.lookAtInverse=Ux;exports.lookAtObject=cc;exports.lookAtScreenPoint=zx;exports.makeId=ox;exports.makeIdFromRandomWords=lb;exports.makeNameSafe=ji;exports.markAsInstancedRendered=Ev;exports.microphonePermissionsGranted=bx;exports.nameof=ix;exports.nameofFactory=rb;exports.objectSerializer=r0;exports.offXRSessionEnd=bS;exports.offXRSessionStart=_S;exports.onAfterRender=y1;exports.onBeforeRender=g1;exports.onClear=p1;exports.onDestroy=m1;exports.onInitialized=Yv;exports.onStart=eu;exports.onUpdate=Kv;exports.onXRSessionEnd=hm;exports.onXRSessionStart=Wd;exports.parseSync=Bw;exports.placeOnSurface=Eb;exports.postprocessFBXMaterials=om;exports.prefix=U1;exports.pushState=ab;exports.randomNumber=rx;exports.registerBinaryType=fm;exports.registerComponent=Jd;exports.registerComponentExtension=Zm;exports.registerCustomEffectType=$i;exports.registerExportExtensions=Jm;exports.registerExtensions=Rd;exports.registerHotReloadType=Jv;exports.registerLoader=lm;exports.registerPrefabProvider=pv;exports.registerPrototypeExtensions=Sv;exports.registerType=uC;exports.relativePathPrefix=hb;exports.removeAttributeChangeCallback=ub;exports.removeComponent=Om;exports.removeCustomImportExtensionType=oO;exports.removePatch=gS;exports.resolveUrl=Js;exports.sanitizeString=cb;exports.saveImage=Lw;exports.screenshot=WE;exports.screenshot2=Jg;exports.sendDestroyed=wm;exports.serializable=f;exports.serializeObject=_v;exports.serializeable=$e;exports.setActive=Ll;exports.setAllowBalloonMessages=gb;exports.setAllowOverlayMessages=Ox;exports.setAutoFitEnabled=cd;exports.setCameraController=np;exports.setDestroyed=Tv;exports.setDevEnvironment=sS;exports.setDisposable=tv;exports.setDontDestroy=Fr;exports.setOrAddParamsToUrl=ep;exports.setParam=sx;exports.setParamWithoutReload=Wl;exports.setPeerOptions=kS;exports.setResourceTrackingEnabled=XS;exports.setState=Qp;exports.setVisibleInCustomShadowRendering=sm;exports.setWorldEuler=nm;exports.setWorldPosition=ot;exports.setWorldPositionXYZ=Wo;exports.setWorldQuaternion=Ji;exports.setWorldQuaternionXYZW=tm;exports.setWorldRotation=Cb;exports.setWorldRotationXYZ=hc;exports.setWorldScale=aa;exports.showBalloonError=dc;exports.showBalloonMessage=Se;exports.showBalloonWarning=he;exports.showDebugConsole=rm;exports.slerp=Fx;exports.syncDestroy=uc;exports.syncField=pg;exports.syncInstantiate=xm;exports.textureToCanvas=Kx;exports.tryCastBinary=Nb;exports.tryDetermineMimetypeFromBinary=P0;exports.tryDetermineMimetypeFromURL=C0;exports.tryFindObject=ra;exports.tryGetGuid=Vb;exports.unregisterHotReloadType=e0;exports.unwatchWrite=Yp;exports.useForAutoFit=vb;exports.validate=yt;exports.watchWrite=zd;
|