@needle-tools/engine 4.16.3 → 4.16.4-alpha.1
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-CYtylxkF.umd.cjs → needle-engine.bundle-B77DaJNC.umd.cjs} +28 -28
- package/dist/{needle-engine.bundle-eJXdUwvK.min.js → needle-engine.bundle-D2W9eiXc.min.js} +30 -30
- package/dist/{needle-engine.bundle-BE9apg0j.js → needle-engine.bundle-DtZtb-k4.js} +8 -8
- package/dist/needle-engine.d.ts +17 -17
- package/dist/needle-engine.js +2 -2
- package/dist/needle-engine.min.js +1 -1
- package/dist/needle-engine.umd.cjs +1 -1
- package/dist/{postprocessing-C-WOZQC5.js → postprocessing-BUS23YkY.js} +2 -2
- package/dist/{postprocessing-CtXfLXvp.umd.cjs → postprocessing-C_736uMz.umd.cjs} +2 -2
- package/dist/{postprocessing-DXm8YKbQ.min.js → postprocessing-CaEfRjRY.min.js} +2 -2
- package/dist/tsconfig.tsbuildinfo +1 -0
- package/lib/engine/engine_application.js.map +1 -1
- package/lib/engine-components/RendererLightmap.js +2 -2
- package/lib/engine-components/RendererLightmap.js.map +1 -1
- package/lib/engine-components/splines/Spline.d.ts +2 -2
- package/lib/engine-components/splines/Spline.js +5 -4
- package/lib/engine-components/splines/Spline.js.map +1 -1
- package/package.json +1 -1
- package/src/engine/engine_application.ts +2 -2
- package/src/engine-components/RendererLightmap.ts +2 -2
- package/src/engine-components/splines/Spline.ts +5 -4
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import{Vector2 as K,Vector3 as b,Vector4 as ye,Quaternion as N,PlaneGeometry as vn,WebGLRenderer as yr,PerspectiveCamera as de,OrthographicCamera as Cd,Scene as Hi,Mesh as H,Texture as Se,Uniform$1 as Gi,Color as oe,ShaderMaterial as Vn,Box3 as Yt,ShadowMaterial as gb,Euler as at,MeshStandardMaterial as gt,Box3Helper as GS,GridHelper as fb,Object3D as M,Material as we,Matrix3 as yb,Matrix4 as J,Layers as _s,Ray as So,MathUtils as Co,AxesHelper as Pi,MeshBasicMaterial as Ce,DoubleSide as Oi,BufferGeometry as wn,Group as Po,CylinderGeometry as bb,SphereGeometry as Pd,BoxGeometry as Aa,SpriteMaterial as qS,Sprite as XS,Shape as QS,ExtrudeGeometry as YS,Fog as _b,DirectionalLight as km,PointLight as Mm,TextureLoader as br,EdgesGeometry as ZS,LineSegments as vb,LineBasicMaterial as Em,Line as Ia,BufferAttribute as ft,Raycaster as Od,Sphere as kd,ArrayCamera as KS,Plane as _r,SkinnedMesh as vs,InterleavedBufferAttribute as wb,Skeleton as JS,Bone as eC,WebGLCubeRenderTarget as tC,CubeCamera as iC,AnimationClip as ki,FileLoader as Rm,PropertyBinding as La,KeyframeTrack as nC,LinearSRGBColorSpace as Oo,ShaderChunk as Zt,DataTexture as Tm,RGBAFormat as Md,EquirectangularReflectionMapping as ko,SRGBColorSpace as Mo,Clock as oC,NeutralToneMapping as ja,AgXToneMapping as Ed,ACESFilmicToneMapping as Rd,NoToneMapping as Td,PCFSoftShadowMap$1 as sC,BasicNodeLibrary as rC,WebGLRenderTarget as $n,DepthTexture as xb,NearestFilter as Ad,LoopRepeat as aC,LoopOnce as Am,AnimationMixer as Im,CompressedTexture as lC,FrontSide as ws,Camera as cC,Frustum as Sb,AudioListener as hC,PositionalAudio as dC,AudioLoader as Lm,EventDispatcher as jm,BackSide as Id,MeshDepthMaterial as uC,CustomBlending as pC,MaxEquation as mC,AlwaysStencilFunc as gC,GreaterEqualStencilFunc as fC,NotEqualStencilFunc as yC,GreaterStencilFunc as bC,LessEqualStencilFunc as _C,EqualStencilFunc as vC,LessStencilFunc as wC,NeverStencilFunc as Cb,InvertStencilOp as xC,DecrementWrapStencilOp as SC,IncrementWrapStencilOp as CC,DecrementStencilOp as PC,IncrementStencilOp as OC,ReplaceStencilOp as kC,ZeroStencilOp as MC,KeepStencilOp as EC,CubeUVReflectionMapping as Pb,CubeTexture as Ob,AmbientLight as RC,HemisphereLight as TC,Loader as AC,RawShaderMaterial as kb,GLSL3 as IC,AlwaysDepth as LC,GreaterEqualDepth as jC,GreaterDepth as DC,LessEqualDepth as BC,LessDepth as FC,NotEqualDepth as UC,EqualDepth as zC,BatchedMesh as Mb,LinearFilter as Ld,UnsignedByteType as NC,MeshPhysicalMaterial as Eb,RingGeometry as WC,Line3 as VC,AdditiveBlending as Rb,BoxHelper as $C,SpotLight as HC,DirectionalLightHelper as GC,CameraHelper as qC,LOD as XC,Triangle as QC,NormalBlending as YC,ReinhardToneMapping as Dm,LinearToneMapping as Bm,HalfFloatType as Fm,VideoTexture as ZC,CompressedCubeTexture as KC,EquirectangularRefractionMapping as JC,CatmullRomCurve3 as eP,VectorKeyframeTrack as tP,QuaternionKeyframeTrack as iP,Audio as nP,ShaderLib as jd,UniformsUtils as Tb,MirroredRepeatWrapping as Ab,MeshNormalMaterial as oP,AudioContext as sP,PMREMGenerator$1 as rP}from"./three.min.js";import{createLoaders as Um,getRaycastMesh as Ib,LODsManager as vr,NEEDLE_progressive as Ve,addDracoAndKTX2Loaders as aP,configureLoader as lP,setKTX2TranscoderLocation as cP,setDracoDecoderLocation as hP}from"./gltf-progressive-DQa78GTA.min.js";import{GroundedSkybox as Da,Font as dP,TextGeometry as uP,FontLoader as pP,GLTFLoader as Eo,TransformControlsGizmo as Lb,EXRLoader as zm,RGBELoader as jb,Stats as mP,nodeFrame as Db,OrbitControls as gP,PositionalAudioHelper as fP,HorizontalBlurShader as yP,VerticalBlurShader as bP,GLTFExporter as Bb,strToU8 as Fb,zipSync as _P,XRControllerModelFactory as vP,XRHandMeshModel as wP,Line2 as xP,LineGeometry as SP,LineMaterial as CP,TransformControls as PP,InteractiveGroup as OP,HTMLMesh as kP,VertexNormalsHelper as MP,OBJLoader as Nm,FBXLoader as Ub,mergeVertices as EP}from"./three-examples.min.js";import{fetchProfile as RP,MotionController as TP,$70d766613f57b014$export$2e2bcd8739ae039 as zb,ByteBuffer as AP,v5 as Nb,md5 as Wb,SIZE_PREFIX_LENGTH as Vb,Builder as Wm,createNoise4D as IP,Matrix4 as Vm,BatchedParticleRenderer as LP,ParticleSystem as jP,RenderMode as Ro,ConstantColor as DP,Vector4 as BP,ConstantValue as FP,TrailParticle as $b,WorkerBase as UP,MeshBVH as zP}from"./vendor-DZ45lcA8.min.js";import{__webpack_exports__default as Pe,__webpack_exports__Text as Hb,__webpack_exports__Block as Gb,__webpack_exports__update as NP,SimpleStateBehavior as WP,__webpack_exports__Inline as $m,__webpack_exports__FontLibrary as qb,ThreeMeshUI as Xb}from"./three-mesh-ui-n3JU4M2W.min.js";import{EffectAttribute as VP}from"./postprocessing-
|
|
1
|
+
import{Vector2 as K,Vector3 as b,Vector4 as ye,Quaternion as N,PlaneGeometry as vn,WebGLRenderer as yr,PerspectiveCamera as de,OrthographicCamera as Cd,Scene as Hi,Mesh as H,Texture as Se,Uniform$1 as Gi,Color as oe,ShaderMaterial as Vn,Box3 as Yt,ShadowMaterial as gb,Euler as at,MeshStandardMaterial as gt,Box3Helper as GS,GridHelper as fb,Object3D as M,Material as we,Matrix3 as yb,Matrix4 as J,Layers as _s,Ray as So,MathUtils as Co,AxesHelper as Pi,MeshBasicMaterial as Ce,DoubleSide as Oi,BufferGeometry as wn,Group as Po,CylinderGeometry as bb,SphereGeometry as Pd,BoxGeometry as Aa,SpriteMaterial as qS,Sprite as XS,Shape as QS,ExtrudeGeometry as YS,Fog as _b,DirectionalLight as km,PointLight as Mm,TextureLoader as br,EdgesGeometry as ZS,LineSegments as vb,LineBasicMaterial as Em,Line as Ia,BufferAttribute as ft,Raycaster as Od,Sphere as kd,ArrayCamera as KS,Plane as _r,SkinnedMesh as vs,InterleavedBufferAttribute as wb,Skeleton as JS,Bone as eC,WebGLCubeRenderTarget as tC,CubeCamera as iC,AnimationClip as ki,FileLoader as Rm,PropertyBinding as La,KeyframeTrack as nC,LinearSRGBColorSpace as Oo,ShaderChunk as Zt,DataTexture as Tm,RGBAFormat as Md,EquirectangularReflectionMapping as ko,SRGBColorSpace as Mo,Clock as oC,NeutralToneMapping as ja,AgXToneMapping as Ed,ACESFilmicToneMapping as Rd,NoToneMapping as Td,PCFSoftShadowMap$1 as sC,BasicNodeLibrary as rC,WebGLRenderTarget as $n,DepthTexture as xb,NearestFilter as Ad,LoopRepeat as aC,LoopOnce as Am,AnimationMixer as Im,CompressedTexture as lC,FrontSide as ws,Camera as cC,Frustum as Sb,AudioListener as hC,PositionalAudio as dC,AudioLoader as Lm,EventDispatcher as jm,BackSide as Id,MeshDepthMaterial as uC,CustomBlending as pC,MaxEquation as mC,AlwaysStencilFunc as gC,GreaterEqualStencilFunc as fC,NotEqualStencilFunc as yC,GreaterStencilFunc as bC,LessEqualStencilFunc as _C,EqualStencilFunc as vC,LessStencilFunc as wC,NeverStencilFunc as Cb,InvertStencilOp as xC,DecrementWrapStencilOp as SC,IncrementWrapStencilOp as CC,DecrementStencilOp as PC,IncrementStencilOp as OC,ReplaceStencilOp as kC,ZeroStencilOp as MC,KeepStencilOp as EC,CubeUVReflectionMapping as Pb,CubeTexture as Ob,AmbientLight as RC,HemisphereLight as TC,Loader as AC,RawShaderMaterial as kb,GLSL3 as IC,AlwaysDepth as LC,GreaterEqualDepth as jC,GreaterDepth as DC,LessEqualDepth as BC,LessDepth as FC,NotEqualDepth as UC,EqualDepth as zC,BatchedMesh as Mb,LinearFilter as Ld,UnsignedByteType as NC,MeshPhysicalMaterial as Eb,RingGeometry as WC,Line3 as VC,AdditiveBlending as Rb,BoxHelper as $C,SpotLight as HC,DirectionalLightHelper as GC,CameraHelper as qC,LOD as XC,Triangle as QC,NormalBlending as YC,ReinhardToneMapping as Dm,LinearToneMapping as Bm,HalfFloatType as Fm,VideoTexture as ZC,CompressedCubeTexture as KC,EquirectangularRefractionMapping as JC,CatmullRomCurve3 as eP,VectorKeyframeTrack as tP,QuaternionKeyframeTrack as iP,Audio as nP,ShaderLib as jd,UniformsUtils as Tb,MirroredRepeatWrapping as Ab,MeshNormalMaterial as oP,AudioContext as sP,PMREMGenerator$1 as rP}from"./three.min.js";import{createLoaders as Um,getRaycastMesh as Ib,LODsManager as vr,NEEDLE_progressive as Ve,addDracoAndKTX2Loaders as aP,configureLoader as lP,setKTX2TranscoderLocation as cP,setDracoDecoderLocation as hP}from"./gltf-progressive-DQa78GTA.min.js";import{GroundedSkybox as Da,Font as dP,TextGeometry as uP,FontLoader as pP,GLTFLoader as Eo,TransformControlsGizmo as Lb,EXRLoader as zm,RGBELoader as jb,Stats as mP,nodeFrame as Db,OrbitControls as gP,PositionalAudioHelper as fP,HorizontalBlurShader as yP,VerticalBlurShader as bP,GLTFExporter as Bb,strToU8 as Fb,zipSync as _P,XRControllerModelFactory as vP,XRHandMeshModel as wP,Line2 as xP,LineGeometry as SP,LineMaterial as CP,TransformControls as PP,InteractiveGroup as OP,HTMLMesh as kP,VertexNormalsHelper as MP,OBJLoader as Nm,FBXLoader as Ub,mergeVertices as EP}from"./three-examples.min.js";import{fetchProfile as RP,MotionController as TP,$70d766613f57b014$export$2e2bcd8739ae039 as zb,ByteBuffer as AP,v5 as Nb,md5 as Wb,SIZE_PREFIX_LENGTH as Vb,Builder as Wm,createNoise4D as IP,Matrix4 as Vm,BatchedParticleRenderer as LP,ParticleSystem as jP,RenderMode as Ro,ConstantColor as DP,Vector4 as BP,ConstantValue as FP,TrailParticle as $b,WorkerBase as UP,MeshBVH as zP}from"./vendor-DZ45lcA8.min.js";import{__webpack_exports__default as Pe,__webpack_exports__Text as Hb,__webpack_exports__Block as Gb,__webpack_exports__update as NP,SimpleStateBehavior as WP,__webpack_exports__Inline as $m,__webpack_exports__FontLibrary as qb,ThreeMeshUI as Xb}from"./three-mesh-ui-n3JU4M2W.min.js";import{EffectAttribute as VP}from"./postprocessing-CaEfRjRY.min.js";const Hm=new Map;function Mi(o=globalThis.location?.hostname){if(Hm.has(o))return Hm.get(o);const e=/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})|localhost/.test(o);return Hm.set(o,e),e===!0}function Qb(){return window.location.hostname.includes("glitch.me")}const Yb=typeof window!==void 0?window.location.search.includes("debugcontext"):!1;var ue=(o=>(o.ContextRegistered="ContextRegistered",o.ContextCreationStart="ContextCreationStart",o.ContextCreated="ContextCreated",o.ContextFirstFrameRendered="ContextFirstFrameRendered",o.ContextDestroying="ContextDestroying",o.ContextDestroyed="ContextDestroyed",o.MissingCamera="MissingCamera",o.ContextClearing="ContextClearing",o.ContextCleared="ContextCleared",o))(ue||{});class pe{static get Current(){return globalThis["NeedleEngine.Context.Current"]}static set Current(e){globalThis["NeedleEngine.Context.Current"]=e}static get All(){return this.Registered}static Registered=[];static register(e){this.Registered.indexOf(e)===-1&&(Yb&&console.warn("Registering context"),this.Registered.push(e),this.dispatchCallback("ContextRegistered",e))}static unregister(e){const t=this.Registered.indexOf(e);t!==-1&&(Yb&&console.warn("Unregistering context"),this.Registered.splice(t,1))}static _callbacks={};static registerCallback(e,t){this._callbacks[e]||(this._callbacks[e]=[]),this._callbacks[e].push(t)}static unregisterCallback(e,t){if(!this._callbacks[e])return;const i=this._callbacks[e].indexOf(t);i!==-1&&this._callbacks[e].splice(i,1)}static dispatchCallback(e,t,i){if(!this._callbacks[e])return!0;const n={event:e,context:t};if(i)for(const r in i)n[r]=i[r];const s=new Array;return this._callbacks[e].forEach(r=>{const a=r(n);a instanceof Promise&&s.push(a)}),Promise.all(s)}static addContextCreatedCallback(e){this.registerCallback("ContextCreated",e)}static addContextDestroyedCallback(e){this.registerCallback("ContextDestroyed",e)}}const Zb=()=>o=>o;function $P(o){return Zb()(o)}function HP(){return!!w("debug")}class Ei{_factory;_cache=[];_maxSize;_index=0;constructor(e,t){this._factory=e,this._maxSize=t}get(){const e=this._index%this._maxSize;return this._index++,this._cache.length<=e&&(this._cache[e]=this._factory()),this._cache[e]}}let wr=!1;const Gm=new Array;typeof window<"u"&&setTimeout(()=>{if(wr){const o={},e=new URL(window.location.href),t=new URL(e);t.searchParams.append("console","");const i=t.toString().replace(/=$|=(?=&)/g,"");for(const s of Gm){const r=new URL(e);r.searchParams.append(s,""),o[s]=r.toString().replace(/=$|=(?=&)/g,"")}console.log(`\u{1F335} ?help: Debug Options for Needle Engine.
|
|
2
2
|
Append any of these parameters to the URL to enable specific debug options.
|
|
3
3
|
Example: ${i} will show an onscreen console window.`);const n=wr===!0?"":` (containing "${wr}")`;console.group("Available URL parameters:"+n);for(const s of Object.keys(o).sort())typeof wr=="string"&&!s.toLowerCase().includes(wr.toLowerCase())||(console.groupCollapsed(s),console.log("Reload with this flag enabled:"),console.log(o[s]),console.groupEnd());console.groupEnd()}},100);function dc(){return new URLSearchParams(globalThis.location?.search)}function w(o){wr&&!Gm.includes(o)&&Gm.push(o);const e=dc();if(e.has(o)){const t=e.get(o);if(t){const i=Number(t);return isNaN(i)?t:i}else return!0}return!1}wr=w("help");function GP(o,e){const t=dc();t.has(o)?t.set(o,e):t.append(o,e),document.location.search=t.toString()}function uc(o,e,t=!0){const i=dc();i.has(o)?e===null?i.delete(o):i.set(o,e):e!==null&&i.append(o,e),t?Kb(o,i):Xm(o,i)}function qm(o,e,t){o.has(e)?o.set(e,t.toString()):o.append(e,t.toString())}function Kb(o,e,t){window.history.pushState(t,o,"?"+e.toString())}function Xm(o,e,t){window.history.replaceState(t,o,"?"+e.toString())}function qP(o){for(var e="",t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",i=t.length,n=0;n<o;n++)e+=t.charAt(Math.floor(Math.random()*i));return e}function XP(o,e){return Math.floor(Math.random()*(e-o+1))+o}const Jb=["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"],e_=["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 t_(){const o=Jb[Math.floor(Math.random()*Jb.length)],e=e_[Math.floor(Math.random()*e_.length)];return o+"_"+e}function i_(o){return o=o.replace(/[^a-z0-9áéíóúñü \.,_-]/gim,""),o.trim()}function Ba(o,e,t=!0,i=!1){if(e==null)return null;if(e.userData&&e.userData.guid===o||e.guid==o)return e;if(i&&e.userData?.components){for(const n of e.userData.components)if(n.guid===o)return n}if(t){if(e.scenes)for(const n in e.scenes){const s=e.scenes[n],r=Ba(o,s,t,i);if(r)return r}if(e.children)for(const n in e.children){const s=e.children[n],r=Ba(o,s,t,i);if(r)return r}}}function pc(o,e){if(o!=null&&typeof o=="object"){let t;Array.isArray(o)?t=[]:(t=Object.create(o),Object.assign(t,o));for(const i of Object.keys(o)){const n=o[i];e&&!e(o,i,n)?t[i]=n:n?.clone!==void 0&&typeof n.clone=="function"?t[i]=n.clone():t[i]=pc(n,e)}return t}return o}function To(o){return new Promise((e,t)=>{setTimeout(e,o)})}function mc(o,e){if(o<=0)return Promise.resolve();if(e||(e=pe.Current),!e)return Promise.reject("No context");const t=e.time.frameCount+o;return new Promise((i,n)=>{if(!e)return n("No context");const s=()=>{e.time.frameCount>=t&&(e.pre_update_callbacks.splice(e.pre_update_callbacks.indexOf(s),1),i())};e.pre_update_callbacks.push(s)})}const Dd=w("debugresolveurl"),n_="rel:";function QP(o,e){return Ao(o,e)}function Ao(o,e){if(e===void 0)return Dd&&console.warn("getPath: uri is undefined, returning uri",e),e;if(e.startsWith("./"))return e;if(e.startsWith("http"))return Dd&&console.warn("getPath: uri is absolute, returning uri",e),e;if(o===void 0)return Dd&&console.warn("getPath: source is undefined, returning uri",e),e;e.startsWith(n_)&&(e=e.substring(4));const t=o.lastIndexOf("/");if(t>=0){const i=o.substring(0,t+1);for(;i.endsWith("/")&&e.startsWith("/");)e=e.substring(1);const n=i+e;return Dd&&console.log("source:",o,`changed uri
|
|
4
4
|
from`,e,`
|
|
5
5
|
to `,n,`
|
|
6
|
-
basePath: `+i),n}return e}function o_(o){if(o)return o=o.trim(),o=o.split("?")[0]?.split("#")[0],o}class YP{subscribeWrite(e){this.writeCallbacks.push(e)}unsubscribeWrite(e){const t=this.writeCallbacks.indexOf(e);t!==-1&&this.writeCallbacks.splice(t,1)}writeCallbacks=[];constructor(e,t){this._object=e,this._prop=t,this._wrapperProp=Symbol("$"+t),this.apply()}_applied=!1;_object;_prop;_wrapperProp;apply(){if(this._applied||!this._object)return;const e=this._object,t=this._prop;if(e[t]===void 0)return;this._applied=!0,e[this._wrapperProp]!==void 0&&console.warn("Watcher is being applied to an object that already has a wrapper property. This is not (yet) supported");const i=e[t];e[this._wrapperProp]=i,Object.defineProperty(e,t,{get:()=>e[this._wrapperProp],set:n=>{e[this._wrapperProp]=n;for(const s of this.writeCallbacks)s(n,this._prop)}})}revoke(){if(!this._applied||!this._object)return;this._applied=!1;const e=this._object,t=this._prop;Reflect.deleteProperty(e,t);const i=e[this._wrapperProp];e[t]=i,Reflect.deleteProperty(e,this._wrapperProp)}dispose(){this.revoke(),this.writeCallbacks.length=0,this._object=null}}class ps{_watches=[];constructor(e,t){if(Array.isArray(t))for(const i of t)this._watches.push(new ps(e,i));else this._watches.push(new YP(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 Fa=Symbol("needle:watches");function Bd(o,e){if(!o[Fa])if(o instanceof K)o[Fa]=new ps(o,["x","y"]);else if(o instanceof b)o[Fa]=new ps(o,["x","y","z"]);else if(o instanceof ye||o instanceof N)o[Fa]=new ps(o,["x","y","z","w"]);else return!1;return o[Fa].subscribeWrite(e),!0}function Qm(o,e){if(!o)return;const t=o[Fa];t&&t.unsubscribeWrite(e)}var I;(o=>{let e;function t(){if(e!==void 0)return e;const te=window.navigator.userAgent,We=/Windows|MacOS|Mac OS/.test(te),ci=/Windows NT/.test(te)&&/Edg/.test(te)&&!/Win64/.test(te);return e=We&&!ci&&!k()}o.isDesktop=t;let i;function n(){return i!==void 0?i:typeof window.orientation<"u"||navigator.userAgent.indexOf("IEMobile")!==-1?i=!0:i=/iPhone|iPad|iPod|Android|IEMobile/i.test(navigator.userAgent)}o.isMobileDevice=n;function s(){return a()}o.isIPad=s;let r;function a(){if(r!==void 0)return r;const te=navigator.userAgent.toLowerCase();return r=/iPad/.test(navigator.userAgent)||te.includes("macintosh")&&"ontouchend"in document}o.isiPad=a;let l;function c(){return l!==void 0?l:l=/Android/.test(navigator.userAgent)}o.isAndroidDevice=c;let h;function d(){return h!==void 0?h:h=/WebXRViewer\//i.test(navigator.userAgent)}o.isMozillaXR=d;let p;function m(){return p!==void 0?p:p=/NeedleAppClip\//i.test(navigator.userAgent)}o.isNeedleAppClip=m;let g;function f(){if(g!==void 0)return g;if(k()||a())return g=!1;const te=navigator.userAgent.toLowerCase();return navigator.userAgentData?g=navigator.userAgentData.platform==="macOS":g=te.includes("mac os x")||te.includes("macintosh")}o.isMacOS=f;let y;function _(){return y!==void 0?y:y=a()&&"xr"in navigator&&G()}o.isVisionOS=_;let v;const P=["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"];function k(){return v!==void 0?v:v=P.includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}o.isiOS=k;let O;function
|
|
6
|
+
basePath: `+i),n}return e}function o_(o){if(o)return o=o.trim(),o=o.split("?")[0]?.split("#")[0],o}class YP{subscribeWrite(e){this.writeCallbacks.push(e)}unsubscribeWrite(e){const t=this.writeCallbacks.indexOf(e);t!==-1&&this.writeCallbacks.splice(t,1)}writeCallbacks=[];constructor(e,t){this._object=e,this._prop=t,this._wrapperProp=Symbol("$"+t),this.apply()}_applied=!1;_object;_prop;_wrapperProp;apply(){if(this._applied||!this._object)return;const e=this._object,t=this._prop;if(e[t]===void 0)return;this._applied=!0,e[this._wrapperProp]!==void 0&&console.warn("Watcher is being applied to an object that already has a wrapper property. This is not (yet) supported");const i=e[t];e[this._wrapperProp]=i,Object.defineProperty(e,t,{get:()=>e[this._wrapperProp],set:n=>{e[this._wrapperProp]=n;for(const s of this.writeCallbacks)s(n,this._prop)}})}revoke(){if(!this._applied||!this._object)return;this._applied=!1;const e=this._object,t=this._prop;Reflect.deleteProperty(e,t);const i=e[this._wrapperProp];e[t]=i,Reflect.deleteProperty(e,this._wrapperProp)}dispose(){this.revoke(),this.writeCallbacks.length=0,this._object=null}}class ps{_watches=[];constructor(e,t){if(Array.isArray(t))for(const i of t)this._watches.push(new ps(e,i));else this._watches.push(new YP(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 Fa=Symbol("needle:watches");function Bd(o,e){if(!o[Fa])if(o instanceof K)o[Fa]=new ps(o,["x","y"]);else if(o instanceof b)o[Fa]=new ps(o,["x","y","z"]);else if(o instanceof ye||o instanceof N)o[Fa]=new ps(o,["x","y","z","w"]);else return!1;return o[Fa].subscribeWrite(e),!0}function Qm(o,e){if(!o)return;const t=o[Fa];t&&t.unsubscribeWrite(e)}var I;(o=>{let e;function t(){if(e!==void 0)return e;const te=window.navigator.userAgent,We=/Windows|MacOS|Mac OS/.test(te),ci=/Windows NT/.test(te)&&/Edg/.test(te)&&!/Win64/.test(te);return e=We&&!ci&&!k()}o.isDesktop=t;let i;function n(){return i!==void 0?i:typeof window.orientation<"u"||navigator.userAgent.indexOf("IEMobile")!==-1?i=!0:i=/iPhone|iPad|iPod|Android|IEMobile/i.test(navigator.userAgent)}o.isMobileDevice=n;function s(){return a()}o.isIPad=s;let r;function a(){if(r!==void 0)return r;const te=navigator.userAgent.toLowerCase();return r=/iPad/.test(navigator.userAgent)||te.includes("macintosh")&&"ontouchend"in document}o.isiPad=a;let l;function c(){return l!==void 0?l:l=/Android/.test(navigator.userAgent)}o.isAndroidDevice=c;let h;function d(){return h!==void 0?h:h=/WebXRViewer\//i.test(navigator.userAgent)}o.isMozillaXR=d;let p;function m(){return p!==void 0?p:p=/NeedleAppClip\//i.test(navigator.userAgent)}o.isNeedleAppClip=m;let g;function f(){if(g!==void 0)return g;if(k()||a())return g=!1;const te=navigator.userAgent.toLowerCase();return navigator.userAgentData?g=navigator.userAgentData.platform==="macOS":g=te.includes("mac os x")||te.includes("macintosh")}o.isMacOS=f;let y;function _(){return y!==void 0?y:y=a()&&"xr"in navigator&&G()}o.isVisionOS=_;let v;const P=["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"];function k(){return v!==void 0?v:v=P.includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}o.isiOS=k;let O;function D(){return O!==void 0||(O=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)),O}o.isSafari=D;let L;function V(){return L!==void 0?L:L=navigator.userAgent.includes("OculusBrowser")}o.isQuest=V;let W;function G(){return W!==void 0||(W=document.createElement("a").relList.supports("ar")),W}o.supportsQuickLookAR=G;async function X(){try{return(await navigator.permissions.query({name:"microphone"})).state!=="denied"}catch(te){return console.error("Error querying `microphone` permissions.",te),!1}}o.microphonePermissionsGranted=X;let R;function $(){if(R!==void 0)return R;const te=navigator.userAgent.match(/iPhone OS (\d+_\d+)/);if(te&&(R=te[1].replace("_",".")),!R){const We=navigator.userAgent.match(/(?:\(Macintosh;|iPhone;|iPad;).*Version\/(\d+\.\d+)/);We&&(R=We[1])}return R||(R=null),R}o.getiOSVersion=$;let q;function he(){if(q!==void 0)return q;const te=navigator.userAgent.match(/(?:CriOS|Chrome)\/(\d+\.\d+\.\d+\.\d+)/);return te?q=te[1].replace("_","."):q=null,q}o.getChromeVersion=he;let re;function me(){if(re!==void 0)return re;const te=navigator.userAgent.match(/Version\/(\d+\.\d+)/);return te&&D()?re=te[1]:re=null,re}o.getSafariVersion=me})(I||(I={}));function ZP(){return I.isDesktop()}function KP(){return I.isMobileDevice()}function JP(){return I.isiPad()}function eO(){return I.isiPad()}function tO(){return I.isAndroidDevice()}function iO(){return I.isMozillaXR()}function nO(){return I.isMacOS()}function oO(){return I.isiOS()}function sO(){return I.isSafari()}function rO(){return I.isQuest()}async function aO(){return I.microphonePermissionsGranted()}const xs=new WeakMap;function Ym(o,e,t){if(!xs.get(o)){const n=new MutationObserver(s=>{lO(o,s)});xs.set(o,{observer:n,attributeChangedListeners:new Map}),n.observe(o,{attributes:!0})}const i=xs.get(o).attributeChangedListeners;return i.has(e)||i.set(e,[]),i.get(e).push(t),()=>{Zm(o,e,t)}}function Zm(o,e,t){if(!xs.get(o))return;const i=xs.get(o).attributeChangedListeners;if(!i.has(e))return;const n=i.get(e),s=n.indexOf(t);s!==-1&&(n.splice(s,1),n.length<=0&&(i.delete(e),xs.get(o)?.observer.disconnect(),xs.delete(o)))}function lO(o,e){const t=xs.get(o).attributeChangedListeners;for(const i of e)if(i.type==="attributes"){const n=i.attributeName,s=o.getAttribute(n);if(t.has(n))for(const r of t.get(n))r(s)}}class Km{reason;constructor(e){this.reason=e}}async function Jm(o){const e=await Promise.allSettled(o).catch(n=>[new Km(n.message)]);let t=!1;const i=e.map(n=>"value"in n?n.value:(t=!0,new Km(n.reason)));return{anyFailed:t,results:i}}const cO=w("debugdebug");let eg=!1;(w("noerrors")||w("nooverlaymessages"))&&(eg=!0);const tg="needle_engine_global_error_container";var Ri=(o=>(o[o.Log=0]="Log",o[o.Warn=1]="Warn",o[o.Error=2]="Error",o))(Ri||{});function s_(){return l_}const ig=new Array;function hO(o){ig.push(o)}let ng=!1;function dO(...o){if(!ng){ng=!0;try{for(let e=0;e<ig.length;e++)ig[e](...o)}catch(e){console.error(e)}ng=!1}}const r_=console.error,uO=function(...o){r_.apply(console,o),gO(o),xr(2,o,{}),mO(...o)};function a_(o){eg=!o,o?console.error=uO:console.error=r_}function pO(o){return a_(o)}let l_=0;function mO(...o){l_+=1,dO(...o)}function gO(o){if(Array.isArray(o))for(let e=0;e<o.length;e++){const t=o[e];typeof t=="string"&&t.startsWith("THREE.PropertyBinding: Trying to update node for track:")&&(o[e]="Some animated objects couldn't be found: see console for details")}}const c_=new Set;function xr(o,e,t={},i,n){if(eg)return;if(t.once===!0){let a="";if(Array.isArray(e))for(let l=0;l<e.length;l++){let c=e[l];c instanceof Error&&(c=c.message),typeof c!="object"&&(l>0&&(a+=" "),a+=c)}else typeof e=="string"&&(a=e);if(c_.has(a))return;c_.add(a)}const s=pe.Current;let r=s?.domElement??document.querySelector("needle-engine");if(s?.isInAR&&(r=s.arOverlayElement),!!r){if(Array.isArray(e)){let a="";for(let l=0;l<e.length;l++){let c=e[l];c instanceof Error&&(c=c.message),typeof c!="object"&&(l>0&&(a+=" "),a+=c)}e=a}!e||e.length<=0||fO(o,r,e,t)}}const Ua=new Map,h_=.2;function fO(o,e,t,i={}){if(t==null)return;const n=_O(e);if(n.childElementCount>=20){const c=n.lastElementChild;u_(c)}t.length>400&&(t=t.substring(0,400)+"...");const s=i.key??t;if(Ua.has(s)){Ua.get(s)?.update(t,i);return}const r=vO(o,t);n.prepend(r);const a=()=>{Ua.delete(s),u_(r)};let l=setTimeout(a,Math.max(h_,i.duration??10)*1e3);Ua.set(s,{update:(c,h)=>{c.length>400&&(c=c.substring(0,400)+"..."),r.innerHTML=c,h.duration&&(clearTimeout(l),l=setTimeout(a,Math.max(h_,h.duration)*1e3))},removeFunction:a})}function yO(){cO&&console.log("Clearing messages");for(const o of Ua.values())o?.removeFunction.call(o);Ua.clear()}const bO=`
|
|
7
7
|
|
|
8
8
|
@import url('https://fonts.googleapis.com/css2?family=Roboto+Flex:opsz,wght@8..144,100..1000&display=swap');
|
|
9
9
|
|
|
@@ -54,7 +54,7 @@ div[data-needle_engine_debug_overlay] .error strong {
|
|
|
54
54
|
color: white;
|
|
55
55
|
overflow: auto;
|
|
56
56
|
word-break: break-word;
|
|
57
|
-
`,I.isNeedleAppClip()&&(t.style.left="5px",t.style.right="unset");const i=document.querySelector('meta[name="viewport"]');i&&!i.getAttribute("content")?.includes("viewport-fit=")&&i.setAttribute("content",i.getAttribute("content")+",viewport-fit=cover"),o.shadowRoot?o.shadowRoot.appendChild(t):o.appendChild(t);const n=document.createElement("style");return n.innerHTML=bO,t.appendChild(n),t}}const d_=Symbol("logtype"),Fd=new Map;function u_(o){o.remove();const e=o[d_],t=Fd.get(e)??[];t.push(o),Fd.set(e,t)}function vO(o,e){if(Fd.has(o)){const i=Fd.get(o);if(i.length>0){const n=i.pop();return n.innerHTML=e,n}}const t=document.createElement("div");switch(t.setAttribute("data-id","__needle_engine_debug_overlay"),t.style.marginRight="5px",t.style.padding=".5em",t.style.backgroundColor="rgba(0,0,0,.9)",t.style.marginTop="5px",t.style.marginBottom="3px",t.style.borderRadius="8px",t.style.pointerEvents="all",t.style.userSelect="text",t.style.maxWidth="250px",t.style.whiteSpace="pre-wrap",t.style["backdrop-filter"]="blur(10px)",t.style["-webkit-backdrop-filter"]="blur(10px)",t.style.backgroundColor="rgba(20,20,20,.8)",t.style.boxShadow="inset 0 0 80px rgba(0,0,0,.2), 0 0 5px rgba(0,0,0,.2)",t.style.border="1px solid rgba(160,160,160,.2)",t[d_]=o,o){case 0:t.classList.add("log"),t.style.color="rgba(200,200,200,.7)",t.style.backgroundColor="rgba(40,40,40,.7)";break;case 1:t.classList.add("warn"),t.style.color="rgb(255, 255, 150)",t.style.backgroundColor="rgba(50,50,20,.8)";break;case 2:t.classList.add("error"),t.style.color="rgb(255, 50, 50",t.style.backgroundColor="rgba(50,20,20,.8)";break}return t.title="Open the browser console (F12) for more information",t.innerHTML=e,t}class wO{random(e,t){return Array.isArray(e)?e.length<=0?null:e[Math.floor(Math.random()*e.length)]:e!==void 0&&t!==void 0?Math.random()*(t-e)+e:Math.random()}randomVector3(e,t=0,i=1){e.x=this.random(t,i),e.y=this.random(t,i),e.z=this.random(t,i)}clamp(e,t,i){return e<t?t:e>i?i:e}clamp01(e){return this.clamp(e,0,1)}lerp(e,t,i){return i=i<0?0:i,i=i>1?1:i,e+(t-e)*i}inverseLerp(e,t,i){return(i-e)/(t-e)}remap(e,t,i,n,s){return n+(s-n)*(e-t)/(i-t)}moveTowards(e,t,i){return e+=i,(i<0&&e<t||i>0&&e>t)&&(e=t),e}Rad2Deg=180/Math.PI;Deg2Rad=Math.PI/180;Epsilon=1e-5;toDegrees(e){return e*180/Math.PI}toRadians(e){return e*Math.PI/180}tan(e){return Math.tan(e)}gammaToLinear(e){return Math.pow(e,2.2)}linearToGamma(e){return Math.pow(e,1/2.2)}approximately(e,t,i=Number.EPSILON){for(const n of xO){const s=e[n],r=t[n];if(s===void 0||r===void 0)break;if(Math.abs(s-r)>i)return!1}return!0}easeInOutCubic(e){return e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2}}const xO=["x","y","z","w"],
|
|
57
|
+
`,I.isNeedleAppClip()&&(t.style.left="5px",t.style.right="unset");const i=document.querySelector('meta[name="viewport"]');i&&!i.getAttribute("content")?.includes("viewport-fit=")&&i.setAttribute("content",i.getAttribute("content")+",viewport-fit=cover"),o.shadowRoot?o.shadowRoot.appendChild(t):o.appendChild(t);const n=document.createElement("style");return n.innerHTML=bO,t.appendChild(n),t}}const d_=Symbol("logtype"),Fd=new Map;function u_(o){o.remove();const e=o[d_],t=Fd.get(e)??[];t.push(o),Fd.set(e,t)}function vO(o,e){if(Fd.has(o)){const i=Fd.get(o);if(i.length>0){const n=i.pop();return n.innerHTML=e,n}}const t=document.createElement("div");switch(t.setAttribute("data-id","__needle_engine_debug_overlay"),t.style.marginRight="5px",t.style.padding=".5em",t.style.backgroundColor="rgba(0,0,0,.9)",t.style.marginTop="5px",t.style.marginBottom="3px",t.style.borderRadius="8px",t.style.pointerEvents="all",t.style.userSelect="text",t.style.maxWidth="250px",t.style.whiteSpace="pre-wrap",t.style["backdrop-filter"]="blur(10px)",t.style["-webkit-backdrop-filter"]="blur(10px)",t.style.backgroundColor="rgba(20,20,20,.8)",t.style.boxShadow="inset 0 0 80px rgba(0,0,0,.2), 0 0 5px rgba(0,0,0,.2)",t.style.border="1px solid rgba(160,160,160,.2)",t[d_]=o,o){case 0:t.classList.add("log"),t.style.color="rgba(200,200,200,.7)",t.style.backgroundColor="rgba(40,40,40,.7)";break;case 1:t.classList.add("warn"),t.style.color="rgb(255, 255, 150)",t.style.backgroundColor="rgba(50,50,20,.8)";break;case 2:t.classList.add("error"),t.style.color="rgb(255, 50, 50",t.style.backgroundColor="rgba(50,20,20,.8)";break}return t.title="Open the browser console (F12) for more information",t.innerHTML=e,t}class wO{random(e,t){return Array.isArray(e)?e.length<=0?null:e[Math.floor(Math.random()*e.length)]:e!==void 0&&t!==void 0?Math.random()*(t-e)+e:Math.random()}randomVector3(e,t=0,i=1){e.x=this.random(t,i),e.y=this.random(t,i),e.z=this.random(t,i)}clamp(e,t,i){return e<t?t:e>i?i:e}clamp01(e){return this.clamp(e,0,1)}lerp(e,t,i){return i=i<0?0:i,i=i>1?1:i,e+(t-e)*i}inverseLerp(e,t,i){return(i-e)/(t-e)}remap(e,t,i,n,s){return n+(s-n)*(e-t)/(i-t)}moveTowards(e,t,i){return e+=i,(i<0&&e<t||i>0&&e>t)&&(e=t),e}Rad2Deg=180/Math.PI;Deg2Rad=Math.PI/180;Epsilon=1e-5;toDegrees(e){return e*180/Math.PI}toRadians(e){return e*Math.PI/180}tan(e){return Math.tan(e)}gammaToLinear(e){return Math.pow(e,2.2)}linearToGamma(e){return Math.pow(e,1/2.2)}approximately(e,t,i=Number.EPSILON){for(const n of xO){const s=e[n],r=t[n];if(s===void 0||r===void 0)break;if(Math.abs(s-r)>i)return!1}return!0}easeInOutCubic(e){return e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2}}const xO=["x","y","z","w"],j=new wO;class p_{y;s;alpha=0;constructor(e){this.setAlpha(e),this.y=null,this.s=null}setAlpha(e){if(e<=0||e>1)throw new Error;this.alpha=e}filter(e,t){t&&this.setAlpha(t);let i;return this.y?i=this.alpha*e+(1-this.alpha)*this.s:i=e,this.y=e,this.s=i,i}lastValue(){return this.y}reset(e){this.y=e,this.s=e}}class Ud{freq;minCutOff;beta;dCutOff;x;dx;lasttime;constructor(e,t=1,i=0,n=1){if(e<=0||t<=0||n<=0)throw new Error;this.freq=e,this.minCutOff=t,this.beta=i,this.dCutOff=n,this.x=new p_(this.alpha(this.minCutOff)),this.dx=new p_(this.alpha(this.dCutOff)),this.lasttime=null}alpha(e){const t=1/this.freq;return 1/(1+1/(2*Math.PI*e)/t)}filter(e,t=null){this.lasttime&&t&&(this.freq=1/(t-this.lasttime)),this.lasttime=t;const i=this.x.lastValue(),n=i?(e-i)*this.freq:0,s=this.dx.filter(n,this.alpha(this.dCutOff)),r=this.minCutOff+this.beta*Math.abs(s);return this.x.filter(e,this.alpha(r))}reset(e){e!=null&&this.x.reset(e),this.x.alpha=this.alpha(this.minCutOff),this.dx.alpha=this.alpha(this.dCutOff),this.lasttime=null}}class og{x;y;z;constructor(e,t=1,i=0,n=1){this.x=new Ud(e,t,i,n),this.y=new Ud(e,t,i,n),this.z=new Ud(e,t,i,n)}filter(e,t,i=null){t.x=this.x.filter(e.x,i),t.y=this.y.filter(e.y,i),t.z=this.z.filter(e.z,i)}reset(e){this.x.reset(e?.x),this.y.reset(e?.y),this.z.reset(e?.z)}}const zd="needle:cameraController";function m_(o){return o[zd]}function sg(o,e,t){t?o[zd]=e:o[zd]===e&&(o[zd]=null)}const rg="needle:autofit";function g_(o){return o[rg]===void 0?!0:o[rg]!==!1}function Nd(o,e){o[rg]=e}let xn;const SO={x:0,y:0,width:0,height:0},CO=w("debugfocusrect");function PO(o,e,t,i,n){o instanceof Element&&(CO&&o instanceof HTMLElement&&(o.style.outline="2px dashed rgba(255, 150, 0, .8)"),o=o.getBoundingClientRect()),xn=n.domElement.getBoundingClientRect();const s=SO;s.x=o.x,s.y=o.y,s.width=o.width,s.height=o.height,s.x-=xn.x,s.y-=xn.y;const r=xn.width,a=xn.height,l=i.view,c=e.zoom;let h=l?.offsetX||0,d=l?.offsetY||0,p=xn.width,m=xn.height;p/=c,m/=c,h=p*(c-1)*.5,d=m*(c-1)*.5;const g=s.x+s.width*.5,f=s.y+s.height*.5,y=xn.width*.5,_=xn.height*.5,v=g-y,P=f-_;h-=v/c,d-=P/c,e.offsetX!==void 0&&(h+=e.offsetX*(xn.width*.5)),e.offsetY!==void 0&&(d-=e.offsetY*(xn.height*.5));const k=l?.offsetX||h,O=l?.offsetY||d;h=j.lerp(k,h,t),d=j.lerp(O,d,t);const D=l?.width||r,L=l?.height||a;p=j.lerp(D,p,t),m=j.lerp(L,m,t),i.setViewOffset(r,a,h,d,p,m),i.updateProjectionMatrix(),e.damping>0&&(e.damping*=1-t,e.damping<.01&&(e.damping=0),e.damping=Math.max(0,e.damping))}function OO(o,e,t){const i=o.length(),n=e.length(),s=j.lerp(i,n,t);return o.lerp(e,t).normalize().multiplyScalar(s)}const ag=new N,f_=new N().setFromAxisAngle(new b(0,1,0),Math.PI);function kO(o,e){o.lookAt(e),o.quaternion.multiply(f_)}function gc(o,e,t=!0,i=!1){if(o===e)return;ag.copy(o.quaternion);const n=ee(e),s=ee(o);if(i){if(Sn(o,_e(e)),t){const r=s.y,a=s.sub(w_(o));a.y=r,o.lookAt(a),o.quaternion.multiply(f_)}Number.isNaN(o.quaternion.x)&&o.quaternion.copy(ag);return}t&&(n.y=s.y),o.lookAt(n),Number.isNaN(o.quaternion.x)&&o.quaternion.copy(ag)}function MO(o,e,t,i=1){if(t){const n=F(0,0,0),s=e.x/window.innerWidth*2-1,r=-(e.y/window.innerHeight)*2+1;n.set(s,r,0),n.unproject(t);const a=t.worldPosition,l=o.worldPosition.distanceTo(a),c=n.sub(a);c.multiplyScalar(i*3.6*l);const h=t.worldPosition.add(c);return o.lookAt(h),h}return null}const EO=new Ei(()=>new b,100);function F(o,e,t){const i=EO.get();return i.set(0,0,0),o instanceof b?i.copy(o):Array.isArray(o)?i.set(o[0],o[1],o[2]):o instanceof DOMPointReadOnly?i.set(o.x,o.y,o.z):typeof o=="number"?(i.x=o,i.y=e!==void 0?e:i.x,i.z=t!==void 0?t:i.x):typeof o=="object"&&(i.x=o.x,i.y=o.y,i.z=o.z),i}const RO=new Ei(()=>new oe,30);function y_(o){const e=RO.get();return o?e.copy(o):e.set(0,0,0),e}const TO=new Ei(()=>new N,100);function hi(o,e,t,i){const n=TO.get();return n.identity(),o instanceof N?n.copy(o):o instanceof DOMPointReadOnly?n.set(o.x,o.y,o.z,o.w):typeof o=="number"&&e!==void 0&&t!==void 0&&i!==void 0?n.set(o,e,t,i):typeof o=="object"&&"x"in o&&"y"in o&&"z"in o&&"w"in o&&n.set(o.x,o.y,o.z,o.w),n}const lg=new Ei(()=>new b,100),b_=Symbol("lastMatrixWorldUpdateKey");function ee(o,e=null,t=!0){const i=e??lg.get();return o?o.parent?(t&&o.updateWorldMatrix(!0,!1),o.matrixWorldNeedsUpdate&&o[b_]!==Date.now()&&(o[b_]=Date.now(),o.updateMatrixWorld()),i.setFromMatrixPosition(o.matrixWorld),i):i.copy(o.position):i.set(0,0,0)}function yt(o,e){if(!o)return o;const t=lg.get();return e!==t&&t.copy(e),o.parent!==null&&o.parent.worldToLocal(t),o.position.set(t.x,t.y,t.z),o}function Sr(o,e,t,i){const n=lg.get();return n.set(e,t,i),yt(o,n),o}const Wd=new Ei(()=>new N,100),Cr=new N,cg=new N;function _e(o,e=null){if(!o)return Wd.get().identity();const t=e??Wd.get();return o.parent?(o.getWorldQuaternion(t),t):t.copy(o.quaternion)}function Sn(o,e){if(!o)return;e!==Cr&&Cr.copy(e);const t=Cr;o?.parent?.getWorldQuaternion(cg),cg.invert();const i=cg.multiply(t);o.quaternion.set(i.x,i.y,i.z,i.w)}function hg(o,e,t,i,n){Cr.set(e,t,i,n),Sn(o,Cr)}const AO=new Ei(()=>new b,100),IO=new b;function $e(o,e=null){return e||(e=AO.get()),o?o.parent?(o.getWorldScale(e),e):e.copy(o.scale):e.set(0,0,0)}function za(o,e){if(!o)return;if(!o.parent){o.scale.copy(e);return}const t=IO;o.parent.getWorldScale(t),o.scale.copy(e),o.scale.divide(t)}const LO=new b,__=new N;function jO(o){return _e(o,__),LO.set(0,0,1).applyQuaternion(__)}const DO=new Ei(()=>new b,100),v_=new N;function w_(o,e){return e||(e=DO.get().set(0,0,1)),_e(o,v_),e.applyQuaternion(v_)}const x_=new at,S_=new at,BO=new b;function dg(o){const e=Wd.get();return o.getWorldQuaternion(e),S_.setFromQuaternion(e),S_}function ug(o,e){const t=Wd.get();Sn(o,t.setFromEuler(e))}function Vd(o){const e=dg(o),t=BO;return t.set(e.x,e.y,e.z),t.x=j.toDegrees(t.x),t.y=j.toDegrees(t.y),t.z=j.toDegrees(t.z),t}function C_(o,e){fc(o,e.x,e.y,e.z,!0)}function fc(o,e,t,i,n=!0){n&&(e=j.toRadians(e),t=j.toRadians(t),i=j.toRadians(i)),x_.set(e,t,i),Cr.setFromEuler(x_),Sn(o,Cr)}function $d(o,e=!0){o&&(e?function t(i){console.groupCollapsed((i.name?i.name:"(no name : "+i.type+")")+" %o",i),i.children.forEach(t),console.groupEnd()}(o):o.traverse(function(t){for(var i="|___",n=t;n.parent!==null;)i=" "+i,n=n.parent;console.log(i+t.name+" <"+t.type+">")}))}function FO(o){let e=o?.name||"";if(!o)return e;let t=o.parent;for(;t;)e=t.name+"/"+e,t=t.parent;return e}function P_(o){if(o){const e=o;return e.blendMode!==void 0&&e.clampWhenFinished!==void 0&&e.enabled!==void 0&&e.fadeIn!==void 0&&e.getClip!==void 0}return!1}class xm extends Vn{static vertex=`
|
|
58
58
|
varying vec2 vUv;
|
|
59
59
|
void main(){
|
|
60
60
|
vUv = uv;
|
|
@@ -141,7 +141,7 @@ void main(){
|
|
|
141
141
|
#__vconsole .vc-mask {
|
|
142
142
|
overflow: hidden;
|
|
143
143
|
}
|
|
144
|
-
`,Or?.prepend(i),o===!0&&s_()<=0&&I_(),console.log("\u{1F335} Debug console has loaded")}},e.onerror=()=>{console.warn("\u{1F335} Debug console failed to load."+(window.crossOriginIsolated?"This page is using cross-origin isolation, so external scripts can't be loaded.":"")),vc=!1,ui=null},e.src="https://cdn.jsdelivr.net/npm/vconsole@3.15.1/dist/vconsole.min.js",document.body.appendChild(e)}function ek(){if(!globalThis.VConsole)return;const o=new VConsole.VConsolePlugin("needle-console","\u{1F335} Inspect glTF"),e=()=>document.querySelector("#__vc_plug_"+o._id+" iframe");return o.on("renderTab",function(t){const i=globalThis["needle:codegen_files"];if(!i||i.length===0)return;let n=globalThis["needle:codegen_files"][0];const s=n.indexOf("?");s>-1&&(n=n.substring(0,s));const r=location.protocol+"//"+location.host+location.pathname+"/"+n,a=encodeURIComponent(r);o.fullUrl="https://viewer.needle.tools?inspect&file="+a;var l='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';t(l)}),o.on("show",function(){const t=e();t&&t.src!==o.fullUrl&&(t.src=o.fullUrl)}),o.on("hide",function(){const t=e();t&&(t.src="")}),o.on("addTopBar",function(t){var i=new Array;i.push({name:"Open in new window \u2197",onClick:function(n){window.open(o.fullUrl,"_blank"),ui?.hide()}}),i.push({name:"Reload",onClick:function(n){const s=e();s&&(s.src=o.fullUrl)}}),i.push({name:"Fullscreen",onClick:function(n){const s=e();s.requestFullscreen?s.requestFullscreen():s.webkitRequestFullscreen instanceof Function&&s.webkitRequestFullscreen()}}),t(i)}),o}const bg="padding: 10px; font-family: monospace;",j_="margin-bottom: 10px;",kr="margin-bottom: 10px; margin-top: 15px;",tk="width: 100%; border-collapse: collapse; border: 1px solid rgba(0,0,0,0.1); table-layout: fixed;",D_="border: 1px solid rgba(0,0,0,0.1); padding: 5px;",ik=D_,nk=D_+" word-break: break-all;";function Gn(o,e=!1){e&&o.sort((i,n)=>(n.value?1:0)-(i.value?1:0));let t=`<table style='${tk}'>`;t+="<tbody>";for(const i of o){const n=typeof i.value=="boolean"?i.value?"\u2705":"\u274C":i.value;t+=`<tr><td style='${ik}'>${i.label}</td><td style='${nk}'>${n}</td></tr>`}return t+="</tbody></table>",t}function B_(){try{if(document.createElement("canvas").getContext("webgl2"))return"\u2705"}catch{}return"\u274C"}function ok(){if(!globalThis.VConsole)return;const o=new VConsole.VConsolePlugin("device-utilities","\u{1F4F1} Device Info");return o.on("renderTab",function(e){let t=`<div style='${bg}'>`;const i=mk();t+=`<h3 style='${j_}'>Device: ${i}</h3>`,t+=Gn([{label:"\u{1F4BB} Desktop",value:I.isDesktop()},{label:"\u{1F4F1} Mobile Device",value:I.isMobileDevice()},{label:"\u{1F34E} iOS",value:I.isiOS()},{label:"\u{1F4F1} iPad",value:I.isiPad()},{label:"\u{1F916} Android",value:I.isAndroidDevice()},{label:"\u{1F98A} Mozilla XR",value:I.isMozillaXR()},{label:"\u{1F335} Needle App Clip",value:I.isNeedleAppClip()},{label:"\u{1F34F} macOS",value:I.isMacOS()},{label:"\u{1F453} VisionOS",value:I.isVisionOS()},{label:"\u{1F9ED} Safari",value:I.isSafari()},{label:"\u{1F576}\uFE0F Meta Quest",value:I.isQuest()},{label:"\u{1F517} QuickLook AR Support",value:I.supportsQuickLookAR()}],!0);const n=[],s=I.getiOSVersion();s&&n.push({label:"\u{1F34E} iOS Version",value:s});const r=I.getChromeVersion();r&&n.push({label:"\u{1F310} Chrome Version",value:r});const a=I.getSafariVersion();a&&n.push({label:"\u{1F9ED} Safari Version",value:a}),n.length>0&&(t+=Gn(n,!1)),t+="</div>",t+=`<div style='${bg} margin-top: 20px;'>`,t+=`<h3 style='${j_}'>User Agent Info</h3>`;const l=[{label:"User Agent",value:navigator.userAgent},{label:"Platform",value:navigator.platform},{label:"App Version",value:navigator.appVersion},{label:"User Agent Data",value:navigator.userAgentData?`Platform: ${navigator.userAgentData.platform}, Mobile: ${navigator.userAgentData.mobile}`:"Not supported"},{label:"WebXR",value:"xr"in navigator?"\u2705":"\u274C"},{label:"WebGPU",value:"gpu"in navigator?"\u2705":"\u274C"},{label:"WebGL 2",value:B_()}];t+=Gn(l,!1),t+="</div>",e(t)}),o}function sk(){if(!globalThis.VConsole)return;const o=new VConsole.VConsolePlugin("graphics-info","\u{1F3A8} Graphics Info");return o.on("renderTab",async function(e){let t=`<div style='${bg}'>`;const i=rk();i.length>0&&(t+=`<h3 style='${kr}'>General GPU Info</h3>`,t+=Gn(i,!1));const n=lk();n.length>0&&(t+=`<h3 style='${kr}'>WebGL</h3>`,t+=Gn(n,!1));const s=ck();s.length>0&&(t+=`<h3 style='${kr}'>WebGL 2 Features</h3>`,t+=Gn(s,!1));const r=hk();r.length>0&&(t+=`<h3 style='${kr}'>WebGL Limits</h3>`,t+=Gn(r,!1));const a=dk();a.length>0&&(t+=`<h3 style='${kr}'>Texture Formats</h3>`,t+=Gn(a,!1));const l=await uk();if(l.length>0&&(t+=`<h3 style='${kr}'>WebGPU</h3>`,t+=Gn(l,!1)),I.isSafari()){const c=pk();c.length>0&&(t+=`<h3 style='${kr}'>Safari GPU Info</h3>`,t+=Gn(c,!1))}t+="</div>",e(t)}),o}function rk(){const o=[],e=window.devicePixelRatio;o.push({label:"Device Pixel Ratio",value:e.toString()}),o.push({label:"Width (px)",value:(window.innerWidth*e).toString()}),o.push({label:"Height (px)",value:(window.innerHeight*e).toString()});const t=I.isMobileDevice()?150:96,i=screen.width/t,n=screen.height/t,s=i*2.54,r=n*2.54;o.push({label:"Estimated Width (cm)",value:s.toFixed(1)}),o.push({label:"Estimated Height (cm)",value:r.toFixed(1)});const a=F_();if(a){o.push({label:"GPU",value:a.renderer}),o.push({label:"Driver",value:a.vendor}),o.push({label:"ANGLE",value:a.angle||"Not detected"});const l=ak(a.renderer);l&&(l.manufacturer&&o.push({label:"Manufacturer",value:l.manufacturer}),l.cardVersion&&o.push({label:"Card Version",value:l.cardVersion}),l.brand&&o.push({label:"Brand",value:l.brand}),o.push({label:"Integrated",value:l.integrated?"Yes":"No"}),l.layer&&o.push({label:"WebGL Layer",value:l.layer}))}return o}function ak(o){if(!o)return null;const e=(l,c)=>{const h=c.match(l);return h&&h[0]},t=e(/(ANGLE)/g,o)||void 0,i=e(/((NVIDIA|AMD|Intel)[^\d]*[^\s]+)/,o)||o,n=i.split(" ");n.shift();const s=e(/(NVIDIA|AMD|Intel)/g,i)||void 0,r=n.length>0?n.pop():void 0,a=n.length>0?n.join(" "):void 0;return{manufacturer:s,cardVersion:r,brand:a,integrated:s==="Intel",layer:t,card:i}}function lk(){const o=[],e=F_();return e&&(o.push({label:"\u{1F4CA} WebGL Version",value:e.version}),o.push({label:"\u{1F3AE} WebGL 2 Available",value:B_()})),o}function ck(){const o=[];try{const e=document.createElement("canvas").getContext("webgl2");if(!e)return o;o.push({label:"Float Color Buffer",value:e.getExtension("EXT_color_buffer_float")?"\u2705":"\u274C"}),o.push({label:"Anisotropic Filtering",value:e.getExtension("EXT_texture_filter_anisotropic")?"\u2705":"\u274C"}),o.push({label:"Float Texture Linear",value:e.getExtension("OES_texture_float_linear")?"\u2705":"\u274C"}),o.push({label:"S3TC Compression",value:e.getExtension("WEBGL_compressed_texture_s3tc")?"\u2705":"\u274C"}),o.push({label:"ETC Compression",value:e.getExtension("WEBGL_compressed_texture_etc")?"\u2705":"\u274C"}),o.push({label:"PVRTC Compression",value:e.getExtension("WEBGL_compressed_texture_pvrtc")?"\u2705":"\u274C"}),o.push({label:"ASTC Compression",value:e.getExtension("WEBGL_compressed_texture_astc")?"\u2705":"\u274C"})}catch{}return o}function hk(){const o=[];try{const e=document.createElement("canvas"),t=e.getContext("webgl2")||e.getContext("webgl");if(!t)return o;const i=t instanceof WebGL2RenderingContext;o.push({label:"\u{1F4CF} Max Texture Size",value:t.getParameter(t.MAX_TEXTURE_SIZE).toString()}),o.push({label:"\u{1F3A8} Max Renderbuffer Size",value:t.getParameter(t.MAX_RENDERBUFFER_SIZE).toString()}),o.push({label:"\u{1F517} Max Vertex Attribs",value:t.getParameter(t.MAX_VERTEX_ATTRIBS).toString()}),o.push({label:"\u{1F3AF} Max Texture Units",value:t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS).toString()}),i&&(o.push({label:"\u26A1 Max Samples",value:t.getParameter(t.MAX_SAMPLES).toString()}),o.push({label:"\u{1F504} Max Uniform Buffer Bindings",value:t.getParameter(t.MAX_UNIFORM_BUFFER_BINDINGS).toString()}),o.push({label:"\u{1F4D0} Max 3D Texture Size",value:t.getParameter(t.MAX_3D_TEXTURE_SIZE).toString()}))}catch{}return o}function dk(){const o=[];try{document.createElement("canvas").getContext("webgl")&&(o.push({label:"WebGL 1 RGBA",value:"\u2705"}),o.push({label:"WebGL 1 RGB",value:"\u2705"}));const e=document.createElement("canvas").getContext("webgl2");e&&(o.push({label:"WebGL 2 RGBA32F",value:e.getExtension("EXT_color_buffer_float")?"\u2705":"\u274C"}),o.push({label:"WebGL 2 RGB32F",value:e.getExtension("EXT_color_buffer_float")?"\u2705":"\u274C"}),o.push({label:"WebGL 2 R11F_G11F_B10F",value:"\u2705"}),o.push({label:"WebGL 2 RGB565",value:"\u2705"}),o.push({label:"WebGL 2 RGB5_A1",value:"\u2705"}),o.push({label:"WebGL 2 RGBA4444",value:"\u2705"}))}catch{}return o}async function uk(){const o=[];if(!("gpu"in navigator))return o.push({label:"\u{1F680} WebGPU Support",value:"\u274C Not supported"}),o;o.push({label:"\u{1F680} WebGPU Support",value:"\u2705 Supported"});try{const e=await navigator.gpu.requestAdapter();if(!e)return o.push({label:"\u{1F3AF} Adapter",value:"No adapter available"}),o;o.push({label:"\u{1F3AF} Adapter",value:e.name||"Unknown Adapter"});const t=await e.requestDevice();o.push({label:"\u{1F527} Device",value:t.label||"WebGPU Device"}),o.push({label:"\u{1F4CF} Max Texture 2D",value:t.limits.maxTextureDimension2D.toString()}),o.push({label:"\u{1F4D0} Max Texture 3D",value:t.limits.maxTextureDimension3D.toString()}),o.push({label:"\u{1F4CA} Max Texture Array Layers",value:t.limits.maxTextureArrayLayers.toString()}),o.push({label:"\u{1F4BE} Max Buffer Size",value:`${(t.limits.maxBufferSize/1024/1024).toFixed(1)}MB`}),o.push({label:"\u{1F517} Max Bind Groups",value:t.limits.maxBindGroups.toString()})}catch(e){o.push({label:"\u274C Error",value:e.message})}return o}function F_(){try{const o=document.createElement("canvas"),e=o.getContext("webgl2")||o.getContext("webgl");if(!e)return null;const t=e.getExtension("WEBGL_debug_renderer_info"),i=t?e.getParameter(t.UNMASKED_RENDERER_WEBGL):e.getParameter(e.RENDERER),n=t?e.getParameter(t.UNMASKED_VENDOR_WEBGL):e.getParameter(e.VENDOR),s=e.getParameter(e.VERSION);let r;if(i&&i.includes("ANGLE")){const a=i.match(/ANGLE \(([^)]+)\)/);a&&(r=a[1])}return{renderer:i,vendor:n,version:s,angle:r}}catch{return null}}function pk(){const o=[];try{const e=document.createElement("canvas").getContext("webgl");if(e){const t=e.getExtension("WEBGL_debug_renderer_info");if(t){const i=e.getParameter(t.UNMASKED_RENDERER_WEBGL);i&&i.includes("Apple")&&o.push({label:"\u{1F34E} Apple GPU",value:i})}}}catch{}try{const e=document.createElement("canvas").getContext("webgl");e&&(e.getSupportedExtensions()||[]).includes("WEBGL_compressed_texture_pvrtc")&&o.push({label:"\u{1F5DC}\uFE0F PVRTC Support",value:"\u2705"})}catch{}return o}function mk(){return I.isQuest()?"Meta Quest":I.isVisionOS()?"Vision Pro":I.isiOS()?I.isiPad()?"iPad":"iPhone/iPod":I.isAndroidDevice()?"Android Device":I.isMozillaXR()?"Mozilla XR Browser":I.isNeedleAppClip()?"Needle App Clip":I.isMacOS()?"Mac":I.isDesktop()?"Desktop PC":"Unknown Device"}function gk(){return document.querySelector("#__vconsole .vc-switch")||null}function fk(){return document.querySelector("#__vconsole")||null}const U_=w("debugdefines");Cs('if(!globalThis["NEEDLE_ENGINE_VERSION"]) globalThis["NEEDLE_ENGINE_VERSION"] = "0.0.0";'),Cs('if(!globalThis["NEEDLE_ENGINE_GENERATOR"]) globalThis["NEEDLE_ENGINE_GENERATOR"] = "unknown";'),Cs('if(!globalThis["NEEDLE_PROJECT_BUILD_TIME"]) globalThis["NEEDLE_PROJECT_BUILD_TIME"] = "unknown";'),Cs('if(!globalThis["NEEDLE_PUBLIC_KEY"]) globalThis["NEEDLE_PUBLIC_KEY"] = "unknown";'),Cs('globalThis["__NEEDLE_ENGINE_VERSION__"] = "4.16.3";'),Cs('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";'),Cs('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Sun Mar 15 2026 11:31:10 GMT+0000 (Coordinated Universal Time)";'),Cs('globalThis["__NEEDLE_PUBLIC_KEY__"] = "'+NEEDLE_PUBLIC_KEY+'";');const Ti="4.16.3",Wa="undefined",wc="Sun Mar 15 2026 11:31:10 GMT+0000 (Coordinated Universal Time)";U_&&console.log(`Engine version: ${Ti} (generator: ${Wa})
|
|
144
|
+
`,Or?.prepend(i),o===!0&&s_()<=0&&I_(),console.log("\u{1F335} Debug console has loaded")}},e.onerror=()=>{console.warn("\u{1F335} Debug console failed to load."+(window.crossOriginIsolated?"This page is using cross-origin isolation, so external scripts can't be loaded.":"")),vc=!1,ui=null},e.src="https://cdn.jsdelivr.net/npm/vconsole@3.15.1/dist/vconsole.min.js",document.body.appendChild(e)}function ek(){if(!globalThis.VConsole)return;const o=new VConsole.VConsolePlugin("needle-console","\u{1F335} Inspect glTF"),e=()=>document.querySelector("#__vc_plug_"+o._id+" iframe");return o.on("renderTab",function(t){const i=globalThis["needle:codegen_files"];if(!i||i.length===0)return;let n=globalThis["needle:codegen_files"][0];const s=n.indexOf("?");s>-1&&(n=n.substring(0,s));const r=location.protocol+"//"+location.host+location.pathname+"/"+n,a=encodeURIComponent(r);o.fullUrl="https://viewer.needle.tools?inspect&file="+a;var l='<iframe src="" style="width: 100%; height: 99%; border: none;"></iframe>';t(l)}),o.on("show",function(){const t=e();t&&t.src!==o.fullUrl&&(t.src=o.fullUrl)}),o.on("hide",function(){const t=e();t&&(t.src="")}),o.on("addTopBar",function(t){var i=new Array;i.push({name:"Open in new window \u2197",onClick:function(n){window.open(o.fullUrl,"_blank"),ui?.hide()}}),i.push({name:"Reload",onClick:function(n){const s=e();s&&(s.src=o.fullUrl)}}),i.push({name:"Fullscreen",onClick:function(n){const s=e();s.requestFullscreen?s.requestFullscreen():s.webkitRequestFullscreen instanceof Function&&s.webkitRequestFullscreen()}}),t(i)}),o}const bg="padding: 10px; font-family: monospace;",j_="margin-bottom: 10px;",kr="margin-bottom: 10px; margin-top: 15px;",tk="width: 100%; border-collapse: collapse; border: 1px solid rgba(0,0,0,0.1); table-layout: fixed;",D_="border: 1px solid rgba(0,0,0,0.1); padding: 5px;",ik=D_,nk=D_+" word-break: break-all;";function Gn(o,e=!1){e&&o.sort((i,n)=>(n.value?1:0)-(i.value?1:0));let t=`<table style='${tk}'>`;t+="<tbody>";for(const i of o){const n=typeof i.value=="boolean"?i.value?"\u2705":"\u274C":i.value;t+=`<tr><td style='${ik}'>${i.label}</td><td style='${nk}'>${n}</td></tr>`}return t+="</tbody></table>",t}function B_(){try{if(document.createElement("canvas").getContext("webgl2"))return"\u2705"}catch{}return"\u274C"}function ok(){if(!globalThis.VConsole)return;const o=new VConsole.VConsolePlugin("device-utilities","\u{1F4F1} Device Info");return o.on("renderTab",function(e){let t=`<div style='${bg}'>`;const i=mk();t+=`<h3 style='${j_}'>Device: ${i}</h3>`,t+=Gn([{label:"\u{1F4BB} Desktop",value:I.isDesktop()},{label:"\u{1F4F1} Mobile Device",value:I.isMobileDevice()},{label:"\u{1F34E} iOS",value:I.isiOS()},{label:"\u{1F4F1} iPad",value:I.isiPad()},{label:"\u{1F916} Android",value:I.isAndroidDevice()},{label:"\u{1F98A} Mozilla XR",value:I.isMozillaXR()},{label:"\u{1F335} Needle App Clip",value:I.isNeedleAppClip()},{label:"\u{1F34F} macOS",value:I.isMacOS()},{label:"\u{1F453} VisionOS",value:I.isVisionOS()},{label:"\u{1F9ED} Safari",value:I.isSafari()},{label:"\u{1F576}\uFE0F Meta Quest",value:I.isQuest()},{label:"\u{1F517} QuickLook AR Support",value:I.supportsQuickLookAR()}],!0);const n=[],s=I.getiOSVersion();s&&n.push({label:"\u{1F34E} iOS Version",value:s});const r=I.getChromeVersion();r&&n.push({label:"\u{1F310} Chrome Version",value:r});const a=I.getSafariVersion();a&&n.push({label:"\u{1F9ED} Safari Version",value:a}),n.length>0&&(t+=Gn(n,!1)),t+="</div>",t+=`<div style='${bg} margin-top: 20px;'>`,t+=`<h3 style='${j_}'>User Agent Info</h3>`;const l=[{label:"User Agent",value:navigator.userAgent},{label:"Platform",value:navigator.platform},{label:"App Version",value:navigator.appVersion},{label:"User Agent Data",value:navigator.userAgentData?`Platform: ${navigator.userAgentData.platform}, Mobile: ${navigator.userAgentData.mobile}`:"Not supported"},{label:"WebXR",value:"xr"in navigator?"\u2705":"\u274C"},{label:"WebGPU",value:"gpu"in navigator?"\u2705":"\u274C"},{label:"WebGL 2",value:B_()}];t+=Gn(l,!1),t+="</div>",e(t)}),o}function sk(){if(!globalThis.VConsole)return;const o=new VConsole.VConsolePlugin("graphics-info","\u{1F3A8} Graphics Info");return o.on("renderTab",async function(e){let t=`<div style='${bg}'>`;const i=rk();i.length>0&&(t+=`<h3 style='${kr}'>General GPU Info</h3>`,t+=Gn(i,!1));const n=lk();n.length>0&&(t+=`<h3 style='${kr}'>WebGL</h3>`,t+=Gn(n,!1));const s=ck();s.length>0&&(t+=`<h3 style='${kr}'>WebGL 2 Features</h3>`,t+=Gn(s,!1));const r=hk();r.length>0&&(t+=`<h3 style='${kr}'>WebGL Limits</h3>`,t+=Gn(r,!1));const a=dk();a.length>0&&(t+=`<h3 style='${kr}'>Texture Formats</h3>`,t+=Gn(a,!1));const l=await uk();if(l.length>0&&(t+=`<h3 style='${kr}'>WebGPU</h3>`,t+=Gn(l,!1)),I.isSafari()){const c=pk();c.length>0&&(t+=`<h3 style='${kr}'>Safari GPU Info</h3>`,t+=Gn(c,!1))}t+="</div>",e(t)}),o}function rk(){const o=[],e=window.devicePixelRatio;o.push({label:"Device Pixel Ratio",value:e.toString()}),o.push({label:"Width (px)",value:(window.innerWidth*e).toString()}),o.push({label:"Height (px)",value:(window.innerHeight*e).toString()});const t=I.isMobileDevice()?150:96,i=screen.width/t,n=screen.height/t,s=i*2.54,r=n*2.54;o.push({label:"Estimated Width (cm)",value:s.toFixed(1)}),o.push({label:"Estimated Height (cm)",value:r.toFixed(1)});const a=F_();if(a){o.push({label:"GPU",value:a.renderer}),o.push({label:"Driver",value:a.vendor}),o.push({label:"ANGLE",value:a.angle||"Not detected"});const l=ak(a.renderer);l&&(l.manufacturer&&o.push({label:"Manufacturer",value:l.manufacturer}),l.cardVersion&&o.push({label:"Card Version",value:l.cardVersion}),l.brand&&o.push({label:"Brand",value:l.brand}),o.push({label:"Integrated",value:l.integrated?"Yes":"No"}),l.layer&&o.push({label:"WebGL Layer",value:l.layer}))}return o}function ak(o){if(!o)return null;const e=(l,c)=>{const h=c.match(l);return h&&h[0]},t=e(/(ANGLE)/g,o)||void 0,i=e(/((NVIDIA|AMD|Intel)[^\d]*[^\s]+)/,o)||o,n=i.split(" ");n.shift();const s=e(/(NVIDIA|AMD|Intel)/g,i)||void 0,r=n.length>0?n.pop():void 0,a=n.length>0?n.join(" "):void 0;return{manufacturer:s,cardVersion:r,brand:a,integrated:s==="Intel",layer:t,card:i}}function lk(){const o=[],e=F_();return e&&(o.push({label:"\u{1F4CA} WebGL Version",value:e.version}),o.push({label:"\u{1F3AE} WebGL 2 Available",value:B_()})),o}function ck(){const o=[];try{const e=document.createElement("canvas").getContext("webgl2");if(!e)return o;o.push({label:"Float Color Buffer",value:e.getExtension("EXT_color_buffer_float")?"\u2705":"\u274C"}),o.push({label:"Anisotropic Filtering",value:e.getExtension("EXT_texture_filter_anisotropic")?"\u2705":"\u274C"}),o.push({label:"Float Texture Linear",value:e.getExtension("OES_texture_float_linear")?"\u2705":"\u274C"}),o.push({label:"S3TC Compression",value:e.getExtension("WEBGL_compressed_texture_s3tc")?"\u2705":"\u274C"}),o.push({label:"ETC Compression",value:e.getExtension("WEBGL_compressed_texture_etc")?"\u2705":"\u274C"}),o.push({label:"PVRTC Compression",value:e.getExtension("WEBGL_compressed_texture_pvrtc")?"\u2705":"\u274C"}),o.push({label:"ASTC Compression",value:e.getExtension("WEBGL_compressed_texture_astc")?"\u2705":"\u274C"})}catch{}return o}function hk(){const o=[];try{const e=document.createElement("canvas"),t=e.getContext("webgl2")||e.getContext("webgl");if(!t)return o;const i=t instanceof WebGL2RenderingContext;o.push({label:"\u{1F4CF} Max Texture Size",value:t.getParameter(t.MAX_TEXTURE_SIZE).toString()}),o.push({label:"\u{1F3A8} Max Renderbuffer Size",value:t.getParameter(t.MAX_RENDERBUFFER_SIZE).toString()}),o.push({label:"\u{1F517} Max Vertex Attribs",value:t.getParameter(t.MAX_VERTEX_ATTRIBS).toString()}),o.push({label:"\u{1F3AF} Max Texture Units",value:t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS).toString()}),i&&(o.push({label:"\u26A1 Max Samples",value:t.getParameter(t.MAX_SAMPLES).toString()}),o.push({label:"\u{1F504} Max Uniform Buffer Bindings",value:t.getParameter(t.MAX_UNIFORM_BUFFER_BINDINGS).toString()}),o.push({label:"\u{1F4D0} Max 3D Texture Size",value:t.getParameter(t.MAX_3D_TEXTURE_SIZE).toString()}))}catch{}return o}function dk(){const o=[];try{document.createElement("canvas").getContext("webgl")&&(o.push({label:"WebGL 1 RGBA",value:"\u2705"}),o.push({label:"WebGL 1 RGB",value:"\u2705"}));const e=document.createElement("canvas").getContext("webgl2");e&&(o.push({label:"WebGL 2 RGBA32F",value:e.getExtension("EXT_color_buffer_float")?"\u2705":"\u274C"}),o.push({label:"WebGL 2 RGB32F",value:e.getExtension("EXT_color_buffer_float")?"\u2705":"\u274C"}),o.push({label:"WebGL 2 R11F_G11F_B10F",value:"\u2705"}),o.push({label:"WebGL 2 RGB565",value:"\u2705"}),o.push({label:"WebGL 2 RGB5_A1",value:"\u2705"}),o.push({label:"WebGL 2 RGBA4444",value:"\u2705"}))}catch{}return o}async function uk(){const o=[];if(!("gpu"in navigator))return o.push({label:"\u{1F680} WebGPU Support",value:"\u274C Not supported"}),o;o.push({label:"\u{1F680} WebGPU Support",value:"\u2705 Supported"});try{const e=await navigator.gpu.requestAdapter();if(!e)return o.push({label:"\u{1F3AF} Adapter",value:"No adapter available"}),o;o.push({label:"\u{1F3AF} Adapter",value:e.name||"Unknown Adapter"});const t=await e.requestDevice();o.push({label:"\u{1F527} Device",value:t.label||"WebGPU Device"}),o.push({label:"\u{1F4CF} Max Texture 2D",value:t.limits.maxTextureDimension2D.toString()}),o.push({label:"\u{1F4D0} Max Texture 3D",value:t.limits.maxTextureDimension3D.toString()}),o.push({label:"\u{1F4CA} Max Texture Array Layers",value:t.limits.maxTextureArrayLayers.toString()}),o.push({label:"\u{1F4BE} Max Buffer Size",value:`${(t.limits.maxBufferSize/1024/1024).toFixed(1)}MB`}),o.push({label:"\u{1F517} Max Bind Groups",value:t.limits.maxBindGroups.toString()})}catch(e){o.push({label:"\u274C Error",value:e.message})}return o}function F_(){try{const o=document.createElement("canvas"),e=o.getContext("webgl2")||o.getContext("webgl");if(!e)return null;const t=e.getExtension("WEBGL_debug_renderer_info"),i=t?e.getParameter(t.UNMASKED_RENDERER_WEBGL):e.getParameter(e.RENDERER),n=t?e.getParameter(t.UNMASKED_VENDOR_WEBGL):e.getParameter(e.VENDOR),s=e.getParameter(e.VERSION);let r;if(i&&i.includes("ANGLE")){const a=i.match(/ANGLE \(([^)]+)\)/);a&&(r=a[1])}return{renderer:i,vendor:n,version:s,angle:r}}catch{return null}}function pk(){const o=[];try{const e=document.createElement("canvas").getContext("webgl");if(e){const t=e.getExtension("WEBGL_debug_renderer_info");if(t){const i=e.getParameter(t.UNMASKED_RENDERER_WEBGL);i&&i.includes("Apple")&&o.push({label:"\u{1F34E} Apple GPU",value:i})}}}catch{}try{const e=document.createElement("canvas").getContext("webgl");e&&(e.getSupportedExtensions()||[]).includes("WEBGL_compressed_texture_pvrtc")&&o.push({label:"\u{1F5DC}\uFE0F PVRTC Support",value:"\u2705"})}catch{}return o}function mk(){return I.isQuest()?"Meta Quest":I.isVisionOS()?"Vision Pro":I.isiOS()?I.isiPad()?"iPad":"iPhone/iPod":I.isAndroidDevice()?"Android Device":I.isMozillaXR()?"Mozilla XR Browser":I.isNeedleAppClip()?"Needle App Clip":I.isMacOS()?"Mac":I.isDesktop()?"Desktop PC":"Unknown Device"}function gk(){return document.querySelector("#__vconsole .vc-switch")||null}function fk(){return document.querySelector("#__vconsole")||null}const U_=w("debugdefines");Cs('if(!globalThis["NEEDLE_ENGINE_VERSION"]) globalThis["NEEDLE_ENGINE_VERSION"] = "0.0.0";'),Cs('if(!globalThis["NEEDLE_ENGINE_GENERATOR"]) globalThis["NEEDLE_ENGINE_GENERATOR"] = "unknown";'),Cs('if(!globalThis["NEEDLE_PROJECT_BUILD_TIME"]) globalThis["NEEDLE_PROJECT_BUILD_TIME"] = "unknown";'),Cs('if(!globalThis["NEEDLE_PUBLIC_KEY"]) globalThis["NEEDLE_PUBLIC_KEY"] = "unknown";'),Cs('globalThis["__NEEDLE_ENGINE_VERSION__"] = "4.16.4-alpha.1";'),Cs('globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "undefined";'),Cs('globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "Sun Mar 15 2026 15:44:06 GMT+0000 (Coordinated Universal Time)";'),Cs('globalThis["__NEEDLE_PUBLIC_KEY__"] = "'+NEEDLE_PUBLIC_KEY+'";');const Ti="4.16.4-alpha.1",Wa="undefined",wc="Sun Mar 15 2026 15:44:06 GMT+0000 (Coordinated Universal Time)";U_&&console.log(`Engine version: ${Ti} (generator: ${Wa})
|
|
145
145
|
Project built at ${wc}`);const Ss=NEEDLE_PUBLIC_KEY,Io="needle_isActiveInHierarchy",Mr="builtin_components",xc="needle_editor_guid";function Cs(o){try{(0,eval)(o)}catch(e){U_&&console.error(e)}}let z_,N_=null;function Cn(){return z_}function _g(o){if(o==null){console.warn("Oh no: someone tried registering a non-existend gltf-loader. When you see this log it might mean that needle-engine is being imported multiple times. Please check your project setup.");return}N_!==o&&(N_=o,z_=new o)}function yk(o,e){if(typeof window!==void 0&&window.SPECTOR){console.log(window.SPECTOR);const t=new URLSearchParams(window.location.search);if(t.has("spector")){let i=function(){if(n>o.time.frame)return window.requestAnimationFrame(()=>i());const r=s.captureCanvas(e);r&&r instanceof Promise?r.then(()=>s.displayUI()):s.displayUI()};const n=Number.parseInt(t.get("spector")||"0")||0;console.log("Scheduled Spector capture at frame #"+n);const s=new window.SPECTOR.Spector;s.spyCanvases=!0,i();return}else A()&&console.debug("Spector available: Add '?spector=<frame>' to the URL to enable it and capture a frame.")}}function W_(o){const e=o;return!!(e.parser&&e.parser.json)}var Gd=(o=>(o[o.None=0]="None",o[o.DontExport=1]="DontExport",o))(Gd||{});const V_=Symbol("component-name");function vg(o){return o&&o.isComponent}const bk=Symbol("object"),wg=new Ei(()=>new b,20);class $_{_point;_normal;_tangentVelocity;distance;impulse;friction;get point(){return wg.get().set(this._point.x,this._point.y,this._point.z)}get normal(){return wg.get().set(this._normal.x,this._normal.y,this._normal.z)}get tangentVelocity(){return wg.get().set(this._tangentVelocity.x,this._tangentVelocity.y,this._tangentVelocity.z)}constructor(e,t,i,n,s,r){this._point=e,this.distance=t,this._normal=i,this.impulse=n,this.friction=s,this._tangentVelocity=r}}class H_{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 G_{object;collider;constructor(e,t){this.object=e,this.collider=t}}class Sm{constructor(e){this.context=e,this.root.style.cssText=`
|
|
146
146
|
position: absolute;
|
|
147
147
|
width: 1px; height: 1px;
|
|
@@ -171,9 +171,9 @@ or by using the once option like onStart(()=>{}, { once:true }).
|
|
|
171
171
|
See https://engine.needle.tools/docs/scripting.html#special-lifecycle-hooks for more information.`))}}function Ps(o,e){const t=qa.get(e);if(t){for(let n=0;n<t.length;n++)if(t[n].method===o){t.splice(n,1);return}}const i=Ga.get(e);if(i){for(let n=0;n<i.length;n++)if(i[n].method===o){i.splice(n,1);return}}}function qn(o,e){e===ue.ContextCreated&&kg.delete(o),nv(o,e)}function nv(o,e){e===xe.Start&&Ga.get(ue.ContextCreated)&&nv(o,ue.ContextCreated);const t=e===xe.Start||e===ue.ContextCreated,i=qa.get(e);i&&i.length>0&&sv(o,i,t);const n=Ga.get(e);if(n&&n.length>0){const s=[...n];n.length=0,sv(o,s,t),s.length>0&&(qa.has(e)||qa.set(e,new Array),qa.get(e).push(...s))}}const Kd=new Array,ov={context:null};function sv(o,e,t){Kd.length=0;for(let n=0;n<e.length;n++)Kd.push(e[n]);let i=kg.get(o);for(let n=0;n<Kd.length;n++){const s=Kd[n];let r=!0;if(i&&i.has(s)&&(r=!1),r)try{ov.context=o,s.method?.call(ov,o)}catch(a){console.error("Error in lifecycle method",a)}if(s.options?.once){for(let a=0;a<e.length;a++)if(e[a]===s){e.splice(a,1);break}}else t&&(i||(i=new Set,kg.set(o,i)),i.add(s))}}const kg=new WeakMap,Mg={};function Eg(o,e){Mg[o]=e}function rv(o){const e=o.getBufferIdentifier(),t=Mg[e];return t(o)}function av(o){return typeof o.guid=="function"?o.guid():null}let Rg;function Tk(){return Rg}function Ak(o){Rg=o}function lv(o,e){return e||(e={}),e={...Rg,...e},o?new zb(o,e):new zb(e)}async function cv(){const o=await import("./vendor-DZ45lcA8.min.js").then(e=>e.bundler);return console.log(o),o.default===void 0?o:o.default}class hv{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 cv(),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 Lk(i)})}async trySetupClient(e){const t=await cv();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 Ik{_peer;constructor(e){this._peer=e}}class Lk extends Ik{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 Pn=(o=>(o[o.OnConnection=0]="OnConnection",o[o.OnRoomJoin=1]="OnRoomJoin",o[o.Queued=2]="Queued",o[o.Immediate=3]="Immediate",o))(Pn||{});const dv="https://urls.needle.tools/default-networking-backend/index";let Xi="wss://networking-2.needle.tools/socket";const mi=!!w("debugnet"),Pc=!!(mi||w("debugowner")),Jd=w("debugnetbin");var uv=(o=>(o.ConnectionInfo="connection-start-info",o))(uv||{}),ie=(o=>(o.Join="join-room",o.Leave="leave-room",o.JoinedRoom="joined-room",o.LeftRoom="left-room",o.UserJoinedRoom="user-joined-room",o.UserLeftRoom="user-left-room",o.RoomStateSent="room-state-sent",o))(ie||{});class jk{room;viewId;allowEditing;inRoom}class Dk{room}class Bk{userId}var pv=(o=>(o.RequestHasOwner="request-has-owner",o.ResponseHasOwner="response-has-owner",o.RequestIsOwner="request-is-owner",o.ResponseIsOwner="response-is-owner",o.RequestOwnership="request-ownership",o.GainedOwnership="gained-ownership",o.RemoveOwnership="remove-ownership",o.LostOwnership="lost-ownership",o.GainedOwnershipBroadcast="gained-ownership-broadcast",o.LostOwnershipBroadcast="lost-ownership-broadcast",o))(pv||{});class Tg{guid;connection;get hasOwnership(){return this._hasOwnership}get isOwned(){return this._isOwned}get isConnected(){return this.connection.isConnected}_hasOwnership=!1;_isOwned=void 0;_gainSubscription;_lostSubscription;_hasOwnerResponse;constructor(e,t){this.connection=e,this.guid=t,this._gainSubscription=this.onGainedOwnership.bind(this),this._lostSubscription=this.onLostOwnership.bind(this),e.beginListen("lost-ownership",this._lostSubscription),e.beginListen("gained-ownership-broadcast",this._gainSubscription),this._hasOwnerResponse=this.onHasOwnerResponse.bind(this),e.beginListen("response-has-owner",this._hasOwnerResponse)}_isWaitingForOwnershipResponseCallback=null;updateIsOwned(){this.connection.send("request-has-owner",{guid:this.guid})}onHasOwnerResponse(e){e.guid===this.guid&&(this._isOwned=e.value)}requestOwnershipIfNotOwned(){return this._isWaitingForOwnershipResponseCallback!==null?this:(this._isWaitingForOwnershipResponseCallback=this.waitForHasOwnershipRequestResponse.bind(this),this.connection.beginListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this.connection.send("request-has-owner",{guid:this.guid}),this)}waitForHasOwnershipRequestResponse(e){e.guid===this.guid&&(this._isWaitingForOwnershipResponseCallback&&(this.connection.stopListen("response-has-owner",this._isWaitingForOwnershipResponseCallback),this._isWaitingForOwnershipResponseCallback=null),this._isOwned=e.value,e.value||(Pc&&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 Pc&&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?(Pc&&console.log("GAINED OWNERSHIP",this.guid),this._hasOwnership=!0):this._hasOwnership=!1)}onLostOwnership(e){e===this.guid&&(Pc&&console.log("LOST OWNERSHIP",this.guid),this._hasOwnership=!1,this._isOwned=!1)}}class mv{context;_peer=null;constructor(e){this.context=e}get peer(){return this._peer||(this._peer=new hv),this._peer}tryGetState(e){return e==="invalid"?null:this._state[e]}get connectionId(){return this._connectionId}get isDebugEnabled(){return mi}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(),mi&&console.log("join: "+e),this.send("join-room",{room:e,viewOnly:t},Pn.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=Pn.Queued){if(t===null&&(t={}),i===Pn.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){Jd&&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,Pn.Immediate);break}const s=this.toMessage(n.key,n.value);this._defaultMessagesBufferArray.push(s)}if(this._defaultMessagesBuffer.length=0,this._defaultMessagesBufferArray.length>0&&mi&&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:Qb()&&(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=c=>{i||(i=!0,e(c))};if(Xi===void 0&&(console.log("Fetch default backend url: "+dv),Xi=await(await fetch(dv)).text()),Xi===void 0){n(!1);return}console.debug(`Connecting to networking backend on
|
|
172
172
|
`+Xi);const s=await import("./vendor-DZ45lcA8.min.js").then(c=>c.index),r=s.default?.WebsocketBuilder??s.WebsocketBuilder,a=s.default?.ExponentialBackoff??s.ExponentialBackoff,l=new r(Xi).withMaxRetries(10).withBackoff(new a(2e3,4)).onOpen(()=>{this._connectingToWebsocketPromise=null,this._ws=l,this.connected=!0,A()||mi?console.log(`Connected to networking backend
|
|
173
173
|
`+Xi):console.debug("Connected to networking backend",Xi),n(!0),this.onSendQueued(Pn.OnConnection)}).onClose(c=>{this._connectingToWebsocketPromise=null,this.connected=!1,this._isInRoom=!1,n(!1);let h="Websocket connection closed...";Xi?.includes("/socket")||(h+=' Do you perhaps mean to connect to "/socket"?'),console.error(h)}).onError(c=>{console.error("Websocket connection failed..."),n(!1),gi.sendEvent(this.context,"networking",{event:"connection_error"})}).onRetry(()=>{console.log("Retry connecting to networking websocket")}).build();l.addEventListener(s.WebsocketEvent.message,(c,h)=>{this.onMessage(c,h)})})}onMessage(e,t){const i=t.data;try{if(typeof i!="string"){i.size&&this.handleIncomingBinaryMessage(i);return}const n=JSON.parse(i);if(Array.isArray(n))for(const s of n)this.handleIncomingStringMessage(s);else this.handleIncomingStringMessage(n);return}catch(n){mi&&i==="pong"?console.log("<<",i):A()&&console.error("Failed to parse message",n)}}async handleIncomingBinaryMessage(e){Jd&&console.log("<< bin",this.context.time.frame);const t=await e.arrayBuffer();var i=new Uint8Array(t);const n=new AP(i),s=n.getBufferIdentifier(),r=this._listenersBinary[s],a=rv(n),l=av(a);if(l&&typeof l=="string"&&(this._state[l]=a),!r)return;const c=a??n;for(const h of r)h(c)}handleIncomingStringMessage(e){if(mi&&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,gi.sendEvent(this.context,"networking",{event:"connected"}))}else console.warn("Expected connection id in "+e.key);break;case"joined-room":if(mi&&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),(Jd||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}
|
|
174
|
-
${a.href}`)}this.onSendQueued(Pn.OnRoomJoin),gi.sendEvent(this.context,"networking",{event:"joined_room",room:this._currentRoomName});break;case"left-room":const n=e;n.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentRoomAllowEditing=!0,this._currentInRoom.length=0,(Jd||A())&&console.debug("Left Needle Engine Room: "+n.room)),gi.sendEvent(this.context,"networking",{event:"left_room",room:n.room});break;case"user-joined-room":if(e.data){const r=e.data;this._currentInRoom.push(r.userId),mi&&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&&(mi&&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":mi&&console.log("RECEIVED all-room-state-deleted"),this._state={};break;case"ping":case"pong":const s=e.data?.time;s&&(this._currentDelay=this.context.time.time-s),mi&&console.log(`Current latency: ${(this._currentDelay*1e3).toFixed()} ms`,"Clients in room: "+this._currentInRoom?.length);break}const t=e.data;t&&(this._state[t.guid]=t);let i=this._listeners[e.key];if(i){i=[...i];for(const n of i)try{n(e.data)}catch(s){console.error('Error invoking callback for "'+e.key+'"',s)}}}toMessage(e,t){return{key:e,data:t}}sendWithWebsocket(e,t,i=Pn.OnRoomJoin){if(!this._ws){const s=this._waitingForSocket[i]||[];s.push(()=>this.sendWithWebsocket(e,t,i)),this._waitingForSocket[i]=s;return}const n=JSON.stringify(this.toMessage(e,t));mi&&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 Oc=w("debugwebxr");class Ag{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=>{Oc&&console.log(`XRSync: Received change for ${this.userId}: ${e.type} ${e.handedness}; tracked=${e.isTracking}`);let t=!1;for(let i=0;i<this.controllerStates.length;i++)if(this.controllerStates[i].index===e.index){this.controllerStates[i]=e,t=!0;break}t||this.controllerStates.push(e)};update(e){if(this.context.connection.isConnected!=!1){for(let t=this.controllerStates.length-1;t>=0;t--){const i=this.controllerStates[t];let n=!1;for(let s=0;s<e.controllers.length;s++)e.controllers[s].index===i.index&&(n=!0);n||(Oc&&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),Oc&&console.log(`XRSync: ${i.type} ${i.handedness} added`,i.index)}}}class gv{hasState(e){return e?this._states.has(e):!1}isTracking(e,t){if(!e)return;const i=this._states.get(e);return i?i.controllerStates.find(n=>n.handedness===t)?.isTracking||!1:void 0}getDeviceType(e,t){if(!e)return;const i=this._states.get(e);return i?i.controllerStates.find(n=>n.handedness===t)?.type||"unknown":void 0}context;constructor(e){this.context=e,this.context.connection.beginListen(ie.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(ie.LeftRoom,this.onLeftRoom),this.context.connection.beginListen(ie.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.beginListen(ie.UserLeftRoom,this.onOtherUserLeftRoom)}destroy(){this.context.connection.stopListen(ie.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(ie.LeftRoom,this.onLeftRoom),this.context.connection.stopListen(ie.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.stopListen(ie.UserLeftRoom,this.onOtherUserLeftRoom)}onJoinedRoom=()=>{if(this.context.connection.connectionId){this._states.has(this.context.connection.connectionId)||(Oc&&console.log("XRSync: Local user joined room",this.context.connection.connectionId),this._states.set(this.context.connection.connectionId,new Ag(this.context.connection.connectionId,this.context)));for(const e of this.context.connection.usersInRoom())this._states.has(e)||this._states.set(e,new Ag(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)||(Oc&&console.log("XRSync: Remote user joined room",t),this._states.set(t,new Ag(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 fv{_fadeToColorQuad;_fadeToColorMaterial;constructor(){this._fadeToColorMaterial=new Ce({color:0,transparent:!0,depthTest:!1,fog:!1,side:Oi}),this._fadeToColorQuad=new H(new vn(10,10),this._fadeToColorMaterial)}dispose(){this._fadeToColorQuad.geometry.dispose(),this._fadeToColorMaterial.dispose()}update(e,t){const i=this._fadeToColorQuad,n=this._fadeToColorMaterial;i.parent!==e&&n.opacity>0?e.add(i):n.opacity===0&&i.removeFromParent(),i.layers.set(2),i.material=this._fadeToColorMaterial,i.position.z=-1,i.renderOrder=1/0;const s=this._requestedFadeValue;n.opacity=D.lerp(n.opacity,s,t/.03),Math.abs(n.opacity-s)<=.01&&this._transitionResolve&&(this._transitionResolve(),this._transitionResolve=null,this._transitionPromise=null,this._requestedFadeValue=0)}remove(){this._fadeToColorQuad.removeFromParent()}fadeTransition(){if(this._transitionPromise)return this._transitionPromise;this._requestedFadeValue=1;const e=new Promise(t=>{this._transitionResolve=t});return this._transitionPromise=e,e}_requestedFadeValue=0;_transitionPromise=null;_transitionResolve=null}const Fk='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 160 187.74"><defs><linearGradient id="a" x1="89.64" y1="184.81" x2="90.48" y2="21.85" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#62d399"/><stop offset=".51" stop-color="#acd842"/><stop offset=".9" stop-color="#d7db0a"/></linearGradient><linearGradient id="b" x1="69.68" y1="178.9" x2="68.08" y2="16.77" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#0ba398"/><stop offset=".5" stop-color="#4ca352"/><stop offset="1" stop-color="#76a30a"/></linearGradient><linearGradient id="c" x1="36.6" y1="152.17" x2="34.7" y2="84.19" gradientUnits="userSpaceOnUse"><stop offset=".19" stop-color="#36a382"/><stop offset=".54" stop-color="#49a459"/><stop offset="1" stop-color="#76a30b"/></linearGradient><linearGradient id="d" x1="15.82" y1="153.24" x2="18" y2="90.86" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#267880"/><stop offset=".51" stop-color="#457a5c"/><stop offset="1" stop-color="#717516"/></linearGradient><linearGradient id="e" x1="135.08" y1="135.43" x2="148.93" y2="63.47" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#b0d939"/><stop offset="1" stop-color="#eadb04"/></linearGradient><linearGradient id="f" x1="-4163.25" y1="2285.12" x2="-4160.81" y2="2215.34" gradientTransform="rotate(20 4088.49 13316.712)" gradientUnits="userSpaceOnUse"><stop offset=".17" stop-color="#74af52"/><stop offset=".48" stop-color="#99be32"/><stop offset="1" stop-color="#c0c40a"/></linearGradient><symbol id="g" viewBox="0 0 160 187.74"><path style="fill:url(#a)" d="M79.32 36.98v150.76L95 174.54l6.59-156.31-22.27 18.75z"/><path style="fill:url(#b)" d="M79.32 36.98 57.05 18.23l6.59 156.31 15.68 13.2V36.98z"/><path style="fill:url(#c)" d="m25.19 104.83 8.63 49.04 12.5-14.95-2.46-56.42-18.67 22.33z"/><path style="fill:url(#d)" d="M25.19 104.83 0 90.24l16.97 53.86 16.85 9.77-8.63-49.04z"/><path style="fill:#9c3" d="M43.86 82.5 18.69 67.98 0 90.24l25.18 14.59L43.86 82.5z"/><path style="fill:url(#e)" d="m134.82 78.69-9.97 56.5 15.58-9.04L160 64.1l-25.18 14.59z"/><path style="fill:url(#f)" d="m134.82 78.69-18.68-22.33-2.86 65 11.57 13.83 9.97-56.5z"/><path style="fill:#ffe113" d="m160 64.1-18.69-22.26-25.17 14.52 18.67 22.33L160 64.1z"/><path style="fill:#f3e600" d="M101.59 18.23 79.32 0 57.05 18.23l22.27 18.75 22.27-18.75z"/></symbol></defs><use width="160" height="187.74" xlink:href="#g"/></svg>',Uk=btoa(Fk),zk="data:image/svg+xml;base64,"+Uk,Xa=zk,Nk=`<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'> <svg clip-rule="evenodd" fill-rule="evenodd" stroke-linejoin="round" stroke-miterlimit="2" version="1.1" viewBox="0 0 1014 282" xml:space="preserve" xmlns="http://www.w3.org/2000/svg"> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m665.95 132.73v44.88l-10.56-8.4c-0.8-0.64-1.2-1.44-1.2-2.4v-32.4c0-6.48-4.12-9.72-12.36-9.72-2.16 0-4.18 0.4-6.06 1.2s-3.54 1.8-4.98 3-2.56 2.5-3.36 3.9-1.2 2.7-1.2 3.9v40.92l-10.68-8.4c-0.72-0.64-1.08-1.44-1.08-2.4v-53.76l10.92 8.52c0.32 0.24 0.56 0.44 0.72 0.6s0.36 0.32 0.6 0.48c0.96-1.2 2.14-2.28 3.54-3.24s2.92-1.76 4.56-2.4 3.34-1.14 5.1-1.5 3.44-0.54 5.04-0.54c1.44 0 2.92 0.04 4.44 0.12s2.84 0.28 3.96 0.6c4.56 1.12 7.8 3.12 9.72 6s2.88 6.56 2.88 11.04z" fill-rule="nonzero"/> </g> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m732.38 146.05c0 0.88 0.02 1.5 0.06 1.86s-0.02 0.98-0.18 1.86h-7.08c-2.08 0-4.44-0.02-7.08-0.06s-5.36-0.06-8.16-0.06h-22.08c0 2.88 0.56 5.36 1.68 7.44s2.6 3.8 4.44 5.16 3.94 2.36 6.3 3 4.74 0.96 7.14 0.96c3.04 0 5.9-0.76 8.58-2.28s4.94-3.52 6.78-6c0.64 0.56 1.54 1.48 2.7 2.76s2.94 3.2 5.34 5.76c-2.8 3.36-6.22 6.02-10.26 7.98s-8.42 2.94-13.14 2.94-8.92-0.64-12.84-1.92-7.32-3.24-10.2-5.88-5.12-5.98-6.72-10.02-2.4-8.82-2.4-14.34c0-4.96 0.66-9.42 1.98-13.38s3.22-7.32 5.7-10.08 5.44-4.9 8.88-6.42 7.32-2.28 11.64-2.28c5.76 0 10.52 0.88 14.28 2.64s6.72 4.16 8.88 7.2 3.66 6.54 4.5 10.5 1.26 8.18 1.26 12.66zm-29.4-22.8c-2.16 0.16-4.16 0.72-6 1.68s-3.42 2.2-4.74 3.72-2.36 3.28-3.12 5.28-1.14 4.12-1.14 6.36h33.12c0-2-0.22-4.06-0.66-6.18s-1.3-4.02-2.58-5.7-3.1-3.02-5.46-4.02-5.5-1.38-9.42-1.14z" fill-rule="nonzero"/> </g> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m795.93 146.05c0 0.88 0.02 1.5 0.06 1.86s-0.02 0.98-0.18 1.86h-7.08c-2.08 0-4.44-0.02-7.08-0.06s-5.36-0.06-8.16-0.06h-22.08c0 2.88 0.56 5.36 1.68 7.44s2.6 3.8 4.44 5.16 3.94 2.36 6.3 3 4.74 0.96 7.14 0.96c3.04 0 5.9-0.76 8.58-2.28s4.94-3.52 6.78-6c0.64 0.56 1.54 1.48 2.7 2.76s2.94 3.2 5.34 5.76c-2.8 3.36-6.22 6.02-10.26 7.98s-8.42 2.94-13.14 2.94-8.92-0.64-12.84-1.92-7.32-3.24-10.2-5.88-5.12-5.98-6.72-10.02-2.4-8.82-2.4-14.34c0-4.96 0.66-9.42 1.98-13.38s3.22-7.32 5.7-10.08 5.44-4.9 8.88-6.42 7.32-2.28 11.64-2.28c5.76 0 10.52 0.88 14.28 2.64s6.72 4.16 8.88 7.2 3.66 6.54 4.5 10.5 1.26 8.18 1.26 12.66zm-29.4-22.8c-2.16 0.16-4.16 0.72-6 1.68s-3.42 2.2-4.74 3.72-2.36 3.28-3.12 5.28-1.14 4.12-1.14 6.36h33.12c0-2-0.22-4.06-0.66-6.18s-1.3-4.02-2.58-5.7-3.1-3.02-5.46-4.02-5.5-1.38-9.42-1.14z" fill-rule="nonzero"/> </g> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m858.57 97.21c0.64 0.48 0.96 1.16 0.96 2.04v74.88c-0.08 1.04-0.12 2.12-0.12 3.24-1.84-1.52-3.56-2.92-5.16-4.2-1.36-1.12-2.66-2.18-3.9-3.18s-2.06-1.66-2.46-1.98c-1.76 2.48-4.26 4.44-7.5 5.88s-7.02 2.16-11.34 2.16c-3.84 0-7.4-0.7-10.68-2.1s-6.14-3.44-8.58-6.12-4.34-5.94-5.7-9.78-2.04-8.16-2.04-12.96c0-4.32 0.78-8.34 2.34-12.06s3.6-6.92 6.12-9.6 5.38-4.78 8.58-6.3 6.48-2.28 9.84-2.28c2.56 0 4.82 0.22 6.78 0.66s3.68 1.06 5.16 1.86 2.78 1.74 3.9 2.82 2.16 2.22 3.12 3.42v-35.04l10.68 8.64zm-27.96 67.92c3.6 0 6.52-0.68 8.76-2.04s3.98-3.06 5.22-5.1 2.1-4.22 2.58-6.54 0.72-4.44 0.72-6.36v-1.2c0-1.12-0.22-2.7-0.66-4.74s-1.28-4.06-2.52-6.06-3-3.7-5.28-5.1-5.22-2.02-8.82-1.86c-3.44 0-6.26 0.74-8.46 2.22s-3.96 3.26-5.28 5.34-2.24 4.2-2.76 6.36-0.78 3.92-0.78 5.28c0 1.84 0.24 3.92 0.72 6.24s1.36 4.48 2.64 6.48 3.04 3.68 5.28 5.04 5.12 2.04 8.64 2.04z" fill-rule="nonzero"/> </g> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m882.81 97.09c0.64 0.48 0.96 1.12 0.96 1.92l-0.12 41.04v37.08l-10.56-8.4c-0.72-0.64-1.08-1.44-1.08-2.4v-77.88l10.8 8.64z" fill-rule="nonzero"/> </g> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m950.36 146.05c0 0.88 0.02 1.5 0.06 1.86s-0.02 0.98-0.18 1.86h-7.08c-2.08 0-4.44-0.02-7.08-0.06s-5.36-0.06-8.16-0.06h-22.08c0 2.88 0.56 5.36 1.68 7.44s2.6 3.8 4.44 5.16 3.94 2.36 6.3 3 4.74 0.96 7.14 0.96c3.04 0 5.9-0.76 8.58-2.28s4.94-3.52 6.78-6c0.64 0.56 1.54 1.48 2.7 2.76s2.94 3.2 5.34 5.76c-2.8 3.36-6.22 6.02-10.26 7.98s-8.42 2.94-13.14 2.94-8.92-0.64-12.84-1.92-7.32-3.24-10.2-5.88-5.12-5.98-6.72-10.02-2.4-8.82-2.4-14.34c0-4.96 0.66-9.42 1.98-13.38s3.22-7.32 5.7-10.08 5.44-4.9 8.88-6.42 7.32-2.28 11.64-2.28c5.76 0 10.52 0.88 14.28 2.64s6.72 4.16 8.88 7.2 3.66 6.54 4.5 10.5 1.26 8.18 1.26 12.66zm-29.4-22.8c-2.16 0.16-4.16 0.72-6 1.68s-3.42 2.2-4.74 3.72-2.36 3.28-3.12 5.28-1.14 4.12-1.14 6.36h33.12c0-2-0.22-4.06-0.66-6.18s-1.3-4.02-2.58-5.7-3.1-3.02-5.46-4.02-5.5-1.38-9.42-1.14z" fill-rule="nonzero"/> </g> <g transform="matrix(1.8559 0 0 .7642 45.348 36.475)"> <g transform="translate(2.7114)"> <path d="m3.935 173.02c-0.331 0-0.497-0.402-0.497-1.207v-51.002c0-0.738 0.138-1.107 0.414-1.107h1.781c0.277 0 0.415 0.335 0.415 1.006v5.935c0 0.336 0.027 0.553 0.083 0.654 0.055 0.101 0.151-0.017 0.289-0.352 0.912-1.744 1.754-3.236 2.527-4.477 0.773-1.24 1.554-2.179 2.341-2.816s1.65-0.956 2.588-0.956c1.685 0 3.011 0.922 3.977 2.766 0.967 1.845 1.602 3.84 1.905 5.986 0.056 0.268 0.139 0.369 0.249 0.302s0.221-0.235 0.331-0.503c0.939-1.811 1.802-3.353 2.589-4.628 0.787-1.274 1.581-2.246 2.382-2.917s1.671-1.006 2.61-1.006c2.016 0 3.569 1.392 4.66 4.175 1.09 2.783 1.636 6.421 1.636 10.915v37.925c0 0.871-0.18 1.307-0.539 1.307h-1.739c-0.138 0-0.249-0.1-0.332-0.301-0.083-0.202-0.124-0.503-0.124-0.906v-36.315c0-3.555-0.338-6.321-1.015-8.3-0.676-1.978-1.76-2.967-3.251-2.967-0.884 0-1.726 0.386-2.527 1.157s-1.519 1.727-2.154 2.867-1.201 2.213-1.699 3.219c-0.248 0.469-0.421 0.905-0.517 1.308-0.097 0.402-0.145 0.972-0.145 1.71v37.221c0 0.871-0.166 1.307-0.497 1.307h-1.74c-0.166 0-0.29-0.1-0.373-0.301-0.083-0.202-0.124-0.503-0.124-0.906v-36.315c0-3.555-0.332-6.321-0.994-8.3-0.663-1.978-1.754-2.967-3.273-2.967-1.242 0-2.375 0.704-3.396 2.112-1.022 1.409-2.223 3.555-3.604 6.439v39.031c0 0.805-0.18 1.207-0.539 1.207h-1.698z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m53.642 166.28c-1.077 2.549-2.237 4.477-3.479 5.785-1.243 1.307-2.61 1.961-4.101 1.961-2.154 0-3.853-1.324-5.095-3.973-1.243-2.649-1.864-6.187-1.864-10.613 0-3.488 0.4-6.489 1.201-9.004s1.988-4.51 3.562-5.985c1.574-1.476 3.521-2.414 5.841-2.817l3.686-0.704c0.221-0.067 0.394-0.218 0.518-0.453 0.124-0.234 0.187-0.587 0.187-1.056v-2.917c0-3.89-0.504-6.975-1.512-9.255s-2.354-3.42-4.039-3.42c-1.298 0-2.472 0.72-3.521 2.162s-2.002 3.572-2.858 6.388c-0.083 0.268-0.159 0.453-0.228 0.554-0.069 0.1-0.172 0.083-0.311-0.051l-1.698-1.71c-0.083-0.134-0.138-0.285-0.166-0.453-0.027-0.167 0.014-0.452 0.125-0.855 0.856-3.353 2.009-6.052 3.459-8.098 1.449-2.045 3.224-3.068 5.322-3.068 1.74 0 3.211 0.687 4.412 2.062s2.112 3.37 2.734 5.986c0.621 2.615 0.932 5.7 0.932 9.255v35.712c0 0.536-0.035 0.888-0.104 1.056s-0.2 0.251-0.393 0.251h-1.533c-0.166 0-0.29-0.117-0.373-0.352-0.083-0.234-0.124-0.553-0.124-0.955l-0.083-5.231c-0.055-0.939-0.221-1.006-0.497-0.202zm0.456-19.314c0-1.14-0.194-1.643-0.58-1.509l-3.107 0.603c-1.436 0.202-2.686 0.638-3.749 1.308-1.063 0.671-1.953 1.543-2.671 2.616s-1.257 2.33-1.616 3.772-0.538 3.102-0.538 4.98c0 3.152 0.455 5.616 1.367 7.393 0.911 1.778 2.14 2.666 3.686 2.666 0.939 0 1.85-0.419 2.734-1.257s1.671-1.895 2.361-3.169c0.663-1.408 1.181-2.85 1.553-4.326 0.373-1.475 0.56-2.883 0.56-4.225v-8.852z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m79.034 173.02c-0.166 0-0.297-0.117-0.394-0.352-0.096-0.234-0.145-0.553-0.145-0.955v-4.628c0-0.536-0.041-0.838-0.124-0.905s-0.207 0.1-0.373 0.503c-0.276 0.67-0.69 1.593-1.242 2.766-0.553 1.174-1.271 2.23-2.154 3.169-0.884 0.939-1.961 1.408-3.231 1.408-1.74 0-3.314-0.989-4.722-2.967-1.409-1.979-2.534-4.963-3.376-8.953-0.843-3.991-1.264-8.937-1.264-14.838 0-5.701 0.415-10.68 1.243-14.939s1.988-7.595 3.479-10.009c1.492-2.415 3.204-3.622 5.137-3.622 1.436 0 2.616 0.57 3.541 1.71 0.926 1.14 1.719 2.381 2.382 3.722 0.249 0.47 0.414 0.637 0.497 0.503s0.125-0.536 0.125-1.207v-23.841c0-0.805 0.151-1.208 0.455-1.208h1.864c0.276 0 0.414 0.369 0.414 1.107v72.128c0 0.537-0.041 0.905-0.124 1.107-0.083 0.201-0.235 0.301-0.455 0.301h-1.533zm-0.621-42.049c-0.939-2.213-1.885-3.94-2.838-5.181s-2.009-1.861-3.169-1.861c-1.463 0-2.768 0.889-3.914 2.666s-2.044 4.376-2.693 7.796-0.973 7.578-0.973 12.474c0 5.097 0.338 9.272 1.015 12.524 0.676 3.253 1.567 5.651 2.672 7.193 1.104 1.543 2.305 2.314 3.603 2.314 1.188 0 2.258-0.704 3.211-2.113 0.952-1.408 1.705-3.118 2.257-5.13s0.829-3.957 0.829-5.835v-24.847z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m89.514 149.38c0 3.42 0.345 6.606 1.035 9.557 0.691 2.951 1.609 5.315 2.755 7.092s2.437 2.666 3.873 2.666c1.519 0 2.837-0.738 3.956-2.213 1.118-1.476 2.064-3.655 2.837-6.539 0.083-0.336 0.166-0.52 0.249-0.554 0.083-0.033 0.179 0.017 0.29 0.151l1.408 1.912c0.221 0.268 0.235 0.67 0.041 1.207-0.69 2.548-1.47 4.661-2.34 6.337-0.87 1.677-1.857 2.935-2.962 3.773-1.104 0.838-2.319 1.257-3.645 1.257-2.043 0-3.838-1.14-5.385-3.42-1.546-2.28-2.761-5.482-3.645-9.607-0.884-4.124-1.325-8.836-1.325-14.134 0-5.901 0.455-10.931 1.367-15.089 0.911-4.158 2.14-7.377 3.686-9.658 1.547-2.28 3.3-3.42 5.261-3.42 1.988 0 3.714 1.073 5.178 3.219 1.463 2.146 2.595 5.231 3.396 9.255s1.201 8.886 1.201 14.587c0 0.469-0.02 0.939-0.062 1.408-0.041 0.469-0.214 0.704-0.517 0.704h-16.362c-0.083 0-0.152 0.151-0.207 0.453-0.056 0.302-0.083 0.654-0.083 1.056zm13.752-6.237c0.304 0 0.497-0.1 0.58-0.302 0.083-0.201 0.124-0.57 0.124-1.106 0-3.219-0.283-6.187-0.849-8.903s-1.367-4.896-2.402-6.539c-1.036-1.643-2.272-2.464-3.708-2.464-1.629 0-2.996 0.955-4.101 2.867-1.104 1.911-1.94 4.342-2.506 7.293s-0.849 6.002-0.849 9.154h13.711z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m148.54 119.7c0.165 0 0.283 0.117 0.352 0.352s0.076 0.52 0.02 0.855l-6.254 50.902c-0.028 0.47-0.104 0.788-0.228 0.956s-0.297 0.251-0.518 0.251h-1.615c-0.442 0-0.718-0.402-0.829-1.207l-5.26-40.138c-0.111-0.604-0.201-0.905-0.27-0.905s-0.131 0.301-0.186 0.905l-5.012 40.138c-0.028 0.47-0.097 0.788-0.207 0.956-0.111 0.168-0.277 0.251-0.497 0.251h-1.74c-0.442 0-0.718-0.402-0.829-1.207l-6.503-50.801c-0.055-0.403-0.048-0.721 0.021-0.956s0.2-0.352 0.393-0.352h1.823c0.166 0 0.297 0.067 0.393 0.201 0.097 0.134 0.159 0.403 0.187 0.805l5.302 41.848c0.083 0.671 0.179 0.989 0.29 0.956 0.11-0.034 0.207-0.386 0.29-1.056l5.219-41.949c0.055-0.268 0.124-0.47 0.207-0.604s0.193-0.201 0.331-0.201h1.533c0.138 0 0.262 0.067 0.373 0.201 0.11 0.134 0.179 0.403 0.207 0.805l5.468 41.848c0.083 0.671 0.179 0.989 0.29 0.956 0.11-0.034 0.207-0.386 0.29-1.056l5.053-41.849c0.055-0.335 0.138-0.57 0.249-0.704 0.11-0.134 0.234-0.201 0.373-0.201h1.284z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m156.49 171.51c0 0.604-0.042 1.006-0.125 1.208-0.082 0.201-0.262 0.301-0.538 0.301h-1.533c-0.221 0-0.366-0.083-0.435-0.251s-0.103-0.486-0.103-0.956v-50.902c0-0.805 0.152-1.207 0.456-1.207h1.822c0.304 0 0.456 0.402 0.456 1.207v50.6zm0.165-63.979c0 1.207-0.207 1.811-0.621 1.811h-1.905c-0.221 0-0.366-0.135-0.435-0.403s-0.104-0.67-0.104-1.207v-7.847c0-1.006 0.18-1.509 0.539-1.509h1.988c0.359 0 0.538 0.47 0.538 1.409v7.746z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m168.3 124.83c-0.221 0-0.331 0.269-0.331 0.805v33.801c0 3.42 0.221 5.667 0.663 6.74 0.441 1.073 1.09 1.609 1.946 1.609h3.024c0.138 0 0.242 0.084 0.311 0.252 0.069 0.167 0.103 0.419 0.103 0.754v2.716c0 0.537-0.138 0.906-0.414 1.107-0.248 0.067-0.614 0.134-1.098 0.201-0.483 0.067-0.959 0.118-1.429 0.151-0.469 0.034-0.828 0.05-1.077 0.05-1.712 0-2.934-0.955-3.665-2.867-0.732-1.911-1.098-5.013-1.098-9.305v-35.108c0-0.604-0.124-0.906-0.373-0.906h-3.521c-0.248 0-0.373-0.268-0.373-0.804v-3.521c0-0.537 0.111-0.805 0.332-0.805h3.686c0.166 0 0.263-0.268 0.29-0.805l0.415-16.095c0-0.805 0.124-1.207 0.372-1.207h1.492c0.303 0 0.455 0.436 0.455 1.307v15.995c0 0.537 0.097 0.805 0.29 0.805h5.468c0.221 0 0.331 0.268 0.331 0.805v3.521c0 0.536-0.124 0.804-0.373 0.804h-5.426z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m179.4 173.02c-0.331 0-0.497-0.402-0.497-1.207v-72.329c0-0.738 0.138-1.107 0.414-1.107h1.782c0.276 0 0.414 0.336 0.414 1.006v27.162c0 0.335 0.034 0.536 0.103 0.603s0.159-0.033 0.27-0.302c0.994-1.81 1.898-3.319 2.713-4.526 0.814-1.208 1.629-2.113 2.444-2.717 0.814-0.603 1.691-0.905 2.63-0.905 2.182 0 3.839 1.375 4.971 4.125 1.132 2.749 1.698 6.404 1.698 10.965v37.925c0 0.871-0.166 1.307-0.497 1.307h-1.74c-0.165 0-0.29-0.1-0.373-0.301-0.082-0.202-0.124-0.503-0.124-0.906v-36.315c0-3.555-0.366-6.321-1.097-8.3-0.732-1.978-1.899-2.967-3.501-2.967-0.883 0-1.705 0.318-2.464 0.956-0.76 0.637-1.526 1.576-2.299 2.816-0.773 1.241-1.643 2.834-2.61 4.779v39.031c0 0.805-0.179 1.207-0.538 1.207h-1.699z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> </g> <g transform="matrix(.80638 0 0 .80638 452.53 65.421)" fill-rule="nonzero"> <path d="m79.32 36.98v150.76l15.68-13.2 6.59-156.31-22.27 18.75z" fill="url(#f)"/> <path d="m79.32 36.98-22.27-18.75 6.59 156.31 15.68 13.2v-150.76z" fill="url(#e)"/> <path d="m25.19 104.83 8.63 49.04 12.5-14.95-2.46-56.42-18.67 22.33z" fill="url(#d)"/> <path d="m25.19 104.83-25.19-14.59 16.97 53.86 16.85 9.77-8.63-49.04z" fill="url(#c)"/> <path d="M43.86,82.5L18.69,67.98L0,90.24L25.18,104.83L43.86,82.5Z" fill="#9c3"/> <path d="m134.82 78.69-9.97 56.5 15.58-9.04 19.57-62.05-25.18 14.59z" fill="url(#b)"/> <path d="m134.82 78.69-18.68-22.33-2.86 65 11.57 13.83 9.97-56.5z" fill="url(#a)"/> <path d="m160 64.1-18.69-22.26-25.17 14.52 18.67 22.33 25.19-14.59z" fill="#ffe113"/> <path d="M101.59,18.23L79.32,0L57.05,18.23L79.32,36.98L101.59,18.23Z" fill="#f3e600"/> </g> <defs> <linearGradient id="f" x2="1" gradientTransform="matrix(.84 -162.96 162.96 .84 89.64 184.81)" gradientUnits="userSpaceOnUse"><stop stop-color="#62d399" offset="0"/><stop stop-color="#acd842" offset=".51"/><stop stop-color="#d7db0a" offset=".9"/><stop stop-color="#d7db0a" offset="1"/></linearGradient> <linearGradient id="e" x2="1" gradientTransform="matrix(-1.6,-162.13,162.13,-1.6,69.68,178.9)" gradientUnits="userSpaceOnUse"><stop stop-color="#0ba398" offset="0"/><stop stop-color="#4ca352" offset=".5"/><stop stop-color="#76a30a" offset="1"/></linearGradient> <linearGradient id="d" x2="1" gradientTransform="matrix(-1.9,-67.98,67.98,-1.9,36.6,152.17)" gradientUnits="userSpaceOnUse"><stop stop-color="#36a382" offset="0"/><stop stop-color="#36a382" offset=".19"/><stop stop-color="#49a459" offset=".54"/><stop stop-color="#76a30b" offset="1"/></linearGradient> <linearGradient id="c" x2="1" gradientTransform="matrix(2.18,-62.38,62.38,2.18,15.82,153.24)" gradientUnits="userSpaceOnUse"><stop stop-color="#267880" offset="0"/><stop stop-color="#457a5c" offset=".51"/><stop stop-color="#717516" offset="1"/></linearGradient> <linearGradient id="b" x2="1" gradientTransform="matrix(13.85,-71.96,71.96,13.85,135.08,135.43)" gradientUnits="userSpaceOnUse"><stop stop-color="#b0d939" offset="0"/><stop stop-color="#eadb04" offset="1"/></linearGradient> <linearGradient id="a" x2="1" gradientTransform="matrix(26.159 -64.737 64.737 26.159 107.42 128.14)" gradientUnits="userSpaceOnUse"><stop stop-color="#74af52" offset="0"/><stop stop-color="#74af52" offset=".17"/><stop stop-color="#99be32" offset=".48"/><stop stop-color="#c0c40a" offset="1"/></linearGradient> </defs> </svg>`;btoa(Nk);const Wk='<svg viewBox="0 0 509 154" xmlns="http://www.w3.org/2000/svg" xml:space="preserve" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2"><path d="M665.95 132.73v44.88l-10.56-8.4c-.8-.64-1.2-1.44-1.2-2.4v-32.4c0-6.48-4.12-9.72-12.36-9.72-2.16 0-4.18.4-6.06 1.2-1.88.8-3.54 1.8-4.98 3-1.44 1.2-2.56 2.5-3.36 3.9-.8 1.4-1.2 2.7-1.2 3.9v40.92l-10.68-8.4c-.72-.64-1.08-1.44-1.08-2.4v-53.76l10.92 8.52c.32.24.56.44.72.6.16.16.36.32.6.48.96-1.2 2.14-2.28 3.54-3.24 1.4-.96 2.92-1.76 4.56-2.4 1.64-.64 3.34-1.14 5.1-1.5 1.76-.36 3.44-.54 5.04-.54 1.44 0 2.92.04 4.44.12 1.52.08 2.84.28 3.96.6 4.56 1.12 7.8 3.12 9.72 6 1.92 2.88 2.88 6.56 2.88 11.04ZM732.38 146.05c0 .88.02 1.5.06 1.86.04.36-.02.98-.18 1.86h-7.08c-2.08 0-4.44-.02-7.08-.06-2.64-.04-5.36-.06-8.16-.06h-22.08c0 2.88.56 5.36 1.68 7.44 1.12 2.08 2.6 3.8 4.44 5.16 1.84 1.36 3.94 2.36 6.3 3 2.36.64 4.74.96 7.14.96 3.04 0 5.9-.76 8.58-2.28 2.68-1.52 4.94-3.52 6.78-6 .64.56 1.54 1.48 2.7 2.76 1.16 1.28 2.94 3.2 5.34 5.76-2.8 3.36-6.22 6.02-10.26 7.98-4.04 1.96-8.42 2.94-13.14 2.94-4.72 0-8.92-.64-12.84-1.92-3.92-1.28-7.32-3.24-10.2-5.88-2.88-2.64-5.12-5.98-6.72-10.02-1.6-4.04-2.4-8.82-2.4-14.34 0-4.96.66-9.42 1.98-13.38 1.32-3.96 3.22-7.32 5.7-10.08s5.44-4.9 8.88-6.42c3.44-1.52 7.32-2.28 11.64-2.28 5.76 0 10.52.88 14.28 2.64 3.76 1.76 6.72 4.16 8.88 7.2 2.16 3.04 3.66 6.54 4.5 10.5.84 3.96 1.26 8.18 1.26 12.66Zm-29.4-22.8c-2.16.16-4.16.72-6 1.68-1.84.96-3.42 2.2-4.74 3.72-1.32 1.52-2.36 3.28-3.12 5.28-.76 2-1.14 4.12-1.14 6.36h33.12c0-2-.22-4.06-.66-6.18-.44-2.12-1.3-4.02-2.58-5.7-1.28-1.68-3.1-3.02-5.46-4.02-2.36-1-5.5-1.38-9.42-1.14ZM795.93 146.05c0 .88.02 1.5.06 1.86.04.36-.02.98-.18 1.86h-7.08c-2.08 0-4.44-.02-7.08-.06-2.64-.04-5.36-.06-8.16-.06h-22.08c0 2.88.56 5.36 1.68 7.44 1.12 2.08 2.6 3.8 4.44 5.16 1.84 1.36 3.94 2.36 6.3 3 2.36.64 4.74.96 7.14.96 3.04 0 5.9-.76 8.58-2.28 2.68-1.52 4.94-3.52 6.78-6 .64.56 1.54 1.48 2.7 2.76 1.16 1.28 2.94 3.2 5.34 5.76-2.8 3.36-6.22 6.02-10.26 7.98-4.04 1.96-8.42 2.94-13.14 2.94-4.72 0-8.92-.64-12.84-1.92-3.92-1.28-7.32-3.24-10.2-5.88-2.88-2.64-5.12-5.98-6.72-10.02-1.6-4.04-2.4-8.82-2.4-14.34 0-4.96.66-9.42 1.98-13.38 1.32-3.96 3.22-7.32 5.7-10.08s5.44-4.9 8.88-6.42c3.44-1.52 7.32-2.28 11.64-2.28 5.76 0 10.52.88 14.28 2.64 3.76 1.76 6.72 4.16 8.88 7.2 2.16 3.04 3.66 6.54 4.5 10.5.84 3.96 1.26 8.18 1.26 12.66Zm-29.4-22.8c-2.16.16-4.16.72-6 1.68-1.84.96-3.42 2.2-4.74 3.72-1.32 1.52-2.36 3.28-3.12 5.28-.76 2-1.14 4.12-1.14 6.36h33.12c0-2-.22-4.06-.66-6.18-.44-2.12-1.3-4.02-2.58-5.7-1.28-1.68-3.1-3.02-5.46-4.02-2.36-1-5.5-1.38-9.42-1.14ZM858.57 97.21c.64.48.96 1.16.96 2.04v74.88c-.08 1.04-.12 2.12-.12 3.24-1.84-1.52-3.56-2.92-5.16-4.2-1.36-1.12-2.66-2.18-3.9-3.18-1.24-1-2.06-1.66-2.46-1.98-1.76 2.48-4.26 4.44-7.5 5.88-3.24 1.44-7.02 2.16-11.34 2.16-3.84 0-7.4-.7-10.68-2.1-3.28-1.4-6.14-3.44-8.58-6.12-2.44-2.68-4.34-5.94-5.7-9.78-1.36-3.84-2.04-8.16-2.04-12.96 0-4.32.78-8.34 2.34-12.06 1.56-3.72 3.6-6.92 6.12-9.6 2.52-2.68 5.38-4.78 8.58-6.3 3.2-1.52 6.48-2.28 9.84-2.28 2.56 0 4.82.22 6.78.66 1.96.44 3.68 1.06 5.16 1.86s2.78 1.74 3.9 2.82a35.92 35.92 0 0 1 3.12 3.42V88.57l10.68 8.64Zm-27.96 67.92c3.6 0 6.52-.68 8.76-2.04 2.24-1.36 3.98-3.06 5.22-5.1a20.5 20.5 0 0 0 2.58-6.54c.48-2.32.72-4.44.72-6.36v-1.2c0-1.12-.22-2.7-.66-4.74-.44-2.04-1.28-4.06-2.52-6.06s-3-3.7-5.28-5.1c-2.28-1.4-5.22-2.02-8.82-1.86-3.44 0-6.26.74-8.46 2.22-2.2 1.48-3.96 3.26-5.28 5.34-1.32 2.08-2.24 4.2-2.76 6.36-.52 2.16-.78 3.92-.78 5.28 0 1.84.24 3.92.72 6.24.48 2.32 1.36 4.48 2.64 6.48s3.04 3.68 5.28 5.04c2.24 1.36 5.12 2.04 8.64 2.04ZM882.81 97.09c.64.48.96 1.12.96 1.92l-.12 41.04v37.08l-10.56-8.4c-.72-.64-1.08-1.44-1.08-2.4V88.45l10.8 8.64ZM950.36 146.05c0 .88.02 1.5.06 1.86.04.36-.02.98-.18 1.86h-7.08c-2.08 0-4.44-.02-7.08-.06-2.64-.04-5.36-.06-8.16-.06h-22.08c0 2.88.56 5.36 1.68 7.44 1.12 2.08 2.6 3.8 4.44 5.16 1.84 1.36 3.94 2.36 6.3 3 2.36.64 4.74.96 7.14.96 3.04 0 5.9-.76 8.58-2.28 2.68-1.52 4.94-3.52 6.78-6 .64.56 1.54 1.48 2.7 2.76 1.16 1.28 2.94 3.2 5.34 5.76-2.8 3.36-6.22 6.02-10.26 7.98-4.04 1.96-8.42 2.94-13.14 2.94-4.72 0-8.92-.64-12.84-1.92-3.92-1.28-7.32-3.24-10.2-5.88-2.88-2.64-5.12-5.98-6.72-10.02-1.6-4.04-2.4-8.82-2.4-14.34 0-4.96.66-9.42 1.98-13.38 1.32-3.96 3.22-7.32 5.7-10.08s5.44-4.9 8.88-6.42c3.44-1.52 7.32-2.28 11.64-2.28 5.76 0 10.52.88 14.28 2.64 3.76 1.76 6.72 4.16 8.88 7.2 2.16 3.04 3.66 6.54 4.5 10.5.84 3.96 1.26 8.18 1.26 12.66Zm-29.4-22.8c-2.16.16-4.16.72-6 1.68-1.84.96-3.42 2.2-4.74 3.72-1.32 1.52-2.36 3.28-3.12 5.28-.76 2-1.14 4.12-1.14 6.36h33.12c0-2-.22-4.06-.66-6.18-.44-2.12-1.3-4.02-2.58-5.7-1.28-1.68-3.1-3.02-5.46-4.02-2.36-1-5.5-1.38-9.42-1.14Z" style="fill-rule:nonzero" transform="translate(-452.406 -63.709) scale(1.00797)"/><path d="M79.32 36.98v150.76L95 174.54l6.59-156.31-22.27 18.75Z" style="fill:url(#a);fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="M79.32 36.98 57.05 18.23l6.59 156.31 15.68 13.2V36.98Z" style="fill:url(#b);fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="m25.19 104.83 8.63 49.04 12.5-14.95-2.46-56.42-18.67 22.33Z" style="fill:url(#c);fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="M25.19 104.83 0 90.24l16.97 53.86 16.85 9.77-8.63-49.04Z" style="fill:url(#d);fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="M43.86 82.5 18.69 67.98 0 90.24l25.18 14.59L43.86 82.5Z" style="fill:#9c3;fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="m134.82 78.69-9.97 56.5 15.58-9.04L160 64.1l-25.18 14.59Z" style="fill:url(#e);fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="m134.82 78.69-18.68-22.33-2.86 65 11.57 13.83 9.97-56.5Z" style="fill:url(#f);fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="m160 64.1-18.69-22.26-25.17 14.52 18.67 22.33L160 64.1Z" style="fill:#ffe113;fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="M101.59 18.23 79.32 0 57.05 18.23l22.27 18.75 22.27-18.75Z" style="fill:#f3e600;fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><defs><linearGradient id="a" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="matrix(.84 -162.96 162.96 .84 89.64 184.81)"><stop offset="0" style="stop-color:#62d399;stop-opacity:1"/><stop offset=".51" style="stop-color:#acd842;stop-opacity:1"/><stop offset=".9" style="stop-color:#d7db0a;stop-opacity:1"/><stop offset="1" style="stop-color:#d7db0a;stop-opacity:1"/></linearGradient><linearGradient id="b" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="rotate(-90.565 123.412 54.953) scale(162.14)"><stop offset="0" style="stop-color:#0ba398;stop-opacity:1"/><stop offset=".5" style="stop-color:#4ca352;stop-opacity:1"/><stop offset="1" style="stop-color:#76a30a;stop-opacity:1"/></linearGradient><linearGradient id="c" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="scale(-68) rotate(88.4 .881 -1.396)"><stop offset="0" style="stop-color:#36a382;stop-opacity:1"/><stop offset=".19" style="stop-color:#36a382;stop-opacity:1"/><stop offset=".54" style="stop-color:#49a459;stop-opacity:1"/><stop offset="1" style="stop-color:#76a30b;stop-opacity:1"/></linearGradient><linearGradient id="d" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="rotate(-88 87.255 68.431) scale(62.42)"><stop offset="0" style="stop-color:#267880;stop-opacity:1"/><stop offset=".51" style="stop-color:#457a5c;stop-opacity:1"/><stop offset="1" style="stop-color:#717516;stop-opacity:1"/></linearGradient><linearGradient id="e" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="rotate(-79.1 149.53 -14.065) scale(73.28)"><stop offset="0" style="stop-color:#b0d939;stop-opacity:1"/><stop offset="1" style="stop-color:#eadb04;stop-opacity:1"/></linearGradient><linearGradient id="f" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="rotate(-67.997 148.705 -15.558) scale(69.8226)"><stop offset="0" style="stop-color:#74af52;stop-opacity:1"/><stop offset=".17" style="stop-color:#74af52;stop-opacity:1"/><stop offset=".48" style="stop-color:#99be32;stop-opacity:1"/><stop offset="1" style="stop-color:#c0c40a;stop-opacity:1"/></linearGradient></defs></svg>',Vk=btoa(Wk),$k="data:image/svg+xml;charset=utf-8;base64,"+Vk,yv=$k;var Qa=(o=>(o[o.Quad=0]="Quad",o[o.Cube=1]="Cube",o[o.Sphere=2]="Sphere",o[o.Cylinder=3]="Cylinder",o[o.RoundedCube=10]="RoundedCube",o))(Qa||{});class Os{static createText(e,t){let i=null;const n=t?.font||Gk(t?.familyFamily||null);n instanceof dP?i=this.#t(e,n,t):i==null&&(i=new wn);const s=t?.color||16777215,r=new H(i,t?.material??new gt({color:s}));return this.applyDefaultObjectOptions(r,t),n instanceof Promise?n.then(a=>{r.geometry=this.#t(e,a,t),t?.onGeometry&&t.onGeometry(r)}):t?.onGeometry&&t.onGeometry(r),r}static#t(e,t,i){const n=i?.depth||.1;return new uP(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 Ce({colorWrite:!1,depthWrite:!0,side:Oi});return this.createPrimitive(e,{material:t})}static createPrimitive(e,t){let i;const n=t?.color||16777215;switch(e){case"Quad":case 0:{const s=new vn(1,1,1,1),r=t?.material??new gt({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new H(s,r),i.name="Quad"}break;case"Cube":case 1:{const s=new Aa(1,1,1),r=t?.material??new gt({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new H(s,r),i.name="Cube"}break;case 10:case"RoundedCube":{const s=Hk(1,1,1,.1,2),r=t?.material??new gt({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new H(s,r),i.name="RoundedCube"}break;case"Sphere":case 2:{const s=new Pd(.5,16,16),r=t?.material??new gt({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new H(s,r),i.name="Sphere"}break;case"Cylinder":case 3:{const s=new bb(.5,.5,1,32),r=t?.material??new gt({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new H(s,r),i.name="Cylinder"}break;case"ShaderBall":i=new Po,i.name="ShaderBall",qk(i,t);break}return this.applyDefaultObjectOptions(i,t),i}static createSprite(e){const t=new qS({color:16777215});e?.texture&&"map"in t&&(t.map=e.texture);const i=new XS(t);return this.applyDefaultObjectOptions(i,e),i}static applyDefaultObjectOptions(e,t){e.receiveShadow=!0,e.castShadow=!0,t?.name&&(e.name=t.name),t?.position&&(Array.isArray(t.position)?e.position.set(t.position[0],t.position[1],t.position[2]):e.position.set(t.position.x||0,t.position.y||0,t.position.z||0)),t?.rotation&&(Array.isArray(t.rotation)?e.rotation.set(t.rotation[0],t.rotation[1],t.rotation[2]):e.rotation.set(t.rotation.x||0,t.rotation.y||0,t.rotation.z||0)),t?.scale&&(typeof t.scale=="number"?e.scale.set(t.scale,t.scale,t.scale):Array.isArray(t.scale)?e.scale.set(t.scale[0],t.scale[1],t.scale[2]):e.scale.set(t.scale.x||1,t.scale.y||1,t.scale.z||1)),t?.receiveShadow!=null&&(e.receiveShadow=t.receiveShadow),t?.castShadow!=null&&(e.castShadow=t.castShadow),t?.parent&&t.parent.add(e)}}function Hk(o,e,t,i,n){const s=new QS,r=1e-5,a=i-r;s.absarc(r,r,r,-Math.PI/2,-Math.PI,!0),s.absarc(r,e-a*2,r,Math.PI,Math.PI/2,!0),s.absarc(o-a*2,e-a*2,r,Math.PI/2,0,!0),s.absarc(o-a*2,r,r,0,-Math.PI/2,!0);const l=new YS(s,{bevelEnabled:!0,bevelSegments:n*2,steps:1,bevelSize:a,bevelThickness:i,curveSegments:n,UVGenerator:{generateTopUV:(c,h)=>{const d=[];for(let p=0;p<h.length;p+=3)d.push(new K(h[p]/o,h[p+1]/e));return d},generateSideWallUV:(c,h,d,p,m,g)=>{const f=[];return f.push(new K(h[d]/o,h[d+1]/e)),f.push(new K(h[p]/o,h[p+1]/e)),f.push(new K(h[m]/o,h[m+1]/e)),f.push(new K(h[g]/o,h[g+1]/e)),f}}});return l.scale(1,1,1-i),l.center(),l.index||l.setIndex(Array.from({length:l.attributes.position.count},(c,h)=>h)),l.computeVertexNormals(),l}const eu=new Map;function Gk(o){let e="";switch(o){default:case"OpenSans":e="https://cdn.needle.tools/static/fonts/facetype/Open Sans_Regular_ascii.json";break;case"Helvetiker":e="https://cdn.needle.tools/static/fonts/facetype/Helvetiker_Regular_ascii.json";break}if(eu.has(e)){const n=eu.get(e);if(n)return n}const t=new pP,i=new Promise((n,s)=>{t.load(e,r=>{eu.set(e,r),n(r)},void 0,s)});return eu.set(e,i),i}let Ig=!1,Lg=null;function qk(o,e){if(Lg===null){const t="https://cdn.needle.tools/static/models/shaderball.glb",i=new Eo,n=Um(null);i.setDRACOLoader(n.dracoLoader),i.setKTX2Loader(n.ktx2Loader),Ig=!0,Lg=i.loadAsync(t).then(s=>{const r=s.scene;return r.position.y-=.5,r}).catch(s=>(console.warn("Failed to load shaderball mesh: "+s.message),_v())).finally(()=>{Ig=!1})}if(Ig){const t=_v();t.name="ShaderBall-Placeholder";const i=t.children[0];i?.type==="Mesh"&&bv(i,e),o.add(t)}Lg.then(t=>{o.children.forEach(s=>{s.name==="ShaderBall-Placeholder"&&o.remove(s)});const i=t.clone(),n=i.children[0];n?.type==="Mesh"&&(n.geometry.attributes.tangent||n.geometry.computeTangents(),bv(n,e)),o.add(i)})}function bv(o,e){if(e?.color||e?.material||e?.texture){const t=e?.material??o.material?.clone()??new gt;e.color&&"color"in t&&t.color instanceof oe&&t.color.set(e.color),e?.texture&&"map"in t&&(t.map=e.texture),o.material=t}}function _v(){return new Po().add(Os.createPrimitive("Sphere",{material:new Ce({transparent:!0,opacity:.1})}))}class nc{static _active=null;static get active(){return this._active}static _requestInFlight=!1;static async start(e,t){if(this._active)return console.error("Cannot start a new XR session while one is already active"),null;if(this._requestInFlight)return console.error("Cannot start a new XR session while a request is already in flight"),null;if("xr"in navigator&&navigator.xr){if(!t)return console.error("XRSessionInit must be provided"),null;this._requestInFlight=!0;const i=await navigator.xr.requestSession(e,t).catch(n=>{console.error("Failed to start temporary XR session:",n)});return i?(i.addEventListener("end",()=>{this._active=null}),this._requestInFlight?(this._requestInFlight=!1,this._active=new nc(e,t,i),this._active):(i.end(),null)):(this._requestInFlight=!1,null)}return null}static async handoff(){return this._active?this._active.handoff():null}static async stop(){this._requestInFlight=!1,this._active&&(await this._active.end(),await To(100)),this._active=null}_session;_mode;_init;get isAR(){return this._mode==="immersive-ar"}get isVR(){return this._mode==="immersive-vr"}_renderer;_camera;_scene;constructor(e,t,i){this._mode=e,this._init=t,this._session=i,this._session.addEventListener("end",this.onEnd),this._renderer=new yr({alpha:!0,antialias:!0}),this._renderer.outputColorSpace="srgb",this._renderer.setPixelRatio(Math.min(2,window.devicePixelRatio)),this._renderer.setSize(window.innerWidth,window.innerHeight,!0),I.isNeedleAppClip()&&window.requestAnimationFrame(()=>{const n=Math.min(2,window.devicePixelRatio),s=Math.floor(window.innerWidth*n),r=Math.floor(window.innerHeight*n);this._renderer.domElement.width=s,this._renderer.domElement.height=r}),this._renderer.setAnimationLoop(this.onFrame),this._renderer.xr.setSession(i),this._renderer.xr.enabled=!0,this._camera=new de,this._scene=new Hi,this._scene.fog=new _b(4473924,10,250),this._scene.add(this._camera),this.setupScene()}end(){return this._session?this._session.end():Promise.resolve()}async handoff(){if(!this._session)throw new Error("Cannot handoff a session that has already ended");const e={session:this._session,mode:this._mode,init:this._init};return await this.onBeforeHandoff(),this.onEnd(),this._session=null,e}onEnd=()=>{this._session?.removeEventListener("end",this.onEnd),this._renderer.setAnimationLoop(null),this._renderer.dispose(),this._scene.clear()};_lastTime=0;_frames=0;onFrame=(e,t)=>{const i=e-this._lastTime;this.update(e,i),this._camera.parent!==this._scene&&this._scene.add(this._camera),this._renderer.render(this._scene,this._camera),this._lastTime=e,this._frames++};_roomFlyObjects=[];_logoObject=null;get _logoDistance(){return this.isAR?.3:5}get _logoScale(){return this.isAR?.04:1}update(e,t){const i=e*4e-4;for(let r=0;r<this._roomFlyObjects.length;r++){const a=this._roomFlyObjects[r];a.position.y+=Math.sin(i+r*.5)*.005,a.rotateY(.002)}const n=this._logoObject,s=this._renderer.xr.getCamera();if(n){const r=new b;s.getWorldDirection(r);const a=s.position.clone().addScaledVector(r,this._logoDistance),l=this.isAR?.005:1e-5;n.position.lerp(a,this._frames<=2?1:t*l),n.lookAt(this._camera.position)}}async onBeforeHandoff(){await To(1e3),this._scene.clear()}setupScene(){this._scene.background=new oe(0);let e=Xa;if(Kn()){const h=document.querySelector("needle-engine");if(h){const d=h.getAttribute("logo-src");d?.length&&(e=d,A()&&console.debug("[XR] Using custom loading logo from license:",e))}}const t=this._logoObject=new H(new vn(1,1,1,1),new Ce({transparent:!0,side:2}));t.scale.multiplyScalar(this._logoScale*window.devicePixelRatio),t.renderOrder=1e3,t.material.opacity=0,this._scene.add(t);const i=document.createElement("canvas"),n=i.getContext("2d"),s=new Image,r=h=>{if(!n)return;t.material.opacity=1;const d=1024;i.width=d,i.height=d,n.imageSmoothingQuality="high";const p=d*.19,m=s.width/s.height;{const P=i.height-p*1.5,k=P*m,O=(i.width-k)/2;n.drawImage(s,O,0,k,P)}const g=d*.12,f="Loading...";n.shadowBlur=0,n.fillStyle=this.isAR?"white":"rgba(255,255,255,0.4)",n.font=`${g}px Arial`,n.shadowBlur=d*.02,n.shadowColor="rgba(0,0,0,0.5)",n.shadowOffsetX=0,n.shadowOffsetY=0;const y=n.measureText(f);n.fillText(f,i.width/2-y.width/2,i.height-p/4),n.font=`${g}px Arial`,n.fillText(f,i.width/2-y.width/2,i.height-p/4);const _=new br().load(i.toDataURL());_.generateMipmaps=!0,_.colorSpace="srgb",_.anisotropy=4;const v=i.width/i.height;t.scale.x=this._logoScale*v*window.devicePixelRatio,t.scale.y=this._logoScale*window.devicePixelRatio,t.material.map=_,t.material.needsUpdate=!0};s.onload=()=>r(),s.onerror=h=>{console.error("Failed to load temporary XR logo:",e,h),s.src=Xa},s.crossOrigin="anonymous",s.src=e;const a=new km(16777215,1);a.position.set(0,20,0),a.castShadow=!1,this._scene.add(a);const l=new km(16777215,1);l.position.set(0,-1,0),l.castShadow=!1,this._scene.add(l);const c=new Mm(16777215,1,100,1);if(c.position.set(0,2,0),c.castShadow=!1,c.distance=200,this._scene.add(c),this.isAR===!1)for(let h=0;h<100;h++){const d=new gt({color:2236962,metalness:1,roughness:.8}),p=Qa.Sphere,m=Os.createPrimitive(p,{material:d});m.position.x=D.random(-50,50),m.position.y=D.random(-2,50),m.position.z=D.random(-50,50),m.rotation.x=D.random(0,Math.PI*2),m.rotation.y=D.random(0,Math.PI*2),m.rotation.z=D.random(0,Math.PI*2),m.scale.multiplyScalar(.5+Math.random()*10);const g=m.position.distanceTo(this._camera.position)-m.scale.x;g<10&&(m.position.z+=5,m.position.multiplyScalar(1+1/g)),this._roomFlyObjects.push(m),this._scene.add(m)}}}var kc;(o=>{const e=[];function t(){e?.length||A()&&console.warn("No USDZ exporters found \u2013 cannot export USDZ for QuickLook.");for(const s of e)s.exportAndOpen();return!0}o.exportAndOpen=t;function i(s){e.push(s)}o.registerExporter=i;function n(s){if(!e)return;const r=e.indexOf(s);r>=0&&e.splice(r,1)}o.unregisterExporter=n})(kc||(kc={}));const Xe=w("debugwebxr"),vv=w("stats");let jg=0;function Xk(o){let e=null;const t=o;return t.getAROverlayContainer?e=t.getAROverlayContainer():e=o,e}Qk();async function Qk(){let o="immersive-vr";try{if(I.isNeedleAppClip()?o="immersive-ar":await navigator.xr?.isSessionSupported("immersive-vr")||(o="immersive-ar"),!await navigator.xr?.isSessionSupported("immersive-ar")&&o==="immersive-ar")return}catch(e){console.debug("[NeedleXRSession:granted] Error while checking XR support:",e);return}if(w("debugasap")){let e=globalThis["needle:XRSession"];if(e instanceof Promise){delete globalThis["needle:XRSession"],pe.addContextCreatedCallback(async t=>{if(!e)return;Na(!0);const i=await e;if(i){const n=Z.getDefaultSessionInit(o);Z.setSession(o,i,n,t.context)}else console.error("[NeedleXRSession:granted] ASAP session was rejected");e=void 0});return}}if("xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent)){console.warn("WebXRViewer does not support addEventListener");return}navigator.xr?.addEventListener("sessiongranted",async()=>{const e=sessionStorage.getItem("needle_xr_session_mode"),t=sessionStorage.getItem("needle_xr_session_init")??null,i=t?JSON.parse(t):null;let n=null;if(wv()&&(await nc.start(e||o,i||Z.getDefaultSessionInit(o)).catch(s=>console.warn("[NeedleXRSession:granted] TemporaryXRContext start failed:",s)),await Kk(),n=await nc.handoff()),n)Z.setSession(n.mode,n.session,n.init,U.Current);else if(e&&t){console.log("[NeedleXRSession:granted] Restore last session");const s=JSON.parse(t);Z.start(e,s).catch(r=>console.warn(r))}else Z.start(o).catch(s=>console.warn("[NeedleXRSession:granted] failed:",s))},{once:!0})}}function Yk(o,e){sessionStorage.setItem("needle_xr_session_mode",o),sessionStorage.setItem("needle_xr_session_init",JSON.stringify(e))}function Zk(){sessionStorage.removeItem("needle_xr_session_mode"),sessionStorage.removeItem("needle_xr_session_init")}const Dg=new Set;pe.registerCallback(ue.ContextCreationStart,async o=>{Dg.add(o.context)}),pe.registerCallback(ue.ContextCreated,async o=>{Dg.delete(o.context);const e=o.context?.domElement.getAttribute("autostart")||null;Jk(e)});function wv(){return Dg.size>0}function Kk(){return new Promise(o=>{const e=Date.now(),t=setInterval(()=>{(!wv()||Date.now()-e>6e4)&&(clearInterval(t),o())},100)})}I.isDesktop()&&A()&&window.addEventListener("keydown",o=>{(o.key==="x"||o.key==="Escape")&&Z.active&&Z.stop()});function Jk(o){o&&o?.toLowerCase()==="ar"&&Nn.registerWaitForInteraction(()=>{Z.start("ar")})}const tu=Symbol("initial-fov"),Bg=Symbol("initial-near");class Z{static _sync=null;static getXRSync(e){return this._sync||(this._sync=new gv(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=>(Xe&&console.error(t),!1))??Promise.resolve(!1)}static _currentSessionRequest;static _activeSession;static onSessionRequestStart(e){this._sessionRequestStartListeners.push(e)}static offSessionRequestStart(e){const t=this._sessionRequestStartListeners.indexOf(e);t>=0&&this._sessionRequestStartListeners.splice(t,1)}static _sessionRequestStartListeners=[];static onSessionRequestEnd(e){this._sessionRequestEndListeners.push(e)}static offSessionRequestEnd(e){const t=this._sessionRequestEndListeners.indexOf(e);t>=0&&this._sessionRequestEndListeners.splice(t,1)}static _sessionRequestEndListeners=[];static onXRSessionStart(e){this._xrStartListeners.push(e)}static offXRSessionStart(e){const t=this._xrStartListeners.indexOf(e);t>=0&&this._xrStartListeners.splice(t,1)}static _xrStartListeners=[];static onXRSessionEnd(e){this._xrEndListeners.push(e)}static offXRSessionEnd(e){const t=this._xrEndListeners.indexOf(e);t>=0&&this._xrEndListeners.splice(t,1)}static _xrEndListeners=[];static onControllerAdded(e){this._controllerAddedListeners.push(e)}static offControllerAdded(e){const t=this._controllerAddedListeners.indexOf(e);t>=0&&this._controllerAddedListeners.splice(t,1)}static _controllerAddedListeners=[];static onControllerRemoved(e){this._controllerRemovedListeners.push(e)}static offControllerRemoved(e){const t=this._controllerRemovedListeners.indexOf(e);t>=0&&this._controllerRemovedListeners.splice(t,1)}static _controllerRemovedListeners=[];static offerSession(e,t,i){return"xr"in navigator&&navigator.xr&&"offerSession"in navigator.xr?(typeof navigator.xr.offerSession=="function"&&(console.log("WebXR offerSession is available - requesting mode: "+e),t=="default"&&(t=this.getDefaultSessionInit(e)),navigator.xr.offerSession(e,{...t}).then(n=>Z.setSession(e,n,t,i)).catch(n=>{console.log("XRSession offer rejected (perhaps because another call to offerSession was made or a call to requestSession was made)")})),!0):!1}static getDefaultSessionInit(e){switch(e){case"immersive-ar":const t=["anchors","local-floor","layers","dom-overlay","hit-test","unbounded"];return I.isVisionOS()||t.push("hand-tracking"),{optionalFeatures:t};case"immersive-vr":const i=["local-floor","bounded-floor","high-fixed-foveation-level","layers"];return I.isVisionOS()||i.push("hand-tracking"),{optionalFeatures:i};default:return console.warn("No default session init for mode",e),{}}}static async start(e,t,i){if(t||(t={}),I.isiOS()){const r=await this.isARSupported().catch(()=>!1);if(I.isVisionOS()&&!r&&(e==="ar"||e==="immersive-ar")&&(e="quicklook"),e==="quicklook")return gi.sendEvent(U.Current,"xr",{action:"quicklook_export",source:"NeedleXRSession.start"}),kc.exportAndOpen(),null;if(!r&&(e==="immersive-ar"||e==="ar")){this.invokeSessionRequestStart("immersive-ar",t);const a=new URL("https://appclip.apple.com/id?p=tools.needle.launch-app.Clip");a.searchParams.set("url",location.href);const l=a.toString();gi.sendEvent(U.Current,"xr",{action:"app_clip_launch",source:"NeedleXRSession.start",url:l});const c=window.top||window;try{console.debug("iOS device detected - opening Needle App Clip for AR experience",{mode:e,init:t,url:a}),c.location.href=l}catch(h){console.warn("Error navigating to AppClip "+l+`
|
|
174
|
+
${a.href}`)}this.onSendQueued(Pn.OnRoomJoin),gi.sendEvent(this.context,"networking",{event:"joined_room",room:this._currentRoomName});break;case"left-room":const n=e;n.room===this.currentRoomName&&(this._isInRoom=!1,this._currentRoomName=null,this._currentRoomAllowEditing=!0,this._currentInRoom.length=0,(Jd||A())&&console.debug("Left Needle Engine Room: "+n.room)),gi.sendEvent(this.context,"networking",{event:"left_room",room:n.room});break;case"user-joined-room":if(e.data){const r=e.data;this._currentInRoom.push(r.userId),mi&&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&&(mi&&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":mi&&console.log("RECEIVED all-room-state-deleted"),this._state={};break;case"ping":case"pong":const s=e.data?.time;s&&(this._currentDelay=this.context.time.time-s),mi&&console.log(`Current latency: ${(this._currentDelay*1e3).toFixed()} ms`,"Clients in room: "+this._currentInRoom?.length);break}const t=e.data;t&&(this._state[t.guid]=t);let i=this._listeners[e.key];if(i){i=[...i];for(const n of i)try{n(e.data)}catch(s){console.error('Error invoking callback for "'+e.key+'"',s)}}}toMessage(e,t){return{key:e,data:t}}sendWithWebsocket(e,t,i=Pn.OnRoomJoin){if(!this._ws){const s=this._waitingForSocket[i]||[];s.push(()=>this.sendWithWebsocket(e,t,i)),this._waitingForSocket[i]=s;return}const n=JSON.stringify(this.toMessage(e,t));mi&&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 Oc=w("debugwebxr");class Ag{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=>{Oc&&console.log(`XRSync: Received change for ${this.userId}: ${e.type} ${e.handedness}; tracked=${e.isTracking}`);let t=!1;for(let i=0;i<this.controllerStates.length;i++)if(this.controllerStates[i].index===e.index){this.controllerStates[i]=e,t=!0;break}t||this.controllerStates.push(e)};update(e){if(this.context.connection.isConnected!=!1){for(let t=this.controllerStates.length-1;t>=0;t--){const i=this.controllerStates[t];let n=!1;for(let s=0;s<e.controllers.length;s++)e.controllers[s].index===i.index&&(n=!0);n||(Oc&&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),Oc&&console.log(`XRSync: ${i.type} ${i.handedness} added`,i.index)}}}class gv{hasState(e){return e?this._states.has(e):!1}isTracking(e,t){if(!e)return;const i=this._states.get(e);return i?i.controllerStates.find(n=>n.handedness===t)?.isTracking||!1:void 0}getDeviceType(e,t){if(!e)return;const i=this._states.get(e);return i?i.controllerStates.find(n=>n.handedness===t)?.type||"unknown":void 0}context;constructor(e){this.context=e,this.context.connection.beginListen(ie.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(ie.LeftRoom,this.onLeftRoom),this.context.connection.beginListen(ie.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.beginListen(ie.UserLeftRoom,this.onOtherUserLeftRoom)}destroy(){this.context.connection.stopListen(ie.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(ie.LeftRoom,this.onLeftRoom),this.context.connection.stopListen(ie.UserJoinedRoom,this.onOtherUserJoinedRoom),this.context.connection.stopListen(ie.UserLeftRoom,this.onOtherUserLeftRoom)}onJoinedRoom=()=>{if(this.context.connection.connectionId){this._states.has(this.context.connection.connectionId)||(Oc&&console.log("XRSync: Local user joined room",this.context.connection.connectionId),this._states.set(this.context.connection.connectionId,new Ag(this.context.connection.connectionId,this.context)));for(const e of this.context.connection.usersInRoom())this._states.has(e)||this._states.set(e,new Ag(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)||(Oc&&console.log("XRSync: Remote user joined room",t),this._states.set(t,new Ag(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 fv{_fadeToColorQuad;_fadeToColorMaterial;constructor(){this._fadeToColorMaterial=new Ce({color:0,transparent:!0,depthTest:!1,fog:!1,side:Oi}),this._fadeToColorQuad=new H(new vn(10,10),this._fadeToColorMaterial)}dispose(){this._fadeToColorQuad.geometry.dispose(),this._fadeToColorMaterial.dispose()}update(e,t){const i=this._fadeToColorQuad,n=this._fadeToColorMaterial;i.parent!==e&&n.opacity>0?e.add(i):n.opacity===0&&i.removeFromParent(),i.layers.set(2),i.material=this._fadeToColorMaterial,i.position.z=-1,i.renderOrder=1/0;const s=this._requestedFadeValue;n.opacity=j.lerp(n.opacity,s,t/.03),Math.abs(n.opacity-s)<=.01&&this._transitionResolve&&(this._transitionResolve(),this._transitionResolve=null,this._transitionPromise=null,this._requestedFadeValue=0)}remove(){this._fadeToColorQuad.removeFromParent()}fadeTransition(){if(this._transitionPromise)return this._transitionPromise;this._requestedFadeValue=1;const e=new Promise(t=>{this._transitionResolve=t});return this._transitionPromise=e,e}_requestedFadeValue=0;_transitionPromise=null;_transitionResolve=null}const Fk='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 160 187.74"><defs><linearGradient id="a" x1="89.64" y1="184.81" x2="90.48" y2="21.85" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#62d399"/><stop offset=".51" stop-color="#acd842"/><stop offset=".9" stop-color="#d7db0a"/></linearGradient><linearGradient id="b" x1="69.68" y1="178.9" x2="68.08" y2="16.77" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#0ba398"/><stop offset=".5" stop-color="#4ca352"/><stop offset="1" stop-color="#76a30a"/></linearGradient><linearGradient id="c" x1="36.6" y1="152.17" x2="34.7" y2="84.19" gradientUnits="userSpaceOnUse"><stop offset=".19" stop-color="#36a382"/><stop offset=".54" stop-color="#49a459"/><stop offset="1" stop-color="#76a30b"/></linearGradient><linearGradient id="d" x1="15.82" y1="153.24" x2="18" y2="90.86" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#267880"/><stop offset=".51" stop-color="#457a5c"/><stop offset="1" stop-color="#717516"/></linearGradient><linearGradient id="e" x1="135.08" y1="135.43" x2="148.93" y2="63.47" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#b0d939"/><stop offset="1" stop-color="#eadb04"/></linearGradient><linearGradient id="f" x1="-4163.25" y1="2285.12" x2="-4160.81" y2="2215.34" gradientTransform="rotate(20 4088.49 13316.712)" gradientUnits="userSpaceOnUse"><stop offset=".17" stop-color="#74af52"/><stop offset=".48" stop-color="#99be32"/><stop offset="1" stop-color="#c0c40a"/></linearGradient><symbol id="g" viewBox="0 0 160 187.74"><path style="fill:url(#a)" d="M79.32 36.98v150.76L95 174.54l6.59-156.31-22.27 18.75z"/><path style="fill:url(#b)" d="M79.32 36.98 57.05 18.23l6.59 156.31 15.68 13.2V36.98z"/><path style="fill:url(#c)" d="m25.19 104.83 8.63 49.04 12.5-14.95-2.46-56.42-18.67 22.33z"/><path style="fill:url(#d)" d="M25.19 104.83 0 90.24l16.97 53.86 16.85 9.77-8.63-49.04z"/><path style="fill:#9c3" d="M43.86 82.5 18.69 67.98 0 90.24l25.18 14.59L43.86 82.5z"/><path style="fill:url(#e)" d="m134.82 78.69-9.97 56.5 15.58-9.04L160 64.1l-25.18 14.59z"/><path style="fill:url(#f)" d="m134.82 78.69-18.68-22.33-2.86 65 11.57 13.83 9.97-56.5z"/><path style="fill:#ffe113" d="m160 64.1-18.69-22.26-25.17 14.52 18.67 22.33L160 64.1z"/><path style="fill:#f3e600" d="M101.59 18.23 79.32 0 57.05 18.23l22.27 18.75 22.27-18.75z"/></symbol></defs><use width="160" height="187.74" xlink:href="#g"/></svg>',Uk=btoa(Fk),zk="data:image/svg+xml;base64,"+Uk,Xa=zk,Nk=`<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'> <svg clip-rule="evenodd" fill-rule="evenodd" stroke-linejoin="round" stroke-miterlimit="2" version="1.1" viewBox="0 0 1014 282" xml:space="preserve" xmlns="http://www.w3.org/2000/svg"> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m665.95 132.73v44.88l-10.56-8.4c-0.8-0.64-1.2-1.44-1.2-2.4v-32.4c0-6.48-4.12-9.72-12.36-9.72-2.16 0-4.18 0.4-6.06 1.2s-3.54 1.8-4.98 3-2.56 2.5-3.36 3.9-1.2 2.7-1.2 3.9v40.92l-10.68-8.4c-0.72-0.64-1.08-1.44-1.08-2.4v-53.76l10.92 8.52c0.32 0.24 0.56 0.44 0.72 0.6s0.36 0.32 0.6 0.48c0.96-1.2 2.14-2.28 3.54-3.24s2.92-1.76 4.56-2.4 3.34-1.14 5.1-1.5 3.44-0.54 5.04-0.54c1.44 0 2.92 0.04 4.44 0.12s2.84 0.28 3.96 0.6c4.56 1.12 7.8 3.12 9.72 6s2.88 6.56 2.88 11.04z" fill-rule="nonzero"/> </g> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m732.38 146.05c0 0.88 0.02 1.5 0.06 1.86s-0.02 0.98-0.18 1.86h-7.08c-2.08 0-4.44-0.02-7.08-0.06s-5.36-0.06-8.16-0.06h-22.08c0 2.88 0.56 5.36 1.68 7.44s2.6 3.8 4.44 5.16 3.94 2.36 6.3 3 4.74 0.96 7.14 0.96c3.04 0 5.9-0.76 8.58-2.28s4.94-3.52 6.78-6c0.64 0.56 1.54 1.48 2.7 2.76s2.94 3.2 5.34 5.76c-2.8 3.36-6.22 6.02-10.26 7.98s-8.42 2.94-13.14 2.94-8.92-0.64-12.84-1.92-7.32-3.24-10.2-5.88-5.12-5.98-6.72-10.02-2.4-8.82-2.4-14.34c0-4.96 0.66-9.42 1.98-13.38s3.22-7.32 5.7-10.08 5.44-4.9 8.88-6.42 7.32-2.28 11.64-2.28c5.76 0 10.52 0.88 14.28 2.64s6.72 4.16 8.88 7.2 3.66 6.54 4.5 10.5 1.26 8.18 1.26 12.66zm-29.4-22.8c-2.16 0.16-4.16 0.72-6 1.68s-3.42 2.2-4.74 3.72-2.36 3.28-3.12 5.28-1.14 4.12-1.14 6.36h33.12c0-2-0.22-4.06-0.66-6.18s-1.3-4.02-2.58-5.7-3.1-3.02-5.46-4.02-5.5-1.38-9.42-1.14z" fill-rule="nonzero"/> </g> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m795.93 146.05c0 0.88 0.02 1.5 0.06 1.86s-0.02 0.98-0.18 1.86h-7.08c-2.08 0-4.44-0.02-7.08-0.06s-5.36-0.06-8.16-0.06h-22.08c0 2.88 0.56 5.36 1.68 7.44s2.6 3.8 4.44 5.16 3.94 2.36 6.3 3 4.74 0.96 7.14 0.96c3.04 0 5.9-0.76 8.58-2.28s4.94-3.52 6.78-6c0.64 0.56 1.54 1.48 2.7 2.76s2.94 3.2 5.34 5.76c-2.8 3.36-6.22 6.02-10.26 7.98s-8.42 2.94-13.14 2.94-8.92-0.64-12.84-1.92-7.32-3.24-10.2-5.88-5.12-5.98-6.72-10.02-2.4-8.82-2.4-14.34c0-4.96 0.66-9.42 1.98-13.38s3.22-7.32 5.7-10.08 5.44-4.9 8.88-6.42 7.32-2.28 11.64-2.28c5.76 0 10.52 0.88 14.28 2.64s6.72 4.16 8.88 7.2 3.66 6.54 4.5 10.5 1.26 8.18 1.26 12.66zm-29.4-22.8c-2.16 0.16-4.16 0.72-6 1.68s-3.42 2.2-4.74 3.72-2.36 3.28-3.12 5.28-1.14 4.12-1.14 6.36h33.12c0-2-0.22-4.06-0.66-6.18s-1.3-4.02-2.58-5.7-3.1-3.02-5.46-4.02-5.5-1.38-9.42-1.14z" fill-rule="nonzero"/> </g> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m858.57 97.21c0.64 0.48 0.96 1.16 0.96 2.04v74.88c-0.08 1.04-0.12 2.12-0.12 3.24-1.84-1.52-3.56-2.92-5.16-4.2-1.36-1.12-2.66-2.18-3.9-3.18s-2.06-1.66-2.46-1.98c-1.76 2.48-4.26 4.44-7.5 5.88s-7.02 2.16-11.34 2.16c-3.84 0-7.4-0.7-10.68-2.1s-6.14-3.44-8.58-6.12-4.34-5.94-5.7-9.78-2.04-8.16-2.04-12.96c0-4.32 0.78-8.34 2.34-12.06s3.6-6.92 6.12-9.6 5.38-4.78 8.58-6.3 6.48-2.28 9.84-2.28c2.56 0 4.82 0.22 6.78 0.66s3.68 1.06 5.16 1.86 2.78 1.74 3.9 2.82 2.16 2.22 3.12 3.42v-35.04l10.68 8.64zm-27.96 67.92c3.6 0 6.52-0.68 8.76-2.04s3.98-3.06 5.22-5.1 2.1-4.22 2.58-6.54 0.72-4.44 0.72-6.36v-1.2c0-1.12-0.22-2.7-0.66-4.74s-1.28-4.06-2.52-6.06-3-3.7-5.28-5.1-5.22-2.02-8.82-1.86c-3.44 0-6.26 0.74-8.46 2.22s-3.96 3.26-5.28 5.34-2.24 4.2-2.76 6.36-0.78 3.92-0.78 5.28c0 1.84 0.24 3.92 0.72 6.24s1.36 4.48 2.64 6.48 3.04 3.68 5.28 5.04 5.12 2.04 8.64 2.04z" fill-rule="nonzero"/> </g> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m882.81 97.09c0.64 0.48 0.96 1.12 0.96 1.92l-0.12 41.04v37.08l-10.56-8.4c-0.72-0.64-1.08-1.44-1.08-2.4v-77.88l10.8 8.64z" fill-rule="nonzero"/> </g> <g transform="matrix(1.008 0 0 1.008 -2.239 .61874)"> <path d="m950.36 146.05c0 0.88 0.02 1.5 0.06 1.86s-0.02 0.98-0.18 1.86h-7.08c-2.08 0-4.44-0.02-7.08-0.06s-5.36-0.06-8.16-0.06h-22.08c0 2.88 0.56 5.36 1.68 7.44s2.6 3.8 4.44 5.16 3.94 2.36 6.3 3 4.74 0.96 7.14 0.96c3.04 0 5.9-0.76 8.58-2.28s4.94-3.52 6.78-6c0.64 0.56 1.54 1.48 2.7 2.76s2.94 3.2 5.34 5.76c-2.8 3.36-6.22 6.02-10.26 7.98s-8.42 2.94-13.14 2.94-8.92-0.64-12.84-1.92-7.32-3.24-10.2-5.88-5.12-5.98-6.72-10.02-2.4-8.82-2.4-14.34c0-4.96 0.66-9.42 1.98-13.38s3.22-7.32 5.7-10.08 5.44-4.9 8.88-6.42 7.32-2.28 11.64-2.28c5.76 0 10.52 0.88 14.28 2.64s6.72 4.16 8.88 7.2 3.66 6.54 4.5 10.5 1.26 8.18 1.26 12.66zm-29.4-22.8c-2.16 0.16-4.16 0.72-6 1.68s-3.42 2.2-4.74 3.72-2.36 3.28-3.12 5.28-1.14 4.12-1.14 6.36h33.12c0-2-0.22-4.06-0.66-6.18s-1.3-4.02-2.58-5.7-3.1-3.02-5.46-4.02-5.5-1.38-9.42-1.14z" fill-rule="nonzero"/> </g> <g transform="matrix(1.8559 0 0 .7642 45.348 36.475)"> <g transform="translate(2.7114)"> <path d="m3.935 173.02c-0.331 0-0.497-0.402-0.497-1.207v-51.002c0-0.738 0.138-1.107 0.414-1.107h1.781c0.277 0 0.415 0.335 0.415 1.006v5.935c0 0.336 0.027 0.553 0.083 0.654 0.055 0.101 0.151-0.017 0.289-0.352 0.912-1.744 1.754-3.236 2.527-4.477 0.773-1.24 1.554-2.179 2.341-2.816s1.65-0.956 2.588-0.956c1.685 0 3.011 0.922 3.977 2.766 0.967 1.845 1.602 3.84 1.905 5.986 0.056 0.268 0.139 0.369 0.249 0.302s0.221-0.235 0.331-0.503c0.939-1.811 1.802-3.353 2.589-4.628 0.787-1.274 1.581-2.246 2.382-2.917s1.671-1.006 2.61-1.006c2.016 0 3.569 1.392 4.66 4.175 1.09 2.783 1.636 6.421 1.636 10.915v37.925c0 0.871-0.18 1.307-0.539 1.307h-1.739c-0.138 0-0.249-0.1-0.332-0.301-0.083-0.202-0.124-0.503-0.124-0.906v-36.315c0-3.555-0.338-6.321-1.015-8.3-0.676-1.978-1.76-2.967-3.251-2.967-0.884 0-1.726 0.386-2.527 1.157s-1.519 1.727-2.154 2.867-1.201 2.213-1.699 3.219c-0.248 0.469-0.421 0.905-0.517 1.308-0.097 0.402-0.145 0.972-0.145 1.71v37.221c0 0.871-0.166 1.307-0.497 1.307h-1.74c-0.166 0-0.29-0.1-0.373-0.301-0.083-0.202-0.124-0.503-0.124-0.906v-36.315c0-3.555-0.332-6.321-0.994-8.3-0.663-1.978-1.754-2.967-3.273-2.967-1.242 0-2.375 0.704-3.396 2.112-1.022 1.409-2.223 3.555-3.604 6.439v39.031c0 0.805-0.18 1.207-0.539 1.207h-1.698z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m53.642 166.28c-1.077 2.549-2.237 4.477-3.479 5.785-1.243 1.307-2.61 1.961-4.101 1.961-2.154 0-3.853-1.324-5.095-3.973-1.243-2.649-1.864-6.187-1.864-10.613 0-3.488 0.4-6.489 1.201-9.004s1.988-4.51 3.562-5.985c1.574-1.476 3.521-2.414 5.841-2.817l3.686-0.704c0.221-0.067 0.394-0.218 0.518-0.453 0.124-0.234 0.187-0.587 0.187-1.056v-2.917c0-3.89-0.504-6.975-1.512-9.255s-2.354-3.42-4.039-3.42c-1.298 0-2.472 0.72-3.521 2.162s-2.002 3.572-2.858 6.388c-0.083 0.268-0.159 0.453-0.228 0.554-0.069 0.1-0.172 0.083-0.311-0.051l-1.698-1.71c-0.083-0.134-0.138-0.285-0.166-0.453-0.027-0.167 0.014-0.452 0.125-0.855 0.856-3.353 2.009-6.052 3.459-8.098 1.449-2.045 3.224-3.068 5.322-3.068 1.74 0 3.211 0.687 4.412 2.062s2.112 3.37 2.734 5.986c0.621 2.615 0.932 5.7 0.932 9.255v35.712c0 0.536-0.035 0.888-0.104 1.056s-0.2 0.251-0.393 0.251h-1.533c-0.166 0-0.29-0.117-0.373-0.352-0.083-0.234-0.124-0.553-0.124-0.955l-0.083-5.231c-0.055-0.939-0.221-1.006-0.497-0.202zm0.456-19.314c0-1.14-0.194-1.643-0.58-1.509l-3.107 0.603c-1.436 0.202-2.686 0.638-3.749 1.308-1.063 0.671-1.953 1.543-2.671 2.616s-1.257 2.33-1.616 3.772-0.538 3.102-0.538 4.98c0 3.152 0.455 5.616 1.367 7.393 0.911 1.778 2.14 2.666 3.686 2.666 0.939 0 1.85-0.419 2.734-1.257s1.671-1.895 2.361-3.169c0.663-1.408 1.181-2.85 1.553-4.326 0.373-1.475 0.56-2.883 0.56-4.225v-8.852z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m79.034 173.02c-0.166 0-0.297-0.117-0.394-0.352-0.096-0.234-0.145-0.553-0.145-0.955v-4.628c0-0.536-0.041-0.838-0.124-0.905s-0.207 0.1-0.373 0.503c-0.276 0.67-0.69 1.593-1.242 2.766-0.553 1.174-1.271 2.23-2.154 3.169-0.884 0.939-1.961 1.408-3.231 1.408-1.74 0-3.314-0.989-4.722-2.967-1.409-1.979-2.534-4.963-3.376-8.953-0.843-3.991-1.264-8.937-1.264-14.838 0-5.701 0.415-10.68 1.243-14.939s1.988-7.595 3.479-10.009c1.492-2.415 3.204-3.622 5.137-3.622 1.436 0 2.616 0.57 3.541 1.71 0.926 1.14 1.719 2.381 2.382 3.722 0.249 0.47 0.414 0.637 0.497 0.503s0.125-0.536 0.125-1.207v-23.841c0-0.805 0.151-1.208 0.455-1.208h1.864c0.276 0 0.414 0.369 0.414 1.107v72.128c0 0.537-0.041 0.905-0.124 1.107-0.083 0.201-0.235 0.301-0.455 0.301h-1.533zm-0.621-42.049c-0.939-2.213-1.885-3.94-2.838-5.181s-2.009-1.861-3.169-1.861c-1.463 0-2.768 0.889-3.914 2.666s-2.044 4.376-2.693 7.796-0.973 7.578-0.973 12.474c0 5.097 0.338 9.272 1.015 12.524 0.676 3.253 1.567 5.651 2.672 7.193 1.104 1.543 2.305 2.314 3.603 2.314 1.188 0 2.258-0.704 3.211-2.113 0.952-1.408 1.705-3.118 2.257-5.13s0.829-3.957 0.829-5.835v-24.847z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m89.514 149.38c0 3.42 0.345 6.606 1.035 9.557 0.691 2.951 1.609 5.315 2.755 7.092s2.437 2.666 3.873 2.666c1.519 0 2.837-0.738 3.956-2.213 1.118-1.476 2.064-3.655 2.837-6.539 0.083-0.336 0.166-0.52 0.249-0.554 0.083-0.033 0.179 0.017 0.29 0.151l1.408 1.912c0.221 0.268 0.235 0.67 0.041 1.207-0.69 2.548-1.47 4.661-2.34 6.337-0.87 1.677-1.857 2.935-2.962 3.773-1.104 0.838-2.319 1.257-3.645 1.257-2.043 0-3.838-1.14-5.385-3.42-1.546-2.28-2.761-5.482-3.645-9.607-0.884-4.124-1.325-8.836-1.325-14.134 0-5.901 0.455-10.931 1.367-15.089 0.911-4.158 2.14-7.377 3.686-9.658 1.547-2.28 3.3-3.42 5.261-3.42 1.988 0 3.714 1.073 5.178 3.219 1.463 2.146 2.595 5.231 3.396 9.255s1.201 8.886 1.201 14.587c0 0.469-0.02 0.939-0.062 1.408-0.041 0.469-0.214 0.704-0.517 0.704h-16.362c-0.083 0-0.152 0.151-0.207 0.453-0.056 0.302-0.083 0.654-0.083 1.056zm13.752-6.237c0.304 0 0.497-0.1 0.58-0.302 0.083-0.201 0.124-0.57 0.124-1.106 0-3.219-0.283-6.187-0.849-8.903s-1.367-4.896-2.402-6.539c-1.036-1.643-2.272-2.464-3.708-2.464-1.629 0-2.996 0.955-4.101 2.867-1.104 1.911-1.94 4.342-2.506 7.293s-0.849 6.002-0.849 9.154h13.711z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m148.54 119.7c0.165 0 0.283 0.117 0.352 0.352s0.076 0.52 0.02 0.855l-6.254 50.902c-0.028 0.47-0.104 0.788-0.228 0.956s-0.297 0.251-0.518 0.251h-1.615c-0.442 0-0.718-0.402-0.829-1.207l-5.26-40.138c-0.111-0.604-0.201-0.905-0.27-0.905s-0.131 0.301-0.186 0.905l-5.012 40.138c-0.028 0.47-0.097 0.788-0.207 0.956-0.111 0.168-0.277 0.251-0.497 0.251h-1.74c-0.442 0-0.718-0.402-0.829-1.207l-6.503-50.801c-0.055-0.403-0.048-0.721 0.021-0.956s0.2-0.352 0.393-0.352h1.823c0.166 0 0.297 0.067 0.393 0.201 0.097 0.134 0.159 0.403 0.187 0.805l5.302 41.848c0.083 0.671 0.179 0.989 0.29 0.956 0.11-0.034 0.207-0.386 0.29-1.056l5.219-41.949c0.055-0.268 0.124-0.47 0.207-0.604s0.193-0.201 0.331-0.201h1.533c0.138 0 0.262 0.067 0.373 0.201 0.11 0.134 0.179 0.403 0.207 0.805l5.468 41.848c0.083 0.671 0.179 0.989 0.29 0.956 0.11-0.034 0.207-0.386 0.29-1.056l5.053-41.849c0.055-0.335 0.138-0.57 0.249-0.704 0.11-0.134 0.234-0.201 0.373-0.201h1.284z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m156.49 171.51c0 0.604-0.042 1.006-0.125 1.208-0.082 0.201-0.262 0.301-0.538 0.301h-1.533c-0.221 0-0.366-0.083-0.435-0.251s-0.103-0.486-0.103-0.956v-50.902c0-0.805 0.152-1.207 0.456-1.207h1.822c0.304 0 0.456 0.402 0.456 1.207v50.6zm0.165-63.979c0 1.207-0.207 1.811-0.621 1.811h-1.905c-0.221 0-0.366-0.135-0.435-0.403s-0.104-0.67-0.104-1.207v-7.847c0-1.006 0.18-1.509 0.539-1.509h1.988c0.359 0 0.538 0.47 0.538 1.409v7.746z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m168.3 124.83c-0.221 0-0.331 0.269-0.331 0.805v33.801c0 3.42 0.221 5.667 0.663 6.74 0.441 1.073 1.09 1.609 1.946 1.609h3.024c0.138 0 0.242 0.084 0.311 0.252 0.069 0.167 0.103 0.419 0.103 0.754v2.716c0 0.537-0.138 0.906-0.414 1.107-0.248 0.067-0.614 0.134-1.098 0.201-0.483 0.067-0.959 0.118-1.429 0.151-0.469 0.034-0.828 0.05-1.077 0.05-1.712 0-2.934-0.955-3.665-2.867-0.732-1.911-1.098-5.013-1.098-9.305v-35.108c0-0.604-0.124-0.906-0.373-0.906h-3.521c-0.248 0-0.373-0.268-0.373-0.804v-3.521c0-0.537 0.111-0.805 0.332-0.805h3.686c0.166 0 0.263-0.268 0.29-0.805l0.415-16.095c0-0.805 0.124-1.207 0.372-1.207h1.492c0.303 0 0.455 0.436 0.455 1.307v15.995c0 0.537 0.097 0.805 0.29 0.805h5.468c0.221 0 0.331 0.268 0.331 0.805v3.521c0 0.536-0.124 0.804-0.373 0.804h-5.426z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> <g transform="translate(2.7114)"> <path d="m179.4 173.02c-0.331 0-0.497-0.402-0.497-1.207v-72.329c0-0.738 0.138-1.107 0.414-1.107h1.782c0.276 0 0.414 0.336 0.414 1.006v27.162c0 0.335 0.034 0.536 0.103 0.603s0.159-0.033 0.27-0.302c0.994-1.81 1.898-3.319 2.713-4.526 0.814-1.208 1.629-2.113 2.444-2.717 0.814-0.603 1.691-0.905 2.63-0.905 2.182 0 3.839 1.375 4.971 4.125 1.132 2.749 1.698 6.404 1.698 10.965v37.925c0 0.871-0.166 1.307-0.497 1.307h-1.74c-0.165 0-0.29-0.1-0.373-0.301-0.082-0.202-0.124-0.503-0.124-0.906v-36.315c0-3.555-0.366-6.321-1.097-8.3-0.732-1.978-1.899-2.967-3.501-2.967-0.883 0-1.705 0.318-2.464 0.956-0.76 0.637-1.526 1.576-2.299 2.816-0.773 1.241-1.643 2.834-2.61 4.779v39.031c0 0.805-0.179 1.207-0.538 1.207h-1.699z" fill-rule="nonzero" stroke="#000" stroke-width=".7px"/> </g> </g> <g transform="matrix(.80638 0 0 .80638 452.53 65.421)" fill-rule="nonzero"> <path d="m79.32 36.98v150.76l15.68-13.2 6.59-156.31-22.27 18.75z" fill="url(#f)"/> <path d="m79.32 36.98-22.27-18.75 6.59 156.31 15.68 13.2v-150.76z" fill="url(#e)"/> <path d="m25.19 104.83 8.63 49.04 12.5-14.95-2.46-56.42-18.67 22.33z" fill="url(#d)"/> <path d="m25.19 104.83-25.19-14.59 16.97 53.86 16.85 9.77-8.63-49.04z" fill="url(#c)"/> <path d="M43.86,82.5L18.69,67.98L0,90.24L25.18,104.83L43.86,82.5Z" fill="#9c3"/> <path d="m134.82 78.69-9.97 56.5 15.58-9.04 19.57-62.05-25.18 14.59z" fill="url(#b)"/> <path d="m134.82 78.69-18.68-22.33-2.86 65 11.57 13.83 9.97-56.5z" fill="url(#a)"/> <path d="m160 64.1-18.69-22.26-25.17 14.52 18.67 22.33 25.19-14.59z" fill="#ffe113"/> <path d="M101.59,18.23L79.32,0L57.05,18.23L79.32,36.98L101.59,18.23Z" fill="#f3e600"/> </g> <defs> <linearGradient id="f" x2="1" gradientTransform="matrix(.84 -162.96 162.96 .84 89.64 184.81)" gradientUnits="userSpaceOnUse"><stop stop-color="#62d399" offset="0"/><stop stop-color="#acd842" offset=".51"/><stop stop-color="#d7db0a" offset=".9"/><stop stop-color="#d7db0a" offset="1"/></linearGradient> <linearGradient id="e" x2="1" gradientTransform="matrix(-1.6,-162.13,162.13,-1.6,69.68,178.9)" gradientUnits="userSpaceOnUse"><stop stop-color="#0ba398" offset="0"/><stop stop-color="#4ca352" offset=".5"/><stop stop-color="#76a30a" offset="1"/></linearGradient> <linearGradient id="d" x2="1" gradientTransform="matrix(-1.9,-67.98,67.98,-1.9,36.6,152.17)" gradientUnits="userSpaceOnUse"><stop stop-color="#36a382" offset="0"/><stop stop-color="#36a382" offset=".19"/><stop stop-color="#49a459" offset=".54"/><stop stop-color="#76a30b" offset="1"/></linearGradient> <linearGradient id="c" x2="1" gradientTransform="matrix(2.18,-62.38,62.38,2.18,15.82,153.24)" gradientUnits="userSpaceOnUse"><stop stop-color="#267880" offset="0"/><stop stop-color="#457a5c" offset=".51"/><stop stop-color="#717516" offset="1"/></linearGradient> <linearGradient id="b" x2="1" gradientTransform="matrix(13.85,-71.96,71.96,13.85,135.08,135.43)" gradientUnits="userSpaceOnUse"><stop stop-color="#b0d939" offset="0"/><stop stop-color="#eadb04" offset="1"/></linearGradient> <linearGradient id="a" x2="1" gradientTransform="matrix(26.159 -64.737 64.737 26.159 107.42 128.14)" gradientUnits="userSpaceOnUse"><stop stop-color="#74af52" offset="0"/><stop stop-color="#74af52" offset=".17"/><stop stop-color="#99be32" offset=".48"/><stop stop-color="#c0c40a" offset="1"/></linearGradient> </defs> </svg>`;btoa(Nk);const Wk='<svg viewBox="0 0 509 154" xmlns="http://www.w3.org/2000/svg" xml:space="preserve" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2"><path d="M665.95 132.73v44.88l-10.56-8.4c-.8-.64-1.2-1.44-1.2-2.4v-32.4c0-6.48-4.12-9.72-12.36-9.72-2.16 0-4.18.4-6.06 1.2-1.88.8-3.54 1.8-4.98 3-1.44 1.2-2.56 2.5-3.36 3.9-.8 1.4-1.2 2.7-1.2 3.9v40.92l-10.68-8.4c-.72-.64-1.08-1.44-1.08-2.4v-53.76l10.92 8.52c.32.24.56.44.72.6.16.16.36.32.6.48.96-1.2 2.14-2.28 3.54-3.24 1.4-.96 2.92-1.76 4.56-2.4 1.64-.64 3.34-1.14 5.1-1.5 1.76-.36 3.44-.54 5.04-.54 1.44 0 2.92.04 4.44.12 1.52.08 2.84.28 3.96.6 4.56 1.12 7.8 3.12 9.72 6 1.92 2.88 2.88 6.56 2.88 11.04ZM732.38 146.05c0 .88.02 1.5.06 1.86.04.36-.02.98-.18 1.86h-7.08c-2.08 0-4.44-.02-7.08-.06-2.64-.04-5.36-.06-8.16-.06h-22.08c0 2.88.56 5.36 1.68 7.44 1.12 2.08 2.6 3.8 4.44 5.16 1.84 1.36 3.94 2.36 6.3 3 2.36.64 4.74.96 7.14.96 3.04 0 5.9-.76 8.58-2.28 2.68-1.52 4.94-3.52 6.78-6 .64.56 1.54 1.48 2.7 2.76 1.16 1.28 2.94 3.2 5.34 5.76-2.8 3.36-6.22 6.02-10.26 7.98-4.04 1.96-8.42 2.94-13.14 2.94-4.72 0-8.92-.64-12.84-1.92-3.92-1.28-7.32-3.24-10.2-5.88-2.88-2.64-5.12-5.98-6.72-10.02-1.6-4.04-2.4-8.82-2.4-14.34 0-4.96.66-9.42 1.98-13.38 1.32-3.96 3.22-7.32 5.7-10.08s5.44-4.9 8.88-6.42c3.44-1.52 7.32-2.28 11.64-2.28 5.76 0 10.52.88 14.28 2.64 3.76 1.76 6.72 4.16 8.88 7.2 2.16 3.04 3.66 6.54 4.5 10.5.84 3.96 1.26 8.18 1.26 12.66Zm-29.4-22.8c-2.16.16-4.16.72-6 1.68-1.84.96-3.42 2.2-4.74 3.72-1.32 1.52-2.36 3.28-3.12 5.28-.76 2-1.14 4.12-1.14 6.36h33.12c0-2-.22-4.06-.66-6.18-.44-2.12-1.3-4.02-2.58-5.7-1.28-1.68-3.1-3.02-5.46-4.02-2.36-1-5.5-1.38-9.42-1.14ZM795.93 146.05c0 .88.02 1.5.06 1.86.04.36-.02.98-.18 1.86h-7.08c-2.08 0-4.44-.02-7.08-.06-2.64-.04-5.36-.06-8.16-.06h-22.08c0 2.88.56 5.36 1.68 7.44 1.12 2.08 2.6 3.8 4.44 5.16 1.84 1.36 3.94 2.36 6.3 3 2.36.64 4.74.96 7.14.96 3.04 0 5.9-.76 8.58-2.28 2.68-1.52 4.94-3.52 6.78-6 .64.56 1.54 1.48 2.7 2.76 1.16 1.28 2.94 3.2 5.34 5.76-2.8 3.36-6.22 6.02-10.26 7.98-4.04 1.96-8.42 2.94-13.14 2.94-4.72 0-8.92-.64-12.84-1.92-3.92-1.28-7.32-3.24-10.2-5.88-2.88-2.64-5.12-5.98-6.72-10.02-1.6-4.04-2.4-8.82-2.4-14.34 0-4.96.66-9.42 1.98-13.38 1.32-3.96 3.22-7.32 5.7-10.08s5.44-4.9 8.88-6.42c3.44-1.52 7.32-2.28 11.64-2.28 5.76 0 10.52.88 14.28 2.64 3.76 1.76 6.72 4.16 8.88 7.2 2.16 3.04 3.66 6.54 4.5 10.5.84 3.96 1.26 8.18 1.26 12.66Zm-29.4-22.8c-2.16.16-4.16.72-6 1.68-1.84.96-3.42 2.2-4.74 3.72-1.32 1.52-2.36 3.28-3.12 5.28-.76 2-1.14 4.12-1.14 6.36h33.12c0-2-.22-4.06-.66-6.18-.44-2.12-1.3-4.02-2.58-5.7-1.28-1.68-3.1-3.02-5.46-4.02-2.36-1-5.5-1.38-9.42-1.14ZM858.57 97.21c.64.48.96 1.16.96 2.04v74.88c-.08 1.04-.12 2.12-.12 3.24-1.84-1.52-3.56-2.92-5.16-4.2-1.36-1.12-2.66-2.18-3.9-3.18-1.24-1-2.06-1.66-2.46-1.98-1.76 2.48-4.26 4.44-7.5 5.88-3.24 1.44-7.02 2.16-11.34 2.16-3.84 0-7.4-.7-10.68-2.1-3.28-1.4-6.14-3.44-8.58-6.12-2.44-2.68-4.34-5.94-5.7-9.78-1.36-3.84-2.04-8.16-2.04-12.96 0-4.32.78-8.34 2.34-12.06 1.56-3.72 3.6-6.92 6.12-9.6 2.52-2.68 5.38-4.78 8.58-6.3 3.2-1.52 6.48-2.28 9.84-2.28 2.56 0 4.82.22 6.78.66 1.96.44 3.68 1.06 5.16 1.86s2.78 1.74 3.9 2.82a35.92 35.92 0 0 1 3.12 3.42V88.57l10.68 8.64Zm-27.96 67.92c3.6 0 6.52-.68 8.76-2.04 2.24-1.36 3.98-3.06 5.22-5.1a20.5 20.5 0 0 0 2.58-6.54c.48-2.32.72-4.44.72-6.36v-1.2c0-1.12-.22-2.7-.66-4.74-.44-2.04-1.28-4.06-2.52-6.06s-3-3.7-5.28-5.1c-2.28-1.4-5.22-2.02-8.82-1.86-3.44 0-6.26.74-8.46 2.22-2.2 1.48-3.96 3.26-5.28 5.34-1.32 2.08-2.24 4.2-2.76 6.36-.52 2.16-.78 3.92-.78 5.28 0 1.84.24 3.92.72 6.24.48 2.32 1.36 4.48 2.64 6.48s3.04 3.68 5.28 5.04c2.24 1.36 5.12 2.04 8.64 2.04ZM882.81 97.09c.64.48.96 1.12.96 1.92l-.12 41.04v37.08l-10.56-8.4c-.72-.64-1.08-1.44-1.08-2.4V88.45l10.8 8.64ZM950.36 146.05c0 .88.02 1.5.06 1.86.04.36-.02.98-.18 1.86h-7.08c-2.08 0-4.44-.02-7.08-.06-2.64-.04-5.36-.06-8.16-.06h-22.08c0 2.88.56 5.36 1.68 7.44 1.12 2.08 2.6 3.8 4.44 5.16 1.84 1.36 3.94 2.36 6.3 3 2.36.64 4.74.96 7.14.96 3.04 0 5.9-.76 8.58-2.28 2.68-1.52 4.94-3.52 6.78-6 .64.56 1.54 1.48 2.7 2.76 1.16 1.28 2.94 3.2 5.34 5.76-2.8 3.36-6.22 6.02-10.26 7.98-4.04 1.96-8.42 2.94-13.14 2.94-4.72 0-8.92-.64-12.84-1.92-3.92-1.28-7.32-3.24-10.2-5.88-2.88-2.64-5.12-5.98-6.72-10.02-1.6-4.04-2.4-8.82-2.4-14.34 0-4.96.66-9.42 1.98-13.38 1.32-3.96 3.22-7.32 5.7-10.08s5.44-4.9 8.88-6.42c3.44-1.52 7.32-2.28 11.64-2.28 5.76 0 10.52.88 14.28 2.64 3.76 1.76 6.72 4.16 8.88 7.2 2.16 3.04 3.66 6.54 4.5 10.5.84 3.96 1.26 8.18 1.26 12.66Zm-29.4-22.8c-2.16.16-4.16.72-6 1.68-1.84.96-3.42 2.2-4.74 3.72-1.32 1.52-2.36 3.28-3.12 5.28-.76 2-1.14 4.12-1.14 6.36h33.12c0-2-.22-4.06-.66-6.18-.44-2.12-1.3-4.02-2.58-5.7-1.28-1.68-3.1-3.02-5.46-4.02-2.36-1-5.5-1.38-9.42-1.14Z" style="fill-rule:nonzero" transform="translate(-452.406 -63.709) scale(1.00797)"/><path d="M79.32 36.98v150.76L95 174.54l6.59-156.31-22.27 18.75Z" style="fill:url(#a);fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="M79.32 36.98 57.05 18.23l6.59 156.31 15.68 13.2V36.98Z" style="fill:url(#b);fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="m25.19 104.83 8.63 49.04 12.5-14.95-2.46-56.42-18.67 22.33Z" style="fill:url(#c);fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="M25.19 104.83 0 90.24l16.97 53.86 16.85 9.77-8.63-49.04Z" style="fill:url(#d);fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="M43.86 82.5 18.69 67.98 0 90.24l25.18 14.59L43.86 82.5Z" style="fill:#9c3;fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="m134.82 78.69-9.97 56.5 15.58-9.04L160 64.1l-25.18 14.59Z" style="fill:url(#e);fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="m134.82 78.69-18.68-22.33-2.86 65 11.57 13.83 9.97-56.5Z" style="fill:url(#f);fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="m160 64.1-18.69-22.26-25.17 14.52 18.67 22.33L160 64.1Z" style="fill:#ffe113;fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><path d="M101.59 18.23 79.32 0 57.05 18.23l22.27 18.75 22.27-18.75Z" style="fill:#f3e600;fill-rule:nonzero" transform="matrix(.80638 0 0 .80638 2.361 1.094)"/><defs><linearGradient id="a" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="matrix(.84 -162.96 162.96 .84 89.64 184.81)"><stop offset="0" style="stop-color:#62d399;stop-opacity:1"/><stop offset=".51" style="stop-color:#acd842;stop-opacity:1"/><stop offset=".9" style="stop-color:#d7db0a;stop-opacity:1"/><stop offset="1" style="stop-color:#d7db0a;stop-opacity:1"/></linearGradient><linearGradient id="b" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="rotate(-90.565 123.412 54.953) scale(162.14)"><stop offset="0" style="stop-color:#0ba398;stop-opacity:1"/><stop offset=".5" style="stop-color:#4ca352;stop-opacity:1"/><stop offset="1" style="stop-color:#76a30a;stop-opacity:1"/></linearGradient><linearGradient id="c" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="scale(-68) rotate(88.4 .881 -1.396)"><stop offset="0" style="stop-color:#36a382;stop-opacity:1"/><stop offset=".19" style="stop-color:#36a382;stop-opacity:1"/><stop offset=".54" style="stop-color:#49a459;stop-opacity:1"/><stop offset="1" style="stop-color:#76a30b;stop-opacity:1"/></linearGradient><linearGradient id="d" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="rotate(-88 87.255 68.431) scale(62.42)"><stop offset="0" style="stop-color:#267880;stop-opacity:1"/><stop offset=".51" style="stop-color:#457a5c;stop-opacity:1"/><stop offset="1" style="stop-color:#717516;stop-opacity:1"/></linearGradient><linearGradient id="e" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="rotate(-79.1 149.53 -14.065) scale(73.28)"><stop offset="0" style="stop-color:#b0d939;stop-opacity:1"/><stop offset="1" style="stop-color:#eadb04;stop-opacity:1"/></linearGradient><linearGradient id="f" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="rotate(-67.997 148.705 -15.558) scale(69.8226)"><stop offset="0" style="stop-color:#74af52;stop-opacity:1"/><stop offset=".17" style="stop-color:#74af52;stop-opacity:1"/><stop offset=".48" style="stop-color:#99be32;stop-opacity:1"/><stop offset="1" style="stop-color:#c0c40a;stop-opacity:1"/></linearGradient></defs></svg>',Vk=btoa(Wk),$k="data:image/svg+xml;charset=utf-8;base64,"+Vk,yv=$k;var Qa=(o=>(o[o.Quad=0]="Quad",o[o.Cube=1]="Cube",o[o.Sphere=2]="Sphere",o[o.Cylinder=3]="Cylinder",o[o.RoundedCube=10]="RoundedCube",o))(Qa||{});class Os{static createText(e,t){let i=null;const n=t?.font||Gk(t?.familyFamily||null);n instanceof dP?i=this.#t(e,n,t):i==null&&(i=new wn);const s=t?.color||16777215,r=new H(i,t?.material??new gt({color:s}));return this.applyDefaultObjectOptions(r,t),n instanceof Promise?n.then(a=>{r.geometry=this.#t(e,a,t),t?.onGeometry&&t.onGeometry(r)}):t?.onGeometry&&t.onGeometry(r),r}static#t(e,t,i){const n=i?.depth||.1;return new uP(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 Ce({colorWrite:!1,depthWrite:!0,side:Oi});return this.createPrimitive(e,{material:t})}static createPrimitive(e,t){let i;const n=t?.color||16777215;switch(e){case"Quad":case 0:{const s=new vn(1,1,1,1),r=t?.material??new gt({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new H(s,r),i.name="Quad"}break;case"Cube":case 1:{const s=new Aa(1,1,1),r=t?.material??new gt({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new H(s,r),i.name="Cube"}break;case 10:case"RoundedCube":{const s=Hk(1,1,1,.1,2),r=t?.material??new gt({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new H(s,r),i.name="RoundedCube"}break;case"Sphere":case 2:{const s=new Pd(.5,16,16),r=t?.material??new gt({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new H(s,r),i.name="Sphere"}break;case"Cylinder":case 3:{const s=new bb(.5,.5,1,32),r=t?.material??new gt({color:n});t?.texture&&"map"in r&&(r.map=t.texture),i=new H(s,r),i.name="Cylinder"}break;case"ShaderBall":i=new Po,i.name="ShaderBall",qk(i,t);break}return this.applyDefaultObjectOptions(i,t),i}static createSprite(e){const t=new qS({color:16777215});e?.texture&&"map"in t&&(t.map=e.texture);const i=new XS(t);return this.applyDefaultObjectOptions(i,e),i}static applyDefaultObjectOptions(e,t){e.receiveShadow=!0,e.castShadow=!0,t?.name&&(e.name=t.name),t?.position&&(Array.isArray(t.position)?e.position.set(t.position[0],t.position[1],t.position[2]):e.position.set(t.position.x||0,t.position.y||0,t.position.z||0)),t?.rotation&&(Array.isArray(t.rotation)?e.rotation.set(t.rotation[0],t.rotation[1],t.rotation[2]):e.rotation.set(t.rotation.x||0,t.rotation.y||0,t.rotation.z||0)),t?.scale&&(typeof t.scale=="number"?e.scale.set(t.scale,t.scale,t.scale):Array.isArray(t.scale)?e.scale.set(t.scale[0],t.scale[1],t.scale[2]):e.scale.set(t.scale.x||1,t.scale.y||1,t.scale.z||1)),t?.receiveShadow!=null&&(e.receiveShadow=t.receiveShadow),t?.castShadow!=null&&(e.castShadow=t.castShadow),t?.parent&&t.parent.add(e)}}function Hk(o,e,t,i,n){const s=new QS,r=1e-5,a=i-r;s.absarc(r,r,r,-Math.PI/2,-Math.PI,!0),s.absarc(r,e-a*2,r,Math.PI,Math.PI/2,!0),s.absarc(o-a*2,e-a*2,r,Math.PI/2,0,!0),s.absarc(o-a*2,r,r,0,-Math.PI/2,!0);const l=new YS(s,{bevelEnabled:!0,bevelSegments:n*2,steps:1,bevelSize:a,bevelThickness:i,curveSegments:n,UVGenerator:{generateTopUV:(c,h)=>{const d=[];for(let p=0;p<h.length;p+=3)d.push(new K(h[p]/o,h[p+1]/e));return d},generateSideWallUV:(c,h,d,p,m,g)=>{const f=[];return f.push(new K(h[d]/o,h[d+1]/e)),f.push(new K(h[p]/o,h[p+1]/e)),f.push(new K(h[m]/o,h[m+1]/e)),f.push(new K(h[g]/o,h[g+1]/e)),f}}});return l.scale(1,1,1-i),l.center(),l.index||l.setIndex(Array.from({length:l.attributes.position.count},(c,h)=>h)),l.computeVertexNormals(),l}const eu=new Map;function Gk(o){let e="";switch(o){default:case"OpenSans":e="https://cdn.needle.tools/static/fonts/facetype/Open Sans_Regular_ascii.json";break;case"Helvetiker":e="https://cdn.needle.tools/static/fonts/facetype/Helvetiker_Regular_ascii.json";break}if(eu.has(e)){const n=eu.get(e);if(n)return n}const t=new pP,i=new Promise((n,s)=>{t.load(e,r=>{eu.set(e,r),n(r)},void 0,s)});return eu.set(e,i),i}let Ig=!1,Lg=null;function qk(o,e){if(Lg===null){const t="https://cdn.needle.tools/static/models/shaderball.glb",i=new Eo,n=Um(null);i.setDRACOLoader(n.dracoLoader),i.setKTX2Loader(n.ktx2Loader),Ig=!0,Lg=i.loadAsync(t).then(s=>{const r=s.scene;return r.position.y-=.5,r}).catch(s=>(console.warn("Failed to load shaderball mesh: "+s.message),_v())).finally(()=>{Ig=!1})}if(Ig){const t=_v();t.name="ShaderBall-Placeholder";const i=t.children[0];i?.type==="Mesh"&&bv(i,e),o.add(t)}Lg.then(t=>{o.children.forEach(s=>{s.name==="ShaderBall-Placeholder"&&o.remove(s)});const i=t.clone(),n=i.children[0];n?.type==="Mesh"&&(n.geometry.attributes.tangent||n.geometry.computeTangents(),bv(n,e)),o.add(i)})}function bv(o,e){if(e?.color||e?.material||e?.texture){const t=e?.material??o.material?.clone()??new gt;e.color&&"color"in t&&t.color instanceof oe&&t.color.set(e.color),e?.texture&&"map"in t&&(t.map=e.texture),o.material=t}}function _v(){return new Po().add(Os.createPrimitive("Sphere",{material:new Ce({transparent:!0,opacity:.1})}))}class nc{static _active=null;static get active(){return this._active}static _requestInFlight=!1;static async start(e,t){if(this._active)return console.error("Cannot start a new XR session while one is already active"),null;if(this._requestInFlight)return console.error("Cannot start a new XR session while a request is already in flight"),null;if("xr"in navigator&&navigator.xr){if(!t)return console.error("XRSessionInit must be provided"),null;this._requestInFlight=!0;const i=await navigator.xr.requestSession(e,t).catch(n=>{console.error("Failed to start temporary XR session:",n)});return i?(i.addEventListener("end",()=>{this._active=null}),this._requestInFlight?(this._requestInFlight=!1,this._active=new nc(e,t,i),this._active):(i.end(),null)):(this._requestInFlight=!1,null)}return null}static async handoff(){return this._active?this._active.handoff():null}static async stop(){this._requestInFlight=!1,this._active&&(await this._active.end(),await To(100)),this._active=null}_session;_mode;_init;get isAR(){return this._mode==="immersive-ar"}get isVR(){return this._mode==="immersive-vr"}_renderer;_camera;_scene;constructor(e,t,i){this._mode=e,this._init=t,this._session=i,this._session.addEventListener("end",this.onEnd),this._renderer=new yr({alpha:!0,antialias:!0}),this._renderer.outputColorSpace="srgb",this._renderer.setPixelRatio(Math.min(2,window.devicePixelRatio)),this._renderer.setSize(window.innerWidth,window.innerHeight,!0),I.isNeedleAppClip()&&window.requestAnimationFrame(()=>{const n=Math.min(2,window.devicePixelRatio),s=Math.floor(window.innerWidth*n),r=Math.floor(window.innerHeight*n);this._renderer.domElement.width=s,this._renderer.domElement.height=r}),this._renderer.setAnimationLoop(this.onFrame),this._renderer.xr.setSession(i),this._renderer.xr.enabled=!0,this._camera=new de,this._scene=new Hi,this._scene.fog=new _b(4473924,10,250),this._scene.add(this._camera),this.setupScene()}end(){return this._session?this._session.end():Promise.resolve()}async handoff(){if(!this._session)throw new Error("Cannot handoff a session that has already ended");const e={session:this._session,mode:this._mode,init:this._init};return await this.onBeforeHandoff(),this.onEnd(),this._session=null,e}onEnd=()=>{this._session?.removeEventListener("end",this.onEnd),this._renderer.setAnimationLoop(null),this._renderer.dispose(),this._scene.clear()};_lastTime=0;_frames=0;onFrame=(e,t)=>{const i=e-this._lastTime;this.update(e,i),this._camera.parent!==this._scene&&this._scene.add(this._camera),this._renderer.render(this._scene,this._camera),this._lastTime=e,this._frames++};_roomFlyObjects=[];_logoObject=null;get _logoDistance(){return this.isAR?.3:5}get _logoScale(){return this.isAR?.04:1}update(e,t){const i=e*4e-4;for(let r=0;r<this._roomFlyObjects.length;r++){const a=this._roomFlyObjects[r];a.position.y+=Math.sin(i+r*.5)*.005,a.rotateY(.002)}const n=this._logoObject,s=this._renderer.xr.getCamera();if(n){const r=new b;s.getWorldDirection(r);const a=s.position.clone().addScaledVector(r,this._logoDistance),l=this.isAR?.005:1e-5;n.position.lerp(a,this._frames<=2?1:t*l),n.lookAt(this._camera.position)}}async onBeforeHandoff(){await To(1e3),this._scene.clear()}setupScene(){this._scene.background=new oe(0);let e=Xa;if(Kn()){const h=document.querySelector("needle-engine");if(h){const d=h.getAttribute("logo-src");d?.length&&(e=d,A()&&console.debug("[XR] Using custom loading logo from license:",e))}}const t=this._logoObject=new H(new vn(1,1,1,1),new Ce({transparent:!0,side:2}));t.scale.multiplyScalar(this._logoScale*window.devicePixelRatio),t.renderOrder=1e3,t.material.opacity=0,this._scene.add(t);const i=document.createElement("canvas"),n=i.getContext("2d"),s=new Image,r=h=>{if(!n)return;t.material.opacity=1;const d=1024;i.width=d,i.height=d,n.imageSmoothingQuality="high";const p=d*.19,m=s.width/s.height;{const P=i.height-p*1.5,k=P*m,O=(i.width-k)/2;n.drawImage(s,O,0,k,P)}const g=d*.12,f="Loading...";n.shadowBlur=0,n.fillStyle=this.isAR?"white":"rgba(255,255,255,0.4)",n.font=`${g}px Arial`,n.shadowBlur=d*.02,n.shadowColor="rgba(0,0,0,0.5)",n.shadowOffsetX=0,n.shadowOffsetY=0;const y=n.measureText(f);n.fillText(f,i.width/2-y.width/2,i.height-p/4),n.font=`${g}px Arial`,n.fillText(f,i.width/2-y.width/2,i.height-p/4);const _=new br().load(i.toDataURL());_.generateMipmaps=!0,_.colorSpace="srgb",_.anisotropy=4;const v=i.width/i.height;t.scale.x=this._logoScale*v*window.devicePixelRatio,t.scale.y=this._logoScale*window.devicePixelRatio,t.material.map=_,t.material.needsUpdate=!0};s.onload=()=>r(),s.onerror=h=>{console.error("Failed to load temporary XR logo:",e,h),s.src=Xa},s.crossOrigin="anonymous",s.src=e;const a=new km(16777215,1);a.position.set(0,20,0),a.castShadow=!1,this._scene.add(a);const l=new km(16777215,1);l.position.set(0,-1,0),l.castShadow=!1,this._scene.add(l);const c=new Mm(16777215,1,100,1);if(c.position.set(0,2,0),c.castShadow=!1,c.distance=200,this._scene.add(c),this.isAR===!1)for(let h=0;h<100;h++){const d=new gt({color:2236962,metalness:1,roughness:.8}),p=Qa.Sphere,m=Os.createPrimitive(p,{material:d});m.position.x=j.random(-50,50),m.position.y=j.random(-2,50),m.position.z=j.random(-50,50),m.rotation.x=j.random(0,Math.PI*2),m.rotation.y=j.random(0,Math.PI*2),m.rotation.z=j.random(0,Math.PI*2),m.scale.multiplyScalar(.5+Math.random()*10);const g=m.position.distanceTo(this._camera.position)-m.scale.x;g<10&&(m.position.z+=5,m.position.multiplyScalar(1+1/g)),this._roomFlyObjects.push(m),this._scene.add(m)}}}var kc;(o=>{const e=[];function t(){e?.length||A()&&console.warn("No USDZ exporters found \u2013 cannot export USDZ for QuickLook.");for(const s of e)s.exportAndOpen();return!0}o.exportAndOpen=t;function i(s){e.push(s)}o.registerExporter=i;function n(s){if(!e)return;const r=e.indexOf(s);r>=0&&e.splice(r,1)}o.unregisterExporter=n})(kc||(kc={}));const Xe=w("debugwebxr"),vv=w("stats");let jg=0;function Xk(o){let e=null;const t=o;return t.getAROverlayContainer?e=t.getAROverlayContainer():e=o,e}Qk();async function Qk(){let o="immersive-vr";try{if(I.isNeedleAppClip()?o="immersive-ar":await navigator.xr?.isSessionSupported("immersive-vr")||(o="immersive-ar"),!await navigator.xr?.isSessionSupported("immersive-ar")&&o==="immersive-ar")return}catch(e){console.debug("[NeedleXRSession:granted] Error while checking XR support:",e);return}if(w("debugasap")){let e=globalThis["needle:XRSession"];if(e instanceof Promise){delete globalThis["needle:XRSession"],pe.addContextCreatedCallback(async t=>{if(!e)return;Na(!0);const i=await e;if(i){const n=Z.getDefaultSessionInit(o);Z.setSession(o,i,n,t.context)}else console.error("[NeedleXRSession:granted] ASAP session was rejected");e=void 0});return}}if("xr"in navigator){if(/WebXRViewer\//i.test(navigator.userAgent)){console.warn("WebXRViewer does not support addEventListener");return}navigator.xr?.addEventListener("sessiongranted",async()=>{const e=sessionStorage.getItem("needle_xr_session_mode"),t=sessionStorage.getItem("needle_xr_session_init")??null,i=t?JSON.parse(t):null;let n=null;if(wv()&&(await nc.start(e||o,i||Z.getDefaultSessionInit(o)).catch(s=>console.warn("[NeedleXRSession:granted] TemporaryXRContext start failed:",s)),await Kk(),n=await nc.handoff()),n)Z.setSession(n.mode,n.session,n.init,U.Current);else if(e&&t){console.log("[NeedleXRSession:granted] Restore last session");const s=JSON.parse(t);Z.start(e,s).catch(r=>console.warn(r))}else Z.start(o).catch(s=>console.warn("[NeedleXRSession:granted] failed:",s))},{once:!0})}}function Yk(o,e){sessionStorage.setItem("needle_xr_session_mode",o),sessionStorage.setItem("needle_xr_session_init",JSON.stringify(e))}function Zk(){sessionStorage.removeItem("needle_xr_session_mode"),sessionStorage.removeItem("needle_xr_session_init")}const Dg=new Set;pe.registerCallback(ue.ContextCreationStart,async o=>{Dg.add(o.context)}),pe.registerCallback(ue.ContextCreated,async o=>{Dg.delete(o.context);const e=o.context?.domElement.getAttribute("autostart")||null;Jk(e)});function wv(){return Dg.size>0}function Kk(){return new Promise(o=>{const e=Date.now(),t=setInterval(()=>{(!wv()||Date.now()-e>6e4)&&(clearInterval(t),o())},100)})}I.isDesktop()&&A()&&window.addEventListener("keydown",o=>{(o.key==="x"||o.key==="Escape")&&Z.active&&Z.stop()});function Jk(o){o&&o?.toLowerCase()==="ar"&&Nn.registerWaitForInteraction(()=>{Z.start("ar")})}const tu=Symbol("initial-fov"),Bg=Symbol("initial-near");class Z{static _sync=null;static getXRSync(e){return this._sync||(this._sync=new gv(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=>(Xe&&console.error(t),!1))??Promise.resolve(!1)}static _currentSessionRequest;static _activeSession;static onSessionRequestStart(e){this._sessionRequestStartListeners.push(e)}static offSessionRequestStart(e){const t=this._sessionRequestStartListeners.indexOf(e);t>=0&&this._sessionRequestStartListeners.splice(t,1)}static _sessionRequestStartListeners=[];static onSessionRequestEnd(e){this._sessionRequestEndListeners.push(e)}static offSessionRequestEnd(e){const t=this._sessionRequestEndListeners.indexOf(e);t>=0&&this._sessionRequestEndListeners.splice(t,1)}static _sessionRequestEndListeners=[];static onXRSessionStart(e){this._xrStartListeners.push(e)}static offXRSessionStart(e){const t=this._xrStartListeners.indexOf(e);t>=0&&this._xrStartListeners.splice(t,1)}static _xrStartListeners=[];static onXRSessionEnd(e){this._xrEndListeners.push(e)}static offXRSessionEnd(e){const t=this._xrEndListeners.indexOf(e);t>=0&&this._xrEndListeners.splice(t,1)}static _xrEndListeners=[];static onControllerAdded(e){this._controllerAddedListeners.push(e)}static offControllerAdded(e){const t=this._controllerAddedListeners.indexOf(e);t>=0&&this._controllerAddedListeners.splice(t,1)}static _controllerAddedListeners=[];static onControllerRemoved(e){this._controllerRemovedListeners.push(e)}static offControllerRemoved(e){const t=this._controllerRemovedListeners.indexOf(e);t>=0&&this._controllerRemovedListeners.splice(t,1)}static _controllerRemovedListeners=[];static offerSession(e,t,i){return"xr"in navigator&&navigator.xr&&"offerSession"in navigator.xr?(typeof navigator.xr.offerSession=="function"&&(console.log("WebXR offerSession is available - requesting mode: "+e),t=="default"&&(t=this.getDefaultSessionInit(e)),navigator.xr.offerSession(e,{...t}).then(n=>Z.setSession(e,n,t,i)).catch(n=>{console.log("XRSession offer rejected (perhaps because another call to offerSession was made or a call to requestSession was made)")})),!0):!1}static getDefaultSessionInit(e){switch(e){case"immersive-ar":const t=["anchors","local-floor","layers","dom-overlay","hit-test","unbounded"];return I.isVisionOS()||t.push("hand-tracking"),{optionalFeatures:t};case"immersive-vr":const i=["local-floor","bounded-floor","high-fixed-foveation-level","layers"];return I.isVisionOS()||i.push("hand-tracking"),{optionalFeatures:i};default:return console.warn("No default session init for mode",e),{}}}static async start(e,t,i){if(t||(t={}),I.isiOS()){const r=await this.isARSupported().catch(()=>!1);if(I.isVisionOS()&&!r&&(e==="ar"||e==="immersive-ar")&&(e="quicklook"),e==="quicklook")return gi.sendEvent(U.Current,"xr",{action:"quicklook_export",source:"NeedleXRSession.start"}),kc.exportAndOpen(),null;if(!r&&(e==="immersive-ar"||e==="ar")){this.invokeSessionRequestStart("immersive-ar",t);const a=new URL("https://appclip.apple.com/id?p=tools.needle.launch-app.Clip");a.searchParams.set("url",location.href);const l=a.toString();gi.sendEvent(U.Current,"xr",{action:"app_clip_launch",source:"NeedleXRSession.start",url:l});const c=window.top||window;try{console.debug("iOS device detected - opening Needle App Clip for AR experience",{mode:e,init:t,url:a}),c.location.href=l}catch(h){console.warn("Error navigating to AppClip "+l+`
|
|
175
175
|
`,h),window!==window.top?window.open(l,"_blank"):window.location.href=l}return setTimeout(()=>{this.invokeSessionRequestEnd("immersive-ar",t||{},null)},3e3),null}}if(e==="quicklook")return console.warn("QuickLook mode is only supported on iOS devices"),null;if(e=="ar"&&(e="immersive-ar"),A()&&w("debugxrpreroom"))return console.warn("Debug: Starting temporary XR session"),await nc.start(e,t||Z.getDefaultSessionInit(e)),null;if(this._currentSessionRequest)return console.warn("A XRSession is already being requested"),(Xe||A())&&be("A XRSession is already being requested"),this._currentSessionRequest.then(()=>this._activeSession);if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;if(i||(i=U.Current),i||(i=pe.All[0]),!i)throw new Error("No Needle Engine Context found");switch(e){case"immersive-ar":{if(await this.xrSystem?.isSessionSupported("immersive-ar")!==!0)return console.error(e+" is not supported by this browser."),null;const r=this.getDefaultSessionInit(e),a=Xk(i.domElement);a&&!I.isQuest()&&(r.domOverlay={root:a},r.optionalFeatures.push("dom-overlay")),t={...r,...t}}break;case"immersive-vr":{if(await this.xrSystem?.isSessionSupported("immersive-vr")!==!0)return console.error(e+" is not supported by this browser."),null;t={...this.getDefaultSessionInit(e),...t}}break;default:console.warn("No default session init for mode",e);break}t.optionalFeatures??=[],t.requiredFeatures??=[],await nc.stop();const n=e=="immersive-ar"?i.scripts_immersive_ar:i.scripts_immersive_vr;Xe?console.log(`%cRequesting ${e} session`,"font-weight:bold;",t,n):console.log(`%cRequesting ${e} session`,"font-weight:bold;");for(const r of n)r.onBeforeXR&&r.activeAndEnabled&&!r.destroyed&&r.onBeforeXR(e,t);this.invokeSessionRequestStart(e,t),Xe&&Oe("Requesting "+e+" session ("+Date.now()+")"),gi.sendEvent(U.Current,"xr",{action:"session_request",mode:e,features:(t.requiredFeatures??[]).concat(t.optionalFeatures??[]).join(","),source:"NeedleXRSession.start"}),this._currentSessionRequest=navigator?.xr?.requestSession(e,t),this._currentSessionRequestMode=e;const s=await this._currentSessionRequest?.catch(r=>{console.error(r,"Code: "+r?.code),r?.code===9&&be("Couldn't start XR session. Make sure you allow the required permissions."),console.log("If the specified XR configuration is not supported (e.g. entering AR doesnt work) - make sure you access the website on a secure connection (HTTPS) and your device has the required permissions (e.g. camera access)"),location.protocol==="http:"&&be("XR requires a secure connection (HTTPS)")});return this._currentSessionRequest=void 0,this._currentSessionRequestMode=null,this.invokeSessionRequestEnd(e,t,s),s?this.setSession(e,s,t,i):(console.warn("XR Session request was rejected"),null)}static invokeSessionRequestStart(e,t){for(const i of this._sessionRequestStartListeners)i({mode:e,init:t})}static invokeSessionRequestEnd(e,t,i){for(const n of this._sessionRequestEndListeners)n({mode:e,init:t,newSession:i||null})}static setSession(e,t,i,n){if(this._activeSession)return console.error("A XRSession is already running"),this._activeSession;const s=e=="immersive-ar"?n.scripts_immersive_ar:n.scripts_immersive_vr;return this._activeSession=new Z(e,t,n,{scripts:s,controller_added:this._controllerAddedListeners,controller_removed:this._controllerRemovedListeners,init:i}),t.addEventListener("end",this.onEnd),Xe?console.log(`%cStarted ${e} session`,"font-weight:bold;",s):console.log(`%cStarted ${e} session`,"font-weight:bold;"),this._activeSession}static $_stop_request=Symbol();static stop(){const e=this._activeSession;e&&(e[this.$_stop_request]===void 0?(Xe&&console.log("[NeedleXRSession] Stopping XR Session... (new)"),e[this.$_stop_request]=setTimeout(()=>{e.end()})):Xe&&console.warn("[NeedleXRSession] XR Session stop already requested"))}static onEnd=()=>{Xe&&console.log("XR Session ended"),this._activeSession=null};context;get sync(){return Z._sync}get running(){return!this._ended&&this.session!=null}session;mode;get interactionMode(){return this.session.interactionMode}get visibilityState(){return this.session.visibilityState}get isVisibleBlurred(){return this.session.visibilityState==="visible-blurred"}get isSystemKeyboardSupported(){return this.session.isSystemKeyboardSupported}get environmentBlendMode(){return this.session.environmentBlendMode}get frame(){return this.context.xrFrame}controllers=[];get leftController(){return this.controllers.find(e=>e.side==="left")}get rightController(){return this.controllers.find(e=>e.side==="right")}getController(e){return typeof e=="number"?this.controllers[e]||null:this.controllers.find(t=>t.side===e)||null}get isPassThrough(){return!!(this.environmentBlendMode!=="opaque"&&this.interactionMode==="world-space"||this.mode==="immersive-ar"&&this.environmentBlendMode!=="opaque"&&this.controllers.some(e=>e.inputSource.targetRayMode==="tracked-pointer")||A()&&I.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&&Br(e.gameObject)||e?.isActive===!1?(this.updateActiveXRRig(),this._rigs[0]??null):e}_rigScale=1;_lastRigScaleUpdate=-1;get rigScale(){return this._rigs[0]?(this._lastRigScaleUpdate!==this.context.time.frame&&(this._lastRigScaleUpdate=this.context.time.frame,this._rigScale=this._rigs[0].gameObject.worldScale.x),this._rigScale):1}addRig(e){this._rigs.indexOf(e)>=0||(e.priority===void 0&&(e.priority=0),this._rigs.push(e),this.updateActiveXRRig())}removeRig(e){const t=this._rigs.indexOf(e);t!==-1&&(this._rigs.splice(t,1),this.updateActiveXRRig())}setRigActive(e){const t=this._rigs.indexOf(e),i=this._rigs[0];this._rigs.splice(t,1),this._rigs.unshift(e),e.priority=i?.priority??0,this.updateActiveXRRig()}getUserOffsetInRig(){const e=this.context.mainCamera?.position;if(!e||!this.rig)return F(0,0,0);const t=F(e);return t.x*=-1,t.z*=-1,t.applyQuaternion(hi(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(Br(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)}Xe&&(e===t?console.log("Updated Active XR Rig:",t,"prev:",e):console.log("Updated Active XRRig:",t," (the same as before)"))}_rigs=[];_viewerHitTestSource=null;getHitTest(e){if(e)return this.getControllerHitTest(e);if(!this._viewerHitTestSource)return null;const t=this._viewerHitTestSource,i=this.frame.getHitTestResults(t);if(i.length>0){const n=i[0];return this.convertHitTestResult(n)}return null}getControllerHitTest(e){const t=e.getHitTestSource();if(!t)return null;const i=this.frame.getHitTestResultsForTransientInput(t);for(const n of i)if(n.inputSource===e.inputSource)for(const s of n.results)return this.convertHitTestResult(s);return null}convertHitTestResult(e){const t=this.context.renderer.xr.getReferenceSpace(),i=t&&e.getPose(t);if(i){const n=F(i.transform.position),s=hi(i.transform.orientation),r=this.context.mainCamera;if(r?.parent!==this._cameraRenderParent&&n.applyMatrix4(Ha),r?.parent){n.applyMatrix4(r.parent.matrixWorld),s.multiply(qi);const a=_e(r.parent);a.premultiply(qi),s.premultiply(a)}return{hit:e,position:n,quaternion:s}}return null}convertSpace(e){const t=F(e.position);t.applyMatrix4(Ha);const i=hi(e.orientation);return i.premultiply(qi),{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){Yk(e,n.init),this.session=t,this.mode=e,this.context=i,(Xe||w("console"))&&Na(!0),this._xr_scripts=[...n.scripts],this._xr_update_scripts=this._xr_scripts.filter(s=>typeof s.onUpdateXR=="function"),this._controllerAdded=n.controller_added,this._controllerRemoved=n.controller_removed,Do(this.onBefore,xe.LateUpdate),this.context.pre_render_callbacks.push(this.onBeforeRender),this.context.post_render_callbacks.push(this.onAfterRender),(n.init.optionalFeatures?.includes("hit-test")||n.init.requiredFeatures?.includes("hit-test"))&&t.requestReferenceSpace("viewer").then(s=>t.requestHitTestSource?.call(t,{space:s})?.then(r=>this._viewerHitTestSource=r).catch(r=>console.error(r))).catch(s=>console.error(s)),this.context.mainCamera&&(this._originalCameraWorldPosition=ee(this.context.mainCamera,new b),this._originalCameraWorldRotation=_e(this.context.mainCamera,new N),this._originalCameraWorldScale=$e(this.context.mainCamera,new b),this._originalCameraParent=this.context.mainCamera.parent,this.context.mainCamera instanceof de&&(this.context.mainCamera[tu]=this.context.mainCamera.fov)),this._defaultRig=new Ok,this.context.scene.add(this._defaultRig.gameObject),this.addRig(this._defaultRig);for(let s=0;s<t.inputSources.length;s++){const r=t.inputSources[s];if(!r.handedness){console.warn("Input source in xr session has no handedness - ignoring",s);continue}this.onInputSourceAdded(r)}this.session.addEventListener("end",this.onEnd),this.session.addEventListener("inputsourceschange",s=>{for(const r of s.removed)this.disconnectInputSource(r);for(const r of s.added)this.onInputSourceAdded(r)}),this.context.xr=this,this.context.renderer.xr.setSession(this.session).then(this.onRendererSessionSet),"controllerAutoUpdate"in this.context.renderer.xr?(console.debug("Disabling three.js controllerAutoUpdate"),this.context.renderer.xr.controllerAutoUpdate=!1):Xe&&console.warn("controllerAutoUpdate is not available in three.js - cannot disable it"),I.isNeedleAppClip()&&window.requestAnimationFrame(()=>{const s=this.context.renderer.domElement,r=window.devicePixelRatio||1,a=s.width,l=s.height,c=Math.floor(window.innerWidth*r),h=Math.floor(window.innerHeight*r);(Math.abs(a-c)>2||Math.abs(l-h)>2)&&(s.width=c,s.height=h,console.debug("Applied DPR scaling for Needle AppClip XR session",r,s.width,s.height))})}onRendererSessionSet=()=>{this.running&&(this.context.renderer.xr.enabled=!0,this.context.renderer.xr.updateCamera(this.context.mainCamera),this.context.mainCameraComponent?.applyClearFlags())};onInputSourceAdded=e=>{if(e.targetRayMode==="screen")return;let t=0;for(let n=0;n<this.session.inputSources.length;n++)if(this.session.inputSources[n]===e){t=n;break}if(this.controllers.find(n=>n.inputSource===e)){console.debug("Controller already exists for input source",t);return}else if(this._newControllers.find(n=>n.inputSource===e)){console.debug("Controller already registered for input source",t);return}const i=new Pg(this,e,t);this._newControllers.push(i)};disconnectInputSource(e){const t=(s,r)=>{if(s.inputSource===e){Xe&&console.log("Disconnecting controller",s.index);const a=r.indexOf(s);a>=0&&r.splice(a,1),this.invokeControllerEvent(s,this._controllerRemoved,"removed");const l={xr:this,controller:s,change:"removed"};for(const c of this._xr_scripts)c.onXRControllerRemoved&&c.onXRControllerRemoved(l);s.onDisconnected()}},i=[...this.controllers];for(let s=i.length-1;s>=0;s--){const r=i[s];t(r,this.controllers)}const n=[...this._newControllers];for(let s=n.length-1;s>=0;s--){const r=n[s];t(r,this._newControllers)}}end(){this._ended||this.session.end().catch(e=>console.warn(e))}_ended=!1;_newControllers=[];onEnd=e=>{if(this._ended)return;this._ended=!0,console.debug("XR Session ended"),gi.sendEvent(U.Current,"xr",{action:"session_end",mode:this.mode,source:"NeedleXRSession.onEnd"}),Zk(),this.onAfterRender(),this.revertCustomForward(),this._didStart=!1,this._previousCameraParent=null,this.requestedCameraNearPlane=null,Ps(this.onBefore,xe.LateUpdate);const t=this.context.pre_render_callbacks.indexOf(this.onBeforeRender);t>=0&&this.context.pre_render_callbacks.splice(t,1);const i=this.context.post_render_callbacks.indexOf(this.onAfterRender);i>=0&&this.context.post_render_callbacks.splice(i,1),this.context.xr=null,this.context.renderer.xr.enabled=!1,this.context.pre_update_oneshot_callbacks.push(()=>{this.context.mainCameraComponent?.applyClearFlags(),this.context.mainCameraComponent?.applyClippingPlane()}),K_({session:this});for(const s of Z._xrEndListeners)s({xr:this});const n=[...this.controllers];for(let s=0;s<n.length;s++)this.disconnectInputSource(n[s].inputSource);this.controllers.length=0,this._newControllers.length=0;for(const s of this._xr_scripts)s?.onLeaveXR?.({xr:this});this.sync?.onExitXR(this),this.context.mainCamera&&(this._originalCameraParent?.add(this.context.mainCamera),this._originalCameraWorldPosition&&yt(this.context.mainCamera,this._originalCameraWorldPosition),this._originalCameraWorldRotation&&Sn(this.context.mainCamera,this._originalCameraWorldRotation),this._originalCameraWorldScale&&za(this.context.mainCamera,this._originalCameraWorldScale),this.context.mainCamera instanceof de&&(this.context.mainCamera[tu]&&(this.context.mainCamera.fov=this.context.mainCamera[tu],this.context.mainCamera[tu]=0),this.context.mainCamera[Bg]&&(this.context.mainCamera.near=this.context.mainCamera[Bg],this.context.mainCamera[Bg]=0))),this.context.requestSizeUpdate(),this._defaultRig.gameObject.removeFromParent(),Na(!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&&(Xe&&console.warn("Latest rig is not active - trying to activate a different rig",this.rig),this.updateActiveXRRig()),this.rig&&this._mainCamera?.gameObject&&this._mainCamera?.gameObject?.parent!==this.rig.gameObject&&this.rig.gameObject.add(this._mainCamera?.gameObject),this.internalUpdateState(),this.applyCustomForward();const i={xr:this};if(this._didStart){if(this.context.new_scripts_xr.length>0){const n=[...this.context.new_scripts_xr];for(let s=0;s<n.length;s++){const r=this.context.new_scripts_xr[s];if(!r||r.destroyed||r.supportsXR?.(this.mode)==!1){this.context.new_scripts_xr.splice(s,1);continue}if(!r.activeAndEnabled){this.context.new_scripts_xr.splice(s,1),this.markInactive(r);continue}if(this.addScript(r)){this.invokeCallback_EnterXR(r);for(const a of this.controllers)this.invokeCallback_ControllerAdded(r,a)}}}}else{if(this._didStart=!0,this.mode==="immersive-vr"){const s=di(this.context.scene.children);if(s){const r=s.getSize(F());if(r.length()>0){const a=this._defaultRig.gameObject;a.position.set(s.min.x+r.x*.5,s.min.y,s.max.z+r.z*.5+1.5);const l=s.getCenter(F());l.y=a.position.y,a.lookAt(l)}}}Z_({session:this}),Rr();for(const s of Z._xrStartListeners)s(i);const n=[...this._xr_scripts];Xe&&console.log("NeedleXRSession start, handle scripts:",n);for(const s of n){if(s.destroyed){this._script_to_remove.push(s);continue}if(!s.activeAndEnabled){this.markInactive(s);continue}this.invokeCallback_EnterXR(s);for(const r of this.controllers)this.invokeCallback_ControllerAdded(s,r)}}this.syncCameraCullingMask();for(const n of this.controllers)n.onUpdate(t);if(this._newControllers.length>0){const n=[...this._newControllers];this._newControllers.length=0;for(const s of n){if(!s.connected){console.warn("New controller is not connected",s);continue}this.controllers.push(s);for(const r of this._xr_scripts){if(r.destroyed){this._script_to_remove.push(r);continue}r.activeAndEnabled!==!1&&this.invokeCallback_ControllerAdded(r,s)}}this.controllers.sort((s,r)=>s.index-r.index)}Xe&&this.context.time.frame%30===0&&this.controllers.length<=0&&this.session.inputSources.length>0&&(Na(!0),console.error("XRControllers are not added but inputSources are present"));for(const n of this._xr_update_scripts){if(n.destroyed===!0){this._script_to_remove.push(n);continue}if(n.activeAndEnabled===!1){this.markInactive(n);continue}n.onUpdateXR&&n.onUpdateXR(i)}if(this.handleInactiveScripts(),this._script_to_remove.length>0){const n=[...new Set(this._script_to_remove)];this._script_to_remove.length=0;for(const s of n)!s.destroyed&&this.running&&s.onLeaveXR?.(i),this.removeScript(s)}this.sync?.onUpdate(this),this.onRenderDebug()};onRenderDebug(){if(Xe)for(const e of this.controllers)e.onRenderDebug();if((Xe||vv)&&this.rig&&(jg++,jg>=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()}`,Xe||vv)for(const s of this.controllers)n+=`
|
|
176
|
-
${s.hand?"hand":"ctrl"} ${s.inputSource.handedness}[${s.index}] con:${s.connected} tr:${s.isTracking} hts:${s.hasHitTestSource?"yes":"no"}`;jg=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 de&&(this.context.mainCamera.near=this.requestedCameraNearPlane,this.requestedCameraNearPlane=null))};onAfterRender=()=>{if(this.onUpdateFade_PostRender(),I.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:(Xe&&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){Xe&&console.log("Remove XRScript",e);const i=this._xr_scripts.indexOf(e);i>=0&&this._xr_scripts.splice(i,1);const n=this._xr_update_scripts.indexOf(e);if(n>=0&&this._xr_update_scripts.splice(n,1),t){const s=this._inactive_scripts.indexOf(e);s>=0&&this._inactive_scripts.splice(s,1)}}invokeCallback_EnterXR(e){e.onEnterXR&&e.onEnterXR({xr:this})}invokeCallback_ControllerAdded(e,t){e.onXRControllerAdded&&e.onXRControllerAdded({xr:this,controller:t,change:"added"})}invokeCallback_ControllerRemoved(e,t){e.onXRControllerRemoved&&e.onXRControllerRemoved({xr:this,controller:t,change:"removed"})}invokeCallback_LeaveXR(e){e.onLeaveXR&&!e.destroyed&&e.onLeaveXR({xr:this})}syncCameraCullingMask(){const e=this.context.xrCamera,t=this.context.mainCameraComponent?.cullingMask;if(e&&t!==void 0){for(const i of e.cameras)i.layers.mask=t;e.layers.mask=t}else if(e){for(const i of e.cameras)i.layers.enableAll();e.layers.enableAll()}}invokeControllerEvent(e,t,i){for(let n=t.length-1;n>=0;n--){const s=t[n];if(s)try{s({xr:this,controller:e,change:i})}catch(r){console.error(r)}}}_camera;_cameraRenderParent=new M().rotateY(Math.PI);_previousCameraParent;_customforward=!0;originalCameraNearPlane;requestedCameraNearPlane=null;applyCustomForward(){if(this.context.mainCamera&&this._customforward){this._camera=this.context.mainCamera,this._camera.parent!==this._cameraRenderParent&&(this._previousCameraParent=this._camera.parent,this._previousCameraParent?.add(this._cameraRenderParent)),this._cameraRenderParent.name="XR Camera Render Parent",this._cameraRenderParent.add(this._camera);{let e=.02;const t=.001;if(this.rig){const i=$e(this.rig.gameObject);e*=i.x}this._camera instanceof de&&Math.abs(this._camera.near-e)>t&&(this.isAR?this.originalCameraNearPlane=this._camera.near:this._camera.near=e,Xe&&console.debug(`Setting camera near plane to ${e} (was ${this.originalCameraNearPlane}) to account for XR rendering scale`))}}}revertCustomForward(){this._camera&&this._previousCameraParent&&this._previousCameraParent.add(this._camera),this._previousCameraParent=null,this._camera instanceof de&&this.originalCameraNearPlane!=null&&(this._camera.near=this.originalCameraNearPlane,this.originalCameraNearPlane=void 0)}_viewerPose;_transformOrientation=new N;_transformPosition=new b;internalUpdateState(){const e=this.context.renderer.xr.getReferenceSpace();if(!e){this._viewerPose=void 0;return}if(this._viewerPose=this.frame.getViewerPose(e),this._viewerPose){const t=this._viewerPose.transform;this._transformPosition.set(t.position.x,t.position.y,t.position.z),this._transformOrientation.set(t.orientation.x,t.orientation.y,t.orientation.z,t.orientation.w)}}_transition;get transition(){return this._transition||(this._transition=new fv),this._transition}fadeTransition(){return this._transition||(this._transition=new fv),this._transition.fadeTransition()}updateFade(e){this._transition&&e instanceof de&&this._transition.update(e,this.context.time.deltaTime)}onUpdateFade_PostRender(){this._transition?.remove()}}const Fg=w("debugwebxr");class xv{static tryFindAvatarObjects(e,t,i){if(i.head&&i.leftHand&&i.rightHand)return;const n=e.name.toLocaleLowerCase();!i.head&&n.includes("head")&&(Fg&&console.log("FOUND AVATAR HEAD",e.name),i.head=new ne("",t,e)),n.includes("hand")&&(!i.leftHand&&n.includes("left")&&(Fg&&console.log("FOUND AVATAR LEFT HAND",e.name),i.leftHand=new ne("",t,e)),!i.rightHand&&n.includes("right")&&(Fg&&console.log("FOUND AVATAR RIGHT HAND",e.name),i.rightHand=new ne("",t,e)));for(let s=0;s<e.children.length;s++){if(i.head&&i.leftHand&&i.rightHand)return;const r=e.children[s];this.tryFindAvatarObjects(r,t,i)}}}class se extends oe{alpha=1;get isRGBAColor(){return!0}set a(e){this.alpha=e}get a(){return this.alpha}constructor(e,t,i,n){super(),typeof e=="number"&&typeof t=="number"&&typeof i=="number"?(this.set(e,t,i),this.alpha=typeof n=="number"?n:1):e!==void 0&&(this.set(e),this.alpha=1)}clone(){const e=super.clone();return e.alpha=this.alpha,e}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,"alpha"in e&&typeof e.alpha=="number"?this.alpha=e.alpha:typeof e.a=="number"&&(this.alpha=e.a),this}lerp(e,t){const i=e;return i.alpha!=null&&(this.alpha=D.lerp(this.alpha,i.alpha,t)),super.lerp(e,t)}lerpColors(e,t,i){const n=e,s=t;return n.alpha!=null&&s.alpha!=null&&(this.alpha=D.lerp(n.alpha,s.alpha,i)),super.lerpColors(e,t,i)}multiply(e){const t=e;return t.alpha!=null&&(this.alpha=this.alpha*t.alpha),super.multiply(e)}fromArray(e,t=0){return this.alpha=e[t+3],super.fromArray(e,t)}static fromColorRepresentation(e){if(typeof e=="string"){if(e.trim()==="transparent")return new se(0,0,0,0);if(e.startsWith("#")&&e.length===9){const t=parseInt(e.slice(1,9),16),i=t>>24&255,n=t>>16&255,s=t>>8&255,r=t>>0&255;return new se(i/255,n/255,s/255,r/255)}else if(e.startsWith("#")){const t=parseInt(e.slice(1),16),i=t>>16&255,n=t>>8&255,s=t>>0&255;return new se(i/255,n/255,s/255,1)}else if(e.startsWith("rgba")){const t=e.slice(5,-1).split(",").map(Number);return new se(t[0]/255,t[1]/255,t[2]/255,t[3])}else if(e.startsWith("rgb")){const t=e.slice(4,-1).split(",").map(Number);return new se(t[0]/255,t[1]/255,t[2]/255,1)}}else if(Array.isArray(e)){if(e.length===4)return new se(e[0],e[1],e[2],e[3]);if(e.length===3)return new se(e[0],e[1],e[2],1);console.error("Invalid color array length. Expected 3 or 4, got "+e.length)}return new se(e)}}const Ft=new b,Sv=new b,Cv=new N,eM=w("debuggizmos"),On=8947848,Ug=32;class B{constructor(){}static enabled=!0;static isGizmo(e){return e[zg]!==void 0}static setVisible(e){for(const t of Qi.timedObjectsBuffer)t.visible=e}static DrawLabel(e,t,i=.05,n=0,s,r,a){if(!B.enabled)return null;s||(s=On);const l=Z.active?.rigScale??1,c=Qi.getTextLabel(n,t,i*l,s,r);return a instanceof M&&a.add(c),c.position.x=e.x,c.position.y=e.y,c.position.z=e.z,c}static DrawRay(e,t,i=On,n=0,s=!0){if(!B.enabled)return;const r=Qi.getLine(n),a=r.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),Ft.set(t.x,t.y,t.z).multiplyScalar(999999999),a.setXYZ(1,e.x+Ft.x,e.y+Ft.y,e.z+Ft.z),a.needsUpdate=!0,r.material.depthTest=s,r.material.depthWrite=!1,r.material.fog=!1,kn(r.material,i)}static DrawDirection(e,t,i=On,n=0,s=!0,r=1){if(!B.enabled)return;const a=Qi.getLine(n),l=a.geometry.getAttribute("position");l.setXYZ(0,e.x,e.y,e.z),t.w!==void 0?(Ft.set(0,0,-r),Cv.set(t.x,t.y,t.z,t.w),Ft.applyQuaternion(Cv)):(Ft.set(t.x,t.y,t.z),Ft.multiplyScalar(r)),l.setXYZ(1,e.x+Ft.x,e.y+Ft.y,e.z+Ft.z),l.needsUpdate=!0,a.material.depthTest=s,a.material.depthWrite=!1,kn(a.material,i)}static DrawLine(e,t,i=On,n=0,s=!0){if(!B.enabled)return;const r=Qi.getLine(n),a=r.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),a.setXYZ(1,t.x,t.y,t.z),a.needsUpdate=!0,r.material.depthTest=s,r.material.depthWrite=!1,r.material.fog=!1,kn(r.material,i)}static DrawCircle(e,t,i,n=On,s=0,r=!0){if(!B.enabled)return;const a=Qi.getCircle(s);a.position.set(e.x,e.y,e.z),a.scale.set(i,i,i),a.quaternion.setFromUnitVectors(this._up,Ft.set(t.x,t.y,t.z).normalize()),a.material.depthTest=r,a.material.depthWrite=!1,a.material.fog=!1,kn(a.material,n)}static DrawWireSphere(e,t,i=On,n=0,s=!0){if(!B.enabled)return;const r=Qi.getSphere(t,n,!0);Sr(r,e.x,e.y,e.z),r.material.depthTest=s,r.material.depthWrite=!1,r.material.fog=!1,kn(r.material,i)}static DrawSphere(e,t,i=On,n=0,s=!0){if(!B.enabled)return;const r=Qi.getSphere(t,n,!1);Sr(r,e.x,e.y,e.z),r.material.depthTest=s,r.material.depthWrite=!1,kn(r.material,i)}static DrawWireBox(e,t,i=On,n=0,s=!0,r=void 0){if(!B.enabled)return;const a=Qi.getBox(n);a.position.set(e.x,e.y,e.z),a.scale.set(t.x,t.y,t.z),r?a.quaternion.copy(r):a.quaternion.identity(),a.material.depthTest=s,a.material.wireframe=!0,a.material.depthWrite=!1,a.material.fog=!1,kn(a.material,i)}static DrawWireBox3(e,t=On,i=0,n=!0){if(!B.enabled)return;const s=Qi.getBox(i);s.position.copy(e.getCenter(Ft)),s.scale.copy(e.getSize(Ft)),s.material.depthTest=n,s.material.wireframe=!0,s.material.depthWrite=!1,s.material.fog=!1,kn(s.material,t)}static _up=new b(0,1,0);static DrawArrow(e,t,i=On,n=0,s=!0,r=!1){if(!B.enabled)return;const a=Qi.getArrowHead(n);a.position.set(t.x,t.y,t.z),a.quaternion.setFromUnitVectors(this._up.set(0,1,0),Ft.set(t.x,t.y,t.z).sub(Sv.set(e.x,e.y,e.z)).normalize());const l=Ft.set(t.x,t.y,t.z).sub(Sv.set(e.x,e.y,e.z)).length()*.1;a.scale.set(l,l,l),a.material.depthTest=s,a.material.wireframe=r,kn(a.material,i),this.DrawLine(e,t,i,n,s)}static DrawWireMesh(e){const t=Qi.getMesh(e.duration??0);"mesh"in e?(t.geometry=e.mesh.geometry,t.matrixWorld.copy(e.mesh.matrixWorld)):(t.geometry=e.geometry,t.matrixWorld.copy(e.matrix)),t.matrixAutoUpdate=!1,t.matrixWorldAutoUpdate=!1,t.material.depthTest=e.depthTest??!0,t.material.wireframe=!0,kn(t.material,e.color??On)}}const tM=new Aa(1,1,1);function iu(o=null){const e=new oe(o??14540253),t=new ZS(tM);return new vb(t,new Em({color:e}))}function kn(o,e){if(Array.isArray(o)){for(const i of o)kn(i,e);return}const t=e instanceof se?e.a:1;o.color.set(e),o.opacity=t,o.transparent=t<1}const zg=Symbol("GizmoCache");class Qi{static familyName="needle-gizmos";static ensureFont(){let e=Pe.FontLibrary.getFontFamily(this.familyName);e||(e=Pe.FontLibrary.addFontFamily(this.familyName),e.addVariant("normal","normal","https://cdn.needle.tools/static/fonts/msdf/arial/arial-msdf.json","https://cdn.needle.tools/static/fonts/msdf/arial/arial.png")?.addEventListener("ready",()=>{Pe.update()}))}static getTextLabel(e,t,i,n,s){this.ensureFont();let r=this.textLabelCache.pop(),a=1;s&&typeof s=="string"&&s?.length>=8&&s.startsWith("#")?(a=parseInt(s.substring(7),16)/255,s=s.substring(0,7),eM&&console.log(s,a)):typeof s=="object"&&s.a!==void 0&&(a=s.a);const l={boxSizing:"border-box",fontFamily:this.familyName,width:"auto",fontSize:i,color:n,lineHeight:1,backgroundColor:s??void 0,backgroundOpacity:a,textContent:t,borderRadius:.5*i,padding:.8*i,whiteSpace:"pre",offset:.05*i};if(r)r.set(l);else{r=new Hb(l);const c=this,h=r;h.setText=function(d){this.set({textContent:d}),c.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(U.Current,r,e,this.textLabelCache),r}static getBox(e){let t=this.boxesCache.pop();if(!t){const i=new Aa(1,1,1);t=new H(i)}return this.registerTimedObject(U.Current,t,e,this.boxesCache),t}static getLine(e){let t=this.linesCache.pop();if(!t){t=new Ia;let i=t.geometry.getAttribute("position");i||(i=new ft(new Float32Array(6),3),t.geometry.setAttribute("position",i))}return t.frustumCulled=!1,this.registerTimedObject(U.Current,t,e,this.linesCache),t}static getCircle(e){let t=this.circlesCache.pop();if(!t){t=new Ia;let i=t.geometry.getAttribute("position");if(!i){i=new ft(new Float32Array(Ug*3),3),t.geometry.setAttribute("position",i);const n=F(0,1,0),s=F(0,0,1),r=F(s);r.cross(n).normalize();const a=F(r),l=Math.PI*2/(Ug-1);for(let c=0;c<Ug+1;c++){const h=l*c;n.copy(a).multiplyScalar(Math.cos(h)*1),r.copy(s).multiplyScalar(Math.sin(h)*1);const d=n.add(r);i.setXYZ(c,d.x,d.y,d.z)}}}return t.frustumCulled=!1,this.registerTimedObject(U.Current,t,e,this.circlesCache),t}static getSphere(e,t,i){let n=this.spheresCache.pop();return n||(n=new H(new Pd(1,8,8))),n.scale.set(e,e,e),n.material.wireframe=i,this.registerTimedObject(U.Current,n,t,this.spheresCache),n}static getArrowHead(e){let t=this.arrowHeadsCache.pop();return t||(t=new H(new bb(0,.5,1,8))),this.registerTimedObject(U.Current,t,e,this.arrowHeadsCache),t}static getMesh(e){let t=this.mesh.pop();return t||(t=new H,t.material=new Ce),this.registerTimedObject(U.Current,t,e,this.mesh),t}static linesCache=[];static circlesCache=[];static spheresCache=[];static boxesCache=[];static arrowHeadsCache=[];static mesh=[];static textLabelCache=[];static registerTimedObject(e,t,i,n){if(!e){console.error("No Needle Engine context available. Did you call a Gizmos function in global scope?");return}const s=this.contextBeforeRenderCallbacks.get(e),r=this.contextPostRenderCallbacks.get(e);if(s){if(e.pre_render_callbacks[e.pre_render_callbacks.length-1]!==s){const a=e.pre_render_callbacks.indexOf(s);a>=0&&e.pre_render_callbacks.splice(a,1),e.pre_render_callbacks.push(s)}}else{const a=()=>{this.onBeforeRender(e,this.timedObjectsBuffer)};this.contextBeforeRenderCallbacks.set(e,a),e.pre_render_callbacks.push(a)}if(r){if(e.post_render_callbacks[e.post_render_callbacks.length-1]!==r){const a=e.post_render_callbacks.indexOf(r);a>=0&&e.post_render_callbacks.splice(a,1),e.post_render_callbacks.push(r)}}else{const a=()=>{this.onPostRender(e,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(e,a),e.post_render_callbacks.push(a)}t.traverse(a=>{a.layers.disableAll(),a.layers.enable(2)}),t.renderOrder=999999,t[zg]=n,t.castShadow=!1,t.receiveShadow=!1,t.isGizmo=!0,this.timedObjectsBuffer.push(t),this.timesBuffer.push(U.Current.time.realtimeSinceStartup+i),e.scene.add(t)}static timedObjectsBuffer=new Array;static timesBuffer=new Array;static contextPostRenderCallbacks=new Map;static contextBeforeRenderCallbacks=new Map;static tmuiNeedsUpdate=!1;static onBeforeRender(e,t){this.tmuiNeedsUpdate&&(this.tmuiNeedsUpdate=!1,Pe.update());for(let i=0;i<t.length;i++){const n=t[i];if(e.mainCamera&&n instanceof Pe.MeshUIBaseElement){if(Br(n))continue;const s=e.isInVR,r=!1,a=!s;gc(n,e.mainCamera,r,a)}}}static onPostRender(e,t,i){const n=e.time.realtimeSinceStartup;for(let s=t.length-1;s>=0;s--){const r=t[s];n>=i[s]-1e-6&&(t.splice(s,1),i.splice(s,1),r.removeFromParent(),Br(r)!=!0&&r[zg].push(r))}}}const Kt=w("debugphysics"),iM=w("debugworker"),Pv=new _s;class ks{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 K),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setLayer(e){Pv.set(e),this.layerMask=Pv}setMask(e){this.layerMask||(this.layerMask=new _s);const t=this.layerMask;t?t.mask=e:this.layerMask=e}}class Ng{distance;point;object;constructor(e,t,i){this.object=e,this.distance=t,this.point=i}}class oc{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 Od;defaultRaycastOptions=new ks;targetBuffer=new Array(1);defaultThresholds={Mesh:{},Line:{threshold:-1},LOD:{},Points:{threshold:0},Sprite:{}};sphereResults=new Array;sphereMask=new _s;sphere=new kd;sphereOverlap(e,t,i=!0,n=!1,s=null){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;const r=this.sphereMask;r.enableAll(),r.disable(2);for(const a of this.context.scene.children)this.intersectSphere(a,e,t,r,this.sphereResults,i,n,s);return this.sphereResults.sort((a,l)=>a.distance-l.distance)}raycastFromRay(e,t=null){const i=t??this.defaultRaycastOptions;i.ray=e;const n=this.raycast(i);return i===this.defaultRaycastOptions&&(i.ray=void 0),n}raycast(e=null){Kt&&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 Kt&&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 KS&&l.cameras.length>0?i.setFromCamera(t,l.cameras[0]):i.setFromCamera(t,a)}let n=e.targets;n||(n=this.targetBuffer,n.length=1,n[0]=this.context.scene);let s=e.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),s||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),s=this.defaultRaycastOptions.results),e.layerMask!==void 0?e.layerMask instanceof _s?i.layers.mask=e.layerMask.mask:i.layers.mask=e.layerMask:(i.layers.enableAll(),i.layers.disable(2)),Kt&&console.time("raycast"),s.length=0,oc._raycasting++,this.intersect(this.raycaster,n,s,e),s.sort((a,l)=>a.distance-l.distance);const r=e.ignore;return r!==void 0&&r.length>0&&(s=s.filter(a=>!r.includes(a.object))),oc._raycasting--,Kt&&(console.timeEnd("raycast"),console.warn("#"+this.context.time.frame+", hits:",s?.length?[...s]:"nothing"),performance.mark("raycast.end"),performance.measure("raycast","raycast.start","raycast.end")),s}intersect(e,t,i,n){for(const s of t){if(!s||s.visible===!1||B.isGizmo(s)||n.lineThreshold!==void 0&&n.lineThreshold<0&&s instanceof Ia)continue;let r=!0;const a=s,l=a.geometry;if(s.raycastAllowed===!1&&(r=!1),r&&n.testObject){const c=n.testObject?.(s);if(c===!1)continue;c==="continue in children"&&(r=!1)}else r&&(l&&Ov(l)||(r=!1));if(r){const c=i.length,h=s.raycastPreference||"lod";let d=h!=="bounds";if(n.precise===!1&&(d=!1),l&&(d||=l.getAttribute("position")?.array?.length<64),a instanceof Da&&(d=!1),h==="lod"){const p=Ib(s);p&&(a.geometry=p)}if(!d&&oM(a,e,i)||(n.useAcceleratedRaycast!==!1?ou.runMeshBVHRaycast(e,a,i,this.context,n):e.intersectObject(a,!1,i)),a.geometry=l,Kt&&i.length!=c){const p=i[i.length-1];B.DrawWireSphere(p.point,.1,7798784,1,!1),B.DrawWireMesh({mesh:s,depthTest:!1,duration:.2,color:7798784})}}n.recursive!==!1&&this.intersect(e,s.children,i,n)}return i}tempBoundingBox=new Yt;intersectSphere(e,t,i,n,s,r,a,l){let c=e&&e.isMesh&&e.layers.test(n)&&!B.isGizmo(e);c&&=e.visible,c&&=!(e instanceof Ia),c&&=!(e instanceof Da);const h=e,d=h.geometry;if(c&&l){const p=l(e);if(p===!1)return;p==="continue in children"&&(c=!1)}if(d&&Ov(d)||(c=!1),c){if(a){const p=this.sphere;p.center.copy(t),p.radius=i;const m=s.length;if(ou.runMeshBVHRaycast(this.sphere,h,s,this.context,{}),m!=s.length&&!r)return}else if(d.boundingBox||d.computeBoundingBox(),d.boundingBox){h.matrixWorldNeedsUpdate&&h.updateWorldMatrix(!1,!1);const p=this.tempBoundingBox.copy(d.boundingBox).applyMatrix4(h.matrixWorld),m=this.sphere;if(m.center.copy(t),m.radius=i,m.intersectsBox(p)){const g=ee(e),f=g.distanceTo(m.center),y=new Ng(e,f,g);if(s.push(y),!r)return}}}if(e.children)for(const p of e.children){const m=s.length;if(this.intersectSphere(p,t,i,n,s,r,a,l),m!=s.length&&!r)return}}}function Ov(o){return!(o.index&&o.index.array.length<3)}const Tr=new kd,nu=new _r,nM=new yb;function oM(o,e,t){const i=o._computeIntersections;if(!i)return!1;let n=o["_computeIntersections:Needle"];return n||(n=o["_computeIntersections:Needle"]=function(s,r,a){const l=this,c=l.geometry.boundingSphere;if(c){if(l instanceof Da){nu.setFromNormalAndCoplanarPoint(F(0,1,0),F(0,-l.position.y,0)),nu.applyMatrix4(l.matrixWorld,nM);const d=s.ray.intersectPlane(nu,F());if(d){Tr.copy(c),Tr.applyMatrix4(l.matrixWorld);const p=F(d).sub(s.ray.origin).length(),m=Tr.radius*.5;p<m&&r.push({distance:p,point:d,object:l,normal:nu.normal.clone()})}return}Tr.copy(c),Tr.applyMatrix4(l.matrixWorld);const h=s.ray.intersectSphere(Tr,F());if(h){const d=F(h).sub(s.ray.origin),p=d.length();if(p>Tr.radius){const m=d.clone().normalize();r.push({distance:p,point:h,object:l,normal:m})}}}}),o._computeIntersections=n,e.intersectObject(o,!1,t),o._computeIntersections=i,!0}var ou;(o=>{let e=0;function t(v,P,k,O,j){if(!P.geometry||!P.geometry.hasAttribute("position"))return!1;const L=P.geometry;if(P?.isSkinnedMesh){const V=P,W=V.bvhNeedsUpdate;if(!V.staticGenerator)l(),r&&(V.staticGenerator=new r(P),V.staticGenerator.applyWorldTransforms=!1,V.staticGeometry=V.staticGenerator.generate(),L.boundsTree=a?.call(V.staticGeometry),V.staticGeometryLastUpdate=performance.now()+Math.random()*200,V.bvhNeedsUpdate=!0);else if(L.boundsTree&&(V.autoUpdateMeshBvhInterval!==void 0&&V.autoUpdateMeshBvhInterval>=0||W===!0)){const G=performance.now(),X=G-V.staticGeometryLastUpdate,R=V.autoUpdateMeshBvhInterval??100;(W||X>R)&&(Kt&&console.warn(`Physics: updating skinned mesh bvh for ${P.name} after ${X.toFixed(2)}ms`),V.bvhNeedsUpdate=!1,V.staticGeometryLastUpdate=G,V.staticGenerator?.generate(V.staticGeometry),L.boundsTree.refit())}}else if(!L.boundsTree){h||_();let V=!0;if((O.xr||L[g]===!1||L.getAttribute("position")?.isInterleavedBufferAttribute||L.index&&L.index?.isInterleavedBufferAttribute||e>10)&&(V=!1),V&&p){if(L[m]===void 0){let W=null;if(y.length>0){const G=y.shift();G&&!G.running&&(W=G)}if(!W&&f.length<3)try{iM&&console.warn("[GenerateMeshBVHWorker] Creating worker with import.meta.url:",import.meta.url),W=new p,f.push(W)}catch(G){G instanceof DOMException&&G.name==="SecurityError"?(console.warn("Failed to create MeshBVH worker, falling back to main thread generation. This can happen when running from file://, if the browser does not support workers or if the browser is blocking workers for other reasons."),console.debug(G),e+=10):(console.error("Failed to create MeshBVH worker. Please see below for more details:"),console.log(G)),e++}if(W!=null&&!W.running){const G=P.name;Kt&&console.log("<<<< worker start",G,W),L[m]="queued",performance.mark("bvh.create.start");const X=L.clone();try{W.generate(X).then(R=>{L[m]="done",L.boundsTree=R}).catch(R=>{L[m]="failed - "+R?.message,L[g]=!1,Kt&&console.error("Failed to generate mesh bvh on worker",R)}).finally(()=>{Kt&&console.log(">>>>> worker done",G,{hasBoundsTre:L.boundsTree!=null}),y.push(W),X.dispose(),performance.mark("bvh.create.end"),performance.measure("bvh.create (worker)","bvh.create.start","bvh.create.end")})}catch(R){console.error("Failed to generate mesh bvh on worker",R)}}else Kt&&console.warn("No worker available")}}else(!d||!V)&&(l(),s&&(performance.mark("bvh.create.start"),L.boundsTree=new s(L),performance.mark("bvh.create.end"),performance.measure("bvh.create","bvh.create.start","bvh.create.end")))}if(v instanceof Od){const V=v,W=P.raycast;if(L.boundsTree)l(),n&&(P.acceleratedRaycast||(P.acceleratedRaycast=n.bind(P),Kt&&console.debug(`Physics: bind acceleratedRaycast fn to "${P.name}"`)),P.raycast=P.acceleratedRaycast);else if(Kt&&console.warn("No bounds tree found for mesh",P.name,{workerTask:L[m],hasAcceleratedRaycast:n!=null}),j.allowSlowRaycastFallback===!1&&(L.getAttribute("position")?.array?.length??0)>2e3)return Kt&&console.warn("Skipping raycast because no bounds tree is available and allowSlowRaycastFallback is false"),!1;const G=V.firstHitOnly;return V.firstHitOnly=!1,V.intersectObject(P,!1,k),V.firstHitOnly=G,P.raycast=W,!0}else if(v instanceof kd){const V=L.boundsTree;if(V){const W=v;if(c.copy(P.matrixWorld).invert(),W.applyMatrix4(c),V.intersectsSphere(W)){const G=ee(P),X=G.distanceTo(W.center),R=new Ng(P,X,G);k.push(R)}}return!0}return!1}o.runMeshBVHRaycast=t;let i=!1,n=null,s=null,r=null,a=null;function l(){i||(i=!0,import("./vendor-DZ45lcA8.min.js").then(v=>v.index$1).then(v=>{n=v.acceleratedRaycast,s=v.MeshBVH,r=v.StaticGeometryGenerator,a=v.computeBoundsTree}).catch(v=>{(Kt||A())&&console.error("Failed to load BVH library...",v.message)}))}const c=new J;let h=!1,d=!1,p=null;const m=Symbol("Needle:MeshBVH-Worker"),g=Symbol("Needle:MeshBVH-CanUseWorker"),f=[],y=[];function _(){h=!0,d=!0,Promise.resolve().then(()=>cj).then(v=>{p=v.GenerateMeshBVHWorker}).catch(v=>{Kt||A()?console.warn("Failed to setup mesh bvh worker"):console.debug("Failed to setup mesh bvh worker",v)}).finally(()=>{d=!1})}})(ou||(ou={}));const kv=Symbol("gltf-loader-internal-usage-tracker"),sM=w("debugusers");class sc{get name(){return"NEEDLE_internal_usage_tracker"}static isLoading(e){return sc._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(){sc._loadingProcesses++;const e=this,t=this._getDependency;return this.parser.getDependency=function(i,n){const s=t.call(this,i,n);return s.then(r=>(r&&(e._loadedObjects.add(r),r[kv]=e._loadingId),r)),s},null}afterRoot(e){sc._loadingProcesses--,this.parser.getDependency=this._getDependency;for(const t of this._loadedObjects)delete t[kv],t instanceof M&&(t.parent||t instanceof H&&setTimeout(()=>{sM&&console.warn("> GLTF LOADER: Mesh not used in scene!",t),t.material=null,t.geometry=null},1e3));return null}}class Mv{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:
|
|
176
|
+
${s.hand?"hand":"ctrl"} ${s.inputSource.handedness}[${s.index}] con:${s.connected} tr:${s.isTracking} hts:${s.hasHitTestSource?"yes":"no"}`;jg=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 de&&(this.context.mainCamera.near=this.requestedCameraNearPlane,this.requestedCameraNearPlane=null))};onAfterRender=()=>{if(this.onUpdateFade_PostRender(),I.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:(Xe&&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){Xe&&console.log("Remove XRScript",e);const i=this._xr_scripts.indexOf(e);i>=0&&this._xr_scripts.splice(i,1);const n=this._xr_update_scripts.indexOf(e);if(n>=0&&this._xr_update_scripts.splice(n,1),t){const s=this._inactive_scripts.indexOf(e);s>=0&&this._inactive_scripts.splice(s,1)}}invokeCallback_EnterXR(e){e.onEnterXR&&e.onEnterXR({xr:this})}invokeCallback_ControllerAdded(e,t){e.onXRControllerAdded&&e.onXRControllerAdded({xr:this,controller:t,change:"added"})}invokeCallback_ControllerRemoved(e,t){e.onXRControllerRemoved&&e.onXRControllerRemoved({xr:this,controller:t,change:"removed"})}invokeCallback_LeaveXR(e){e.onLeaveXR&&!e.destroyed&&e.onLeaveXR({xr:this})}syncCameraCullingMask(){const e=this.context.xrCamera,t=this.context.mainCameraComponent?.cullingMask;if(e&&t!==void 0){for(const i of e.cameras)i.layers.mask=t;e.layers.mask=t}else if(e){for(const i of e.cameras)i.layers.enableAll();e.layers.enableAll()}}invokeControllerEvent(e,t,i){for(let n=t.length-1;n>=0;n--){const s=t[n];if(s)try{s({xr:this,controller:e,change:i})}catch(r){console.error(r)}}}_camera;_cameraRenderParent=new M().rotateY(Math.PI);_previousCameraParent;_customforward=!0;originalCameraNearPlane;requestedCameraNearPlane=null;applyCustomForward(){if(this.context.mainCamera&&this._customforward){this._camera=this.context.mainCamera,this._camera.parent!==this._cameraRenderParent&&(this._previousCameraParent=this._camera.parent,this._previousCameraParent?.add(this._cameraRenderParent)),this._cameraRenderParent.name="XR Camera Render Parent",this._cameraRenderParent.add(this._camera);{let e=.02;const t=.001;if(this.rig){const i=$e(this.rig.gameObject);e*=i.x}this._camera instanceof de&&Math.abs(this._camera.near-e)>t&&(this.isAR?this.originalCameraNearPlane=this._camera.near:this._camera.near=e,Xe&&console.debug(`Setting camera near plane to ${e} (was ${this.originalCameraNearPlane}) to account for XR rendering scale`))}}}revertCustomForward(){this._camera&&this._previousCameraParent&&this._previousCameraParent.add(this._camera),this._previousCameraParent=null,this._camera instanceof de&&this.originalCameraNearPlane!=null&&(this._camera.near=this.originalCameraNearPlane,this.originalCameraNearPlane=void 0)}_viewerPose;_transformOrientation=new N;_transformPosition=new b;internalUpdateState(){const e=this.context.renderer.xr.getReferenceSpace();if(!e){this._viewerPose=void 0;return}if(this._viewerPose=this.frame.getViewerPose(e),this._viewerPose){const t=this._viewerPose.transform;this._transformPosition.set(t.position.x,t.position.y,t.position.z),this._transformOrientation.set(t.orientation.x,t.orientation.y,t.orientation.z,t.orientation.w)}}_transition;get transition(){return this._transition||(this._transition=new fv),this._transition}fadeTransition(){return this._transition||(this._transition=new fv),this._transition.fadeTransition()}updateFade(e){this._transition&&e instanceof de&&this._transition.update(e,this.context.time.deltaTime)}onUpdateFade_PostRender(){this._transition?.remove()}}const Fg=w("debugwebxr");class xv{static tryFindAvatarObjects(e,t,i){if(i.head&&i.leftHand&&i.rightHand)return;const n=e.name.toLocaleLowerCase();!i.head&&n.includes("head")&&(Fg&&console.log("FOUND AVATAR HEAD",e.name),i.head=new ne("",t,e)),n.includes("hand")&&(!i.leftHand&&n.includes("left")&&(Fg&&console.log("FOUND AVATAR LEFT HAND",e.name),i.leftHand=new ne("",t,e)),!i.rightHand&&n.includes("right")&&(Fg&&console.log("FOUND AVATAR RIGHT HAND",e.name),i.rightHand=new ne("",t,e)));for(let s=0;s<e.children.length;s++){if(i.head&&i.leftHand&&i.rightHand)return;const r=e.children[s];this.tryFindAvatarObjects(r,t,i)}}}class se extends oe{alpha=1;get isRGBAColor(){return!0}set a(e){this.alpha=e}get a(){return this.alpha}constructor(e,t,i,n){super(),typeof e=="number"&&typeof t=="number"&&typeof i=="number"?(this.set(e,t,i),this.alpha=typeof n=="number"?n:1):e!==void 0&&(this.set(e),this.alpha=1)}clone(){const e=super.clone();return e.alpha=this.alpha,e}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,"alpha"in e&&typeof e.alpha=="number"?this.alpha=e.alpha:typeof e.a=="number"&&(this.alpha=e.a),this}lerp(e,t){const i=e;return i.alpha!=null&&(this.alpha=j.lerp(this.alpha,i.alpha,t)),super.lerp(e,t)}lerpColors(e,t,i){const n=e,s=t;return n.alpha!=null&&s.alpha!=null&&(this.alpha=j.lerp(n.alpha,s.alpha,i)),super.lerpColors(e,t,i)}multiply(e){const t=e;return t.alpha!=null&&(this.alpha=this.alpha*t.alpha),super.multiply(e)}fromArray(e,t=0){return this.alpha=e[t+3],super.fromArray(e,t)}static fromColorRepresentation(e){if(typeof e=="string"){if(e.trim()==="transparent")return new se(0,0,0,0);if(e.startsWith("#")&&e.length===9){const t=parseInt(e.slice(1,9),16),i=t>>24&255,n=t>>16&255,s=t>>8&255,r=t>>0&255;return new se(i/255,n/255,s/255,r/255)}else if(e.startsWith("#")){const t=parseInt(e.slice(1),16),i=t>>16&255,n=t>>8&255,s=t>>0&255;return new se(i/255,n/255,s/255,1)}else if(e.startsWith("rgba")){const t=e.slice(5,-1).split(",").map(Number);return new se(t[0]/255,t[1]/255,t[2]/255,t[3])}else if(e.startsWith("rgb")){const t=e.slice(4,-1).split(",").map(Number);return new se(t[0]/255,t[1]/255,t[2]/255,1)}}else if(Array.isArray(e)){if(e.length===4)return new se(e[0],e[1],e[2],e[3]);if(e.length===3)return new se(e[0],e[1],e[2],1);console.error("Invalid color array length. Expected 3 or 4, got "+e.length)}return new se(e)}}const Ft=new b,Sv=new b,Cv=new N,eM=w("debuggizmos"),On=8947848,Ug=32;class B{constructor(){}static enabled=!0;static isGizmo(e){return e[zg]!==void 0}static setVisible(e){for(const t of Qi.timedObjectsBuffer)t.visible=e}static DrawLabel(e,t,i=.05,n=0,s,r,a){if(!B.enabled)return null;s||(s=On);const l=Z.active?.rigScale??1,c=Qi.getTextLabel(n,t,i*l,s,r);return a instanceof M&&a.add(c),c.position.x=e.x,c.position.y=e.y,c.position.z=e.z,c}static DrawRay(e,t,i=On,n=0,s=!0){if(!B.enabled)return;const r=Qi.getLine(n),a=r.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),Ft.set(t.x,t.y,t.z).multiplyScalar(999999999),a.setXYZ(1,e.x+Ft.x,e.y+Ft.y,e.z+Ft.z),a.needsUpdate=!0,r.material.depthTest=s,r.material.depthWrite=!1,r.material.fog=!1,kn(r.material,i)}static DrawDirection(e,t,i=On,n=0,s=!0,r=1){if(!B.enabled)return;const a=Qi.getLine(n),l=a.geometry.getAttribute("position");l.setXYZ(0,e.x,e.y,e.z),t.w!==void 0?(Ft.set(0,0,-r),Cv.set(t.x,t.y,t.z,t.w),Ft.applyQuaternion(Cv)):(Ft.set(t.x,t.y,t.z),Ft.multiplyScalar(r)),l.setXYZ(1,e.x+Ft.x,e.y+Ft.y,e.z+Ft.z),l.needsUpdate=!0,a.material.depthTest=s,a.material.depthWrite=!1,kn(a.material,i)}static DrawLine(e,t,i=On,n=0,s=!0){if(!B.enabled)return;const r=Qi.getLine(n),a=r.geometry.getAttribute("position");a.setXYZ(0,e.x,e.y,e.z),a.setXYZ(1,t.x,t.y,t.z),a.needsUpdate=!0,r.material.depthTest=s,r.material.depthWrite=!1,r.material.fog=!1,kn(r.material,i)}static DrawCircle(e,t,i,n=On,s=0,r=!0){if(!B.enabled)return;const a=Qi.getCircle(s);a.position.set(e.x,e.y,e.z),a.scale.set(i,i,i),a.quaternion.setFromUnitVectors(this._up,Ft.set(t.x,t.y,t.z).normalize()),a.material.depthTest=r,a.material.depthWrite=!1,a.material.fog=!1,kn(a.material,n)}static DrawWireSphere(e,t,i=On,n=0,s=!0){if(!B.enabled)return;const r=Qi.getSphere(t,n,!0);Sr(r,e.x,e.y,e.z),r.material.depthTest=s,r.material.depthWrite=!1,r.material.fog=!1,kn(r.material,i)}static DrawSphere(e,t,i=On,n=0,s=!0){if(!B.enabled)return;const r=Qi.getSphere(t,n,!1);Sr(r,e.x,e.y,e.z),r.material.depthTest=s,r.material.depthWrite=!1,kn(r.material,i)}static DrawWireBox(e,t,i=On,n=0,s=!0,r=void 0){if(!B.enabled)return;const a=Qi.getBox(n);a.position.set(e.x,e.y,e.z),a.scale.set(t.x,t.y,t.z),r?a.quaternion.copy(r):a.quaternion.identity(),a.material.depthTest=s,a.material.wireframe=!0,a.material.depthWrite=!1,a.material.fog=!1,kn(a.material,i)}static DrawWireBox3(e,t=On,i=0,n=!0){if(!B.enabled)return;const s=Qi.getBox(i);s.position.copy(e.getCenter(Ft)),s.scale.copy(e.getSize(Ft)),s.material.depthTest=n,s.material.wireframe=!0,s.material.depthWrite=!1,s.material.fog=!1,kn(s.material,t)}static _up=new b(0,1,0);static DrawArrow(e,t,i=On,n=0,s=!0,r=!1){if(!B.enabled)return;const a=Qi.getArrowHead(n);a.position.set(t.x,t.y,t.z),a.quaternion.setFromUnitVectors(this._up.set(0,1,0),Ft.set(t.x,t.y,t.z).sub(Sv.set(e.x,e.y,e.z)).normalize());const l=Ft.set(t.x,t.y,t.z).sub(Sv.set(e.x,e.y,e.z)).length()*.1;a.scale.set(l,l,l),a.material.depthTest=s,a.material.wireframe=r,kn(a.material,i),this.DrawLine(e,t,i,n,s)}static DrawWireMesh(e){const t=Qi.getMesh(e.duration??0);"mesh"in e?(t.geometry=e.mesh.geometry,t.matrixWorld.copy(e.mesh.matrixWorld)):(t.geometry=e.geometry,t.matrixWorld.copy(e.matrix)),t.matrixAutoUpdate=!1,t.matrixWorldAutoUpdate=!1,t.material.depthTest=e.depthTest??!0,t.material.wireframe=!0,kn(t.material,e.color??On)}}const tM=new Aa(1,1,1);function iu(o=null){const e=new oe(o??14540253),t=new ZS(tM);return new vb(t,new Em({color:e}))}function kn(o,e){if(Array.isArray(o)){for(const i of o)kn(i,e);return}const t=e instanceof se?e.a:1;o.color.set(e),o.opacity=t,o.transparent=t<1}const zg=Symbol("GizmoCache");class Qi{static familyName="needle-gizmos";static ensureFont(){let e=Pe.FontLibrary.getFontFamily(this.familyName);e||(e=Pe.FontLibrary.addFontFamily(this.familyName),e.addVariant("normal","normal","https://cdn.needle.tools/static/fonts/msdf/arial/arial-msdf.json","https://cdn.needle.tools/static/fonts/msdf/arial/arial.png")?.addEventListener("ready",()=>{Pe.update()}))}static getTextLabel(e,t,i,n,s){this.ensureFont();let r=this.textLabelCache.pop(),a=1;s&&typeof s=="string"&&s?.length>=8&&s.startsWith("#")?(a=parseInt(s.substring(7),16)/255,s=s.substring(0,7),eM&&console.log(s,a)):typeof s=="object"&&s.a!==void 0&&(a=s.a);const l={boxSizing:"border-box",fontFamily:this.familyName,width:"auto",fontSize:i,color:n,lineHeight:1,backgroundColor:s??void 0,backgroundOpacity:a,textContent:t,borderRadius:.5*i,padding:.8*i,whiteSpace:"pre",offset:.05*i};if(r)r.set(l);else{r=new Hb(l);const c=this,h=r;h.setText=function(d){this.set({textContent:d}),c.tmuiNeedsUpdate=!0}}return this.tmuiNeedsUpdate=!0,this.registerTimedObject(U.Current,r,e,this.textLabelCache),r}static getBox(e){let t=this.boxesCache.pop();if(!t){const i=new Aa(1,1,1);t=new H(i)}return this.registerTimedObject(U.Current,t,e,this.boxesCache),t}static getLine(e){let t=this.linesCache.pop();if(!t){t=new Ia;let i=t.geometry.getAttribute("position");i||(i=new ft(new Float32Array(6),3),t.geometry.setAttribute("position",i))}return t.frustumCulled=!1,this.registerTimedObject(U.Current,t,e,this.linesCache),t}static getCircle(e){let t=this.circlesCache.pop();if(!t){t=new Ia;let i=t.geometry.getAttribute("position");if(!i){i=new ft(new Float32Array(Ug*3),3),t.geometry.setAttribute("position",i);const n=F(0,1,0),s=F(0,0,1),r=F(s);r.cross(n).normalize();const a=F(r),l=Math.PI*2/(Ug-1);for(let c=0;c<Ug+1;c++){const h=l*c;n.copy(a).multiplyScalar(Math.cos(h)*1),r.copy(s).multiplyScalar(Math.sin(h)*1);const d=n.add(r);i.setXYZ(c,d.x,d.y,d.z)}}}return t.frustumCulled=!1,this.registerTimedObject(U.Current,t,e,this.circlesCache),t}static getSphere(e,t,i){let n=this.spheresCache.pop();return n||(n=new H(new Pd(1,8,8))),n.scale.set(e,e,e),n.material.wireframe=i,this.registerTimedObject(U.Current,n,t,this.spheresCache),n}static getArrowHead(e){let t=this.arrowHeadsCache.pop();return t||(t=new H(new bb(0,.5,1,8))),this.registerTimedObject(U.Current,t,e,this.arrowHeadsCache),t}static getMesh(e){let t=this.mesh.pop();return t||(t=new H,t.material=new Ce),this.registerTimedObject(U.Current,t,e,this.mesh),t}static linesCache=[];static circlesCache=[];static spheresCache=[];static boxesCache=[];static arrowHeadsCache=[];static mesh=[];static textLabelCache=[];static registerTimedObject(e,t,i,n){if(!e){console.error("No Needle Engine context available. Did you call a Gizmos function in global scope?");return}const s=this.contextBeforeRenderCallbacks.get(e),r=this.contextPostRenderCallbacks.get(e);if(s){if(e.pre_render_callbacks[e.pre_render_callbacks.length-1]!==s){const a=e.pre_render_callbacks.indexOf(s);a>=0&&e.pre_render_callbacks.splice(a,1),e.pre_render_callbacks.push(s)}}else{const a=()=>{this.onBeforeRender(e,this.timedObjectsBuffer)};this.contextBeforeRenderCallbacks.set(e,a),e.pre_render_callbacks.push(a)}if(r){if(e.post_render_callbacks[e.post_render_callbacks.length-1]!==r){const a=e.post_render_callbacks.indexOf(r);a>=0&&e.post_render_callbacks.splice(a,1),e.post_render_callbacks.push(r)}}else{const a=()=>{this.onPostRender(e,this.timedObjectsBuffer,this.timesBuffer)};this.contextPostRenderCallbacks.set(e,a),e.post_render_callbacks.push(a)}t.traverse(a=>{a.layers.disableAll(),a.layers.enable(2)}),t.renderOrder=999999,t[zg]=n,t.castShadow=!1,t.receiveShadow=!1,t.isGizmo=!0,this.timedObjectsBuffer.push(t),this.timesBuffer.push(U.Current.time.realtimeSinceStartup+i),e.scene.add(t)}static timedObjectsBuffer=new Array;static timesBuffer=new Array;static contextPostRenderCallbacks=new Map;static contextBeforeRenderCallbacks=new Map;static tmuiNeedsUpdate=!1;static onBeforeRender(e,t){this.tmuiNeedsUpdate&&(this.tmuiNeedsUpdate=!1,Pe.update());for(let i=0;i<t.length;i++){const n=t[i];if(e.mainCamera&&n instanceof Pe.MeshUIBaseElement){if(Br(n))continue;const s=e.isInVR,r=!1,a=!s;gc(n,e.mainCamera,r,a)}}}static onPostRender(e,t,i){const n=e.time.realtimeSinceStartup;for(let s=t.length-1;s>=0;s--){const r=t[s];n>=i[s]-1e-6&&(t.splice(s,1),i.splice(s,1),r.removeFromParent(),Br(r)!=!0&&r[zg].push(r))}}}const Kt=w("debugphysics"),iM=w("debugworker"),Pv=new _s;class ks{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 K),this.screenPoint.x=e/window.innerWidth*2-1,this.screenPoint.y=-(t/window.innerHeight)*2+1}setLayer(e){Pv.set(e),this.layerMask=Pv}setMask(e){this.layerMask||(this.layerMask=new _s);const t=this.layerMask;t?t.mask=e:this.layerMask=e}}class Ng{distance;point;object;constructor(e,t,i){this.object=e,this.distance=t,this.point=i}}class oc{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 Od;defaultRaycastOptions=new ks;targetBuffer=new Array(1);defaultThresholds={Mesh:{},Line:{threshold:-1},LOD:{},Points:{threshold:0},Sprite:{}};sphereResults=new Array;sphereMask=new _s;sphere=new kd;sphereOverlap(e,t,i=!0,n=!1,s=null){if(this.sphereResults.length=0,!this.context.scene)return this.sphereResults;const r=this.sphereMask;r.enableAll(),r.disable(2);for(const a of this.context.scene.children)this.intersectSphere(a,e,t,r,this.sphereResults,i,n,s);return this.sphereResults.sort((a,l)=>a.distance-l.distance)}raycastFromRay(e,t=null){const i=t??this.defaultRaycastOptions;i.ray=e;const n=this.raycast(i);return i===this.defaultRaycastOptions&&(i.ray=void 0),n}raycast(e=null){Kt&&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 Kt&&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 KS&&l.cameras.length>0?i.setFromCamera(t,l.cameras[0]):i.setFromCamera(t,a)}let n=e.targets;n||(n=this.targetBuffer,n.length=1,n[0]=this.context.scene);let s=e.results;this.defaultRaycastOptions.results&&(this.defaultRaycastOptions.results.length=0),s||(this.defaultRaycastOptions.results||(this.defaultRaycastOptions.results=new Array),s=this.defaultRaycastOptions.results),e.layerMask!==void 0?e.layerMask instanceof _s?i.layers.mask=e.layerMask.mask:i.layers.mask=e.layerMask:(i.layers.enableAll(),i.layers.disable(2)),Kt&&console.time("raycast"),s.length=0,oc._raycasting++,this.intersect(this.raycaster,n,s,e),s.sort((a,l)=>a.distance-l.distance);const r=e.ignore;return r!==void 0&&r.length>0&&(s=s.filter(a=>!r.includes(a.object))),oc._raycasting--,Kt&&(console.timeEnd("raycast"),console.warn("#"+this.context.time.frame+", hits:",s?.length?[...s]:"nothing"),performance.mark("raycast.end"),performance.measure("raycast","raycast.start","raycast.end")),s}intersect(e,t,i,n){for(const s of t){if(!s||s.visible===!1||B.isGizmo(s)||n.lineThreshold!==void 0&&n.lineThreshold<0&&s instanceof Ia)continue;let r=!0;const a=s,l=a.geometry;if(s.raycastAllowed===!1&&(r=!1),r&&n.testObject){const c=n.testObject?.(s);if(c===!1)continue;c==="continue in children"&&(r=!1)}else r&&(l&&Ov(l)||(r=!1));if(r){const c=i.length,h=s.raycastPreference||"lod";let d=h!=="bounds";if(n.precise===!1&&(d=!1),l&&(d||=l.getAttribute("position")?.array?.length<64),a instanceof Da&&(d=!1),h==="lod"){const p=Ib(s);p&&(a.geometry=p)}if(!d&&oM(a,e,i)||(n.useAcceleratedRaycast!==!1?ou.runMeshBVHRaycast(e,a,i,this.context,n):e.intersectObject(a,!1,i)),a.geometry=l,Kt&&i.length!=c){const p=i[i.length-1];B.DrawWireSphere(p.point,.1,7798784,1,!1),B.DrawWireMesh({mesh:s,depthTest:!1,duration:.2,color:7798784})}}n.recursive!==!1&&this.intersect(e,s.children,i,n)}return i}tempBoundingBox=new Yt;intersectSphere(e,t,i,n,s,r,a,l){let c=e&&e.isMesh&&e.layers.test(n)&&!B.isGizmo(e);c&&=e.visible,c&&=!(e instanceof Ia),c&&=!(e instanceof Da);const h=e,d=h.geometry;if(c&&l){const p=l(e);if(p===!1)return;p==="continue in children"&&(c=!1)}if(d&&Ov(d)||(c=!1),c){if(a){const p=this.sphere;p.center.copy(t),p.radius=i;const m=s.length;if(ou.runMeshBVHRaycast(this.sphere,h,s,this.context,{}),m!=s.length&&!r)return}else if(d.boundingBox||d.computeBoundingBox(),d.boundingBox){h.matrixWorldNeedsUpdate&&h.updateWorldMatrix(!1,!1);const p=this.tempBoundingBox.copy(d.boundingBox).applyMatrix4(h.matrixWorld),m=this.sphere;if(m.center.copy(t),m.radius=i,m.intersectsBox(p)){const g=ee(e),f=g.distanceTo(m.center),y=new Ng(e,f,g);if(s.push(y),!r)return}}}if(e.children)for(const p of e.children){const m=s.length;if(this.intersectSphere(p,t,i,n,s,r,a,l),m!=s.length&&!r)return}}}function Ov(o){return!(o.index&&o.index.array.length<3)}const Tr=new kd,nu=new _r,nM=new yb;function oM(o,e,t){const i=o._computeIntersections;if(!i)return!1;let n=o["_computeIntersections:Needle"];return n||(n=o["_computeIntersections:Needle"]=function(s,r,a){const l=this,c=l.geometry.boundingSphere;if(c){if(l instanceof Da){nu.setFromNormalAndCoplanarPoint(F(0,1,0),F(0,-l.position.y,0)),nu.applyMatrix4(l.matrixWorld,nM);const d=s.ray.intersectPlane(nu,F());if(d){Tr.copy(c),Tr.applyMatrix4(l.matrixWorld);const p=F(d).sub(s.ray.origin).length(),m=Tr.radius*.5;p<m&&r.push({distance:p,point:d,object:l,normal:nu.normal.clone()})}return}Tr.copy(c),Tr.applyMatrix4(l.matrixWorld);const h=s.ray.intersectSphere(Tr,F());if(h){const d=F(h).sub(s.ray.origin),p=d.length();if(p>Tr.radius){const m=d.clone().normalize();r.push({distance:p,point:h,object:l,normal:m})}}}}),o._computeIntersections=n,e.intersectObject(o,!1,t),o._computeIntersections=i,!0}var ou;(o=>{let e=0;function t(v,P,k,O,D){if(!P.geometry||!P.geometry.hasAttribute("position"))return!1;const L=P.geometry;if(P?.isSkinnedMesh){const V=P,W=V.bvhNeedsUpdate;if(!V.staticGenerator)l(),r&&(V.staticGenerator=new r(P),V.staticGenerator.applyWorldTransforms=!1,V.staticGeometry=V.staticGenerator.generate(),L.boundsTree=a?.call(V.staticGeometry),V.staticGeometryLastUpdate=performance.now()+Math.random()*200,V.bvhNeedsUpdate=!0);else if(L.boundsTree&&(V.autoUpdateMeshBvhInterval!==void 0&&V.autoUpdateMeshBvhInterval>=0||W===!0)){const G=performance.now(),X=G-V.staticGeometryLastUpdate,R=V.autoUpdateMeshBvhInterval??100;(W||X>R)&&(Kt&&console.warn(`Physics: updating skinned mesh bvh for ${P.name} after ${X.toFixed(2)}ms`),V.bvhNeedsUpdate=!1,V.staticGeometryLastUpdate=G,V.staticGenerator?.generate(V.staticGeometry),L.boundsTree.refit())}}else if(!L.boundsTree){h||_();let V=!0;if((O.xr||L[g]===!1||L.getAttribute("position")?.isInterleavedBufferAttribute||L.index&&L.index?.isInterleavedBufferAttribute||e>10)&&(V=!1),V&&p){if(L[m]===void 0){let W=null;if(y.length>0){const G=y.shift();G&&!G.running&&(W=G)}if(!W&&f.length<3)try{iM&&console.warn("[GenerateMeshBVHWorker] Creating worker with import.meta.url:",import.meta.url),W=new p,f.push(W)}catch(G){G instanceof DOMException&&G.name==="SecurityError"?(console.warn("Failed to create MeshBVH worker, falling back to main thread generation. This can happen when running from file://, if the browser does not support workers or if the browser is blocking workers for other reasons."),console.debug(G),e+=10):(console.error("Failed to create MeshBVH worker. Please see below for more details:"),console.log(G)),e++}if(W!=null&&!W.running){const G=P.name;Kt&&console.log("<<<< worker start",G,W),L[m]="queued",performance.mark("bvh.create.start");const X=L.clone();try{W.generate(X).then(R=>{L[m]="done",L.boundsTree=R}).catch(R=>{L[m]="failed - "+R?.message,L[g]=!1,Kt&&console.error("Failed to generate mesh bvh on worker",R)}).finally(()=>{Kt&&console.log(">>>>> worker done",G,{hasBoundsTre:L.boundsTree!=null}),y.push(W),X.dispose(),performance.mark("bvh.create.end"),performance.measure("bvh.create (worker)","bvh.create.start","bvh.create.end")})}catch(R){console.error("Failed to generate mesh bvh on worker",R)}}else Kt&&console.warn("No worker available")}}else(!d||!V)&&(l(),s&&(performance.mark("bvh.create.start"),L.boundsTree=new s(L),performance.mark("bvh.create.end"),performance.measure("bvh.create","bvh.create.start","bvh.create.end")))}if(v instanceof Od){const V=v,W=P.raycast;if(L.boundsTree)l(),n&&(P.acceleratedRaycast||(P.acceleratedRaycast=n.bind(P),Kt&&console.debug(`Physics: bind acceleratedRaycast fn to "${P.name}"`)),P.raycast=P.acceleratedRaycast);else if(Kt&&console.warn("No bounds tree found for mesh",P.name,{workerTask:L[m],hasAcceleratedRaycast:n!=null}),D.allowSlowRaycastFallback===!1&&(L.getAttribute("position")?.array?.length??0)>2e3)return Kt&&console.warn("Skipping raycast because no bounds tree is available and allowSlowRaycastFallback is false"),!1;const G=V.firstHitOnly;return V.firstHitOnly=!1,V.intersectObject(P,!1,k),V.firstHitOnly=G,P.raycast=W,!0}else if(v instanceof kd){const V=L.boundsTree;if(V){const W=v;if(c.copy(P.matrixWorld).invert(),W.applyMatrix4(c),V.intersectsSphere(W)){const G=ee(P),X=G.distanceTo(W.center),R=new Ng(P,X,G);k.push(R)}}return!0}return!1}o.runMeshBVHRaycast=t;let i=!1,n=null,s=null,r=null,a=null;function l(){i||(i=!0,import("./vendor-DZ45lcA8.min.js").then(v=>v.index$1).then(v=>{n=v.acceleratedRaycast,s=v.MeshBVH,r=v.StaticGeometryGenerator,a=v.computeBoundsTree}).catch(v=>{(Kt||A())&&console.error("Failed to load BVH library...",v.message)}))}const c=new J;let h=!1,d=!1,p=null;const m=Symbol("Needle:MeshBVH-Worker"),g=Symbol("Needle:MeshBVH-CanUseWorker"),f=[],y=[];function _(){h=!0,d=!0,Promise.resolve().then(()=>cj).then(v=>{p=v.GenerateMeshBVHWorker}).catch(v=>{Kt||A()?console.warn("Failed to setup mesh bvh worker"):console.debug("Failed to setup mesh bvh worker",v)}).finally(()=>{d=!1})}})(ou||(ou={}));const kv=Symbol("gltf-loader-internal-usage-tracker"),sM=w("debugusers");class sc{get name(){return"NEEDLE_internal_usage_tracker"}static isLoading(e){return sc._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(){sc._loadingProcesses++;const e=this,t=this._getDependency;return this.parser.getDependency=function(i,n){const s=t.call(this,i,n);return s.then(r=>(r&&(e._loadedObjects.add(r),r[kv]=e._loadingId),r)),s},null}afterRoot(e){sc._loadingProcesses--,this.parser.getDependency=this._getDependency;for(const t of this._loadedObjects)delete t[kv],t instanceof M&&(t.parent||t instanceof H&&setTimeout(()=>{sM&&console.warn("> GLTF LOADER: Mesh not used in scene!",t),t.material=null,t.geometry=null},1e3));return null}}class Mv{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:
|
|
177
177
|
`+i.src),e.preventDefault())}})}}const su=w("trackresources");function Ev(){return su==="dispose"}let Ar=!0;su===0&&(Ar=!1);function rM(o){Ar=o}function Rv(){return Ar}const Tv=Symbol("disposable");function Av(o,e){o&&(o[Tv]=e,Ir&&console.warn("Set disposable",e,o))}const Iv=Symbol("disposed");function aM(o){return o[Iv]===!0}function ke(o){if(o){if(o[Tv]===!1){Ir&&console.warn("Object is marked as not disposable",o);return}if(typeof o=="object"&&(o[Iv]=!0),o instanceof Hi)ke(o.environment),ke(o.background),ke(o.customDepthMaterial),ke(o.customDistanceMaterial);else if(o instanceof vs)ke(o.geometry),ke(o.material),ke(o.skeleton),ke(o.bindMatrix),ke(o.bindMatrixInverse),ke(o.customDepthMaterial),ke(o.customDistanceMaterial),o.visible=!1;else if(o instanceof H)ke(o.geometry),ke(o.material),ke(o.customDepthMaterial),ke(o.customDistanceMaterial),o.visible=!1;else if(o instanceof M)o.visible=!1;else if(o instanceof wn){Ya(o);for(const e of Object.keys(o.attributes)){const t=o.attributes[e];ke(t)}}else if(o instanceof ft||o instanceof wb)Ir&&console.warn("BufferAttribute dispose not supported",o.count);else if(o instanceof Array)for(const e of o)e instanceof we&&ke(e);else if(o instanceof we){Ya(o);for(const t of Object.keys(o)){const i=o[t];i instanceof Se&&ke(i)}const e=o.uniforms;if(e)for(const t of Object.keys(e)){const i=e[t];i instanceof Se?ke(i):i instanceof Gi&&ke(i.value)}}else o instanceof Se?(Ya(o),Ya(o.source),o.source?.data instanceof ImageBitmap&&Ya(o.source.data)):o instanceof JS?(Ya(o.boneTexture),o.boneTexture=null):o instanceof eC||!(o instanceof M)&&Ir&&console.warn("Unknown object type",o)}}function Ya(o){o&&((Ir||Ev()||su)&&console.warn("\u{1F9E8} FREE",o),o instanceof ImageBitmap||"dispose"in o&&typeof o.dispose=="function"&&o.dispose())}function lM(o){}const cM=new Set;function Wg(o,e,t=null,i){if(i||(i=cM,i.clear()),!o)return i;const n=o[Mc];if(n)for(const s of n)i.has(s)||t?.call(null,s)!==!1&&(i.add(s),e&&Wg(s,!0,t,i));return i}function hM(o){return o[Ec]}const Ir=w("debugresourceusers")||w("debugmemory"),Mc=Symbol("needle-resource-users"),Ec=Symbol("needle-resource-users-count");function Jt(o,e){qd(o,e,function(t,i){Ar&&!oc.raycasting&&(ru(Mc,this,t,!1),ru(Mc,this,i,!0))})}Ar&&(Jt(H.prototype,"material"),Jt(H.prototype,"geometry"),Jt(we.prototype,"map"),Jt(we.prototype,"bumpMap"),Jt(we.prototype,"alphaMap"),Jt(we.prototype,"normalMap"),Jt(we.prototype,"displacementMap"),Jt(we.prototype,"roughnessMap"),Jt(we.prototype,"metalnessMap"),Jt(we.prototype,"emissiveMap"),Jt(we.prototype,"specularMap"),Jt(we.prototype,"envMap"),Jt(we.prototype,"lightMap"),Jt(we.prototype,"aoMap"),Jt(we.prototype,"gradientMap"));function dM(o){if(Ar===!1)return;const e=o[Mc];if(e)for(const t of e)ru(Mc,t,o,!1)}Ar&&qd(we.prototype,"dispose",function(){dM(this)});let Vg=0;function ru(o,e,t,i){if(Vg>0)return;if(Array.isArray(t)){for(const s of t)ru(o,e,s,i);return}if(!t)return;let n=t[o];if(n||(n=new Set),i){if(e&&!n.has(e)){n.add(e);let s=t[Ec]||0;s+=1,t[Ec]=s,Ir&&console.warn(`\u{1F7E2} Added user of "${t.type}"`,e,t,s,"users:",n)}}else if(e&&n.has(e)){n.delete(e);let s=t[Ec]||0;s>0&&(s-=1,t[Ec]=s),Ir&&console.warn(`\u{1F534} Removed user of "${t.type}"`,e,t,s,"users:",n),s<=0&&(sc.isLoading(t)||(su&&console.warn(`\u{1F534} Removed all user of "${t.type}"`,t),Ev()&&ke(t)))}t[o]=n}try{qd(yr.prototype,"render",function(){Vg++},function(){Vg--})}catch(o){console.warn("Could not wrap WebGLRenderer.render",o)}const Lv=w("debugcomponentevents");class au{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),Lv&&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(Lv&&console.log("Dispatching event "+e,i),!!i)for(const n of i)n(t)}}const Rc=Symbol("NEEDLE_NEED_UPDATE_INSTANCE"),jv=Symbol("isUsingInstancing"),Dv=Symbol("instancingRenderer"),Tc=Symbol("instancingAutoUpdateBounds");class pn{static isUsingInstancing(e){return e[jv]===!0}static getRenderer(e){return e[Dv]||null}setAutoUpdateBounds(e,t){const i=pn.getRenderer(e);i&&(i[Tc]=t)}static markDirty(e,t=!0){if(e&&(this.isUsingInstancing(e)&&(e[Rc]=!0,e.matrixWorldNeedsUpdate=!0),t))for(const i of e.children)pn.markDirty(i,!0)}}var Ac;(o=>{o.experimentalSmartHierarchyUpdate=!1})(Ac||(Ac={}));function Za(o,e){try{e||o()}catch(t){return console.error(t),!1}return!0}const $g=w("debugnewscripts"),uM=w("debughierarchy"),Ie=[];function pM(){return Ie.length>0}function lu(o){if($g&&console.log("Register new components",o.new_scripts.length,[...o.new_scripts],o.alias?"element: "+o.alias:o.hash,o),o.new_scripts_pre_setup_callbacks.length>0){for(const e of o.new_scripts_pre_setup_callbacks)e&&e();o.new_scripts_pre_setup_callbacks.length=0}if(!(o.new_scripts.length<=0)){Ie.length=0,o.new_scripts.length>0&&Ie.push(...o.new_scripts),o.new_scripts.length=0;for(let e=0;e<Ie.length;e++)try{const t=Ie[e];if(t.isComponent!==!0){(A()||$g)&&console.error(`Registered script is not a Needle Engine component.
|
|
178
178
|
The script will be ignored. Please make sure your component extends "Behaviour" imported from "@needle-tools/engine"
|
|
179
179
|
`,t),Ie.splice(e,1),e--;continue}if(t.destroyed)continue;if(!t.gameObject){console.warn(`Component can not be initialized: no GameObject assigned.
|
|
@@ -225,7 +225,7 @@ TEX `+i.texture_lod;if(gf=="density"&&(f+=`
|
|
|
225
225
|
`+(g/n.lastScreenCoverage).toFixed(0)+` dens
|
|
226
226
|
`+(n.lastScreenCoverage*100).toFixed(1)+`% cov
|
|
227
227
|
`+(n.lastCentrality*100).toFixed(1)+`% centr
|
|
228
|
-
`+(xu.min.x.toFixed(2)+"-"+xu.max.x.toFixed(2)+"x"+xu.min.y.toFixed(2)+"-"+xu.max.y.toFixed(2))+" scr"),n.lastScreenCoverage>.1){const y=e,_=y.worldForward,v=y.worldPosition,P=F(_).multiplyScalar(c*.7).add(l),k=P.distanceTo(v),O=h[Math.min(h.length-1,Math.max(0,s))]+"88",
|
|
228
|
+
`+(xu.min.x.toFixed(2)+"-"+xu.max.x.toFixed(2)+"x"+xu.min.y.toFixed(2)+"-"+xu.max.y.toFixed(2))+" scr"),n.lastScreenCoverage>.1){const y=e,_=y.worldForward,v=y.worldPosition,P=F(_).multiplyScalar(c*.7).add(l),k=P.distanceTo(v),O=h[Math.min(h.length-1,Math.max(0,s))]+"88",D=this.context.domHeight>0?screen.height/this.context.domHeight:1,L=e.isPerspectiveCamera?Math.tan(e.fov*Math.PI/180/2):1;B.DrawLabel(P,f,k*.012*D*L,void 0,16777215,O)}}}}}const tE=w("debugplayerview");var Uo=(o=>(o.Browser="browser",o.Headset="headset",o.Handheld="handheld",o))(Uo||{});class kw{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 Mw{context;playerViews=new Map;constructor(e){this.context=e}setPlayerView(e,t,i){let n=this.playerViews.get(e);n||(n=new kw(e,this.context),this.playerViews.set(e,n)),n.viewDevice=i,n.currentObject=t,n.removed=!1}getPlayerView(e){if(!!e){if(!this.context.connection.userIsInRoom(e)){this.playerViews.delete(e);return}return this.playerViews.get(e)}}removePlayerView(e,t){const i=this.playerViews.get(e);i?.viewDevice===t&&(tE&&console.log("REMOVE",e),i.removed=!0,this.playerViews.delete(e))}}new Rm;const Nc=new Uint8Array(4);Nc[0]=255,Nc[1]=255,Nc[2]=255,Nc[3]=255;const iE=new Tm(Nc,1,1,Md);function ff(o,e=1){const t="alpha"in o,i=e*e,n=new Uint8Array(4*i),s=Math.floor(o.r*255),r=Math.floor(o.g*255),a=Math.floor(o.b*255);for(let c=0;c<i;c++){const h=c*4;n[h+0]=s,n[h+1]=r,n[h+2]=a,t?n[h+3]=Math.floor(o.alpha*255):n[h+3]=255}const l=new Tm(n,e,e);return l.needsUpdate=!0,l}function nE(o,e,t,i=1,n=3){const s=i*n,r=[o,e,t],a=r.length,l=new Uint8Array(4*a*s),c=new oe;for(let d=0;d<n;d++){const p=Math.floor(d/n*a),m=j.clamp(p+1,0,a-1),g=r[p],f=r[m],y=d/n*a%1;c.lerpColors(g,f,y);const _=Math.floor(c.r*255),v=Math.floor(c.g*255),P=Math.floor(c.b*255);for(let k=0;k<i;k++){const O=(d*i+k)*4;l[O+0]=_,l[O+1]=v,l[O+2]=P,l[O+3]=255}}const h=new Tm(l,i,n);return h.needsUpdate=!0,h}function Cu(o,e){const t=o.elements;e||(e=[]),e.length=0;for(let i=0;i<16;i+=4){const n=t[i],s=t[i+1],r=t[i+2],a=t[i+3],l=new ye(n,s,r,a);e.push(l)}return e}const yf=[],Ew=[];function oE(o,e){if(yf.length===0)for(let t=0;t<27;t++)yf.push(0);e||(e=yf);for(let t=0;t<27;t++)Ew[t]=e[t];e=Ew,o.unity_SHAr={value:new ye(e[9],e[3],e[6],e[0])},o.unity_SHBr={value:new ye(e[12],e[15],e[18],e[21])},o.unity_SHAg={value:new ye(e[10],e[4],e[7],e[1])},o.unity_SHBg={value:new ye(e[13],e[16],e[19],e[22])},o.unity_SHAb={value:new ye(e[11],e[5],e[8],e[2])},o.unity_SHBb={value:new ye(e[14],e[17],e[20],e[23])},o.unity_SHC={value:new ye(e[24],e[25],e[26],1)}}class sE{vertexShader;fragmentShader;technique;constructor(e,t,i){this.vertexShader=e,this.fragmentShader=t,this.technique=i}}async function rE(o,e){if(!o)return console.error("Can not find technique: no shader data"),null;const t=o.programs[e],i=t.vertexShader,n=t.fragmentShader;if(i!==void 0&&n!==void 0){const s=o.shaders[i],r=o.shaders[n];if(s.uri&&r.uri||s.code&&r.code){if(!s.code&&s.uri&&await Rw(s),!r.code&&r.uri&&await Rw(r),!s.code||!r.code)return null;const a=o.techniques[e];return new sE(s.code,r.code,a)}}return console.error("Shader technique not found",e),null}async function Rw(o){const e=o.uri;if(e)if(e.endsWith(".glsl")){const t=await new Rm().loadAsync(e);o.code=t.toString()}else o.code=aE(o.uri)}function aE(o){return decodeURIComponent(Array.prototype.map.call(atob(o),function(e){return"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)}).join(""))}const En=w("debugenvlight");var rl=(o=>(o[o.Skybox=0]="Skybox",o[o.Trilight=1]="Trilight",o[o.Flat=3]="Flat",o[o.Custom=4]="Custom",o))(rl||{}),Pu=(o=>(o[o.Skybox=0]="Skybox",o[o.Custom=1]="Custom",o))(Pu||{});class Tw{context;constructor(e){this.context=e,this.context.pre_update_callbacks.push(this.preUpdate.bind(this))}_currentLightSettingsId;_sceneLightSettings;get currentLightSettingsId(){return this._currentLightSettingsId}preUpdate(){const e=this.context.time;this._timevec4.x=e.time,this._timevec4.y=Math.sin(e.time),this._timevec4.z=Math.cos(e.time),this._timevec4.w=e.deltaTime}_timevec4=new ye;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 ne&&(e=e.url);const t=this._sceneLightSettings?.get(e);return t?(En&&console.log("Enable scene light settings",e,t),e!==this._currentLightSettingsId&&this._currentLightSettingsId&&this.disable(this._currentLightSettingsId),this._currentLightSettingsId=e,t.enabled=!0,!0):(En&&console.warn("No light settings found for",e),!1)}disable(e){if(e instanceof ne&&(e=e.url),e==null)return!1;const t=this._sceneLightSettings?.get(e);return t?(En&&console.log("Disable scene light settings",e,t),t.enabled=!1,!0):!1}enableCurrent(){return this._currentLightSettingsId?(this.enable(this._currentLightSettingsId),this._currentLightSettingsId??null):null}disableCurrent(){if(this._currentLightSettingsId){const e=this._currentLightSettingsId;return this.disable(this._currentLightSettingsId),e}return null}internalRegisterSceneLightSettings(e){const t=e.sourceId;if(!t){console.error("Missing source id for scene light settings, can not register:",e);return}En&&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}En&&console.log("Unregister "+e?.sourceId+" lighting",e),this._sceneLightSettings&&this._sceneLightSettings.delete(t)}internalRegisterReflection(e,t){En&&console.log("Register reflection",e,t);const i=new Aw(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(En&&console.log("Enable reflection",e,t?rl[t.ambientMode]:"Unknown ambient mode",t),t?.ambientMode){case 0:case 4:const i=this.internalGetReflection(e);if(i&&i.Source){En&&console.log("Setting environment reflection",i);const n=this.context.scene,s=i.Source;return s.mapping=ko,n.environment=s,n.environmentIntensity=this.environmentIntensity||1,s}else En&&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=nE(i[0],i[1],i[2],64,64);return n.colorSpace=Mo,n.mapping=ko,this.context.scene.environment=n,n}else console.error("Missing ambient trilight",t.sourceId);case 3:if(t.ambientLight){const i=ff(t.ambientLight,64);return i.colorSpace=Mo,i.mapping=ko,this.context.scene.environment=i,i}else console.error("Missing ambientlight",t.sourceId)}return null}internalDisableReflection(e){if(e&&e!==this.__currentReflectionId){En&&console.log("Not disabling reflection for",e,"because it is not the current light settings id",this.__currentReflectionId);return}En&&console.log("Disable reflection",e);const t=this.context.scene;t.environment=null}_lighting={}}class Aw{get Source(){return this._source}_source;constructor(e,t,i=1){this._source=t,t.mapping=ko}}const Iw=w("timescale");let bf=1;typeof Iw=="number"&&(bf=Iw);class Lw{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 oC;_smoothedFps=0;_smoothedDeltaTime=0;_fpsSamples=[];_fpsSampleIndex=0;constructor(){typeof bf=="number"&&(this.timeScale=bf)}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 jw=!1;function Dw(o){jw||(jw=!0,lE(),cE())}Dw();function lE(){const o=`
|
|
229
229
|
float startCompression = 0.8;
|
|
230
230
|
float desaturation = 0.5;
|
|
231
231
|
// Patched tonemapping function
|
|
@@ -357,7 +357,7 @@ vec3 AgXToneMapping( vec3 color ) {
|
|
|
357
357
|
color = _agxLook(color); // Optional
|
|
358
358
|
color = _agxEotf(color);
|
|
359
359
|
return color;
|
|
360
|
-
`,e="vec3 AgXToneMapping( vec3 color ) {",t="return color;",i=Zt.tonemapping_pars_fragment.indexOf(e),n=Zt.tonemapping_pars_fragment.indexOf(t,i);if(i>=0&&n>=0){const s=Zt.tonemapping_pars_fragment.substring(i,n+t.length);Zt.tonemapping_pars_fragment=Zt.tonemapping_pars_fragment.replace(s,o)}else A()&&console.error("Couldn't find AgXToneMapping in ShaderChunk.tonemapping_pars_fragment")}function Bw(o){if(typeof o=="string")switch(o=o.toLowerCase(),o){case"none":return Td;case"neutral":return ja;case"aces":return Rd;case"agx":return Ed;case"khronos_neutral":return ja;default:console.warn("[PostProcessing] Unknown tone mapping mode",o);return}}var Wc;(o=>{function e(n){return n==="0"||n?.toLowerCase()==="false"}o.isFalsey=e;function t(n,s,r){const a=n.getAttribute(s);return e(a)?null:(r?.onAttribute?.call(null,a),a)}o.getAttributeValueIfNotFalsey=t;function i(n,s,r){const a=n.getAttribute(s);return a===null?null:e(a)?(r?.onAttribute?.call(null,a,!0),!1):(r?.onAttribute?.call(null,a,!1),a)}o.getAttributeAndCheckFalsey=i})(Wc||(Wc={}));async function Fw(o){if(!globalThis.QRCode){const l="https://cdn.jsdelivr.net/gh/davidshimjs/qrcodejs@gh-pages/qrcode.min.js";let c=document.head.querySelector(`script[src="${l}"]`);c||(c=document.createElement("script"),c.src=l,document.head.appendChild(c)),await new Promise((h,d)=>{c.addEventListener("load",()=>{h(!0)})})}const e=globalThis.QRCode,t=o.domElement??document.createElement("div"),i=new e(t,{width:o.width??256,height:o.height??256,colorDark:"#000000",colorLight:"#ffffff",correctLevel:o.showLogo?e.CorrectionLevel.H:e.CorrectLevel.M,...o}),n=i?._oQRCode.moduleCount||0,s=i?._oDrawing?._elCanvas;let r=.25;n<40?r=Math.floor(n/4)/n:r=Math.floor(n/6)/n;const a=Math.floor(n/20)/n;try{const l=await hE(s,{showLogo:o.showLogo,logoSize:r,logoPadding:a}).catch(c=>{});l&&(t.innerHTML="",t.append(l))}catch{}if(o.showUrl!==!1&&o.text){const l=t.querySelector(".qr-code-link-label");let c=o.text.replace(/^(https?:\/\/)?(www\.)?/,"").replace(/\/+$/,"").replace(/\?+$/,"");if(c="Scan to visit "+c,l)l.textContent=c;else{const h=document.createElement("div");h.classList.add("qr-code-link-label"),o.text=c,h.textContent=o.text,h.addEventListener("click",d=>{d.stopImmediatePropagation()}),h.style.textAlign="center",h.style.fontSize="0.8em",h.style.marginTop="0.1em",h.style.color="#000000",h.style.fontFamily="'Roboto Flex', sans-serif",h.style.opacity="0.5",h.style.wordBreak="break-all",h.style.wordWrap="break-word",h.style.marginBottom="0.3em",t.style.width="calc(210px + 20px)",t.appendChild(h)}}return t}async function hE(o,e){if(!o)return;const t=8,i=20,n=e.logoPadding||1/32,s="transparent",r=0,a=new Image,l=document.querySelector("needle-engine");l||console.debug("[QR Code] No web component found");const c=Kn();let h=null;if(h=Wc.getAttributeAndCheckFalsey(l,"qrcode-logo-src"),c&&e.showLogo!==!0&&h===!1||(h||=Wc.getAttributeAndCheckFalsey(l,"logo-src"),c&&e.showLogo!==!0&&h===!1)||(h||=Wc.getAttributeAndCheckFalsey(l,"loading-logo-src",{onAttribute:()=>{A()?console.warn("[QR Code] 'loading-logo-src' is deprecated, please use 'logo-src' or 'qrcode-logo-src' instead."):console.debug("[QR Code] 'loading-logo-src' is deprecated.")}}),c&&e.showLogo!==!0&&h===!1)||(h&&!c&&(console.warn("[QR Code] Custom logo is only available with a commercial license. Using default Needle logo. Please get a commercial license at https://needle.tools/pricing."),h=null),h||=Xa,!h))return;let d=!1;e.showLogo!==!1&&(a.src=h,d=await new Promise((P,k)=>{a.onload=()=>P(!0),a.onerror=O=>{const
|
|
360
|
+
`,e="vec3 AgXToneMapping( vec3 color ) {",t="return color;",i=Zt.tonemapping_pars_fragment.indexOf(e),n=Zt.tonemapping_pars_fragment.indexOf(t,i);if(i>=0&&n>=0){const s=Zt.tonemapping_pars_fragment.substring(i,n+t.length);Zt.tonemapping_pars_fragment=Zt.tonemapping_pars_fragment.replace(s,o)}else A()&&console.error("Couldn't find AgXToneMapping in ShaderChunk.tonemapping_pars_fragment")}function Bw(o){if(typeof o=="string")switch(o=o.toLowerCase(),o){case"none":return Td;case"neutral":return ja;case"aces":return Rd;case"agx":return Ed;case"khronos_neutral":return ja;default:console.warn("[PostProcessing] Unknown tone mapping mode",o);return}}var Wc;(o=>{function e(n){return n==="0"||n?.toLowerCase()==="false"}o.isFalsey=e;function t(n,s,r){const a=n.getAttribute(s);return e(a)?null:(r?.onAttribute?.call(null,a),a)}o.getAttributeValueIfNotFalsey=t;function i(n,s,r){const a=n.getAttribute(s);return a===null?null:e(a)?(r?.onAttribute?.call(null,a,!0),!1):(r?.onAttribute?.call(null,a,!1),a)}o.getAttributeAndCheckFalsey=i})(Wc||(Wc={}));async function Fw(o){if(!globalThis.QRCode){const l="https://cdn.jsdelivr.net/gh/davidshimjs/qrcodejs@gh-pages/qrcode.min.js";let c=document.head.querySelector(`script[src="${l}"]`);c||(c=document.createElement("script"),c.src=l,document.head.appendChild(c)),await new Promise((h,d)=>{c.addEventListener("load",()=>{h(!0)})})}const e=globalThis.QRCode,t=o.domElement??document.createElement("div"),i=new e(t,{width:o.width??256,height:o.height??256,colorDark:"#000000",colorLight:"#ffffff",correctLevel:o.showLogo?e.CorrectionLevel.H:e.CorrectLevel.M,...o}),n=i?._oQRCode.moduleCount||0,s=i?._oDrawing?._elCanvas;let r=.25;n<40?r=Math.floor(n/4)/n:r=Math.floor(n/6)/n;const a=Math.floor(n/20)/n;try{const l=await hE(s,{showLogo:o.showLogo,logoSize:r,logoPadding:a}).catch(c=>{});l&&(t.innerHTML="",t.append(l))}catch{}if(o.showUrl!==!1&&o.text){const l=t.querySelector(".qr-code-link-label");let c=o.text.replace(/^(https?:\/\/)?(www\.)?/,"").replace(/\/+$/,"").replace(/\?+$/,"");if(c="Scan to visit "+c,l)l.textContent=c;else{const h=document.createElement("div");h.classList.add("qr-code-link-label"),o.text=c,h.textContent=o.text,h.addEventListener("click",d=>{d.stopImmediatePropagation()}),h.style.textAlign="center",h.style.fontSize="0.8em",h.style.marginTop="0.1em",h.style.color="#000000",h.style.fontFamily="'Roboto Flex', sans-serif",h.style.opacity="0.5",h.style.wordBreak="break-all",h.style.wordWrap="break-word",h.style.marginBottom="0.3em",t.style.width="calc(210px + 20px)",t.appendChild(h)}}return t}async function hE(o,e){if(!o)return;const t=8,i=20,n=e.logoPadding||1/32,s="transparent",r=0,a=new Image,l=document.querySelector("needle-engine");l||console.debug("[QR Code] No web component found");const c=Kn();let h=null;if(h=Wc.getAttributeAndCheckFalsey(l,"qrcode-logo-src"),c&&e.showLogo!==!0&&h===!1||(h||=Wc.getAttributeAndCheckFalsey(l,"logo-src"),c&&e.showLogo!==!0&&h===!1)||(h||=Wc.getAttributeAndCheckFalsey(l,"loading-logo-src",{onAttribute:()=>{A()?console.warn("[QR Code] 'loading-logo-src' is deprecated, please use 'logo-src' or 'qrcode-logo-src' instead."):console.debug("[QR Code] 'loading-logo-src' is deprecated.")}}),c&&e.showLogo!==!0&&h===!1)||(h&&!c&&(console.warn("[QR Code] Custom logo is only available with a commercial license. Using default Needle logo. Please get a commercial license at https://needle.tools/pricing."),h=null),h||=Xa,!h))return;let d=!1;e.showLogo!==!1&&(a.src=h,d=await new Promise((P,k)=>{a.onload=()=>P(!0),a.onerror=O=>{const D=h!==Xa?"'"+h+"'":null;console.error("[QR Code] Error loading logo image for QR code",D,A()?O:""),P(!1)}}));const p=document.createElement("canvas");p.width=o.width+t,p.height=o.height+t;const m=p.getContext("2d");if(!m)return;m.fillStyle="#ffffff",m.fillRect(0,0,p.width,p.height),m.drawImage(o,t/2,t/2),m.imageSmoothingEnabled=!0,m.imageSmoothingQuality="high",m.mozImageSmoothingEnabled=!0,m.webkitImageSmoothingEnabled=!0,m.globalCompositeOperation="lighten";const g=m.createLinearGradient(0,0,0,p.height);g.addColorStop(0,"rgb(45, 45, 45)"),g.addColorStop(1,"rgb(45, 45, 45)"),m.fillStyle=g,m.fillRect(0,0,p.width,p.height),m.globalCompositeOperation="source-over";let f=Math.min(o.width,o.height)*(e.logoSize||.25),y=f;if(d){const P=a.width/a.height;P>1?y=f/P:f=y*P;const k=n*o.width,O=Math.max(f,y),D=Math.round(O+k),L=Math.round(O+k),V=(p.width-O)/2,W=(p.height-O)/2;m.shadowColor=s,m.shadowBlur=i;const G=r,X=Math.round(V-k/2),R=Math.round(W-k/2);m.beginPath(),m.moveTo(X+G,R),m.lineTo(X+D-G,R),m.quadraticCurveTo(X+D,R,X+D,R+G),m.lineTo(X+D,R+L-G),m.quadraticCurveTo(X+D,R+L,X+D-G,R+L),m.lineTo(X+G,R+L),m.quadraticCurveTo(X,R+L,X,R+L-G),m.lineTo(X,R+G),m.quadraticCurveTo(X,R,X+G,R),m.fillStyle="#ffffff",m.closePath(),m.fill(),m.clip(),m.shadowColor="transparent";const $=(p.width-f)/2,q=(p.height-y)/2;m.drawImage(a,$,q,f,y)}const _=p.toDataURL("image/png"),v=document.createElement("img");return v.src=_,v.style.width="100%",v.style.height="auto",v}const _f="Material Symbols Outlined";function Pt(o){const e=document.createElement("span");return e.style.maxWidth="48px",e.style.maxHeight="48px",e.style.overflow="hidden",e.classList.add("material-symbols-outlined","notranslate"),e.setAttribute("translate","no"),e.innerText=o,e.style.visibility="hidden",e.style.userSelect="none",e.setAttribute("role","img"),e.setAttribute("aria-label",o+" icon"),e.setAttribute("aria-hidden","true"),xf(_f).then(t=>{t?e.style.visibility="":o==="more_vert"?(e.style.visibility="",e.innerText="More"):e.style.display="none"}),e}function Uw(o){return o.classList?.contains("material-symbols-outlined")||!1}const Ou=new Map;async function vf(o){if(await xf(_f),Ou.has(o))return Ou.get(o);const e=document.createElement("canvas"),t=48;e.width=t,e.height=t;const i=e.getContext("2d");if(i){i.font=`${t}px '${_f}'`,i.fillStyle="black",i.fillText(o,0,t);const n=e.toDataURL(),s=new Se;return s.name=o+" icon",s.image=new Image,s.image.src=n,s.needsUpdate=!0,Ou.set(o,s),s}return Ou.set(o,null),null}const wf=new Map;async function xf(o,e=5,t=0){document.fonts.check(`1em '${o}'`)||await document.fonts.ready;const i=wf.get(o)||document.fonts.load(`1em '${o}'`).then(n=>n?.length>0).finally(()=>{wf.delete(o)});return wf.set(o,i),await i?!0:t<e?new Promise(n=>{setTimeout(()=>{n(xf(o,e,t+1))},1e3)}):!1}class mn{static _instance;static get instance(){return this.getOrCreate()}static getOrCreate(){return this._instance||(this._instance=new mn),this._instance}static create(){return new mn}_fullscreenButton;get fullscreenButton(){return this._fullscreenButton}createFullscreenButton(e){if(this._fullscreenButton)return this._fullscreenButton;if(!document.fullscreenEnabled)return A()&&console.warn("NeedleMenu: Fullscreen button could not be created, device doesn't support the Fullscreen API"),null;const t=document.createElement("button");this._fullscreenButton=t,t.classList.add("fullscreen-button"),t.title="Click to enter fullscreen mode",Es.setElementPriority(t,3);const i=Pt("fullscreen"),n=Pt("fullscreen_exit");return t.appendChild(i),t.onclick=()=>{document.fullscreenElement?document.exitFullscreen():"webkitRequestFullscreen"in e.domElement&&typeof e.domElement.webkitRequestFullscreen=="function"?e.domElement.webkitRequestFullscreen():"requestFullscreen"in e.domElement&&e.domElement.requestFullscreen()},document.addEventListener("fullscreenchange",()=>{document.fullscreenElement?(i.remove(),t.appendChild(n),t.title="Click to enter fullscreen mode"):(n.remove(),t.appendChild(i),t.title="Click to exit fullscreen mode")}),globalThis.addEventListener("needle-xrsession-start",()=>{t.style.display="none"}),globalThis.addEventListener("needle-xrsession-end",()=>{t.style.display=""}),t}_muteButton;get muteButton(){return this._muteButton}createMuteButton(e){if(this._muteButton)return this._muteButton;const t=document.createElement("button");this._muteButton=t,t.classList.add("mute-button"),t.title="Click to mute/unmute";const i=Pt("volume_off"),n=Pt("volume_up");return Es.setElementPriority(t,1),e.application.muted?t.appendChild(i):t.appendChild(n),t.onclick=()=>{e.application.muted?(i.remove(),t.appendChild(n),e.application.muted=!1):(n.remove(),t.appendChild(i),e.application.muted=!0)},t}_qrButton;get qrButton(){return this._qrButton}_customQRButtonUrl;set qrButtonUrl(e){try{new URL(e),this._customQRButtonUrl=e}catch{console.warn(`[Needle] QR code button URL is not a valid URL '${e}'`)}}get qrButtonUrl(){return this._customQRButtonUrl||window.location.href}createQRCode(e){if(this._qrButton)return this._qrButton;const t=this,i=document.createElement("button");this._qrButton=i,i.innerText="QR Code",i.prepend(Pt("qr_code")),i.title="Scan this QR code with your phone to open this page",this.hideElementDuringXRSession(i),Es.setElementPriority(this._qrButton,20);const n=document.createElement("div");n.style.cssText=`
|
|
361
361
|
position: fixed;
|
|
362
362
|
display: inline-block;
|
|
363
363
|
padding: 0.5rem;
|
|
@@ -887,10 +887,10 @@ Target Framerate: `+this.targetFrameRate)}}this._dispatchReadyAfterFrame&&(this.
|
|
|
887
887
|
padding-left: 25px;
|
|
888
888
|
border-radius: .5em;
|
|
889
889
|
border: 2px solid rgba(160,160,160,.3);
|
|
890
|
-
`,i=`Needle Engine \u2014 No license active, commercial use is not allowed. Visit https://needle.tools/pricing for more information and licensing options! v${Ti}`;U.Current?.xr||navigator.webdriver?console.log(i):console.log("%c "+i,t)}async function ME(o){if(!window.crossOriginIsolated){if(!gi.isAllowed(o)){Ot&&console.debug("Telemetry is disabled via no-telemetry attribute");return}try{const e="https://needle.tools/api/v1/needle-engine/ping";if(e){const t=window.location.href.split("?")[0],i={license:Rn,url:t,hostname:window.location.hostname,pathname:window.location.pathname,version:Ti,generator:Wa,build_time:wc,public_key:Ss},n=navigator.sendBeacon?.(e,JSON.stringify(i));Ot&&console.debug("Sent beacon: "+n)}}catch(e){Ot&&console.log("Failed to send non-commercial usage message to analytics backend",e)}}}const EE=w("debugdecoders");let Tf=null;function Xw(){if(!Tf){const o=Um(null);Tf={dracoLoader:o.dracoLoader,ktx2Loader:o.ktx2Loader,meshoptDecoder:o.meshoptDecoder}}return Tf}function Qw(o){o!==void 0&&typeof o=="string"&&hP(o)}function Yw(o){if(o!==void 0&&typeof o=="string"&&o!=="js"){const e=Xw();EE&&console.log("Setting draco decoder type to",o),e.dracoLoader.setDecoderConfig({type:o})}}function Zw(o){o!==void 0&&typeof o=="string"&&cP(o)}function Af(o,e){const t=Xw();return e.renderer?t.ktx2Loader.detectSupport(e.renderer):console.warn("No renderer provided to detect ktx2 support - loading KTX2 textures will probably fail"),aP(o),o.dracoLoader||o.setDRACOLoader(t.dracoLoader),o.ktx2Loader||o.setKTX2Loader(t.ktx2Loader),o.meshoptDecoder||o.setMeshoptDecoder(t.meshoptDecoder),lP(o,{progressive:!0}),o}const Ye=function(o){return u(o)},u=function(o){if(o===void 0&&(o=null),!Array.isArray(o))o=Kw(o);else for(let e=0;e<o.length;e++){const t=o[e];o[e]=Kw(t)}return function(e,t){if(!e){const n=typeof t=="string"?t:t.name;console.warn(`@serializable without a target at '${n}'.`);return}typeof t!="string"&&(t=t.name),Object.getOwnPropertyDescriptor(e,"$serializedTypes")||(e.$serializedTypes={});const i=e.$serializedTypes=e.$serializedTypes||{};i[t]=o}};function Kw(o){switch(o?.prototype?.constructor?.name){case"Number":case"String":case"Boolean":return null}return o}const Rs=w("debughotreload");let $c=!1;const Hc=new Map;function RE(){return $c}function If(){return globalThis.NEEDLE_HOT_RELOAD_ENABLED===!0}function Jw(o){if($c){Rs&&console.warn("[Needle Engine] Hot reloading is in progress, not registering instance",o);return}Rs&&console.log("[Needle Engine] Registering hot reload instance",o);const e=o.constructor.name;Hc.has(e)?Hc.get(e)?.push(o):Hc.set(e,[o])}function ex(o){if($c){Rs&&console.warn("[Needle Engine] Hot reloading is in progress, not unregistering instance",o);return}Rs&&console.log("[Needle Engine] Unregistering hot reload instance",o);const e=o.constructor.name,t=Hc.get(e);if(!t)return;const i=t.indexOf(o);i!==-1&&t.splice(i,1)}let tx=!1;function TE(){if(Rs||tx)return;tx=!0;const o=console.error;console.error=(...e)=>{if(e.length){const t=e[0];if(typeof t=="string"&&t.includes("[hmr] Failed to reload ")){console.log("[Needle Engine] Hot reloading failed"),window.location.reload();return}}o.apply(console,e)}}function AE(o){Rs&&console.log("[HMR] Apply changes",o,Object.keys(o)),TE();for(const e of Object.keys(o))try{$c=!0;const t=C.get(e);if(!t){Rs&&console.log("[HMR] Type not found: "+e);continue}const i=o[e],n=Hc.get(i.name);let s="[Needle Engine] Updating type: "+e;const r=n?.length??-1;r>0?s+=" x"+r:s+=" (No instances registered)",console.log(s);const a=Object.getOwnPropertyNames(t.prototype),l=Object.getOwnPropertyDescriptors(i.prototype);for(const c in l)l[c].writable&&(t.prototype[c]=o[e].prototype[c]);for(const c of a)l[c]||delete t.prototype[c];if(n){const c=new i,h=Object.getOwnPropertyDescriptors(c);for(const d of n){const p=d,m=p.isComponent===!0,g=m?p.activeAndEnabled:!0,f=m?p.context:void 0;try{if(m&&f&&Bo(p,f),m&&g&&(p.enabled=!1),d.onBeforeHotReloadFields&&d.onBeforeHotReloadFields()===!1)continue;for(const y in h)if(h[y].writable){if(d[y]===void 0)d[y]=c[y];else if(typeof d[y]=="function"&&!d[y].prototype){const _=d[y],v=_.name,P="bound ";if(v===P)continue;const k=_.name.substring(P.length),O=i.prototype[k];O&&(d[y]=O.bind(d))}}d.onAfterHotReloadFields&&d.onAfterHotReloadFields()}finally{m&&f&&Hg(p,f),m&&g&&(p.enabled=!0)}}}}catch(t){if(Rs)console.error(t);else return!1}finally{$c=!1,xr(Ri.Log,"Script changes applied (HMR)")}return!0}class S extends M{guid;static isDestroyed(e){return Br(e)}static setActive(e,t,i=!0){e&&(zc(e,t),cu(e),t&&i&&Bv(U.Current,e))}static isActiveSelf(e){return il(e)}static isActiveInHierarchy(e){return gw(e)}static markAsInstancedRendered(e,t){fw(e,t)}static isUsingInstancing(e){return bu(e)}static foreachComponent(e,t,i=!0){return Fr(e,t,i)}static instantiateSynced(e,t){return e?Kg(e,t):null}static instantiate(e,t=null){return"isAssetReference"in e,Ur(e,t)}static destroySynced(e,t,i=!0){if(!e)return;const n=e;t=t??U.Current,Lc(n,t.connection,i)}static destroy(e,t=!0){return Ii(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=U.Current),t.add(e),zc(e,!0),cu(e),i?S.foreachComponent(e,n=>{Hg(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),zc(e,!1),cu(e),S.foreachComponent(e,t=>{mM(t)},!0))}static invokeOnChildren(e,t,...i){this.invoke(e,t,!0,i)}static invoke(e,t,i=!1,...n){e&&this.foreachComponent(e,s=>{const r=s[t];r&&typeof r=="function"&&r?.call(s,...n)},i)}static addNewComponent(e,t,i,n=!0){return Mn(e,t,i,{callAwake:n})}static addComponent(e,t,i,n){return Mn(e,t,i,n)}static moveComponent(e,t){return Mn(e,t)}static removeComponent(e){return cf(e.gameObject,e),e}static getOrAddComponent(e,t){return Dc(e,t)}static getComponent(e,t){return e===null?null:jr(e,t)}static getComponents(e,t,i=null){return e===null?i??[]:Bc(e,t,i)}static findByGuid(e,t){return hf(e,t)}static findObjectOfType(e,t,i=!0){return tl(e,t??U.Current,i)}static findObjectsOfType(e,t){const i=[];return mw(e,i,t),i}static getComponentInChildren(e,t,i=!1){return Fc(e,t,i)}static getComponentsInChildren(e,t,i=null){return el(e,t,i??void 0)}static getComponentInParent(e,t){return Uc(e,t)}static getComponentsInParent(e,t,i=null){return gu(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 E{get isComponent(){return!0}get[V_](){return C.getKey(this.constructor)||void 0}__context;get context(){return this.__context??U.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[Io];return e===void 0?!0:e}set __isActiveInHierarchy(e){this.gameObject&&(this.gameObject[Io]=e)}gameObject;guid="invalid";sourceId;awake(){}onEnable(){}onDisable(){}onDestroy(){this.__destroyed=!0}startCoroutine(e,t=xe.Update){return this.context.registerCoroutineUpdate(this,e,t)}stopCoroutine(e,t=xe.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),If()&&Jw(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}))),dw(this),If()&&ex(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 ee(this.gameObject)}set worldPosition(e){yt(this.gameObject,e)}setWorldPosition(e,t,i){Sr(this.gameObject,e,t,i)}get worldQuaternion(){return _e(this.gameObject)}set worldQuaternion(e){Sn(this.gameObject,e)}setWorldQuaternion(e,t,i,n){hg(this.gameObject,e,t,i,n)}get worldEuler(){return dg(this.gameObject)}set worldEuler(e){ug(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){fc(this.gameObject,e,t,i,n)}static _forward=new b;get forward(){return E._forward.set(0,0,-1).applyQuaternion(this.worldQuaternion)}static _right=new b;get right(){return E._right.set(1,0,0).applyQuaternion(this.worldQuaternion)}static _up=new b;get up(){return E._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 IE=Object.freeze(Object.defineProperty({__proto__:null,Behaviour:E,Component:E,GameObject:S},Symbol.toStringTag,{value:"Module"}));var LE=Object.defineProperty,ix=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&LE(e,t,n),n};class Gc extends E{from;to;width=0;centered=!0;_centerPos;awake(){this._centerPos=new b}update(){if(!this.from||!this.to)return;const e=ee(this.from).clone(),t=ee(this.to).clone(),i=e.distanceTo(t);this._centerPos.copy(e),this._centerPos.add(t),this._centerPos.multiplyScalar(.5),yt(this.gameObject,this.centered?this._centerPos:e),this.gameObject.lookAt(ee(this.to).clone()),this.gameObject.scale.set(this.width,this.width,i)}}ix([u(S)],Gc.prototype,"from"),ix([u(S)],Gc.prototype,"to");var jE=Object.defineProperty,DE=Object.getOwnPropertyDescriptor,Nr=(o,e,t,i)=>{for(var n=i>1?void 0:i?DE(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&jE(e,t,n),n};const Ts=w("debuganimation");let nx=class{x;y};class Ut extends E{get isAnimationComponent(){return!0}addClip(e){this.animations||(this.animations=[]),this.animations.includes(e)||this.animations.push(e)}playAutomatically=!0;randomStartTime=!1;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){Ts&&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,Ts&&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){Ts&&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){Ts&&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(Ts&&console.log("PLAY",e),this.ensureMixer(),!this.mixer){Ts&&console.warn("Missing mixer",this);return}e===void 0&&(e=0);let i=e;if(typeof e=="number"){if(e>=this.animations.length){Ts&&console.log("No animation at index",e);return}i=this.animations[e]}else typeof e=="string"&&(i=this.animations.find(s=>s.name===e));if(!i){console.error("Could not find clip",e);return}t||(t={});for(const s of this.actions)if(s.getClip()===i)return this.internalOnPlay(s,t);if(!i.tracks){console.warn("Clip is no AnimationClip",i);return}const n=this.mixer.clipAction(i);return this.actions.push(n),this.internalOnPlay(n,t)}internalOnPlay(e,t){var i=this.actions.find(s=>s===e);if(i===e&&i.isRunning()&&i.time<i.getClip().duration){const s=this.tryFindHandle(e);if(i.paused&&(i.paused=!1),s)return s.waitForFinish()}if(t.loop===void 0&&(t.loop=this.loop),t.clampWhenFinished===void 0&&(t.clampWhenFinished=this.clampWhenFinished),t.minMaxOffsetNormalized===void 0&&this.randomStartTime&&(t.minMaxOffsetNormalized=this.minMaxOffsetNormalized),t.minMaxSpeed===void 0&&(t.minMaxSpeed=this.minMaxSpeed),t?.exclusive??!0)for(const s of this.actions)s!=i&&(t.fadeDuration?s.fadeOut(t.fadeDuration):s.stop());if(t?.fadeDuration&&e.fadeIn(t.fadeDuration),e.enabled=!0,t?.startTime!=null)e.time=t.startTime;else if(t?.minMaxOffsetNormalized&&t.minMaxOffsetNormalized.x!=0&&t.minMaxOffsetNormalized.y!=0){const s=e.getClip();e.time=D.lerp(t.minMaxOffsetNormalized.x,t.minMaxOffsetNormalized.y,Math.random())*s.duration}else e.time>=e.getClip().duration&&(e.time=0);t?.minMaxSpeed?e.timeScale=D.lerp(t.minMaxSpeed.x,t.minMaxSpeed.y,Math.random()):e.timeScale=t?.speed??1,t?.loop!=null?e.loop=t.loop?aC:Am:e.loop=Am,t?.clampWhenFinished&&(e.clampWhenFinished=!0),e.paused=!1,e.play(),window.requestAnimationFrame(()=>Qn.testIfRootCanAnimate(e)),Ts&&console.log("PLAY",e.getClip().name,e);const n=new BE(e,this.mixer,t,s=>{this._handles.splice(this._handles.indexOf(n),1)});return this._handles.push(n),n.waitForFinish()}tryFindHandle(e){for(const t of this._handles)if(t.action===e)return t}ensureMixer(){if(!this.mixer){const e="animationMixer";this.gameObject[e]&&(this.mixer=this.gameObject[e]),(!this.mixer||!this.mixer.clipAction)&&(this.mixer=new Im(this.gameObject),this.gameObject[e]=this.mixer)}this.context.animations.registerAnimationMixer(this.mixer)}}Nr([u()],Ut.prototype,"playAutomatically",2),Nr([u()],Ut.prototype,"randomStartTime",2),Nr([u(nx)],Ut.prototype,"minMaxSpeed",2),Nr([u(nx)],Ut.prototype,"minMaxOffsetNormalized",2),Nr([u()],Ut.prototype,"loop",2),Nr([u()],Ut.prototype,"clampWhenFinished",2),Nr([u(ki)],Ut.prototype,"clips",1);class BE{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 Iu=Symbol("objectIsAnimatedData");function ox(o,e,t){if(!o)return;if(o[Iu]===void 0){if(!t)return;o[Iu]=new Set}const i=o[Iu];t?i.add(e):i.has(e)&&i.delete(e)}function FE(o){if(!o)return!1;const e=o[Iu];return e!==void 0&&e.size>0}class UE{_context;get context(){return this._context??U.Current}get isStateMachineBehaviour(){return!0}}class qc{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 sx(o,e){return{name:"Empty",isLooping:!1,guid:e?.generateUUID()??Co.generateUUID(),index:-1,clip:new ki(o,0,[])}}var As=(o=>(o[o.If=1]="If",o[o.IfNot=2]="IfNot",o[o.Greater=3]="Greater",o[o.Less=4]="Less",o[o.Equals=6]="Equals",o[o.NotEqual=7]="NotEqual",o))(As||{}),Lf=(o=>(o[o.Float=1]="Float",o[o.Int=3]="Int",o[o.Bool=4]="Bool",o[o.Trigger=9]="Trigger",o))(Lf||{});const lt=w("debuganimatorcontroller"),Lu=w("debugrootmotion");class gn{static createFromClips(e,t={looping:!1,autoTransition:!0,transitionDuration:0}){const i=[];for(let s=0;s<e.length;s++){const r=e[s],a=[];if(t.autoTransition!==!1){const c=t.transitionDuration??0,h=c/r.duration;let d=s;(t.autoTransition===void 0||t.autoTransition===!0)&&(d=(s+1)%e.length),a.push({exitTime:1-h,offset:0,duration:c,hasExitTime:!0,destinationState:d,conditions:[]})}const l={name:r.name,hash:s,motion:{name:r.name,clip:r,isLooping:t?.looping??!1},transitions:a,behaviours:[]};i.push(l)}const n={name:"AnimatorController",guid:new Dt(Date.now()).generateUUID(),parameters:[],layers:[{name:"Base Layer",stateMachine:{defaultState:0,states:i}}]};return new gn(n)}play(e,t=-1,i=Number.NEGATIVE_INFINITY,n=0){if(t<0)t=0;else if(t>=this.model.layers.length){console.warn("invalid layer");return}const s=this.model.layers[t].stateMachine;for(const r of s.states)if(r.name===e||r.hash===e){lt&&console.log("transition to ",r),this.transitionTo(r,n,i);return}console.warn("Could not find "+e+" to play")}reset(){this.setStartTransition()}setBool(e,t){const i=typeof e=="string"?"name":"hash";return this.model?.parameters?.filter(n=>n[i]===e).forEach(n=>n.value=t)}getBool(e){const t=typeof e=="string"?"name":"hash";return this.model?.parameters?.find(i=>i[t]===e)?.value??!1}setFloat(e,t){const i=typeof e=="string"?"name":"hash",n=this.model?.parameters?.filter(s=>s[i]===e);return n.forEach(s=>s.value=t),n?.length>0}getFloat(e){const t=typeof e=="string"?"name":"hash";return this.model?.parameters?.find(i=>i[t]===e)?.value??0}setInteger(e,t){const i=typeof e=="string"?"name":"hash";return this.model?.parameters?.filter(n=>n[i]===e).forEach(n=>n.value=t)}getInteger(e){const t=typeof e=="string"?"name":"hash";return this.model?.parameters?.find(i=>i[t]===e)?.value??0}setTrigger(e){lt&&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 qc(this._activeState,i,t,this._speed)}get currentAction(){return this._activeState&&this._activeState.motion.action||null}normalizedStartOffset=0;animator;model;get context(){return this.animator?.context}get mixer(){return this._mixer}dispose(){if(this._mixer.stopAllAction(),this.animator){this._mixer.uncacheRoot(this.animator.gameObject);for(const e of this._activeStates)e.motion.clip&&this.mixer.uncacheAction(e.motion.clip,this.animator.gameObject)}this.context?.animations.unregisterAnimationMixer(this._mixer)}bind(e){e?this.animator!==e&&(this._mixer&&(this._mixer.stopAllAction(),this.context?.animations.unregisterAnimationMixer(this._mixer)),this.animator=e,this._mixer=new Im(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;lt&&console.warn("AnimatorController clone()",this.model);const e=pc(this.model,(t,i,n)=>n==null?!0:!(n.type==="Object3D"||n.isObject3D===!0||P_(n)||n.tracks!==void 0||n instanceof gn));return console.assert(e!==this.model),new gn(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,lt&&console.log(this)}_activeStates=[];updateActiveStates(e){for(let t=0;t<this._activeStates.length;t++){const i=this._activeStates[t],n=i.motion;if(!n.action)this._activeStates.splice(t,1),t--;else{const s=n.action;s.weight=e,s.getEffectiveWeight()<=0&&!s.isRunning()&&(lt&&console.debug("REMOVE",i.name,s.getEffectiveWeight(),s.isRunning(),s.isScheduled()),this._activeStates.splice(t,1),t--)}}}setStartTransition(){this.model.layers.length>1&&(lt||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&&(lt&&console.warn("AnimatorController default state is undefined, will assign state 0 as default",e),t.defaultState=0);const i=t.states[t.defaultState];this.transitionTo(i,0,this.normalizedStartOffset);break}}evaluateTransitions(){let e=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;e=!0}const t=this._activeState,i=t.motion.action;for(const s of t.transitions){if(!s.hasExitTime&&s.conditions.length<=0)continue;let r=!0;for(const a of s.conditions)if(!this.evaluateCondition(a)){r=!1;break}if(r)if(i){const a=t.motion.clip.duration,l=a<=0?1:Math.abs(i.time/a);let c=s.exitTime;i.timeScale<0&&(c=1-c);let h=!1;if(s.hasExitTime?i.timeScale>0?h=l>=s.exitTime:i.timeScale<0&&(h=1-l>=s.exitTime):h=!0,h){for(const d of s.conditions){const p=this.model.parameters.find(m=>m.name===d.parameter);p?.type===Lf.Trigger&&p.value&&(p.value=!1)}if(i.clampWhenFinished=!0,lt){const d=this.getState(s.destinationState,0);console.log(`Transition to ${s.destinationState} / ${d?.name}`,s,`
|
|
890
|
+
`,i=`Needle Engine \u2014 No license active, commercial use is not allowed. Visit https://needle.tools/pricing for more information and licensing options! v${Ti}`;U.Current?.xr||navigator.webdriver?console.log(i):console.log("%c "+i,t)}async function ME(o){if(!window.crossOriginIsolated){if(!gi.isAllowed(o)){Ot&&console.debug("Telemetry is disabled via no-telemetry attribute");return}try{const e="https://needle.tools/api/v1/needle-engine/ping";if(e){const t=window.location.href.split("?")[0],i={license:Rn,url:t,hostname:window.location.hostname,pathname:window.location.pathname,version:Ti,generator:Wa,build_time:wc,public_key:Ss},n=navigator.sendBeacon?.(e,JSON.stringify(i));Ot&&console.debug("Sent beacon: "+n)}}catch(e){Ot&&console.log("Failed to send non-commercial usage message to analytics backend",e)}}}const EE=w("debugdecoders");let Tf=null;function Xw(){if(!Tf){const o=Um(null);Tf={dracoLoader:o.dracoLoader,ktx2Loader:o.ktx2Loader,meshoptDecoder:o.meshoptDecoder}}return Tf}function Qw(o){o!==void 0&&typeof o=="string"&&hP(o)}function Yw(o){if(o!==void 0&&typeof o=="string"&&o!=="js"){const e=Xw();EE&&console.log("Setting draco decoder type to",o),e.dracoLoader.setDecoderConfig({type:o})}}function Zw(o){o!==void 0&&typeof o=="string"&&cP(o)}function Af(o,e){const t=Xw();return e.renderer?t.ktx2Loader.detectSupport(e.renderer):console.warn("No renderer provided to detect ktx2 support - loading KTX2 textures will probably fail"),aP(o),o.dracoLoader||o.setDRACOLoader(t.dracoLoader),o.ktx2Loader||o.setKTX2Loader(t.ktx2Loader),o.meshoptDecoder||o.setMeshoptDecoder(t.meshoptDecoder),lP(o,{progressive:!0}),o}const Ye=function(o){return u(o)},u=function(o){if(o===void 0&&(o=null),!Array.isArray(o))o=Kw(o);else for(let e=0;e<o.length;e++){const t=o[e];o[e]=Kw(t)}return function(e,t){if(!e){const n=typeof t=="string"?t:t.name;console.warn(`@serializable without a target at '${n}'.`);return}typeof t!="string"&&(t=t.name),Object.getOwnPropertyDescriptor(e,"$serializedTypes")||(e.$serializedTypes={});const i=e.$serializedTypes=e.$serializedTypes||{};i[t]=o}};function Kw(o){switch(o?.prototype?.constructor?.name){case"Number":case"String":case"Boolean":return null}return o}const Rs=w("debughotreload");let $c=!1;const Hc=new Map;function RE(){return $c}function If(){return globalThis.NEEDLE_HOT_RELOAD_ENABLED===!0}function Jw(o){if($c){Rs&&console.warn("[Needle Engine] Hot reloading is in progress, not registering instance",o);return}Rs&&console.log("[Needle Engine] Registering hot reload instance",o);const e=o.constructor.name;Hc.has(e)?Hc.get(e)?.push(o):Hc.set(e,[o])}function ex(o){if($c){Rs&&console.warn("[Needle Engine] Hot reloading is in progress, not unregistering instance",o);return}Rs&&console.log("[Needle Engine] Unregistering hot reload instance",o);const e=o.constructor.name,t=Hc.get(e);if(!t)return;const i=t.indexOf(o);i!==-1&&t.splice(i,1)}let tx=!1;function TE(){if(Rs||tx)return;tx=!0;const o=console.error;console.error=(...e)=>{if(e.length){const t=e[0];if(typeof t=="string"&&t.includes("[hmr] Failed to reload ")){console.log("[Needle Engine] Hot reloading failed"),window.location.reload();return}}o.apply(console,e)}}function AE(o){Rs&&console.log("[HMR] Apply changes",o,Object.keys(o)),TE();for(const e of Object.keys(o))try{$c=!0;const t=C.get(e);if(!t){Rs&&console.log("[HMR] Type not found: "+e);continue}const i=o[e],n=Hc.get(i.name);let s="[Needle Engine] Updating type: "+e;const r=n?.length??-1;r>0?s+=" x"+r:s+=" (No instances registered)",console.log(s);const a=Object.getOwnPropertyNames(t.prototype),l=Object.getOwnPropertyDescriptors(i.prototype);for(const c in l)l[c].writable&&(t.prototype[c]=o[e].prototype[c]);for(const c of a)l[c]||delete t.prototype[c];if(n){const c=new i,h=Object.getOwnPropertyDescriptors(c);for(const d of n){const p=d,m=p.isComponent===!0,g=m?p.activeAndEnabled:!0,f=m?p.context:void 0;try{if(m&&f&&Bo(p,f),m&&g&&(p.enabled=!1),d.onBeforeHotReloadFields&&d.onBeforeHotReloadFields()===!1)continue;for(const y in h)if(h[y].writable){if(d[y]===void 0)d[y]=c[y];else if(typeof d[y]=="function"&&!d[y].prototype){const _=d[y],v=_.name,P="bound ";if(v===P)continue;const k=_.name.substring(P.length),O=i.prototype[k];O&&(d[y]=O.bind(d))}}d.onAfterHotReloadFields&&d.onAfterHotReloadFields()}finally{m&&f&&Hg(p,f),m&&g&&(p.enabled=!0)}}}}catch(t){if(Rs)console.error(t);else return!1}finally{$c=!1,xr(Ri.Log,"Script changes applied (HMR)")}return!0}class S extends M{guid;static isDestroyed(e){return Br(e)}static setActive(e,t,i=!0){e&&(zc(e,t),cu(e),t&&i&&Bv(U.Current,e))}static isActiveSelf(e){return il(e)}static isActiveInHierarchy(e){return gw(e)}static markAsInstancedRendered(e,t){fw(e,t)}static isUsingInstancing(e){return bu(e)}static foreachComponent(e,t,i=!0){return Fr(e,t,i)}static instantiateSynced(e,t){return e?Kg(e,t):null}static instantiate(e,t=null){return"isAssetReference"in e,Ur(e,t)}static destroySynced(e,t,i=!0){if(!e)return;const n=e;t=t??U.Current,Lc(n,t.connection,i)}static destroy(e,t=!0){return Ii(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=U.Current),t.add(e),zc(e,!0),cu(e),i?S.foreachComponent(e,n=>{Hg(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),zc(e,!1),cu(e),S.foreachComponent(e,t=>{mM(t)},!0))}static invokeOnChildren(e,t,...i){this.invoke(e,t,!0,i)}static invoke(e,t,i=!1,...n){e&&this.foreachComponent(e,s=>{const r=s[t];r&&typeof r=="function"&&r?.call(s,...n)},i)}static addNewComponent(e,t,i,n=!0){return Mn(e,t,i,{callAwake:n})}static addComponent(e,t,i,n){return Mn(e,t,i,n)}static moveComponent(e,t){return Mn(e,t)}static removeComponent(e){return cf(e.gameObject,e),e}static getOrAddComponent(e,t){return Dc(e,t)}static getComponent(e,t){return e===null?null:jr(e,t)}static getComponents(e,t,i=null){return e===null?i??[]:Bc(e,t,i)}static findByGuid(e,t){return hf(e,t)}static findObjectOfType(e,t,i=!0){return tl(e,t??U.Current,i)}static findObjectsOfType(e,t){const i=[];return mw(e,i,t),i}static getComponentInChildren(e,t,i=!1){return Fc(e,t,i)}static getComponentsInChildren(e,t,i=null){return el(e,t,i??void 0)}static getComponentInParent(e,t){return Uc(e,t)}static getComponentsInParent(e,t,i=null){return gu(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 E{get isComponent(){return!0}get[V_](){return C.getKey(this.constructor)||void 0}__context;get context(){return this.__context??U.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[Io];return e===void 0?!0:e}set __isActiveInHierarchy(e){this.gameObject&&(this.gameObject[Io]=e)}gameObject;guid="invalid";sourceId;awake(){}onEnable(){}onDisable(){}onDestroy(){this.__destroyed=!0}startCoroutine(e,t=xe.Update){return this.context.registerCoroutineUpdate(this,e,t)}stopCoroutine(e,t=xe.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),If()&&Jw(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}))),dw(this),If()&&ex(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 ee(this.gameObject)}set worldPosition(e){yt(this.gameObject,e)}setWorldPosition(e,t,i){Sr(this.gameObject,e,t,i)}get worldQuaternion(){return _e(this.gameObject)}set worldQuaternion(e){Sn(this.gameObject,e)}setWorldQuaternion(e,t,i,n){hg(this.gameObject,e,t,i,n)}get worldEuler(){return dg(this.gameObject)}set worldEuler(e){ug(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){fc(this.gameObject,e,t,i,n)}static _forward=new b;get forward(){return E._forward.set(0,0,-1).applyQuaternion(this.worldQuaternion)}static _right=new b;get right(){return E._right.set(1,0,0).applyQuaternion(this.worldQuaternion)}static _up=new b;get up(){return E._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 IE=Object.freeze(Object.defineProperty({__proto__:null,Behaviour:E,Component:E,GameObject:S},Symbol.toStringTag,{value:"Module"}));var LE=Object.defineProperty,ix=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&LE(e,t,n),n};class Gc extends E{from;to;width=0;centered=!0;_centerPos;awake(){this._centerPos=new b}update(){if(!this.from||!this.to)return;const e=ee(this.from).clone(),t=ee(this.to).clone(),i=e.distanceTo(t);this._centerPos.copy(e),this._centerPos.add(t),this._centerPos.multiplyScalar(.5),yt(this.gameObject,this.centered?this._centerPos:e),this.gameObject.lookAt(ee(this.to).clone()),this.gameObject.scale.set(this.width,this.width,i)}}ix([u(S)],Gc.prototype,"from"),ix([u(S)],Gc.prototype,"to");var jE=Object.defineProperty,DE=Object.getOwnPropertyDescriptor,Nr=(o,e,t,i)=>{for(var n=i>1?void 0:i?DE(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&jE(e,t,n),n};const Ts=w("debuganimation");let nx=class{x;y};class Ut extends E{get isAnimationComponent(){return!0}addClip(e){this.animations||(this.animations=[]),this.animations.includes(e)||this.animations.push(e)}playAutomatically=!0;randomStartTime=!1;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){Ts&&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,Ts&&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){Ts&&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){Ts&&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(Ts&&console.log("PLAY",e),this.ensureMixer(),!this.mixer){Ts&&console.warn("Missing mixer",this);return}e===void 0&&(e=0);let i=e;if(typeof e=="number"){if(e>=this.animations.length){Ts&&console.log("No animation at index",e);return}i=this.animations[e]}else typeof e=="string"&&(i=this.animations.find(s=>s.name===e));if(!i){console.error("Could not find clip",e);return}t||(t={});for(const s of this.actions)if(s.getClip()===i)return this.internalOnPlay(s,t);if(!i.tracks){console.warn("Clip is no AnimationClip",i);return}const n=this.mixer.clipAction(i);return this.actions.push(n),this.internalOnPlay(n,t)}internalOnPlay(e,t){var i=this.actions.find(s=>s===e);if(i===e&&i.isRunning()&&i.time<i.getClip().duration){const s=this.tryFindHandle(e);if(i.paused&&(i.paused=!1),s)return s.waitForFinish()}if(t.loop===void 0&&(t.loop=this.loop),t.clampWhenFinished===void 0&&(t.clampWhenFinished=this.clampWhenFinished),t.minMaxOffsetNormalized===void 0&&this.randomStartTime&&(t.minMaxOffsetNormalized=this.minMaxOffsetNormalized),t.minMaxSpeed===void 0&&(t.minMaxSpeed=this.minMaxSpeed),t?.exclusive??!0)for(const s of this.actions)s!=i&&(t.fadeDuration?s.fadeOut(t.fadeDuration):s.stop());if(t?.fadeDuration&&e.fadeIn(t.fadeDuration),e.enabled=!0,t?.startTime!=null)e.time=t.startTime;else if(t?.minMaxOffsetNormalized&&t.minMaxOffsetNormalized.x!=0&&t.minMaxOffsetNormalized.y!=0){const s=e.getClip();e.time=j.lerp(t.minMaxOffsetNormalized.x,t.minMaxOffsetNormalized.y,Math.random())*s.duration}else e.time>=e.getClip().duration&&(e.time=0);t?.minMaxSpeed?e.timeScale=j.lerp(t.minMaxSpeed.x,t.minMaxSpeed.y,Math.random()):e.timeScale=t?.speed??1,t?.loop!=null?e.loop=t.loop?aC:Am:e.loop=Am,t?.clampWhenFinished&&(e.clampWhenFinished=!0),e.paused=!1,e.play(),window.requestAnimationFrame(()=>Qn.testIfRootCanAnimate(e)),Ts&&console.log("PLAY",e.getClip().name,e);const n=new BE(e,this.mixer,t,s=>{this._handles.splice(this._handles.indexOf(n),1)});return this._handles.push(n),n.waitForFinish()}tryFindHandle(e){for(const t of this._handles)if(t.action===e)return t}ensureMixer(){if(!this.mixer){const e="animationMixer";this.gameObject[e]&&(this.mixer=this.gameObject[e]),(!this.mixer||!this.mixer.clipAction)&&(this.mixer=new Im(this.gameObject),this.gameObject[e]=this.mixer)}this.context.animations.registerAnimationMixer(this.mixer)}}Nr([u()],Ut.prototype,"playAutomatically",2),Nr([u()],Ut.prototype,"randomStartTime",2),Nr([u(nx)],Ut.prototype,"minMaxSpeed",2),Nr([u(nx)],Ut.prototype,"minMaxOffsetNormalized",2),Nr([u()],Ut.prototype,"loop",2),Nr([u()],Ut.prototype,"clampWhenFinished",2),Nr([u(ki)],Ut.prototype,"clips",1);class BE{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 Iu=Symbol("objectIsAnimatedData");function ox(o,e,t){if(!o)return;if(o[Iu]===void 0){if(!t)return;o[Iu]=new Set}const i=o[Iu];t?i.add(e):i.has(e)&&i.delete(e)}function FE(o){if(!o)return!1;const e=o[Iu];return e!==void 0&&e.size>0}class UE{_context;get context(){return this._context??U.Current}get isStateMachineBehaviour(){return!0}}class qc{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 sx(o,e){return{name:"Empty",isLooping:!1,guid:e?.generateUUID()??Co.generateUUID(),index:-1,clip:new ki(o,0,[])}}var As=(o=>(o[o.If=1]="If",o[o.IfNot=2]="IfNot",o[o.Greater=3]="Greater",o[o.Less=4]="Less",o[o.Equals=6]="Equals",o[o.NotEqual=7]="NotEqual",o))(As||{}),Lf=(o=>(o[o.Float=1]="Float",o[o.Int=3]="Int",o[o.Bool=4]="Bool",o[o.Trigger=9]="Trigger",o))(Lf||{});const lt=w("debuganimatorcontroller"),Lu=w("debugrootmotion");class gn{static createFromClips(e,t={looping:!1,autoTransition:!0,transitionDuration:0}){const i=[];for(let s=0;s<e.length;s++){const r=e[s],a=[];if(t.autoTransition!==!1){const c=t.transitionDuration??0,h=c/r.duration;let d=s;(t.autoTransition===void 0||t.autoTransition===!0)&&(d=(s+1)%e.length),a.push({exitTime:1-h,offset:0,duration:c,hasExitTime:!0,destinationState:d,conditions:[]})}const l={name:r.name,hash:s,motion:{name:r.name,clip:r,isLooping:t?.looping??!1},transitions:a,behaviours:[]};i.push(l)}const n={name:"AnimatorController",guid:new Dt(Date.now()).generateUUID(),parameters:[],layers:[{name:"Base Layer",stateMachine:{defaultState:0,states:i}}]};return new gn(n)}play(e,t=-1,i=Number.NEGATIVE_INFINITY,n=0){if(t<0)t=0;else if(t>=this.model.layers.length){console.warn("invalid layer");return}const s=this.model.layers[t].stateMachine;for(const r of s.states)if(r.name===e||r.hash===e){lt&&console.log("transition to ",r),this.transitionTo(r,n,i);return}console.warn("Could not find "+e+" to play")}reset(){this.setStartTransition()}setBool(e,t){const i=typeof e=="string"?"name":"hash";return this.model?.parameters?.filter(n=>n[i]===e).forEach(n=>n.value=t)}getBool(e){const t=typeof e=="string"?"name":"hash";return this.model?.parameters?.find(i=>i[t]===e)?.value??!1}setFloat(e,t){const i=typeof e=="string"?"name":"hash",n=this.model?.parameters?.filter(s=>s[i]===e);return n.forEach(s=>s.value=t),n?.length>0}getFloat(e){const t=typeof e=="string"?"name":"hash";return this.model?.parameters?.find(i=>i[t]===e)?.value??0}setInteger(e,t){const i=typeof e=="string"?"name":"hash";return this.model?.parameters?.filter(n=>n[i]===e).forEach(n=>n.value=t)}getInteger(e){const t=typeof e=="string"?"name":"hash";return this.model?.parameters?.find(i=>i[t]===e)?.value??0}setTrigger(e){lt&&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 qc(this._activeState,i,t,this._speed)}get currentAction(){return this._activeState&&this._activeState.motion.action||null}normalizedStartOffset=0;animator;model;get context(){return this.animator?.context}get mixer(){return this._mixer}dispose(){if(this._mixer.stopAllAction(),this.animator){this._mixer.uncacheRoot(this.animator.gameObject);for(const e of this._activeStates)e.motion.clip&&this.mixer.uncacheAction(e.motion.clip,this.animator.gameObject)}this.context?.animations.unregisterAnimationMixer(this._mixer)}bind(e){e?this.animator!==e&&(this._mixer&&(this._mixer.stopAllAction(),this.context?.animations.unregisterAnimationMixer(this._mixer)),this.animator=e,this._mixer=new Im(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;lt&&console.warn("AnimatorController clone()",this.model);const e=pc(this.model,(t,i,n)=>n==null?!0:!(n.type==="Object3D"||n.isObject3D===!0||P_(n)||n.tracks!==void 0||n instanceof gn));return console.assert(e!==this.model),new gn(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,lt&&console.log(this)}_activeStates=[];updateActiveStates(e){for(let t=0;t<this._activeStates.length;t++){const i=this._activeStates[t],n=i.motion;if(!n.action)this._activeStates.splice(t,1),t--;else{const s=n.action;s.weight=e,s.getEffectiveWeight()<=0&&!s.isRunning()&&(lt&&console.debug("REMOVE",i.name,s.getEffectiveWeight(),s.isRunning(),s.isScheduled()),this._activeStates.splice(t,1),t--)}}}setStartTransition(){this.model.layers.length>1&&(lt||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&&(lt&&console.warn("AnimatorController default state is undefined, will assign state 0 as default",e),t.defaultState=0);const i=t.states[t.defaultState];this.transitionTo(i,0,this.normalizedStartOffset);break}}evaluateTransitions(){let e=!1;if(!this._activeState){if(this.setStartTransition(),!this._activeState)return;e=!0}const t=this._activeState,i=t.motion.action;for(const s of t.transitions){if(!s.hasExitTime&&s.conditions.length<=0)continue;let r=!0;for(const a of s.conditions)if(!this.evaluateCondition(a)){r=!1;break}if(r)if(i){const a=t.motion.clip.duration,l=a<=0?1:Math.abs(i.time/a);let c=s.exitTime;i.timeScale<0&&(c=1-c);let h=!1;if(s.hasExitTime?i.timeScale>0?h=l>=s.exitTime:i.timeScale<0&&(h=1-l>=s.exitTime):h=!0,h){for(const d of s.conditions){const p=this.model.parameters.find(m=>m.name===d.parameter);p?.type===Lf.Trigger&&p.value&&(p.value=!1)}if(i.clampWhenFinished=!0,lt){const d=this.getState(s.destinationState,0);console.log(`Transition to ${s.destinationState} / ${d?.name}`,s,`
|
|
891
891
|
Timescale: `+i.timeScale,`
|
|
892
892
|
Normalized time: `+l.toFixed(3),`
|
|
893
|
-
Exit Time: `+c,s.hasExitTime)}this.transitionTo(s.destinationState,s.duration,s.offset);return}}else{this.transitionTo(s.destinationState,s.duration,s.offset);return}}i&&this.setTimescale(i,t);let n=!1;if(t.motion.isLooping&&i&&(i.time>=i.getClip().duration?(n=!0,i.reset(),i.time=0,i.play()):i.time<=0&&i.timeScale<0&&(n=!0,i.reset(),i.time=i.getClip().duration,i.play())),!n&&t&&!e&&i&&this.animator&&t.behaviours){const s=i?.getClip().duration,r=i.time/s,a=new qc(this._activeState,r,s,this._speed);for(const l of t.behaviours)l.instance&&l.instance.onStateUpdate?.call(l.instance,this.animator,a,0)}}setTimescale(e,t){let i=t.speed??1;t.speedParameter&&(i*=this.getFloat(t.speedParameter)),i!==void 0&&(e.timeScale=i*this._speed)}getState(e,t){return typeof e=="number"&&(e==-1&&(e=this.model.layers[t].stateMachine.defaultState,e===void 0&&(lt&&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 ki))return;const s=this._activeState===e;if(s){const h=e.motion;if(!h.action_loopback&&h.clip){const d=this.rootMotionHandler?this.animator.gameObject.matrix.clone():null;this._mixer.uncacheAction(h.clip,this.animator.gameObject),d&&d.decompose(this.animator.gameObject.position,this.animator.gameObject.quaternion,this.animator.gameObject.scale),h.action_loopback=this.createAction(h.clip)}}if(this._activeState?.behaviours&&this._activeState.motion.action){const h=this._activeState?.motion.clip.duration,d=this._activeState.motion.action.time/h,p=new qc(this._activeState,d,h,this._speed);for(const m of this._activeState.behaviours)m.instance?.onStateExit?.call(m.instance,this.animator,p,n)}const r=this._activeState?.motion.action;s&&(e.motion.action=e.motion.action_loopback,e.motion.action_loopback=r);const a=this._activeState;this._activeState=e;const l=e.motion?.action,c=e.motion.clip;if(c?.duration<=0&&c.tracks.length<=0?r&&this._heldActions.push(r):r&&(r.fadeOut(t),this.releaseHeldActions(t)),l){if(i=Math.max(0,Math.min(1,i)),e.cycleOffsetParameter){let d=this.getFloat(e.cycleOffsetParameter);typeof d=="number"?(d<0&&(d+=1),i+=d,i%=1):lt&&console.warn("AnimatorController cycle offset parameter is not a number",e.cycleOffsetParameter)}else typeof e.cycleOffset=="number"&&(i+=e.cycleOffset,i%=1);l.isRunning()&&l.stop(),l.reset(),l.enabled=!0,this.setTimescale(l,e);const h=e.motion.clip.duration;if(l.time=s?0:i*h,l.timeScale<0&&(l.time=h-l.time),l.clampWhenFinished=!0,l.setLoop(Am,0),t>0?l.fadeIn(t):l.weight=1,l.play(),window.requestAnimationFrame(()=>Qn.testIfRootCanAnimate(l)),this.rootMotionHandler&&this.rootMotionHandler.onStart(l),this._activeStates.includes(e)||this._activeStates.push(e),this._activeState.behaviours){const d=new qc(e,i,h,this._speed);for(const p of this._activeState.behaviours)p.instance?.onStateEnter?.call(p.instance,this.animator,d,n)}}else lt&&(e.__warned_no_motion||(e.__warned_no_motion=!0,console.warn("No action",e.motion,this)));lt&&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 zE(this));const t=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,t,e)}else return this._mixer.clipAction(e)}evaluateCondition(e){const t=this.model.parameters.find(i=>i.name===e.parameter);if(!t)return!1;switch(e.mode){case As.If:return t.value===!0;case As.IfNot:return t.value===!1;case As.Greater:return t.value>e.threshold;case As.Less:return t.value<e.threshold;case As.Equals:return t.value===e.threshold;case As.NotEqual:return t.value!==e.threshold}return!1}createActions(e){lt&&console.log("AnimatorController createActions",this.model);for(const t of this.model.layers){const i=t.stateMachine;for(let n=0;n<i.states.length;n++){const s=i.states[n];s.transitions||(s.transitions=[]);for(const r of s.transitions)r.conditions||(r.conditions=[]);if(s.motion||(lt&&console.warn("No motion",s),s.motion=sx(s.name)),this.animator&&s.motion.clips){const r=s.motion.clips?.find(a=>a.node.name===this.animator?.gameObject?.name);r?s.motion.clip=r.clip:(lt||A())&&console.warn('Could not find clip for animator "'+this.animator?.gameObject?.name+'"',s.motion.clips.map(a=>a.node.name))}if(!s.motion.clip){lt&&console.warn("No clip assigned to state",s);const r=new ki(void 0,void 0,[]);s.motion.clip=r}if(s.motion?.clip){const r=s.motion.clip;if(r instanceof ki){const a=this.createAction(r);s.motion.action=a}else(lt||A())&&console.warn("No valid animationclip assigned",s)}if(s.behaviours&&Array.isArray(s.behaviours))for(const r of s.behaviours){if(!r?.typeName)continue;const a=C.get(r.typeName);if(a){const l=new a;l.isStateMachineBehaviour&&(l._context=this.context??void 0,Ja(l,r.properties),r.instance=l),lt&&console.log("Created animator controller behaviour",s.name,r.typeName,r.properties,l)}else(lt||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 rx{track;createdInterpolant;originalEvaluate;customEvaluate;constructor(e,t){this.track=e;const i=e,n=i.createInterpolant.bind(e);i.createInterpolant=()=>(i.createInterpolant=n,this.createdInterpolant=n(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=s=>{if(!this.originalEvaluate)return;const r=this.originalEvaluate(s);return t(s,r)},this.createdInterpolant.evaluate=this.customEvaluate,this.createdInterpolant)}dispose(){this.createdInterpolant&&this.originalEvaluate&&(this.createdInterpolant.evaluate=this.originalEvaluate),this.track=void 0,this.createdInterpolant=null,this.originalEvaluate=void 0,this.customEvaluate=void 0}}class mt{static lastObjPosition={};static lastObjRotation={};static firstKeyframeRotation={};static spaceRotation={};static effectiveSpaceRotation={};static clipOffsetRotation={};set action(e){this._action=e}get action(){return this._action}get cacheId(){return this.root.uuid}_action;root;clip;positionWrapper=null;rotationWrapper=null;context;positionChange=new b;rotationChange=new N;constructor(e,t,i,n,s){if(this.context=e,this.root=t,this.clip=i,mt.firstKeyframeRotation[this.cacheId]||(mt.firstKeyframeRotation[this.cacheId]=new N),s){const r=s.values;mt.firstKeyframeRotation[this.cacheId].set(r[0],r[1],r[2],r[3])}mt.spaceRotation[this.cacheId]||(mt.spaceRotation[this.cacheId]=new N),mt.effectiveSpaceRotation[this.cacheId]||(mt.effectiveSpaceRotation[this.cacheId]=new N),mt.clipOffsetRotation[this.cacheId]=new N,s&&mt.clipOffsetRotation[this.cacheId].set(s.values[0],s.values[1],s.values[2],s.values[3]).invert(),this.handlePosition(i,n),this.handleRotation(i,s)}onStart(e){if(e.getClip()!==this.clip)return;mt.lastObjRotation[this.cacheId]||(mt.lastObjRotation[this.cacheId]=this.root.quaternion.clone());const t=mt.lastObjRotation[this.cacheId];if(mt.spaceRotation[this.cacheId].copy(t),Lu){const i=new at().setFromQuaternion(t);console.log("START",this.clip.name,D.toDegrees(i.y),this.root.position.z)}}getClipRotationOffset(){return mt.clipOffsetRotation[this.cacheId]}_prevTime=0;handlePosition(e,t){if(t){const i=this.root;Lu&&i.add(new Pi),mt.lastObjPosition[this.cacheId]||(mt.lastObjPosition[this.cacheId]=this.root.position.clone());const n=new b,s=new b;this.positionWrapper=new rx(t,(r,a)=>{const l=this.action.getEffectiveWeight();return Lu&&i.position.length()>8&&i.position.set(0,i.position.y,0),r>this._prevTime&&(n.set(a[0],a[1],a[2]),n.sub(s),n.multiplyScalar(l),n.applyQuaternion(this.getClipRotationOffset()),n.applyQuaternion(i.quaternion),this.positionChange.copy(n)),s.fromArray(a),this._prevTime=r,a[0]=0,a[1]=0,a[2]=0,a})}}static identityQuaternion=new N;handleRotation(e,t){if(t){if(Lu){const r=t.values,a=new at().setFromQuaternion(new N(r[0],r[1],r[2],r[3]));console.log(e.name,t.name,"FIRST ROTATION IN TRACK",D.toDegrees(a.y));const l=t.values.length-4,c=new N().set(r[l],r[l+1],r[l+2],r[l+3]),h=new at().setFromQuaternion(c);console.log(e.name,t.name,"LAST ROTATION IN TRACK",D.toDegrees(h.y))}let i=0;const n=new N,s=new N;this.rotationWrapper=new rx(t,(r,a)=>(r>i&&(s.set(a[0],a[1],a[2],a[3]),n.invert(),s.multiply(n),this.rotationChange.copy(s)),n.fromArray(a),i=r,a[0]=0,a[1]=0,a[2]=0,a[3]=1,a))}}onBeforeUpdate(e){this.positionChange.set(0,0,0),this.rotationChange.set(0,0,0,1)}onAfterUpdate(e){return!this.action||(e*=this.action.getEffectiveWeight(),e<=0)?!1:(this.positionChange.multiplyScalar(e),this.rotationChange.slerp(mt.identityQuaternion,1-e),!0)}}class zE{controller;handler=[];root;basePosition=new b;baseQuaternion=new N;baseRotation=new at;constructor(e){this.controller=e}createClip(e,t,i){this.root=t,t&&"name"in t&&t.name;const n=this.findRootTrack(i,".position"),s=this.findRootTrack(i,".quaternion"),r=new mt(this.controller.context,t,i,n,s);this.handler.push(r);const a=e.clipAction(i);return r.action=a,a}onStart(e){for(const t of this.handler)t.onStart(e)}onBeforeUpdate(e){this.basePosition.copy(this.root.position),this.baseQuaternion.copy(this.root.quaternion);for(const t of this.handler)t.onBeforeUpdate(e)}summedPosition=new b;summedRotation=new N;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 NE extends Zi{onSerialize(e,t){}onDeserialize(e,t){if(t.type===gn&&e?.__type==="AnimatorController")return new gn(e)}}new NE(gn);var WE=Object.defineProperty,VE=Object.getOwnPropertyDescriptor,ju=(o,e,t,i)=>{for(var n=i>1?void 0:i?VE(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&WE(e,t,n),n};const Ki=w("debuganimator");class _t extends E{get isAnimationComponent(){return!0}applyRootMotion=!1;hasRootMotion=!1;keepAnimatorControllerStateOnDisable=!1;set runtimeAnimatorController(e){this._animatorController&&this._animatorController.model===e||(e?e instanceof gn?(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 gn(e.model)),this._animatorController=e,this._animatorController.bind(this)):(Ki&&console.log("Assign animator controller",e,this),this._animatorController=new gn(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){Ki&&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 Ki&&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),Ki&&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 Ki&&console.log("getFloat",e,t),t}SetInteger(e,t){this.setInteger(e,t)}setInteger(e,t){this.runtimeAnimatorController?.getInteger(e)!==t&&(this._parametersAreDirty=!0),Ki&&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 Ki&&console.log("getInteger",e,t),t}SetTrigger(e){this.setTrigger(e)}setTrigger(e){this._parametersAreDirty=!0,Ki&&console.log("setTrigger",e),this.runtimeAnimatorController?.setTrigger(e)}ResetTrigger(e){this.resetTrigger(e)}resetTrigger(e){this._parametersAreDirty=!0,Ki&&console.log("resetTrigger",e),this.runtimeAnimatorController?.resetTrigger(e)}GetTrigger(e){this.getTrigger(e)}getTrigger(e){const t=this.runtimeAnimatorController?.getTrigger(e);return Ki&&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&&(Ki&&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(){Ki&&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,!FE(this.gameObject)&&this._animatorController&&this._animatorController.update(1)}}ju([u()],_t.prototype,"applyRootMotion",2),ju([u()],_t.prototype,"hasRootMotion",2),ju([u()],_t.prototype,"keepAnimatorControllerStateOnDisable",2),ju([u()],_t.prototype,"runtimeAnimatorController",1);const ax=Symbol("previous-visibility");class xo extends $n{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 yr){this.onBeforeRender();const n=i.getRenderTarget(),s=i.xr.enabled;i.xr.enabled=!1,i.setRenderTarget(this),i.clear(!0,!0,!0),i.render(e,t),i.setRenderTarget(n),i.xr.enabled=s,this.onAfterRender()}}static _userSet=new Set;onBeforeRender(){xo._userSet.clear();const e=Wg(this.texture,!0,null,xo._userSet);for(const t of e)t instanceof H&&(t[ax]=t.visible,t.visible=!1)}onAfterRender(){for(const e of xo._userSet)e instanceof H&&(e.visible=e[ax]);xo._userSet.clear()}}var $E=Object.defineProperty,HE=Object.getOwnPropertyDescriptor,Xc=(o,e,t,i)=>{for(var n=i>1?void 0:i?HE(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&$E(e,t,n),n};const Du=w("debuggroundprojection");class Jn extends E{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 ps(this.context.scene,"background"),this._watcher.subscribeWrite(e=>{Du&&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 mc(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 Se&&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 Se)){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){Du&&console.log("Create/Update Ground Projection",e.name),this._projection?.removeFromParent();try{this._projection=new Da(e,this._height,this._radius,64)}catch(s){console.error("Error creating three GroundProjection",s);return}this._projection.position.y=this._height-i,this._projection.name="GroundProjection",pg(this._projection,!1)}else t=!1;if(this._projection.parent||this.gameObject.add(this._projection),this.autoFit&&t){this._projection.updateWorldMatrix(!0,!0);const s=di(this.context.scene.children,[this._projection]),r=s.min.y;if(r<1/0){const a=F();a.x=s.min.x+(s.max.x-s.min.x)*.5;const l=$e(this.gameObject).x;a.y=r+this._height*l-i,a.z=s.min.z+(s.max.z-s.min.z)*.5,yt(this._projection,a)}Du&&B.DrawWireBox3(s,65280,5)}this.context.scene.backgroundBlurriness>.001&&this._needsTextureUpdate&&this.updateBlurriness(e,this.context.scene.backgroundBlurriness),this._lastBackground=e,this._lastHeight=this._height,this._lastRadius=this._radius,this._needsTextureUpdate=!1}_blurrynessShader=null;_lastBlurriness=-1;updateBlurriness(e,t){if(this._projection){if(!e)return}else return;this._needsTextureUpdate=!1,Du&&console.log("Update Blurriness",t),this._blurrynessShader??=new Vn({name:"GroundProjectionBlurriness",uniforms:{map:{value:e},blurriness:{value:t},blending:{value:0},alphaFactor:{value:1}},vertexShader:GE,fragmentShader:qE}),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=pr.copyTexture(e,this._blurrynessShader),this._projection.material.depthTest=!0,this._projection.material.depthWrite=!1}}Xc([u()],Jn.prototype,"applyOnAwake",2),Xc([u()],Jn.prototype,"autoFit",2),Xc([u()],Jn.prototype,"radius",1),Xc([u()],Jn.prototype,"height",1),Xc([u()],Jn.prototype,"arBlending",1);const GE=`
|
|
893
|
+
Exit Time: `+c,s.hasExitTime)}this.transitionTo(s.destinationState,s.duration,s.offset);return}}else{this.transitionTo(s.destinationState,s.duration,s.offset);return}}i&&this.setTimescale(i,t);let n=!1;if(t.motion.isLooping&&i&&(i.time>=i.getClip().duration?(n=!0,i.reset(),i.time=0,i.play()):i.time<=0&&i.timeScale<0&&(n=!0,i.reset(),i.time=i.getClip().duration,i.play())),!n&&t&&!e&&i&&this.animator&&t.behaviours){const s=i?.getClip().duration,r=i.time/s,a=new qc(this._activeState,r,s,this._speed);for(const l of t.behaviours)l.instance&&l.instance.onStateUpdate?.call(l.instance,this.animator,a,0)}}setTimescale(e,t){let i=t.speed??1;t.speedParameter&&(i*=this.getFloat(t.speedParameter)),i!==void 0&&(e.timeScale=i*this._speed)}getState(e,t){return typeof e=="number"&&(e==-1&&(e=this.model.layers[t].stateMachine.defaultState,e===void 0&&(lt&&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 ki))return;const s=this._activeState===e;if(s){const h=e.motion;if(!h.action_loopback&&h.clip){const d=this.rootMotionHandler?this.animator.gameObject.matrix.clone():null;this._mixer.uncacheAction(h.clip,this.animator.gameObject),d&&d.decompose(this.animator.gameObject.position,this.animator.gameObject.quaternion,this.animator.gameObject.scale),h.action_loopback=this.createAction(h.clip)}}if(this._activeState?.behaviours&&this._activeState.motion.action){const h=this._activeState?.motion.clip.duration,d=this._activeState.motion.action.time/h,p=new qc(this._activeState,d,h,this._speed);for(const m of this._activeState.behaviours)m.instance?.onStateExit?.call(m.instance,this.animator,p,n)}const r=this._activeState?.motion.action;s&&(e.motion.action=e.motion.action_loopback,e.motion.action_loopback=r);const a=this._activeState;this._activeState=e;const l=e.motion?.action,c=e.motion.clip;if(c?.duration<=0&&c.tracks.length<=0?r&&this._heldActions.push(r):r&&(r.fadeOut(t),this.releaseHeldActions(t)),l){if(i=Math.max(0,Math.min(1,i)),e.cycleOffsetParameter){let d=this.getFloat(e.cycleOffsetParameter);typeof d=="number"?(d<0&&(d+=1),i+=d,i%=1):lt&&console.warn("AnimatorController cycle offset parameter is not a number",e.cycleOffsetParameter)}else typeof e.cycleOffset=="number"&&(i+=e.cycleOffset,i%=1);l.isRunning()&&l.stop(),l.reset(),l.enabled=!0,this.setTimescale(l,e);const h=e.motion.clip.duration;if(l.time=s?0:i*h,l.timeScale<0&&(l.time=h-l.time),l.clampWhenFinished=!0,l.setLoop(Am,0),t>0?l.fadeIn(t):l.weight=1,l.play(),window.requestAnimationFrame(()=>Qn.testIfRootCanAnimate(l)),this.rootMotionHandler&&this.rootMotionHandler.onStart(l),this._activeStates.includes(e)||this._activeStates.push(e),this._activeState.behaviours){const d=new qc(e,i,h,this._speed);for(const p of this._activeState.behaviours)p.instance?.onStateEnter?.call(p.instance,this.animator,d,n)}}else lt&&(e.__warned_no_motion||(e.__warned_no_motion=!0,console.warn("No action",e.motion,this)));lt&&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 zE(this));const t=this.animator.gameObject;return this.rootMotionHandler.createClip(this._mixer,t,e)}else return this._mixer.clipAction(e)}evaluateCondition(e){const t=this.model.parameters.find(i=>i.name===e.parameter);if(!t)return!1;switch(e.mode){case As.If:return t.value===!0;case As.IfNot:return t.value===!1;case As.Greater:return t.value>e.threshold;case As.Less:return t.value<e.threshold;case As.Equals:return t.value===e.threshold;case As.NotEqual:return t.value!==e.threshold}return!1}createActions(e){lt&&console.log("AnimatorController createActions",this.model);for(const t of this.model.layers){const i=t.stateMachine;for(let n=0;n<i.states.length;n++){const s=i.states[n];s.transitions||(s.transitions=[]);for(const r of s.transitions)r.conditions||(r.conditions=[]);if(s.motion||(lt&&console.warn("No motion",s),s.motion=sx(s.name)),this.animator&&s.motion.clips){const r=s.motion.clips?.find(a=>a.node.name===this.animator?.gameObject?.name);r?s.motion.clip=r.clip:(lt||A())&&console.warn('Could not find clip for animator "'+this.animator?.gameObject?.name+'"',s.motion.clips.map(a=>a.node.name))}if(!s.motion.clip){lt&&console.warn("No clip assigned to state",s);const r=new ki(void 0,void 0,[]);s.motion.clip=r}if(s.motion?.clip){const r=s.motion.clip;if(r instanceof ki){const a=this.createAction(r);s.motion.action=a}else(lt||A())&&console.warn("No valid animationclip assigned",s)}if(s.behaviours&&Array.isArray(s.behaviours))for(const r of s.behaviours){if(!r?.typeName)continue;const a=C.get(r.typeName);if(a){const l=new a;l.isStateMachineBehaviour&&(l._context=this.context??void 0,Ja(l,r.properties),r.instance=l),lt&&console.log("Created animator controller behaviour",s.name,r.typeName,r.properties,l)}else(lt||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 rx{track;createdInterpolant;originalEvaluate;customEvaluate;constructor(e,t){this.track=e;const i=e,n=i.createInterpolant.bind(e);i.createInterpolant=()=>(i.createInterpolant=n,this.createdInterpolant=n(),this.originalEvaluate=this.createdInterpolant.evaluate.bind(this.createdInterpolant),this.customEvaluate=s=>{if(!this.originalEvaluate)return;const r=this.originalEvaluate(s);return t(s,r)},this.createdInterpolant.evaluate=this.customEvaluate,this.createdInterpolant)}dispose(){this.createdInterpolant&&this.originalEvaluate&&(this.createdInterpolant.evaluate=this.originalEvaluate),this.track=void 0,this.createdInterpolant=null,this.originalEvaluate=void 0,this.customEvaluate=void 0}}class mt{static lastObjPosition={};static lastObjRotation={};static firstKeyframeRotation={};static spaceRotation={};static effectiveSpaceRotation={};static clipOffsetRotation={};set action(e){this._action=e}get action(){return this._action}get cacheId(){return this.root.uuid}_action;root;clip;positionWrapper=null;rotationWrapper=null;context;positionChange=new b;rotationChange=new N;constructor(e,t,i,n,s){if(this.context=e,this.root=t,this.clip=i,mt.firstKeyframeRotation[this.cacheId]||(mt.firstKeyframeRotation[this.cacheId]=new N),s){const r=s.values;mt.firstKeyframeRotation[this.cacheId].set(r[0],r[1],r[2],r[3])}mt.spaceRotation[this.cacheId]||(mt.spaceRotation[this.cacheId]=new N),mt.effectiveSpaceRotation[this.cacheId]||(mt.effectiveSpaceRotation[this.cacheId]=new N),mt.clipOffsetRotation[this.cacheId]=new N,s&&mt.clipOffsetRotation[this.cacheId].set(s.values[0],s.values[1],s.values[2],s.values[3]).invert(),this.handlePosition(i,n),this.handleRotation(i,s)}onStart(e){if(e.getClip()!==this.clip)return;mt.lastObjRotation[this.cacheId]||(mt.lastObjRotation[this.cacheId]=this.root.quaternion.clone());const t=mt.lastObjRotation[this.cacheId];if(mt.spaceRotation[this.cacheId].copy(t),Lu){const i=new at().setFromQuaternion(t);console.log("START",this.clip.name,j.toDegrees(i.y),this.root.position.z)}}getClipRotationOffset(){return mt.clipOffsetRotation[this.cacheId]}_prevTime=0;handlePosition(e,t){if(t){const i=this.root;Lu&&i.add(new Pi),mt.lastObjPosition[this.cacheId]||(mt.lastObjPosition[this.cacheId]=this.root.position.clone());const n=new b,s=new b;this.positionWrapper=new rx(t,(r,a)=>{const l=this.action.getEffectiveWeight();return Lu&&i.position.length()>8&&i.position.set(0,i.position.y,0),r>this._prevTime&&(n.set(a[0],a[1],a[2]),n.sub(s),n.multiplyScalar(l),n.applyQuaternion(this.getClipRotationOffset()),n.applyQuaternion(i.quaternion),this.positionChange.copy(n)),s.fromArray(a),this._prevTime=r,a[0]=0,a[1]=0,a[2]=0,a})}}static identityQuaternion=new N;handleRotation(e,t){if(t){if(Lu){const r=t.values,a=new at().setFromQuaternion(new N(r[0],r[1],r[2],r[3]));console.log(e.name,t.name,"FIRST ROTATION IN TRACK",j.toDegrees(a.y));const l=t.values.length-4,c=new N().set(r[l],r[l+1],r[l+2],r[l+3]),h=new at().setFromQuaternion(c);console.log(e.name,t.name,"LAST ROTATION IN TRACK",j.toDegrees(h.y))}let i=0;const n=new N,s=new N;this.rotationWrapper=new rx(t,(r,a)=>(r>i&&(s.set(a[0],a[1],a[2],a[3]),n.invert(),s.multiply(n),this.rotationChange.copy(s)),n.fromArray(a),i=r,a[0]=0,a[1]=0,a[2]=0,a[3]=1,a))}}onBeforeUpdate(e){this.positionChange.set(0,0,0),this.rotationChange.set(0,0,0,1)}onAfterUpdate(e){return!this.action||(e*=this.action.getEffectiveWeight(),e<=0)?!1:(this.positionChange.multiplyScalar(e),this.rotationChange.slerp(mt.identityQuaternion,1-e),!0)}}class zE{controller;handler=[];root;basePosition=new b;baseQuaternion=new N;baseRotation=new at;constructor(e){this.controller=e}createClip(e,t,i){this.root=t,t&&"name"in t&&t.name;const n=this.findRootTrack(i,".position"),s=this.findRootTrack(i,".quaternion"),r=new mt(this.controller.context,t,i,n,s);this.handler.push(r);const a=e.clipAction(i);return r.action=a,a}onStart(e){for(const t of this.handler)t.onStart(e)}onBeforeUpdate(e){this.basePosition.copy(this.root.position),this.baseQuaternion.copy(this.root.quaternion);for(const t of this.handler)t.onBeforeUpdate(e)}summedPosition=new b;summedRotation=new N;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 NE extends Zi{onSerialize(e,t){}onDeserialize(e,t){if(t.type===gn&&e?.__type==="AnimatorController")return new gn(e)}}new NE(gn);var WE=Object.defineProperty,VE=Object.getOwnPropertyDescriptor,ju=(o,e,t,i)=>{for(var n=i>1?void 0:i?VE(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&WE(e,t,n),n};const Ki=w("debuganimator");class _t extends E{get isAnimationComponent(){return!0}applyRootMotion=!1;hasRootMotion=!1;keepAnimatorControllerStateOnDisable=!1;set runtimeAnimatorController(e){this._animatorController&&this._animatorController.model===e||(e?e instanceof gn?(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 gn(e.model)),this._animatorController=e,this._animatorController.bind(this)):(Ki&&console.log("Assign animator controller",e,this),this._animatorController=new gn(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){Ki&&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 Ki&&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),Ki&&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 Ki&&console.log("getFloat",e,t),t}SetInteger(e,t){this.setInteger(e,t)}setInteger(e,t){this.runtimeAnimatorController?.getInteger(e)!==t&&(this._parametersAreDirty=!0),Ki&&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 Ki&&console.log("getInteger",e,t),t}SetTrigger(e){this.setTrigger(e)}setTrigger(e){this._parametersAreDirty=!0,Ki&&console.log("setTrigger",e),this.runtimeAnimatorController?.setTrigger(e)}ResetTrigger(e){this.resetTrigger(e)}resetTrigger(e){this._parametersAreDirty=!0,Ki&&console.log("resetTrigger",e),this.runtimeAnimatorController?.resetTrigger(e)}GetTrigger(e){this.getTrigger(e)}getTrigger(e){const t=this.runtimeAnimatorController?.getTrigger(e);return Ki&&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&&(Ki&&console.log("setSpeed",e),this._speed=e,this._animatorController?.animator==this&&this._animatorController.setSpeed(e))}set minMaxSpeed(e){this._speed=j.lerp(e.x,e.y,Math.random()),this._animatorController?.animator==this&&this._animatorController.setSpeed(this._speed)}set minMaxOffsetNormalized(e){this._normalizedStartOffset=j.lerp(e.x,e.y,Math.random()),this.runtimeAnimatorController?.animator==this&&(this.runtimeAnimatorController.normalizedStartOffset=this._normalizedStartOffset)}_speed=1;_normalizedStartOffset=0;_animatorController=null;awake(){Ki&&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,!FE(this.gameObject)&&this._animatorController&&this._animatorController.update(1)}}ju([u()],_t.prototype,"applyRootMotion",2),ju([u()],_t.prototype,"hasRootMotion",2),ju([u()],_t.prototype,"keepAnimatorControllerStateOnDisable",2),ju([u()],_t.prototype,"runtimeAnimatorController",1);const ax=Symbol("previous-visibility");class xo extends $n{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 yr){this.onBeforeRender();const n=i.getRenderTarget(),s=i.xr.enabled;i.xr.enabled=!1,i.setRenderTarget(this),i.clear(!0,!0,!0),i.render(e,t),i.setRenderTarget(n),i.xr.enabled=s,this.onAfterRender()}}static _userSet=new Set;onBeforeRender(){xo._userSet.clear();const e=Wg(this.texture,!0,null,xo._userSet);for(const t of e)t instanceof H&&(t[ax]=t.visible,t.visible=!1)}onAfterRender(){for(const e of xo._userSet)e instanceof H&&(e.visible=e[ax]);xo._userSet.clear()}}var $E=Object.defineProperty,HE=Object.getOwnPropertyDescriptor,Xc=(o,e,t,i)=>{for(var n=i>1?void 0:i?HE(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&$E(e,t,n),n};const Du=w("debuggroundprojection");class Jn extends E{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 ps(this.context.scene,"background"),this._watcher.subscribeWrite(e=>{Du&&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 mc(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 Se&&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 Se)){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){Du&&console.log("Create/Update Ground Projection",e.name),this._projection?.removeFromParent();try{this._projection=new Da(e,this._height,this._radius,64)}catch(s){console.error("Error creating three GroundProjection",s);return}this._projection.position.y=this._height-i,this._projection.name="GroundProjection",pg(this._projection,!1)}else t=!1;if(this._projection.parent||this.gameObject.add(this._projection),this.autoFit&&t){this._projection.updateWorldMatrix(!0,!0);const s=di(this.context.scene.children,[this._projection]),r=s.min.y;if(r<1/0){const a=F();a.x=s.min.x+(s.max.x-s.min.x)*.5;const l=$e(this.gameObject).x;a.y=r+this._height*l-i,a.z=s.min.z+(s.max.z-s.min.z)*.5,yt(this._projection,a)}Du&&B.DrawWireBox3(s,65280,5)}this.context.scene.backgroundBlurriness>.001&&this._needsTextureUpdate&&this.updateBlurriness(e,this.context.scene.backgroundBlurriness),this._lastBackground=e,this._lastHeight=this._height,this._lastRadius=this._radius,this._needsTextureUpdate=!1}_blurrynessShader=null;_lastBlurriness=-1;updateBlurriness(e,t){if(this._projection){if(!e)return}else return;this._needsTextureUpdate=!1,Du&&console.log("Update Blurriness",t),this._blurrynessShader??=new Vn({name:"GroundProjectionBlurriness",uniforms:{map:{value:e},blurriness:{value:t},blending:{value:0},alphaFactor:{value:1}},vertexShader:GE,fragmentShader:qE}),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=pr.copyTexture(e,this._blurrynessShader),this._projection.material.depthTest=!0,this._projection.material.depthWrite=!1}}Xc([u()],Jn.prototype,"applyOnAwake",2),Xc([u()],Jn.prototype,"autoFit",2),Xc([u()],Jn.prototype,"radius",1),Xc([u()],Jn.prototype,"height",1),Xc([u()],Jn.prototype,"arBlending",1);const GE=`
|
|
894
894
|
varying vec2 vUv;
|
|
895
895
|
|
|
896
896
|
void main() {
|
|
@@ -959,7 +959,7 @@ Exit Time: `+c,s.hasExitTime)}this.transitionTo(s.destinationState,s.duration,s.
|
|
|
959
959
|
// Uncomment to visualize blur amount
|
|
960
960
|
// gl_FragColor = vec4(blurAmount, 0.0, 0.0, 1.0);
|
|
961
961
|
}
|
|
962
|
-
`;function lx(o){if(Z.active)return console.warn("[OrbitControls] Can not fit camera while XR session is active"),null;const e=U.Current;if(!e)return console.warn("[OrbitControls] No context found"),null;const t=o?.camera||e.mainCamera;if(!t)return console.warn("No camera or controls found to fit camera to objects..."),null;o||(o={}),o.autoApply=o.autoApply!==!1,o.minZoom||=0,o.maxZoom||=1/0;const{centerCamera:i,cameraNearFar:n="auto",fitOffset:s=1.1,fov:r=t instanceof de?t?.fov:-1}=o,a=new b,l=new b,c=t instanceof de?t.aspect:1,h=o.objects||e.scene,d=di(h,void 0,t?.layers),p=d.clone();d.getCenter(l);const m=new b;if(d.getSize(m),t instanceof de&&t.updateProjectionMatrix(),t.updateMatrixWorld(),d.applyMatrix4(t.matrixWorldInverse),d.getSize(a),d.setFromCenterAndSize(l,a),Number.isNaN(a.x)||Number.isNaN(a.y)||Number.isNaN(a.z))return console.warn("Camera fit size resultet in NaN",t,d),null;if(a.length()<=1e-10)return console.warn("Camera fit size is zero",d),null;const g=r,f=2*Math.atan(Math.tan(g*Math.PI/360/2)*c)/Math.PI*360,y=a.y/(2*Math.atan(Math.PI*g/360)),_=a.x/(2*Math.atan(Math.PI*f/360)),v=s*Math.max(y,_)+a.z/2;o.maxZoom=v*10,o.minZoom=v*.01,o.debug===!0&&console.log("Fit camera to objects",{fitHeightDistance:y,fitWidthDistance:_,distance:v,verticalFov:g,horizontalFov:f});const P=.05,k=l.clone();if(k.y-=a.y*P,o.targetOffset&&(o.targetOffset.x!==void 0&&(k.x+=o.targetOffset.x),o.targetOffset.y!==void 0&&(k.y+=o.targetOffset.y),o.targetOffset.z!==void 0&&(k.z+=o.targetOffset.z)),o.relativeTargetOffset&&(o.relativeTargetOffset.x!==void 0&&(k.x+=o.relativeTargetOffset.x*a.x),o.relativeTargetOffset.y!==void 0&&(k.y+=o.relativeTargetOffset.y*a.y),o.relativeTargetOffset.z!==void 0&&(k.z+=o.relativeTargetOffset.z*a.z)),n==null||n=="auto"){const L=tl(Jn),V=L?L.radius:0,W=Math.max(m.x,m.y,m.z,V);t instanceof de&&(t.near=v/100,t.far=W+v*10,t.updateProjectionMatrix()),L&&(o.maxZoom=Math.max(Math.min(o.maxZoom,V*.5),v))}o.currentZoom!==void 0&&(o.currentZoom<o.minZoom&&(o.minZoom=o.currentZoom*.9),o.currentZoom>o.maxZoom&&(o.maxZoom=o.currentZoom*1.1));const O=l.clone();o.fitDirection?O.sub(new b().copy(o.fitDirection).multiplyScalar(1e6)):O.sub(t.worldPosition),i==="y"&&(O.y=0),O.normalize(),O.multiplyScalar(v),i==="y"&&(O.y+=-P*4*v);let j=l.clone().sub(O);return o.cameraOffset&&(o.cameraOffset.x!==void 0&&(j.x+=o.cameraOffset.x),o.cameraOffset.y!==void 0&&(j.y+=o.cameraOffset.y),o.cameraOffset.z!==void 0&&(j.z+=o.cameraOffset.z)),o.relativeCameraOffset&&(o.relativeCameraOffset.x!==void 0&&(j.x+=o.relativeCameraOffset.x*a.x),o.relativeCameraOffset.y!==void 0&&(j.y+=o.relativeCameraOffset.y*a.y),o.relativeCameraOffset.z!==void 0&&(j.z+=o.relativeCameraOffset.z*a.z)),t.parent&&(j=t.parent.worldToLocal(j)),o.debug&&(B.DrawWireBox3(d,16777011,10),B.DrawWireBox3(p,65280,10)),o.autoApply&&(t.position.copy(j),t.lookAt(k),r>0&&t instanceof de&&(t.fov=r,t.updateProjectionMatrix())),{camera:t,position:j,lookAt:k,fov:o.fov}}var XE=Object.defineProperty,jf=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&XE(e,t,n),n};class Wr extends E{constraintActive=!0;locked=!1;sources=[];setConstraintPosition(e){const t=this.sources[0];t&&(t.worldPosition=e)}}jf([u()],Wr.prototype,"constraintActive"),jf([u()],Wr.prototype,"locked"),jf([u(M)],Wr.prototype,"sources");let Vr=class{bb=null;bb_pos=0;__init(o,e){return this.bb_pos=o,this.bb=e,this}x(){return this.bb.readFloat32(this.bb_pos)}y(){return this.bb.readFloat32(this.bb_pos+4)}z(){return this.bb.readFloat32(this.bb_pos+8)}static sizeOf(){return 12}static createVec3(o,e,t,i){return o.prep(4,12),o.writeFloat32(i),o.writeFloat32(t),o.writeFloat32(e),o.offset()}};class cx{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}position(e){return(e||new Vr).__init(this.bb_pos,this.bb)}rotation(e){return(e||new Vr).__init(this.bb_pos+12,this.bb)}scale(e){return(e||new Vr).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(e,t,i,n,s,r,a,l,c,h){return e.prep(4,36),e.prep(4,12),e.writeFloat32(h),e.writeFloat32(c),e.writeFloat32(l),e.prep(4,12),e.writeFloat32(a),e.writeFloat32(r),e.writeFloat32(s),e.prep(4,12),e.writeFloat32(n),e.writeFloat32(i),e.writeFloat32(t),e.offset()}}class gs{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedTransformModel(e,t){return(t||new gs).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedTransformModel(e,t){return e.setPosition(e.position()+Vb),(t||new gs).__init(e.readInt32(e.position())+e.position(),e)}guid(e){const t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}fast(){const e=this.bb.__offset(this.bb_pos,6);return e?!!this.bb.readInt8(this.bb_pos+e):!1}transform(e){const t=this.bb.__offset(this.bb_pos,8);return t?(e||new cx).__init(this.bb_pos+t,this.bb):null}dontSave(){const e=this.bb.__offset(this.bb_pos,10);return e?!!this.bb.readInt8(this.bb_pos+e):!1}static startSyncedTransformModel(e){e.startObject(4)}static addGuid(e,t){e.addFieldOffset(0,t,0)}static addFast(e,t){e.addFieldInt8(1,+t,0)}static addTransform(e,t){e.addFieldStruct(2,t,0)}static addDontSave(e,t){e.addFieldInt8(3,+t,0)}static endSyncedTransformModel(e){return e.endObject()}static finishSyncedTransformModelBuffer(e,t){e.finish(t)}static finishSizePrefixedSyncedTransformModelBuffer(e,t){e.finish(t,void 0,!0)}}var T;(o=>{(e=>{e.MAYBEMODULE=null;const t=[];function i(){return e.MODULE?Promise.resolve(e.MODULE):new Promise(s=>{t.push(s)})}e.ready=i;async function n(){if(e.MODULE)return e.MODULE;const s=await import("./materialx-D_ofN96q.min.js");return e.MODULE=s,e.MAYBEMODULE=s,t.forEach(r=>r(s)),t.length=0,s}e.load=n})(o.MaterialX||(o.MaterialX={})),(e=>{e.MAYBEMODULE=null;const t=[];function i(){return e.MODULE?Promise.resolve(e.MODULE):new Promise(s=>{t.push(s)})}e.ready=i;async function n(){if(e.MODULE)return e.MODULE;const s=await import("./rapier-DJ-luMxr.min.js");return e.MODULE=s,e.MAYBEMODULE=s,t.forEach(r=>r(s)),t.length=0,s}e.load=n})(o.RAPIER_PHYSICS||(o.RAPIER_PHYSICS={})),(e=>{e.MAYBEMODULE=null;const t=[];function i(){return e.MODULE?Promise.resolve(e.MODULE):new Promise(s=>{t.push(s)})}e.ready=i;async function n(){if(e.MODULE)return e.MODULE;const s=await import("./postprocessing-DXm8YKbQ.min.js").then(r=>r.index);return e.MODULE=s,e.MAYBEMODULE=s,t.forEach(r=>r(s)),t.length=0,s}e.load=n})(o.POSTPROCESSING||(o.POSTPROCESSING={})),(e=>{e.MAYBEMODULE=null;const t=[];function i(){return e.MODULE?Promise.resolve(e.MODULE):new Promise(s=>{t.push(s)})}e.ready=i;async function n(){if(e.MODULE)return e.MODULE;const s=await import("./postprocessing-DXm8YKbQ.min.js").then(r=>r.N8AO);return e.MODULE=s,e.MAYBEMODULE=s,t.forEach(r=>r(s)),t.length=0,s}e.load=n})(o.POSTPROCESSING_AO||(o.POSTPROCESSING_AO={}))})(T||(T={}));var vt=(o=>(o[o.Average=0]="Average",o[o.Multiply=1]="Multiply",o[o.Minimum=2]="Minimum",o[o.Maximum=3]="Maximum",o))(vt||{}),Bu=(o=>(o[o.Discrete=0]="Discrete",o[o.Continuous=1]="Continuous",o))(Bu||{}),Ze=(o=>(o[o.None=0]="None",o[o.FreezePositionX=2]="FreezePositionX",o[o.FreezePositionY=4]="FreezePositionY",o[o.FreezePositionZ=8]="FreezePositionZ",o[o.FreezePosition=14]="FreezePosition",o[o.FreezeRotationX=16]="FreezeRotationX",o[o.FreezeRotationY=32]="FreezeRotationY",o[o.FreezeRotationZ=64]="FreezeRotationZ",o[o.FreezeRotation=112]="FreezeRotation",o[o.FreezeAll=126]="FreezeAll",o))(Ze||{}),cl=(o=>(o[o.None=0]="None",o[o.X=2]="X",o[o.Y=4]="Y",o[o.Z=8]="Z",o[o.All=-1]="All",o))(cl||{});const kt=function(o,e){return function(t,i,n){QE(t,i,n,o,e)}};function QE(o,e,t,i,n){if(!n&&!i&&!o.onValidate)return;if(t!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",o,e,t),Oe("Invalid usage of validate decorator. Only fields can be validated. Property: "+e,{type:Ri.Error});return}let s="";if(typeof e=="string"?s=e:s=e.name,o.__internalAwake){const r=Symbol(s),a=o.__internalAwake;o.__internalAwake=function(){if(!this.onValidate){A()&&console.warn('Usage of @validate decorate detected but there is no onValidate method in your class: "'+o.constructor?.name+'"');return}if(this[r]===void 0){this[r]=this[s];const l=this[s];if(l instanceof K||l instanceof b||l instanceof ye||l instanceof N){const c=this[s];Bd(c,()=>{this.onValidate(s)})}Object.defineProperty(this,s,{set:function(c){if(this[lf]===!0)this[r]=c;else{i?.call(this,c);const h=this[r];this[r]=c,this.onValidate?.call(this,s,h)}},get:function(){return n?.call(this),this[r]}})}a.call(this)}}}const YE=function(o){return function(e,t,i){let n="";typeof t=="string"?n=t:n=t.name;const s=o.prototype,r=Object.getOwnPropertyDescriptor(s,n);if(!r?.value){console.warn("Can not apply prefix: type does not have method named",t,o);return}const a=r.value,l=e[n];Object.defineProperty(s,n,{value:function(...c){const h=l?.call(this,...c);if(h instanceof Promise){h.then(d=>{if(d!==!1)return a.call(this,...c)});return}if(h!==!1)return a.call(this,...c)}})}};var ZE=Object.defineProperty,KE=Object.getOwnPropertyDescriptor,Li=(o,e,t,i)=>{for(var n=i>1?void 0:i?KE(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&ZE(e,t,n),n};class JE{get isDirty(){return this.positionChanged||this.rotationChanged}positionChanged=!1;rotationChanged=!1;position;quaternion;_positionKeys=["x","y","z"];_quaternionKeys=["_x","_y","_z","_w"];reset(e=!1){if(this.positionChanged=!1,this.rotationChanged=!1,this.mute=!1,e){if(this.position)for(const t of this._positionKeys)delete this.position[t];if(this.quaternion)for(const t of this._quaternionKeys)delete this.quaternion[t]}}syncValues(){for(const e of this._positionKeys)this.position[e]=this.obj.position[e];for(const e of this._quaternionKeys)this.quaternion[e]=this.obj.quaternion[e]}mute=!1;applyValues(){if(this.positionChanged&&this.position)for(const e of this._positionKeys){const t=this.position[e];t!==void 0&&(this.obj.position[e]=t)}if(this.rotationChanged&&this.quaternion)for(const e of this._quaternionKeys){const t=this.quaternion[e];t!==void 0&&(this.obj.quaternion[e]=t)}}context;obj;_positionWatch;_rotationWatch;constructor(e,t){this.context=t,this.obj=e}start(e,t){this.reset(),e&&(this._positionWatch||(this._positionWatch=new ps(this.obj.position,["x","y","z"])),this._positionWatch.apply(),this.position={},this._positionWatch.subscribeWrite((s,r)=>{if(this.context.physics.engine?.isUpdating||this.mute)return;const a=this.position[r];Math.abs(a-s)<1e-5||(this.position[r]=s,this.positionChanged=!0)})),t&&(this._rotationWatch||(this._rotationWatch=new ps(this.obj.quaternion,["_x","_y","_z","_w"])),this._rotationWatch.apply(),this.quaternion={},this._rotationWatch.subscribeWrite((s,r)=>{if(this.context.physics.engine?.isUpdating||this.mute)return;const a=this.quaternion[r];Math.abs(a-s)<1e-5||(this.quaternion[r]=s,this.rotationChanged=!0)}));const i=this.obj.matrixWorld.multiplyMatrices.bind(this.obj.matrixWorld),n=new J;this.obj.matrixWorld.multiplyMatrices=(s,r)=>(this.context.physics.engine?.isUpdating||this.mute||n.equals(s)||(this.positionChanged=!0,this.rotationChanged=!0,n.copy(s)),i(s,r))}stop(){this._positionWatch?.revoke(),this._rotationWatch?.revoke()}}const fi=class bm extends E{get isRigidbody(){return!0}autoMass=!0;set mass(e){e!==this._mass&&(this._mass=e,this._propertiesChanged=!0,this.__didAwake&&(this.autoMass=!1))}get mass(){return this.autoMass?this.context.physics.engine?.getBody(this)?.mass()??-1:this._mass}_mass=0;useGravity=!0;centerOfMass=new b(0,0,0);constraints=Ze.None;isKinematic=!1;drag=0;angularDrag=1;detectCollisions=!0;sleepThreshold=.01;collisionDetectionMode=Bu.Discrete;get lockPositionX(){return(this.constraints&Ze.FreezePositionX)!==0}get lockPositionY(){return(this.constraints&Ze.FreezePositionY)!==0}get lockPositionZ(){return(this.constraints&Ze.FreezePositionZ)!==0}get lockRotationX(){return(this.constraints&Ze.FreezeRotationX)!==0}get lockRotationY(){return(this.constraints&Ze.FreezeRotationY)!==0}get lockRotationZ(){return(this.constraints&Ze.FreezeRotationZ)!==0}set lockPositionX(e){e?this.constraints|=Ze.FreezePositionX:this.constraints&=~Ze.FreezePositionX}set lockPositionY(e){e?this.constraints|=Ze.FreezePositionY:this.constraints&=~Ze.FreezePositionY}set lockPositionZ(e){e?this.constraints|=Ze.FreezePositionZ:this.constraints&=~Ze.FreezePositionZ}set lockRotationX(e){e?this.constraints|=Ze.FreezeRotationX:this.constraints&=~Ze.FreezeRotationX}set lockRotationY(e){e?this.constraints|=Ze.FreezeRotationY:this.constraints&=~Ze.FreezeRotationY}set lockRotationZ(e){e?this.constraints|=Ze.FreezeRotationZ:this.constraints&=~Ze.FreezeRotationZ}set gravityScale(e){this._gravityScale=e}get gravityScale(){return this._gravityScale}_gravityScale=1;dominanceGroup=0;static tempPosition=new b;_propertiesChanged=!1;_currentVelocity=new b;_smoothedVelocity=new b;_smoothedVelocityGetter=new b;_lastPosition=new b;_watch;awake(){this._watch=void 0,this._propertiesChanged=!1}onEnable(){this._watch||(this._watch=new JE(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),xe.LateUpdate),A()&&(globalThis.NEEDLE_USE_RAPIER?T.RAPIER_PHYSICS.ready().then(async()=>{await mc(3),this.context.physics.engine?.getBody(this)||console.warn(`Rigidbody could not be created. Ensure "${this.name}" has a Collider component.`)}):console.warn("Rigidbody could not be created: Rapier physics are explicitly disabled."))}onDisable(){this._watch?.stop(),this.context.physics.engine?.removeBody(this)}onDestroy(){this.context.physics.engine?.removeBody(this)}onValidate(){this._propertiesChanged=!0}*beforePhysics(){for(;;)this._propertiesChanged&&(this._propertiesChanged=!1,this.context.physics.engine?.updateProperties(this)),this._watch?.isDirty?(this._watch.mute=!0,this._watch.applyValues(),this.context.physics.engine?.updateBody(this,this._watch.positionChanged,this._watch.rotationChanged),this._watch.reset()):this._watch?.syncValues(),this.captureVelocity(),yield}teleport(e,t=!0){this._watch?.reset(!0),t?this.gameObject.position.set(e.x,e.y,e.z):this.setWorldPosition(e.x,e.y,e.z),this.resetForcesAndTorques(),this.resetVelocities()}resetForces(e=!0){this.context.physics.engine?.resetForces(this,e)}resetTorques(e=!0){this.context.physics.engine?.resetTorques(this,e)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){this.context.physics.engine?.wakeup(this)}get isSleeping(){return this.context.physics.engine?.isSleeping(this)}updateProperties(){return this._propertiesChanged=!1,this.context.physics.engine?.updateProperties(this)}applyForce(e,t,i=!0){this._propertiesChanged&&this.updateProperties(),this.context.physics.engine?.addForce(this,e,i)}applyImpulse(e,t=!0){this._propertiesChanged&&this.updateProperties(),this.context.physics.engine?.applyImpulse(this,e,t)}setForce(e,t,i,n=!0){this.context.physics.engine?.resetForces(this,n),typeof e=="number"?(t??=0,i??=0,this.context.physics.engine?.addForce(this,{x:e,y:t,z:i},n)):this.context.physics.engine?.addForce(this,e,n)}getVelocity(){const e=this.context.physics.engine?.getLinearVelocity(this);return e?(this._currentVelocity.x=e.x,this._currentVelocity.y=e.y,this._currentVelocity.z=e.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setVelocity(e,t,i,n=!0){if(e instanceof b){const s=e;this.context.physics.engine?.setLinearVelocity(this,s,n);return}t===void 0||i===void 0||this.context.physics.engine?.setLinearVelocity(this,{x:e,y:t,z:i},n)}getAngularVelocity(){const e=this.context.physics.engine?.getAngularVelocity(this);return e?(this._currentVelocity.x=e.x,this._currentVelocity.y=e.y,this._currentVelocity.z=e.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setAngularVelocity(e,t,i,n=!0){if(typeof e=="object"){const s=e;this.context.physics.engine?.setAngularVelocity(this,s,n);return}if(t===void 0||i===void 0||typeof t=="boolean"){console.warn("setAngularVelocity expects either a Vec3 or 3 numbers");return}this.context.physics.engine?.setAngularVelocity(this,{x:e,y:t,z:i},n)}setTorque(e,t,i){typeof e=="number"?this.setAngularVelocity(e,t,i):this.setAngularVelocity(e)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(e=null){}captureVelocity(){const e=this.gameObject.matrixWorld;bm.tempPosition.setFromMatrixPosition(e);const t=bm.tempPosition.sub(this._lastPosition);this._lastPosition.copy(bm.tempPosition),this._smoothedVelocity.lerp(t,this.context.time.deltaTime/.1)}};Li([kt()],fi.prototype,"autoMass",2),Li([u()],fi.prototype,"mass",1),Li([kt(),u()],fi.prototype,"useGravity",2),Li([u(b)],fi.prototype,"centerOfMass",2),Li([kt(),u()],fi.prototype,"constraints",2),Li([kt(),u()],fi.prototype,"isKinematic",2),Li([kt(),u()],fi.prototype,"drag",2),Li([kt(),u()],fi.prototype,"angularDrag",2),Li([kt(),u()],fi.prototype,"detectCollisions",2),Li([kt(),u()],fi.prototype,"sleepThreshold",2),Li([kt(),u()],fi.prototype,"collisionDetectionMode",2),Li([kt()],fi.prototype,"_gravityScale",2),Li([kt()],fi.prototype,"dominanceGroup",2);let Ke=fi;new b,new b;const Is=w("debugsync"),Qc="STRS";Eg(Qc,gs.getRootAsSyncedTransformModel);const eo=new Wm;function hx(o,e,t=!0){eo.clear();const i=eo.createString(o);gs.startSyncedTransformModel(eo),gs.addGuid(eo,i),gs.addFast(eo,t);const n=e.worldPosition,s=e.worldEuler,r=e.gameObject.scale;gs.addTransform(eo,cx.createTransform(eo,n.x,n.y,n.z,s.x,s.y,s.z,r.x,r.y,r.z));const a=gs.endSyncedTransformModel(eo);return eo.finish(a,Qc),eo.asUint8Array()}let Df=0,Yc=0;$w(o=>{const e=o.connection.currentServerUrl?.includes("glitch")?10:40;Yc=Math.floor(Df/e),Df=0,Is&&Yc>0&&console.log("Sync Transform Fast Interval",Yc)});class Tn extends E{overridePhysics=!0;interpolatePosition=!0;interpolateRotation=!0;fastMode=!1;syncDestroy=!1;_model=null;_needsUpdate=!0;rb=null;_wasKinematic=!1;_receivedDataBefore=!1;_targetPosition;_targetRotation;_receivedFastUpdate=!1;_shouldRequestOwnership=!1;requestOwnership(){Is&&console.log("Request ownership"),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}freeOwnership(){this._model?.freeOwnership()}hasOwnership(){return this._model?.hasOwnership??void 0}isOwned(){return this._model?.isOwned}joinedRoomCallback=null;receivedDataCallback=null;awake(){Is&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new b,this._targetRotation=new N,this.lastPosition=new b,this.lastRotation=new N,this.lastScale=new b,this.rb=S.getComponentInChildren(this.gameObject,Ke),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new Tg(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen(ie.JoinedRoom,this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinary(Qc,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&Zg(this.guid,this.context.connection),this._model=null,this.context.connection.stopListen(ie.JoinedRoom,this.joinedRoomCallback),this.context.connection.stopListenBinary(Qc,this.receivedDataCallback)}tryGetLastState(){const e=this.context.connection.tryGetState(this.guid);e&&this.onReceivedData(e)}tempEuler=new at;onReceivedData(e){if(!this.destroyed&&typeof e.guid=="function"&&e.guid()===this.guid){Is&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,e),this.receivedUpdate=!0,this._receivedFastUpdate=e.fast();const t=e.transform();if(t){pn.markDirty(this.gameObject,!0);const i=t.position();i&&(this.interpolatePosition&&this._targetPosition?.set(i.x(),i.y(),i.z()),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(i.x(),i.y(),i.z()));const n=t.rotation();n&&(this.tempEuler.set(n.x(),n.y(),n.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&ug(this.gameObject,this.tempEuler));const s=t.scale();s&&this.gameObject.scale.set(s.x(),s.y(),s.z())}this._receivedDataBefore=!0}}onEnable(){this.lastPosition.copy(this.worldPosition),this.lastRotation.copy(this.worldQuaternion),this.lastScale.copy(this.gameObject.scale),this._needsUpdate=!0,this._model&&this._model.updateIsOwned()}onDisable(){this._model&&this._model.freeOwnership()}receivedUpdate=!1;lastPosition;lastRotation;lastScale;onBeforeRender(){if(!this.activeAndEnabled||!this.context.connection.isConnected)return;if(!this.context.connection.isInRoom||!this._model){Is&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());const e=this.worldPosition,t=this.worldQuaternion,i=this.gameObject.scale;if(this._model.isOwned&&!this.receivedUpdate){const r=this._model.hasOwnership||this.fastMode?1e-4:.001;(e.distanceTo(this.lastPosition)>r||t.angleTo(this.lastRotation)>r||i.distanceTo(this.lastScale)>r)&&(this._model.hasOwnership?this._needsUpdate=!0:(Is&&console.log(this.guid,"reset because not owned but",this.gameObject.name,this.lastPosition),this.worldPosition=this.lastPosition,e.copy(this.lastPosition),this.worldQuaternion=this.lastRotation,t.copy(this.lastRotation),this.gameObject.scale.copy(this.lastScale),pn.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){const r=this._receivedFastUpdate||this.fastMode?.5:.3;let a=!1;if(this.interpolatePosition&&this._targetPosition){const l=this.worldPosition;l.lerp(this._targetPosition,r),this.worldPosition=l,a=!0}if(this.interpolateRotation&&this._targetRotation){const l=this.worldQuaternion;l.slerp(this._targetRotation,r),this.worldQuaternion=l,a=!0}a&&pn.markDirty(this.gameObject,!0)}if(this.receivedUpdate=!1,this.lastPosition.copy(e),this.lastRotation.copy(t),this.lastScale.copy(i),!this._model||!this._model||this._model.hasOwnership===void 0||!this._model.hasOwnership)return;this.rb&&this.overridePhysics&&this._wasKinematic!==void 0&&(Is&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic);const n=10,s=this.rb||this.fastMode;if(this._needsUpdate&&(this.context.time.frameCount%n===0||s)){if(Df++,s&&Yc>0&&this.context.time.frameCount%Yc!==0)return;Is&&console.debug("[SyncedTransform] Send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this._needsUpdate=!1;const r=hx(this.guid,this,!!s);this.context.connection.sendBinary(r)}}}class vd{event;get deviceIndex(){return this.event.deviceIndex}get pointerId(){return this.event.pointerId}button;buttonName;get pressure(){return this.event.pressure}get used(){return this._used}_used=!1;use(){this._used||(this._used=!0,this.event.use())}_propagationStopped=!1;get propagationStopped(){return this._propagationStopped}stopPropagation(){this._propagationStopped=!0,this.event.stopImmediatePropagation()}stopImmediatePropagation(){this._propagationStopped=!0,this.event.stopImmediatePropagation()}z__pointer_ctured=!1;setPointerCapture(){this.z__pointer_ctured=!0}z__pointer_cture_rleased=!1;releasePointerCapture(){this.z__pointer_cture_rleased=!0}inputSource;get mode(){return this.event.mode}object;point;normal;face;distance;instanceId;intersection;isDown;isUp;isPressed;isClick;isDoubleClick;input;constructor(e,t){this.event=t,this.input=e,this.button=t.button}clone(){const e=new vd(this.input,this.event);return Object.assign(e,this),e}Use(){this.use()}StopPropagation(){this.event.stopImmediatePropagation()}}function Fu(o,e){return S.foreachComponent(o,t=>{if(!t.enabled)return;const i=t;if(e)switch(e){case"pointerdown":if(i.onPointerDown)return!0;break;case"pointerup":if(i.onPointerUp||i.onPointerClick)return!0;break;case"pointermove":if(i.onPointerEnter||i.onPointerExit||i.onPointerMove)return!0;break}else if(i.onPointerDown||i.onPointerUp||i.onPointerEnter||i.onPointerExit||i.onPointerClick)return!0},!1)===!0}const zo=new Array;class No{enabled=!0;target;methodName;arguments;get canClone(){return this.target instanceof Object}constructor(e,t,i,n){this.target=e,this.methodName=t||null,this.arguments=i,n!=null&&(this.enabled=n)}invoke(...e){if(this.enabled!==!1){if(typeof this.target=="function")this.arguments?(zo.length=0,e!==void 0&&e.length>0&&zo.push(...e),zo.push(...this.arguments),this.target(...this.arguments),zo.length=0):this.target(...e);else if(this.methodName!=null){const t=this.target[this.methodName];typeof t=="function"?this.arguments?(zo.length=0,e!==void 0&&e.length>0&&zo.push(...e),zo.push(...this.arguments),t.call(this.target,...zo),zo.length=0):t.call(this.target,...e):this.arguments?e!==void 0&&e.length>0?this.target[this.methodName]=e[0]:this.target[this.methodName]=this.arguments[0]:this.target[this.methodName]=e[0]}}}}const eR=o=>/^[A-Z]*$/.test(o);class Uu extends Event{args}class ae{isEventList=!0;__internalOnInstantiate(e){const t=new Array;for(let i=0;i<this.methods.length;i++){const n=this.methods[i];if(!(n.target instanceof Function)){const s=n.target;let r=s?.uuid;if(s&&(r=s.guid),r){const a=e[r];if(a){const l=n.arguments?.map(c=>c instanceof Object&&c.uuid?e[c.uuid].clone:c?.isComponent?e[c.guid].clone:c);t.push(new No(a.clone,n.methodName,l,n.enabled))}else A()&&console.warn("Could not find target for event listener")}}}return new ae(t)}target;key;setEventTarget(e,t){if(this.key=e,this.target=t,this.key!==void 0){let i="",n=!1;for(const s of this.key)n&&eR(s)&&(i+="-"),n=!0,i+=s.toLowerCase();this.key=i}}get listenerCount(){return this.methods?.length??0}get isInvoking(){return this._isInvoking}_isInvoking=!1;methods=[];_methodsCopy=[];static from(...e){return new ae(e)}constructor(e){if(this.methods=[],Array.isArray(e))for(const t of e)t instanceof No?this.methods.push(t):typeof t=="function"&&this.methods.push(new No(t));else typeof e=="function"&&this.methods.push(new No(e))}invoke(...e){if(this._isInvoking)return console.warn("Circular event invocation detected. Please check your event listeners for circular references.",this),!1;if(this.methods?.length<=0)return!1;this._isInvoking=!0;try{this._methodsCopy.length=0,this._methodsCopy.push(...this.methods);for(const t of this._methodsCopy)t.invoke(...e);if(typeof this.target=="object"&&typeof this.key=="string"){const t=this.target.dispatchEvent;if(typeof t=="function"){const i=new Uu(this.key);i.args=e,t.call(this.target,i)}}}finally{this._isInvoking=!1,this._methodsCopy.length=0}return!0}addEventListener(e){return this.methods.push(new No(e)),e}removeEventListener(e){if(e)for(let t=this.methods.length-1;t>=0;t--)this.methods[t].target===e&&(this.methods[t].enabled=!1,this.methods.splice(t,1))}removeAllEventListeners(){this.methods.length=0}}class tR extends Zi{constructor(){super([oe,se],"ColorSerializer")}onDeserialize(e){if(e!=null)return e.a!==void 0?new se(e.r,e.g,e.b,e.a):e.alpha!==void 0?new se(e.r,e.g,e.b,e.alpha):new oe(e.r,e.g,e.b)}onSerialize(e){if(e!=null)return e.a!==void 0?{r:e.r,g:e.g,b:e.b,a:e.a}:{r:e.r,g:e.g,b:e.b}}}const iR=new tR;class nR extends Zi{constructor(){super([at],"EulerSerializer")}onDeserialize(e,t){if(e!=null){if(e.order)return new at(e.x,e.y,e.z,e.order);if(e.x!=null)return new at(e.x,e.y,e.z)}}onSerialize(e,t){return{x:e.x,y:e.y,z:e.z,order:e.order}}}const oR=new nR;class sR extends Zi{constructor(){super(M,"ObjectSerializer")}onSerialize(e,t){if(t.objectToNode!==void 0&&e.uuid){const i=t.objectToNode[e.uuid];return bt&&console.log(i,e.name,e.uuid),{node:i}}}onDeserialize(e,t){if(typeof e=="string"){if(e.endsWith(".glb")||e.endsWith(".gltf")){if(t.serializable instanceof Array&&t.serializable.includes(ne))return;A()&&be("Detected wrong usage of @serializable with Object3D or GameObject. Instead you should use AssetReference here! Please see the console for details.");const i=t.target?.constructor?.name;console.warn(`Wrong usage of @serializable detected in your script "${i}"
|
|
962
|
+
`;function lx(o){if(Z.active)return console.warn("[OrbitControls] Can not fit camera while XR session is active"),null;const e=U.Current;if(!e)return console.warn("[OrbitControls] No context found"),null;const t=o?.camera||e.mainCamera;if(!t)return console.warn("No camera or controls found to fit camera to objects..."),null;o||(o={}),o.autoApply=o.autoApply!==!1,o.minZoom||=0,o.maxZoom||=1/0;const{centerCamera:i,cameraNearFar:n="auto",fitOffset:s=1.1,fov:r=t instanceof de?t?.fov:-1}=o,a=new b,l=new b,c=t instanceof de?t.aspect:1,h=o.objects||e.scene,d=di(h,void 0,t?.layers),p=d.clone();d.getCenter(l);const m=new b;if(d.getSize(m),t instanceof de&&t.updateProjectionMatrix(),t.updateMatrixWorld(),d.applyMatrix4(t.matrixWorldInverse),d.getSize(a),d.setFromCenterAndSize(l,a),Number.isNaN(a.x)||Number.isNaN(a.y)||Number.isNaN(a.z))return console.warn("Camera fit size resultet in NaN",t,d),null;if(a.length()<=1e-10)return console.warn("Camera fit size is zero",d),null;const g=r,f=2*Math.atan(Math.tan(g*Math.PI/360/2)*c)/Math.PI*360,y=a.y/(2*Math.atan(Math.PI*g/360)),_=a.x/(2*Math.atan(Math.PI*f/360)),v=s*Math.max(y,_)+a.z/2;o.maxZoom=v*10,o.minZoom=v*.01,o.debug===!0&&console.log("Fit camera to objects",{fitHeightDistance:y,fitWidthDistance:_,distance:v,verticalFov:g,horizontalFov:f});const P=.05,k=l.clone();if(k.y-=a.y*P,o.targetOffset&&(o.targetOffset.x!==void 0&&(k.x+=o.targetOffset.x),o.targetOffset.y!==void 0&&(k.y+=o.targetOffset.y),o.targetOffset.z!==void 0&&(k.z+=o.targetOffset.z)),o.relativeTargetOffset&&(o.relativeTargetOffset.x!==void 0&&(k.x+=o.relativeTargetOffset.x*a.x),o.relativeTargetOffset.y!==void 0&&(k.y+=o.relativeTargetOffset.y*a.y),o.relativeTargetOffset.z!==void 0&&(k.z+=o.relativeTargetOffset.z*a.z)),n==null||n=="auto"){const L=tl(Jn),V=L?L.radius:0,W=Math.max(m.x,m.y,m.z,V);t instanceof de&&(t.near=v/100,t.far=W+v*10,t.updateProjectionMatrix()),L&&(o.maxZoom=Math.max(Math.min(o.maxZoom,V*.5),v))}o.currentZoom!==void 0&&(o.currentZoom<o.minZoom&&(o.minZoom=o.currentZoom*.9),o.currentZoom>o.maxZoom&&(o.maxZoom=o.currentZoom*1.1));const O=l.clone();o.fitDirection?O.sub(new b().copy(o.fitDirection).multiplyScalar(1e6)):O.sub(t.worldPosition),i==="y"&&(O.y=0),O.normalize(),O.multiplyScalar(v),i==="y"&&(O.y+=-P*4*v);let D=l.clone().sub(O);return o.cameraOffset&&(o.cameraOffset.x!==void 0&&(D.x+=o.cameraOffset.x),o.cameraOffset.y!==void 0&&(D.y+=o.cameraOffset.y),o.cameraOffset.z!==void 0&&(D.z+=o.cameraOffset.z)),o.relativeCameraOffset&&(o.relativeCameraOffset.x!==void 0&&(D.x+=o.relativeCameraOffset.x*a.x),o.relativeCameraOffset.y!==void 0&&(D.y+=o.relativeCameraOffset.y*a.y),o.relativeCameraOffset.z!==void 0&&(D.z+=o.relativeCameraOffset.z*a.z)),t.parent&&(D=t.parent.worldToLocal(D)),o.debug&&(B.DrawWireBox3(d,16777011,10),B.DrawWireBox3(p,65280,10)),o.autoApply&&(t.position.copy(D),t.lookAt(k),r>0&&t instanceof de&&(t.fov=r,t.updateProjectionMatrix())),{camera:t,position:D,lookAt:k,fov:o.fov}}var XE=Object.defineProperty,jf=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&XE(e,t,n),n};class Wr extends E{constraintActive=!0;locked=!1;sources=[];setConstraintPosition(e){const t=this.sources[0];t&&(t.worldPosition=e)}}jf([u()],Wr.prototype,"constraintActive"),jf([u()],Wr.prototype,"locked"),jf([u(M)],Wr.prototype,"sources");let Vr=class{bb=null;bb_pos=0;__init(o,e){return this.bb_pos=o,this.bb=e,this}x(){return this.bb.readFloat32(this.bb_pos)}y(){return this.bb.readFloat32(this.bb_pos+4)}z(){return this.bb.readFloat32(this.bb_pos+8)}static sizeOf(){return 12}static createVec3(o,e,t,i){return o.prep(4,12),o.writeFloat32(i),o.writeFloat32(t),o.writeFloat32(e),o.offset()}};class cx{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}position(e){return(e||new Vr).__init(this.bb_pos,this.bb)}rotation(e){return(e||new Vr).__init(this.bb_pos+12,this.bb)}scale(e){return(e||new Vr).__init(this.bb_pos+24,this.bb)}static sizeOf(){return 36}static createTransform(e,t,i,n,s,r,a,l,c,h){return e.prep(4,36),e.prep(4,12),e.writeFloat32(h),e.writeFloat32(c),e.writeFloat32(l),e.prep(4,12),e.writeFloat32(a),e.writeFloat32(r),e.writeFloat32(s),e.prep(4,12),e.writeFloat32(n),e.writeFloat32(i),e.writeFloat32(t),e.offset()}}class gs{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedTransformModel(e,t){return(t||new gs).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedTransformModel(e,t){return e.setPosition(e.position()+Vb),(t||new gs).__init(e.readInt32(e.position())+e.position(),e)}guid(e){const t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}fast(){const e=this.bb.__offset(this.bb_pos,6);return e?!!this.bb.readInt8(this.bb_pos+e):!1}transform(e){const t=this.bb.__offset(this.bb_pos,8);return t?(e||new cx).__init(this.bb_pos+t,this.bb):null}dontSave(){const e=this.bb.__offset(this.bb_pos,10);return e?!!this.bb.readInt8(this.bb_pos+e):!1}static startSyncedTransformModel(e){e.startObject(4)}static addGuid(e,t){e.addFieldOffset(0,t,0)}static addFast(e,t){e.addFieldInt8(1,+t,0)}static addTransform(e,t){e.addFieldStruct(2,t,0)}static addDontSave(e,t){e.addFieldInt8(3,+t,0)}static endSyncedTransformModel(e){return e.endObject()}static finishSyncedTransformModelBuffer(e,t){e.finish(t)}static finishSizePrefixedSyncedTransformModelBuffer(e,t){e.finish(t,void 0,!0)}}var T;(o=>{(e=>{e.MAYBEMODULE=null;const t=[];function i(){return e.MODULE?Promise.resolve(e.MODULE):new Promise(s=>{t.push(s)})}e.ready=i;async function n(){if(e.MODULE)return e.MODULE;const s=await import("./materialx-D_ofN96q.min.js");return e.MODULE=s,e.MAYBEMODULE=s,t.forEach(r=>r(s)),t.length=0,s}e.load=n})(o.MaterialX||(o.MaterialX={})),(e=>{e.MAYBEMODULE=null;const t=[];function i(){return e.MODULE?Promise.resolve(e.MODULE):new Promise(s=>{t.push(s)})}e.ready=i;async function n(){if(e.MODULE)return e.MODULE;const s=await import("./rapier-DJ-luMxr.min.js");return e.MODULE=s,e.MAYBEMODULE=s,t.forEach(r=>r(s)),t.length=0,s}e.load=n})(o.RAPIER_PHYSICS||(o.RAPIER_PHYSICS={})),(e=>{e.MAYBEMODULE=null;const t=[];function i(){return e.MODULE?Promise.resolve(e.MODULE):new Promise(s=>{t.push(s)})}e.ready=i;async function n(){if(e.MODULE)return e.MODULE;const s=await import("./postprocessing-CaEfRjRY.min.js").then(r=>r.index);return e.MODULE=s,e.MAYBEMODULE=s,t.forEach(r=>r(s)),t.length=0,s}e.load=n})(o.POSTPROCESSING||(o.POSTPROCESSING={})),(e=>{e.MAYBEMODULE=null;const t=[];function i(){return e.MODULE?Promise.resolve(e.MODULE):new Promise(s=>{t.push(s)})}e.ready=i;async function n(){if(e.MODULE)return e.MODULE;const s=await import("./postprocessing-CaEfRjRY.min.js").then(r=>r.N8AO);return e.MODULE=s,e.MAYBEMODULE=s,t.forEach(r=>r(s)),t.length=0,s}e.load=n})(o.POSTPROCESSING_AO||(o.POSTPROCESSING_AO={}))})(T||(T={}));var vt=(o=>(o[o.Average=0]="Average",o[o.Multiply=1]="Multiply",o[o.Minimum=2]="Minimum",o[o.Maximum=3]="Maximum",o))(vt||{}),Bu=(o=>(o[o.Discrete=0]="Discrete",o[o.Continuous=1]="Continuous",o))(Bu||{}),Ze=(o=>(o[o.None=0]="None",o[o.FreezePositionX=2]="FreezePositionX",o[o.FreezePositionY=4]="FreezePositionY",o[o.FreezePositionZ=8]="FreezePositionZ",o[o.FreezePosition=14]="FreezePosition",o[o.FreezeRotationX=16]="FreezeRotationX",o[o.FreezeRotationY=32]="FreezeRotationY",o[o.FreezeRotationZ=64]="FreezeRotationZ",o[o.FreezeRotation=112]="FreezeRotation",o[o.FreezeAll=126]="FreezeAll",o))(Ze||{}),cl=(o=>(o[o.None=0]="None",o[o.X=2]="X",o[o.Y=4]="Y",o[o.Z=8]="Z",o[o.All=-1]="All",o))(cl||{});const kt=function(o,e){return function(t,i,n){QE(t,i,n,o,e)}};function QE(o,e,t,i,n){if(!n&&!i&&!o.onValidate)return;if(t!==void 0){console.error("Invalid usage of validate decorator. Only fields can be validated.",o,e,t),Oe("Invalid usage of validate decorator. Only fields can be validated. Property: "+e,{type:Ri.Error});return}let s="";if(typeof e=="string"?s=e:s=e.name,o.__internalAwake){const r=Symbol(s),a=o.__internalAwake;o.__internalAwake=function(){if(!this.onValidate){A()&&console.warn('Usage of @validate decorate detected but there is no onValidate method in your class: "'+o.constructor?.name+'"');return}if(this[r]===void 0){this[r]=this[s];const l=this[s];if(l instanceof K||l instanceof b||l instanceof ye||l instanceof N){const c=this[s];Bd(c,()=>{this.onValidate(s)})}Object.defineProperty(this,s,{set:function(c){if(this[lf]===!0)this[r]=c;else{i?.call(this,c);const h=this[r];this[r]=c,this.onValidate?.call(this,s,h)}},get:function(){return n?.call(this),this[r]}})}a.call(this)}}}const YE=function(o){return function(e,t,i){let n="";typeof t=="string"?n=t:n=t.name;const s=o.prototype,r=Object.getOwnPropertyDescriptor(s,n);if(!r?.value){console.warn("Can not apply prefix: type does not have method named",t,o);return}const a=r.value,l=e[n];Object.defineProperty(s,n,{value:function(...c){const h=l?.call(this,...c);if(h instanceof Promise){h.then(d=>{if(d!==!1)return a.call(this,...c)});return}if(h!==!1)return a.call(this,...c)}})}};var ZE=Object.defineProperty,KE=Object.getOwnPropertyDescriptor,Li=(o,e,t,i)=>{for(var n=i>1?void 0:i?KE(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&ZE(e,t,n),n};class JE{get isDirty(){return this.positionChanged||this.rotationChanged}positionChanged=!1;rotationChanged=!1;position;quaternion;_positionKeys=["x","y","z"];_quaternionKeys=["_x","_y","_z","_w"];reset(e=!1){if(this.positionChanged=!1,this.rotationChanged=!1,this.mute=!1,e){if(this.position)for(const t of this._positionKeys)delete this.position[t];if(this.quaternion)for(const t of this._quaternionKeys)delete this.quaternion[t]}}syncValues(){for(const e of this._positionKeys)this.position[e]=this.obj.position[e];for(const e of this._quaternionKeys)this.quaternion[e]=this.obj.quaternion[e]}mute=!1;applyValues(){if(this.positionChanged&&this.position)for(const e of this._positionKeys){const t=this.position[e];t!==void 0&&(this.obj.position[e]=t)}if(this.rotationChanged&&this.quaternion)for(const e of this._quaternionKeys){const t=this.quaternion[e];t!==void 0&&(this.obj.quaternion[e]=t)}}context;obj;_positionWatch;_rotationWatch;constructor(e,t){this.context=t,this.obj=e}start(e,t){this.reset(),e&&(this._positionWatch||(this._positionWatch=new ps(this.obj.position,["x","y","z"])),this._positionWatch.apply(),this.position={},this._positionWatch.subscribeWrite((s,r)=>{if(this.context.physics.engine?.isUpdating||this.mute)return;const a=this.position[r];Math.abs(a-s)<1e-5||(this.position[r]=s,this.positionChanged=!0)})),t&&(this._rotationWatch||(this._rotationWatch=new ps(this.obj.quaternion,["_x","_y","_z","_w"])),this._rotationWatch.apply(),this.quaternion={},this._rotationWatch.subscribeWrite((s,r)=>{if(this.context.physics.engine?.isUpdating||this.mute)return;const a=this.quaternion[r];Math.abs(a-s)<1e-5||(this.quaternion[r]=s,this.rotationChanged=!0)}));const i=this.obj.matrixWorld.multiplyMatrices.bind(this.obj.matrixWorld),n=new J;this.obj.matrixWorld.multiplyMatrices=(s,r)=>(this.context.physics.engine?.isUpdating||this.mute||n.equals(s)||(this.positionChanged=!0,this.rotationChanged=!0,n.copy(s)),i(s,r))}stop(){this._positionWatch?.revoke(),this._rotationWatch?.revoke()}}const fi=class bm extends E{get isRigidbody(){return!0}autoMass=!0;set mass(e){e!==this._mass&&(this._mass=e,this._propertiesChanged=!0,this.__didAwake&&(this.autoMass=!1))}get mass(){return this.autoMass?this.context.physics.engine?.getBody(this)?.mass()??-1:this._mass}_mass=0;useGravity=!0;centerOfMass=new b(0,0,0);constraints=Ze.None;isKinematic=!1;drag=0;angularDrag=1;detectCollisions=!0;sleepThreshold=.01;collisionDetectionMode=Bu.Discrete;get lockPositionX(){return(this.constraints&Ze.FreezePositionX)!==0}get lockPositionY(){return(this.constraints&Ze.FreezePositionY)!==0}get lockPositionZ(){return(this.constraints&Ze.FreezePositionZ)!==0}get lockRotationX(){return(this.constraints&Ze.FreezeRotationX)!==0}get lockRotationY(){return(this.constraints&Ze.FreezeRotationY)!==0}get lockRotationZ(){return(this.constraints&Ze.FreezeRotationZ)!==0}set lockPositionX(e){e?this.constraints|=Ze.FreezePositionX:this.constraints&=~Ze.FreezePositionX}set lockPositionY(e){e?this.constraints|=Ze.FreezePositionY:this.constraints&=~Ze.FreezePositionY}set lockPositionZ(e){e?this.constraints|=Ze.FreezePositionZ:this.constraints&=~Ze.FreezePositionZ}set lockRotationX(e){e?this.constraints|=Ze.FreezeRotationX:this.constraints&=~Ze.FreezeRotationX}set lockRotationY(e){e?this.constraints|=Ze.FreezeRotationY:this.constraints&=~Ze.FreezeRotationY}set lockRotationZ(e){e?this.constraints|=Ze.FreezeRotationZ:this.constraints&=~Ze.FreezeRotationZ}set gravityScale(e){this._gravityScale=e}get gravityScale(){return this._gravityScale}_gravityScale=1;dominanceGroup=0;static tempPosition=new b;_propertiesChanged=!1;_currentVelocity=new b;_smoothedVelocity=new b;_smoothedVelocityGetter=new b;_lastPosition=new b;_watch;awake(){this._watch=void 0,this._propertiesChanged=!1}onEnable(){this._watch||(this._watch=new JE(this.gameObject,this.context)),this._watch.start(!0,!0),this.startCoroutine(this.beforePhysics(),xe.LateUpdate),A()&&(globalThis.NEEDLE_USE_RAPIER?T.RAPIER_PHYSICS.ready().then(async()=>{await mc(3),this.context.physics.engine?.getBody(this)||console.warn(`Rigidbody could not be created. Ensure "${this.name}" has a Collider component.`)}):console.warn("Rigidbody could not be created: Rapier physics are explicitly disabled."))}onDisable(){this._watch?.stop(),this.context.physics.engine?.removeBody(this)}onDestroy(){this.context.physics.engine?.removeBody(this)}onValidate(){this._propertiesChanged=!0}*beforePhysics(){for(;;)this._propertiesChanged&&(this._propertiesChanged=!1,this.context.physics.engine?.updateProperties(this)),this._watch?.isDirty?(this._watch.mute=!0,this._watch.applyValues(),this.context.physics.engine?.updateBody(this,this._watch.positionChanged,this._watch.rotationChanged),this._watch.reset()):this._watch?.syncValues(),this.captureVelocity(),yield}teleport(e,t=!0){this._watch?.reset(!0),t?this.gameObject.position.set(e.x,e.y,e.z):this.setWorldPosition(e.x,e.y,e.z),this.resetForcesAndTorques(),this.resetVelocities()}resetForces(e=!0){this.context.physics.engine?.resetForces(this,e)}resetTorques(e=!0){this.context.physics.engine?.resetTorques(this,e)}resetVelocities(){this.setVelocity(0,0,0),this.setAngularVelocity(0,0,0)}resetForcesAndTorques(){this.resetForces(),this.resetTorques()}wakeUp(){this.context.physics.engine?.wakeup(this)}get isSleeping(){return this.context.physics.engine?.isSleeping(this)}updateProperties(){return this._propertiesChanged=!1,this.context.physics.engine?.updateProperties(this)}applyForce(e,t,i=!0){this._propertiesChanged&&this.updateProperties(),this.context.physics.engine?.addForce(this,e,i)}applyImpulse(e,t=!0){this._propertiesChanged&&this.updateProperties(),this.context.physics.engine?.applyImpulse(this,e,t)}setForce(e,t,i,n=!0){this.context.physics.engine?.resetForces(this,n),typeof e=="number"?(t??=0,i??=0,this.context.physics.engine?.addForce(this,{x:e,y:t,z:i},n)):this.context.physics.engine?.addForce(this,e,n)}getVelocity(){const e=this.context.physics.engine?.getLinearVelocity(this);return e?(this._currentVelocity.x=e.x,this._currentVelocity.y=e.y,this._currentVelocity.z=e.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setVelocity(e,t,i,n=!0){if(e instanceof b){const s=e;this.context.physics.engine?.setLinearVelocity(this,s,n);return}t===void 0||i===void 0||this.context.physics.engine?.setLinearVelocity(this,{x:e,y:t,z:i},n)}getAngularVelocity(){const e=this.context.physics.engine?.getAngularVelocity(this);return e?(this._currentVelocity.x=e.x,this._currentVelocity.y=e.y,this._currentVelocity.z=e.z,this._currentVelocity):this._currentVelocity.set(0,0,0)}setAngularVelocity(e,t,i,n=!0){if(typeof e=="object"){const s=e;this.context.physics.engine?.setAngularVelocity(this,s,n);return}if(t===void 0||i===void 0||typeof t=="boolean"){console.warn("setAngularVelocity expects either a Vec3 or 3 numbers");return}this.context.physics.engine?.setAngularVelocity(this,{x:e,y:t,z:i},n)}setTorque(e,t,i){typeof e=="number"?this.setAngularVelocity(e,t,i):this.setAngularVelocity(e)}get smoothedVelocity(){return this._smoothedVelocityGetter.copy(this._smoothedVelocity),this._smoothedVelocityGetter.multiplyScalar(1/this.context.time.deltaTime)}setBodyFromGameObject(e=null){}captureVelocity(){const e=this.gameObject.matrixWorld;bm.tempPosition.setFromMatrixPosition(e);const t=bm.tempPosition.sub(this._lastPosition);this._lastPosition.copy(bm.tempPosition),this._smoothedVelocity.lerp(t,this.context.time.deltaTime/.1)}};Li([kt()],fi.prototype,"autoMass",2),Li([u()],fi.prototype,"mass",1),Li([kt(),u()],fi.prototype,"useGravity",2),Li([u(b)],fi.prototype,"centerOfMass",2),Li([kt(),u()],fi.prototype,"constraints",2),Li([kt(),u()],fi.prototype,"isKinematic",2),Li([kt(),u()],fi.prototype,"drag",2),Li([kt(),u()],fi.prototype,"angularDrag",2),Li([kt(),u()],fi.prototype,"detectCollisions",2),Li([kt(),u()],fi.prototype,"sleepThreshold",2),Li([kt(),u()],fi.prototype,"collisionDetectionMode",2),Li([kt()],fi.prototype,"_gravityScale",2),Li([kt()],fi.prototype,"dominanceGroup",2);let Ke=fi;new b,new b;const Is=w("debugsync"),Qc="STRS";Eg(Qc,gs.getRootAsSyncedTransformModel);const eo=new Wm;function hx(o,e,t=!0){eo.clear();const i=eo.createString(o);gs.startSyncedTransformModel(eo),gs.addGuid(eo,i),gs.addFast(eo,t);const n=e.worldPosition,s=e.worldEuler,r=e.gameObject.scale;gs.addTransform(eo,cx.createTransform(eo,n.x,n.y,n.z,s.x,s.y,s.z,r.x,r.y,r.z));const a=gs.endSyncedTransformModel(eo);return eo.finish(a,Qc),eo.asUint8Array()}let Df=0,Yc=0;$w(o=>{const e=o.connection.currentServerUrl?.includes("glitch")?10:40;Yc=Math.floor(Df/e),Df=0,Is&&Yc>0&&console.log("Sync Transform Fast Interval",Yc)});class Tn extends E{overridePhysics=!0;interpolatePosition=!0;interpolateRotation=!0;fastMode=!1;syncDestroy=!1;_model=null;_needsUpdate=!0;rb=null;_wasKinematic=!1;_receivedDataBefore=!1;_targetPosition;_targetRotation;_receivedFastUpdate=!1;_shouldRequestOwnership=!1;requestOwnership(){Is&&console.log("Request ownership"),this._model?this._model.requestOwnership():(this._shouldRequestOwnership=!0,this._needsUpdate=!0)}freeOwnership(){this._model?.freeOwnership()}hasOwnership(){return this._model?.hasOwnership??void 0}isOwned(){return this._model?.isOwned}joinedRoomCallback=null;receivedDataCallback=null;awake(){Is&&console.log("new instance",this.guid,this),this._receivedDataBefore=!1,this._targetPosition=new b,this._targetRotation=new N,this.lastPosition=new b,this.lastRotation=new N,this.lastScale=new b,this.rb=S.getComponentInChildren(this.gameObject,Ke),this.rb&&(this._wasKinematic=this.rb.isKinematic),this.receivedUpdate=!0,this._model=new Tg(this.context.connection,this.guid),this.context.connection.isConnected&&this.tryGetLastState(),this.joinedRoomCallback=this.tryGetLastState.bind(this),this.context.connection.beginListen(ie.JoinedRoom,this.joinedRoomCallback),this.receivedDataCallback=this.onReceivedData.bind(this),this.context.connection.beginListenBinary(Qc,this.receivedDataCallback)}onDestroy(){this.syncDestroy&&Zg(this.guid,this.context.connection),this._model=null,this.context.connection.stopListen(ie.JoinedRoom,this.joinedRoomCallback),this.context.connection.stopListenBinary(Qc,this.receivedDataCallback)}tryGetLastState(){const e=this.context.connection.tryGetState(this.guid);e&&this.onReceivedData(e)}tempEuler=new at;onReceivedData(e){if(!this.destroyed&&typeof e.guid=="function"&&e.guid()===this.guid){Is&&console.log("new data",this.context.connection.connectionId,this.context.time.frameCount,this.guid,e),this.receivedUpdate=!0,this._receivedFastUpdate=e.fast();const t=e.transform();if(t){pn.markDirty(this.gameObject,!0);const i=t.position();i&&(this.interpolatePosition&&this._targetPosition?.set(i.x(),i.y(),i.z()),(!this.interpolatePosition||!this._receivedDataBefore)&&this.setWorldPosition(i.x(),i.y(),i.z()));const n=t.rotation();n&&(this.tempEuler.set(n.x(),n.y(),n.z()),this.interpolateRotation&&this._targetRotation.setFromEuler(this.tempEuler),(!this.interpolateRotation||!this._receivedDataBefore)&&ug(this.gameObject,this.tempEuler));const s=t.scale();s&&this.gameObject.scale.set(s.x(),s.y(),s.z())}this._receivedDataBefore=!0}}onEnable(){this.lastPosition.copy(this.worldPosition),this.lastRotation.copy(this.worldQuaternion),this.lastScale.copy(this.gameObject.scale),this._needsUpdate=!0,this._model&&this._model.updateIsOwned()}onDisable(){this._model&&this._model.freeOwnership()}receivedUpdate=!1;lastPosition;lastRotation;lastScale;onBeforeRender(){if(!this.activeAndEnabled||!this.context.connection.isConnected)return;if(!this.context.connection.isInRoom||!this._model){Is&&console.log("no model or room",this.name,this.guid,this.context.connection.isInRoom);return}this._shouldRequestOwnership&&(this._shouldRequestOwnership=!1,this._model.requestOwnership());const e=this.worldPosition,t=this.worldQuaternion,i=this.gameObject.scale;if(this._model.isOwned&&!this.receivedUpdate){const r=this._model.hasOwnership||this.fastMode?1e-4:.001;(e.distanceTo(this.lastPosition)>r||t.angleTo(this.lastRotation)>r||i.distanceTo(this.lastScale)>r)&&(this._model.hasOwnership?this._needsUpdate=!0:(Is&&console.log(this.guid,"reset because not owned but",this.gameObject.name,this.lastPosition),this.worldPosition=this.lastPosition,e.copy(this.lastPosition),this.worldQuaternion=this.lastRotation,t.copy(this.lastRotation),this.gameObject.scale.copy(this.lastScale),pn.markDirty(this.gameObject,!0),this._needsUpdate=!1))}if(this._model&&!this._model.hasOwnership&&this._model.isOwned&&this._receivedDataBefore){const r=this._receivedFastUpdate||this.fastMode?.5:.3;let a=!1;if(this.interpolatePosition&&this._targetPosition){const l=this.worldPosition;l.lerp(this._targetPosition,r),this.worldPosition=l,a=!0}if(this.interpolateRotation&&this._targetRotation){const l=this.worldQuaternion;l.slerp(this._targetRotation,r),this.worldQuaternion=l,a=!0}a&&pn.markDirty(this.gameObject,!0)}if(this.receivedUpdate=!1,this.lastPosition.copy(e),this.lastRotation.copy(t),this.lastScale.copy(i),!this._model||!this._model||this._model.hasOwnership===void 0||!this._model.hasOwnership)return;this.rb&&this.overridePhysics&&this._wasKinematic!==void 0&&(Is&&console.log("reset kinematic",this.rb.name,this._wasKinematic),this.rb.isKinematic=this._wasKinematic);const n=10,s=this.rb||this.fastMode;if(this._needsUpdate&&(this.context.time.frameCount%n===0||s)){if(Df++,s&&Yc>0&&this.context.time.frameCount%Yc!==0)return;Is&&console.debug("[SyncedTransform] Send update",this.context.connection.connectionId,this.guid,this.gameObject.name,this.gameObject.guid),this._needsUpdate=!1;const r=hx(this.guid,this,!!s);this.context.connection.sendBinary(r)}}}class vd{event;get deviceIndex(){return this.event.deviceIndex}get pointerId(){return this.event.pointerId}button;buttonName;get pressure(){return this.event.pressure}get used(){return this._used}_used=!1;use(){this._used||(this._used=!0,this.event.use())}_propagationStopped=!1;get propagationStopped(){return this._propagationStopped}stopPropagation(){this._propagationStopped=!0,this.event.stopImmediatePropagation()}stopImmediatePropagation(){this._propagationStopped=!0,this.event.stopImmediatePropagation()}z__pointer_ctured=!1;setPointerCapture(){this.z__pointer_ctured=!0}z__pointer_cture_rleased=!1;releasePointerCapture(){this.z__pointer_cture_rleased=!0}inputSource;get mode(){return this.event.mode}object;point;normal;face;distance;instanceId;intersection;isDown;isUp;isPressed;isClick;isDoubleClick;input;constructor(e,t){this.event=t,this.input=e,this.button=t.button}clone(){const e=new vd(this.input,this.event);return Object.assign(e,this),e}Use(){this.use()}StopPropagation(){this.event.stopImmediatePropagation()}}function Fu(o,e){return S.foreachComponent(o,t=>{if(!t.enabled)return;const i=t;if(e)switch(e){case"pointerdown":if(i.onPointerDown)return!0;break;case"pointerup":if(i.onPointerUp||i.onPointerClick)return!0;break;case"pointermove":if(i.onPointerEnter||i.onPointerExit||i.onPointerMove)return!0;break}else if(i.onPointerDown||i.onPointerUp||i.onPointerEnter||i.onPointerExit||i.onPointerClick)return!0},!1)===!0}const zo=new Array;class No{enabled=!0;target;methodName;arguments;get canClone(){return this.target instanceof Object}constructor(e,t,i,n){this.target=e,this.methodName=t||null,this.arguments=i,n!=null&&(this.enabled=n)}invoke(...e){if(this.enabled!==!1){if(typeof this.target=="function")this.arguments?(zo.length=0,e!==void 0&&e.length>0&&zo.push(...e),zo.push(...this.arguments),this.target(...this.arguments),zo.length=0):this.target(...e);else if(this.methodName!=null){const t=this.target[this.methodName];typeof t=="function"?this.arguments?(zo.length=0,e!==void 0&&e.length>0&&zo.push(...e),zo.push(...this.arguments),t.call(this.target,...zo),zo.length=0):t.call(this.target,...e):this.arguments?e!==void 0&&e.length>0?this.target[this.methodName]=e[0]:this.target[this.methodName]=this.arguments[0]:this.target[this.methodName]=e[0]}}}}const eR=o=>/^[A-Z]*$/.test(o);class Uu extends Event{args}class ae{isEventList=!0;__internalOnInstantiate(e){const t=new Array;for(let i=0;i<this.methods.length;i++){const n=this.methods[i];if(!(n.target instanceof Function)){const s=n.target;let r=s?.uuid;if(s&&(r=s.guid),r){const a=e[r];if(a){const l=n.arguments?.map(c=>c instanceof Object&&c.uuid?e[c.uuid].clone:c?.isComponent?e[c.guid].clone:c);t.push(new No(a.clone,n.methodName,l,n.enabled))}else A()&&console.warn("Could not find target for event listener")}}}return new ae(t)}target;key;setEventTarget(e,t){if(this.key=e,this.target=t,this.key!==void 0){let i="",n=!1;for(const s of this.key)n&&eR(s)&&(i+="-"),n=!0,i+=s.toLowerCase();this.key=i}}get listenerCount(){return this.methods?.length??0}get isInvoking(){return this._isInvoking}_isInvoking=!1;methods=[];_methodsCopy=[];static from(...e){return new ae(e)}constructor(e){if(this.methods=[],Array.isArray(e))for(const t of e)t instanceof No?this.methods.push(t):typeof t=="function"&&this.methods.push(new No(t));else typeof e=="function"&&this.methods.push(new No(e))}invoke(...e){if(this._isInvoking)return console.warn("Circular event invocation detected. Please check your event listeners for circular references.",this),!1;if(this.methods?.length<=0)return!1;this._isInvoking=!0;try{this._methodsCopy.length=0,this._methodsCopy.push(...this.methods);for(const t of this._methodsCopy)t.invoke(...e);if(typeof this.target=="object"&&typeof this.key=="string"){const t=this.target.dispatchEvent;if(typeof t=="function"){const i=new Uu(this.key);i.args=e,t.call(this.target,i)}}}finally{this._isInvoking=!1,this._methodsCopy.length=0}return!0}addEventListener(e){return this.methods.push(new No(e)),e}removeEventListener(e){if(e)for(let t=this.methods.length-1;t>=0;t--)this.methods[t].target===e&&(this.methods[t].enabled=!1,this.methods.splice(t,1))}removeAllEventListeners(){this.methods.length=0}}class tR extends Zi{constructor(){super([oe,se],"ColorSerializer")}onDeserialize(e){if(e!=null)return e.a!==void 0?new se(e.r,e.g,e.b,e.a):e.alpha!==void 0?new se(e.r,e.g,e.b,e.alpha):new oe(e.r,e.g,e.b)}onSerialize(e){if(e!=null)return e.a!==void 0?{r:e.r,g:e.g,b:e.b,a:e.a}:{r:e.r,g:e.g,b:e.b}}}const iR=new tR;class nR extends Zi{constructor(){super([at],"EulerSerializer")}onDeserialize(e,t){if(e!=null){if(e.order)return new at(e.x,e.y,e.z,e.order);if(e.x!=null)return new at(e.x,e.y,e.z)}}onSerialize(e,t){return{x:e.x,y:e.y,z:e.z,order:e.order}}}const oR=new nR;class sR extends Zi{constructor(){super(M,"ObjectSerializer")}onSerialize(e,t){if(t.objectToNode!==void 0&&e.uuid){const i=t.objectToNode[e.uuid];return bt&&console.log(i,e.name,e.uuid),{node:i}}}onDeserialize(e,t){if(typeof e=="string"){if(e.endsWith(".glb")||e.endsWith(".gltf")){if(t.serializable instanceof Array&&t.serializable.includes(ne))return;A()&&be("Detected wrong usage of @serializable with Object3D or GameObject. Instead you should use AssetReference here! Please see the console for details.");const i=t.target?.constructor?.name;console.warn(`Wrong usage of @serializable detected in your script "${i}"
|
|
963
963
|
|
|
964
964
|
It looks like you used @serializable(Object3D) or @serializable(GameObject) for a prefab or scene reference which is exported to a separate glTF file.
|
|
965
965
|
|
|
@@ -971,17 +971,17 @@ ${t.path}! : AssetReference;
|
|
|
971
971
|
Could not find method ${r.method} on object ${l.name}. Please rename ${r.method} to ${d}?
|
|
972
972
|
`,l[d],`
|
|
973
973
|
in script: `,l),be("EventList methods must start with lowercase letter, see console for details");return}else console.warn(`EventList method:
|
|
974
|
-
Could not find method ${r.method} on object ${l.name}`,l,typeof l[r.method])};if(typeof l[r.method]!="function"){let d=!1,p=l;for(;p;){const m=Object.getOwnPropertyDescriptor(p,r.method);if(m&&(m.writable===!0||m.set)){d=!0;break}p=Object.getPrototypeOf(p)}!d&&(A()||bt)&&h()}}if(l){let h=r.argument;if(h!==void 0?h=a(h):r.arguments!==void 0&&(h=r.arguments.map(a)),l[r.method]===void 0)console.warn(`EventList method not found: "${r.method}" on ${l?.name}`);else{h!==void 0&&!Array.isArray(h)&&(h=[h]);const d=new No(l,r.method,h,r.enabled);i.push(d)}}else A()&&console.warn(`[Dev] EventList: Could not find event listener in scene (${t.object?.name})`,r)}const n=new ae(i);bt&&console.log(n);const s=t.target;return s!==void 0&&t.path!==void 0&&n.setEventTarget(t.path,s),n}}}const lR=new aR,Nu=new WeakMap,cR=Se.prototype.clone;Se.prototype.clone=function(){const o=cR.call(this);return Nu.has(o)||Nu.set(o,this),o};class ux extends Zi{constructor(){super([xo,$n])}onSerialize(e,t){}onDeserialize(e,t){if(e instanceof Se&&t.type===xo){let i=e;Nu.has(i)&&(i=Nu.get(i)),i.isRenderTargetTexture=!0,i.flipY=!0,i.offset.y=1,i.repeat.y=-1,i.needsUpdate=!0,i.mipmaps=[],i instanceof lC&&(i.isCompressedTexture=!1,i.format=Md);const n=new xo(i.image.width,i.image.height,{colorSpace:Oo});return n.texture=i,n}}}new ux;class px extends Zi{constructor(){super([URL])}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"&&e.length>0)return Ao(t.gltfId,e)}}new px;var hR=Object.defineProperty,dR=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&hR(e,t,n),n};class Zc extends E{awake(){li.createIfNoneExists(this.context)}onEnable(){li.get(this.context)?.register(this)}onDisable(){li.get(this.context)?.unregister(this)}}class Ji extends Zc{targets=null;raycastHits=[];ignoreSkinnedMeshes=!1;start(){this.targets=[this.gameObject]}performRaycast(e=null){if(!this.targets)return null;e??=new ks,e.targets=this.targets,e.results=this.raycastHits,e.useAcceleratedRaycast=!0;const t=e.testObject;this.ignoreSkinnedMeshes&&(e.testObject=n=>n instanceof vs?"continue in children":t?t(n):!0);const i=this.context.physics.raycast(e);return e.testObject=t,i}}dR([u()],Ji.prototype,"ignoreSkinnedMeshes");class Wu extends Ji{constructor(){super(),this.ignoreSkinnedMeshes=!0}}class Ca extends Zc{static allow=!0;performRaycast(e){if(!Z.active||!Ca.allow||!e?.ray)return null;const t=e.ray.origin;return this.context.physics.sphereOverlap(t,.015,!1,!0)}}class Bf{static getObject(e){const t=e[Ai];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=Fr(e,s=>{if(s.isGraphic===!0)return s},!1);return t&&n?.isGraphic===!0&&(t.graphic=n),!(n?.raycastTarget===!1||n?.layer===2)}static tryFindCanvasGroup(e){if(!e)return null;const t=Fr(e,i=>{if(i.activeAndEnabled){const n=i;if(n.blocksRaycasts!==void 0&&n.interactable!==void 0)return n}},!1);return t!==void 0?t:this.tryFindCanvasGroup(e.parent)}}function Ff(o){return o[Ai]||(o.parent?Ff(o.parent):null)}function uR(o){return o.isUI===!0||typeof o[Ai]=="object"}function Vu(o,e){if(!o)return;const t=o.material;if(t?.isMaterial===!0){const i=o.parent;i&&i.isText,t.side=e.doubleSided??!0?Oi:ws,t.shadowSide=e.doubleSided?Oi:ws,o.castShadow=e.castShadows?e.castShadows:!1,o.receiveShadow=e.receiveShadows?e.receiveShadows:!1}for(const i of o.children)Vu(i,e)}function hl(o,e,t){o[e]===void 0&&console.warn("Field",e,"is undefined on",o);const i=Proxy.revocable(o[e],{set(r,a,l,c){const h=r[a],d=Reflect.set(r,a,l,c);return t(l,h),d}}),n=i.revoke,s=o[e];return i.revoke=()=>{o[e]=s,n()},o[e]=i.proxy,i}const mx=Symbol("Scheduled action");function pR(o,e,t=xe.OnBeforeRender){let i=o[mx];i||(i=o[mx]={});const n=e.name;i[t]||(i[t]={});const s=i[t];if(s[n])return;function*r(){e?.call(o),s[n]=null}const a=o.startCoroutine(r(),t);s[n]=a}const Ls=w("debugeventsystem");var Uf=(o=>(o.BeforeHandleInput="BeforeHandleInput",o.AfterHandleInput="AfterHandleInput",o))(Uf||{});Pf(o=>{li.createIfNoneExists(o)});class li extends E{static ensureUpdateMeshUI(e,t,i=!1){Kc.update(e,t,i)}static markUIDirty(e){Kc.markDirty()}static createIfNoneExists(e){e.scene.getComponent(li)||e.scene.addComponent(li)}static get(e){return this.createIfNoneExists(e),e.scene.getComponent(li)}static get instance(){return this.get(U.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(Zc)||this.context.scene.addComponent(Ji)}onEnable(){this.context.input.addEventListener(Ae.PointerDown,this.onPointerEvent),this.context.input.addEventListener(Ae.PointerUp,this.onPointerEvent),this.context.input.addEventListener(Ae.PointerMove,this.onPointerEvent)}onDisable(){this.context.input.removeEventListener(Ae.PointerDown,this.onPointerEvent),this.context.input.removeEventListener(Ae.PointerUp,this.onPointerEvent),this.context.input.removeEventListener(Ae.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 vd(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==Ae.PointerDown,t.isUp=e.type==Ae.PointerUp,t.isPressed=this.context.input.getPointerPressed(e.pointerId);const i=new ks;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(Ls&&(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})}Ls&&t.isClick&&Oe("EventSystem: "+t.pointerId+" - "+this.context.time.frame+" - Up:"+t.isUp+", Down:"+t.isDown);const s={sender:this,args:t,hasActiveUI:this.currentActiveMeshUIComponents.length>0};this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:s})),this.handleIntersections(n,t),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:s}))};_sortedHits=[];_testObjectsCache=new Map;_currentlyActiveRaycaster=null;_currentPointerEventName=null;shouldRaycastObject=e=>{const t=e&&"getComponent"in e?e.getComponent(Zc):null;if(t&&t!=this._currentlyActiveRaycaster)return!1;let i=null;if(uR(e)&&(i=e[Ai]?.gameObject),this._testObjectsCache.has(e)||i&&this._testObjectsCache.has(i))return this._testObjectsCache.get(e)===!1?"continue in children":!0;{let n=Fu(e,this._currentPointerEventName);if(!n&&i&&(n=Fu(i,this._currentPointerEventName)),n){this._testObjectsCache.set(e,!0);for(const s of e.children)this.shouldRaycastObject_AddToYesCache(s);return!0}return this._testObjectsCache.set(e,!1),"continue in children"}};shouldRaycastObject_AddToYesCache(e){this._testObjectsCache.set(e,!0);for(const t of e.children)this.shouldRaycastObject_AddToYesCache(t)}performRaycast(e){if(!this.raycaster)return null;this._testObjectsCache.clear(),this._sortedHits.length=0,e.testObject=this.shouldRaycastObject;for(const t of this.raycaster){if(!t.activeAndEnabled)continue;this._currentlyActiveRaycaster=t;const i=t.performRaycast(e);this._currentlyActiveRaycaster=null,i&&i.length>0&&this._sortedHits.push(...i)}return this._sortedHits.sort((t,i)=>t.distance-i.distance),this._sortedHits}assignHitInformation(e,t){t?(e.intersection=t,e.point=t.point,e.normal=t.normal,e.face=t.face,e.distance=t.distance,e.instanceId=t.instanceId):(e.intersection=void 0,e.point=void 0,e.normal=void 0,e.face=void 0,e.distance=void 0,e.instanceId=void 0)}handleIntersections(e,t){if(e?.length){e=this.sortCandidates(e);for(const n of e){if(t.event.immediatePropagationStopped)return!1;if(this.assignHitInformation(t,n),this.handleEventOnObject(n.object,t))return!0}}this.assignHitInformation(t,e?.[0]),this.invokePointerCapture(t);const i=this.hoveredByID.get(t.pointerId);return i&&this.propagatePointerExit(i.obj,i.data,null),this.hoveredByID.delete(t.pointerId),t.isUp&&(this.pressedByID.get(t.pointerId)?.handlers.forEach(n=>this.invokeOnPointerUp(t,n)),this.pressedByID.delete(t.pointerId)),!1}_sortingBuffer=[];_noDepthTestingResults=[];sortCandidates(e){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let t=0;t<e.length;t++){const i=e[t],n=i.object;if(n.material&&n.material.depthTest===!1){this._noDepthTestingResults.push(i);continue}this._sortingBuffer.push(i)}for(const t of this._sortingBuffer)this._noDepthTestingResults.push(t);return this._noDepthTestingResults}out={};handleEventOnObject(e,t){if(!this.testIsVisible(e))return t.isClick&&Ls&&console.log("not allowed",e),!1;if(t.pointerId===void 0)return Ls&&console.error("Event without pointer can't be handled",t),!1;t.object=e;const i=e.parent,n=t.isClick??!1;let s=null;if(i&&i.isUI){const c=(t.isPressed||t.isClick)??!1;if(i[Ai]){const h=i[Ai].gameObject;if(h){if(!Bf.isInteractable(h,this.out))return!1;s=this.out.canvasGroup??null,this.handleMeshUIIntersection(e,c),e=h}}}n&&Ls&&console.log(this.context.time.frame,e);const r=this.hoveredByID.get(t.pointerId),a=r?.obj;a!==e&&a&&this.propagatePointerExit(a,r.data,e);const l=this.hoveredByID.get(t.pointerId);if(l?(l.obj=e,l.data=t):this.hoveredByID.set(t.pointerId,{obj:e,data:t}),t.isDown){const c=this.pressedByID.get(t.pointerId);c?(c.obj=e,c.data=t):this.pressedByID.set(t.pointerId,{obj:e,data:t,handlers:new Set})}return(s===null||s.interactable)&&this.handleMainInteraction(e,t,a??null),!0}propagate(e,t){for(;e;)S.foreachComponent(e,i=>{t(i)},!1),e=e.parent}handleMainInteraction(e,t,i){const n=this.pressedByID.get(t.pointerId),s=i!==e;let r=!0;switch(t.event.pointerType){case"mouse":case"touch":const a=this.context.input.getPointerPositionLastFrame(t.pointerId),l=this.context.input.getPointerPosition(t.pointerId);r=a&&!D.approximately(a,l);break}this.propagate(e,a=>{const l=a;l.interactable!==!1&&(!l.activeAndEnabled||!l.enabled||(l.onPointerEnter&&s&&this.handlePointerEnter(l,t),t.isDown&&l.onPointerDown&&(l.onPointerDown(t),n?.handlers.add(l),this.handlePointerCapture(t,l)),l.onPointerMove&&(r&&l.onPointerMove(t),this.handlePointerCapture(t,l)),t.isUp&&(l.onPointerUp&&(this.invokeOnPointerUp(t,l),n?.handlers.delete(l)),l.onPointerExit&&t.event?.pointerType===Yd.Touch&&(this.handlePointerExit(l,t),this.hoveredByID.delete(t.pointerId))),t.isClick&&l.onPointerClick&&l.onPointerClick(t)))}),t.isUp&&(n?.handlers.forEach(a=>{this.invokeOnPointerUp(t,a)}),this.pressedByID.delete(t.pointerId))}propagatePointerExit(e,t,i){this.propagate(e,n=>{if(!n.gameObject||n.destroyed)return;const s=n;if(s.onPointerExit||s.onPointerEnter){if(i&&this.isChild(i,n.gameObject))return;this.handlePointerExit(s,t)}})}invokeOnPointerUp(e,t){t.onPointerUp?.call(t,e),this.releasePointerCapture(e,t)}handlePointerEnter(e,t){e.onPointerEnter&&this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!0)&&e.onPointerEnter(t),this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!1)}handlePointerExit(e,t){e.onPointerExit&&this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!0)&&e.onPointerExit(t),this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!1)}updatePointerState(e,t,i,n){let s=e[i];if(n)return s&&s.includes(t)?!1:(s=s||[],s.push(t),e[i]=s,!0);{if(!s||!s.includes(t))return!1;const r=s.indexOf(t);return r!==-1&&s.splice(r,1),!0}}_capturedPointer={};handlePointerCapture(e,t){if(e.z__pointer_ctured){e.z__pointer_ctured=!1;const i=e.pointerId;if(t.onPointerMove){const n=this._capturedPointer[i]||[];n.push(t),this._capturedPointer[i]=n}else A()&&!t.z__warned_no_pointermove&&(t.z__warned_no_pointermove=!0,console.warn("PointerCapture was requested but the component doesn't implement onPointerMove. It will not receive any pointer events"))}else e.z__pointer_cture_rleased&&(e.z__pointer_cture_rleased=!1,this.releasePointerCapture(e,t))}releasePointerCapture(e,t){const i=e.pointerId;if(this._capturedPointer[i]){const n=this._capturedPointer[i].indexOf(t);n!==-1&&(this._capturedPointer[i].splice(n,1),Ls&&console.log("released pointer capture",i,t,this._capturedPointer))}}invokePointerCapture(e){if(e.event.type===Ae.PointerMove){const t=e.pointerId,i=this._capturedPointer[t];if(i){Ls&&console.log("Captured",t,i);for(let n=0;n<i.length;n++){const s=i[n];if(s.destroyed){i.splice(n,1),n--;continue}s.onPointerMove?.call(s,e)}}}}pointerEnterSymbol=Symbol("pointerEnter");pointerExitSymbol=Symbol("pointerExit");isChild(e,t){return!e||!t?!1:e===t?!0:e.parent?this.isChild(e.parent,t):!1}handleMeshUiObjectWithoutShadowDom(e,t){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,t)}currentActiveMeshUIComponents=[];handleMeshUIIntersection(e,t){const i=Kc.updateState(e,t);return i&&this.currentActiveMeshUIComponents.push(i),i!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&Kc.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){const t=this.currentActiveMeshUIComponents[e];Kc.resetState(t)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?S.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}}class Kc{static lastSelected=null;static lastUpdateFrame=[];static needsUpdate=!1;static markDirty(){this.needsUpdate=!0}static update(e,t,i=!1){if(i){e.update();return}const n=t.time.frameCount;for(const s of this.lastUpdateFrame)if(s.context===t){if(n===s.frame)return;s.frame=n;let r=this.needsUpdate||n<1;s.nextUpdate<=n&&(r=!0),r&&(Ls&&console.log("Update threemeshui"),this.needsUpdate=!1,s.nextUpdate=n+60,e.update());return}this.lastUpdateFrame=[{context:t,frame:n,nextUpdate:n+60}],e.update(),this.needsUpdate=!1}static updateState(e,t){let i=null;if(e&&(i=this.findBlockOrTextInParent(e),i&&i!==this.lastSelected)){if(i.interactable===!1)return null;this.needsUpdate=!0}return i}static resetLastSelected(){const e=this.lastSelected;e&&(this.lastSelected=null,this.resetState(e))}static resetState(e){e&&(this.needsUpdate=!0)}static findBlockOrTextInParent(e){return e?e.isBlock||e.isText?e:this.findBlockOrTextInParent(e.parent):null}}var mR=Object.defineProperty,gR=Object.getOwnPropertyDescriptor,Me=(o,e,t,i)=>{for(var n=i>1?void 0:i?gR(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&mR(e,t,n),n};const zt=w("debugorbit"),zf=w("freecam"),fR=w("debugcamerafit"),$u=w("smoothcam"),yR={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let Nf;class Jc extends CustomEvent{constructor(e,t){super("target-reached",{detail:{controls:e,type:t}})}}class ge extends E{get isCameraController(){return!0}get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(e){this.controls?.addEventListener("start",e)}autoTarget=!0;autoFit=!1;enableRotate=!0;autoRotate=!1;autoRotateSpeed=1;minAzimuthAngle=1/0;maxAzimuthAngle=1/0;minPolarAngle=0;maxPolarAngle=Math.PI;enableKeys=!1;enableDamping=!0;dampingFactor=.1;enableZoom=!0;minZoom=0;maxZoom=1/0;zoomSpeed=1;zoomToCursor=!1;enablePan=!0;lookAtConstraint=null;lookAtConstraint01=1;allowInterrupt=!0;middleClickToFocus=!0;doubleClickToFocus=!0;clickBackgroundToFitScene=2;get targetElement(){return this._controls?.domElement??this._targetElement}set targetElement(e){this._targetElement=e,this._controls&&this._controls.domElement!==e&&(this._controls.disconnect(),this._controls.domElement=e,this._controls.connect())}_targetElement=null;debugLog=!1;get targetLerpSpeed(){return 5}set targetLerpSpeed(e){this.targetLerpDuration=1/e}get targetLerpDuration(){return this._lookTargetLerpDuration}set targetLerpDuration(e){this._lookTargetLerpDuration=e}_lookTargetLerpDuration=1;targetBounds=null;rotateLeft(e){this._controls?._rotateLeft(e)}rotateUp(e){this._controls?._rotateUp(e)}pan(e,t){this._controls?._pan(e,t)}zoomIn(e){e>0?this._controls?._dollyIn(1-e):e<0&&this._controls?._dollyOut(1+e)}_controls=null;_cameraObject=null;_lookTargetLerpActive=!1;_lookTargetStartPosition=new b;_lookTargetEndPosition=new b;_lookTargetLerp01=0;_cameraLerpActive=!1;_cameraStartPosition=new b;_cameraEndPosition=new b;_cameraLerp01=0;_cameraLerpDuration=0;_fovLerpActive=!1;_fovLerpStartValue=0;_fovLerpEndValue=0;_fovLerp01=0;_fovLerpDuration=0;_inputs=0;_enableTime=0;_startedListeningToKeyEvents=!1;_eventSystem;_afterHandleInputFn;_camera=null;_syncedTransform;_didSetTarget=0;awake(){zt&&console.debug("OrbitControls",this),this._didSetTarget=0,this._startedListeningToKeyEvents=!1,this.context.domElement.cameraControls===!1&&(this.enabled=!1)}start(){this._eventSystem=li.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(Uf.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){this._controls?.dispose(),this._eventSystem?.removeEventListener(Uf.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._didSetTarget=0,this._enableTime=this.context.time.time;const e=S.getComponent(this.gameObject,yi);this._camera=e;let t=e?.threeCamera;if(!t&&this.gameObject instanceof de&&(t=this.gameObject),t&&sg(t,this,!0),!this._controls&&t instanceof M){this._cameraObject=t;const i=this.targetElement??this.context.renderer.domElement,n=t?.quaternion.clone();this._controls=new gP(t,i),t?.quaternion.copy(n),Nf===void 0&&(Nf={...this._controls.keys});const s=ee(t),r=this.gameObject.worldForward,a=s.clone().sub(r.multiplyScalar(2.5));this._controls.target.copy(a)}if(this._controls)if(zf&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,I.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,Tn)??void 0,this.context.pre_render_callbacks.push(this.__onPreRender),this._activePointerEvents=[],this.context.input.addEventListener("pointerdown",this._onPointerDown,{queue:pi.Early}),this.context.input.addEventListener("pointerdown",this._onPointerDownLate,{queue:pi.Late}),this.context.input.addEventListener("pointerup",this._onPointerUp,{queue:pi.Early}),this.context.input.addEventListener("pointerup",this._onPointerUpLate,{queue:pi.Late})}onDisable(){if(this._camera?.threeCamera&&sg(this._camera.threeCamera,this,!1),this._controls){this._controls.enabled=!1,this._controls.autoRotate=!1,this._controls.removeEventListener("start",this.onControlsChangeStarted),this._controls.removeEventListener("endMovement",this.onControlsChangeEnded);try{this._controls.stopListenToKeyEvents()}catch{}this._startedListeningToKeyEvents=!1}this._activePointerEvents.length=0,this.context.input.removeEventListener("pointerdown",this._onPointerDown),this.context.input.removeEventListener("pointerdown",this._onPointerDownLate),this.context.input.removeEventListener("pointerup",this._onPointerUp),this.context.input.removeEventListener("pointerup",this._onPointerUpLate)}_activePointerEvents;_lastTimeClickOnBackground=-1;_clickOnBackgroundCount=0;_onPointerDown=e=>{this._activePointerEvents.push(e)};_onPointerDownLate=e=>{e.used&&this._controls&&(this._controls.enabled=!1)};_onPointerUp=e=>{for(let t=this._activePointerEvents.length-1;t>=0;t--){const i=this._activePointerEvents[t];if(i.pointerId===e.pointerId&&i.button===e.button){this._activePointerEvents.splice(t,1);break}}if(this.clickBackgroundToFitScene>0&&e.isClick&&e.button===0){if(e.hasRay||e.intersections.push(...this.context.physics.raycast()),e.intersections.length<=0){const t=this.context.time.time-this._lastTimeClickOnBackground;this._lastTimeClickOnBackground=this.context.time.time,this.clickBackgroundToFitScene<=1||t<this.clickBackgroundToFitScene*.15?(this._clickOnBackgroundCount+=1,this._clickOnBackgroundCount>=this.clickBackgroundToFitScene-1&&(this.autoRotate=!1,this.fitCamera({objects:this.context.scene,immediate:!1}))):this._clickOnBackgroundCount=0}zt&&console.log(this.clickBackgroundToFitScene,e.intersections.length,this._clickOnBackgroundCount)}};_onPointerUpLate=e=>{this.doubleClickToFocus&&e.isDoubleClick&&!e.used&&this.setTargetFromRaycast()};updateTargetNow(e){const t=new So(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?(zt&&B.DrawWireSphere(n.point,.1,16711680,2),this._controls?.target.copy(i[0].point)):zt&&console.log("OrbitControls: No hit found when updating target",{hits:[...i]})}_orbitStartAngle=0;_zoomStartDistance=0;onControlsChangeStarted=()=>{zt&&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(zt&&console.debug("OrbitControls: Change ended",{autoTarget:this.autoTarget}),this._controls&&this.autoTarget){const e=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle()-this._orbitStartAngle;Math.abs(e)<.01?(zt&&console.debug("OrbitControls: Update target",{deltaAngle:e}),this.updateTargetNow({allowSlowRaycastFallback:!1})):zt&&console.debug("OrbitControls: No target update",{deltaAngle:e})}};_shouldDisable=!1;afterHandleInput(e){e.detail.args.pointerId===0&&(e.detail.args.isDown?this._controls&&this._eventSystem&&(this._shouldDisable=this._eventSystem.hasActiveUI):(!e.detail.args.isPressed||e.detail.args.isUp)&&(this._shouldDisable=!1))}onPausedChanged(e){this._controls&&e&&(this._controls.enabled=!1)}onBeforeRender(){if(!!this._controls){if(this._cameraObject!==this.context.mainCamera){this._controls.enabled=!1;return}if(this._controls.enabled=!0,(this.context.input.getPointerDown(1)||this.context.input.getPointerDown(2)||this.context.input.mouseWheelChanged||this.context.input.getPointerPressed(0)&&this.context.input.getPointerPositionDelta(0)?.length())&&(this._inputs+=1),this._inputs>0&&this.allowInterrupt&&(this.enableRotate&&(this.autoRotate=!1),this._cameraLerpActive=!1,this._lookTargetLerpActive=!1),this._inputs=0,this.autoTarget&&this._didSetTarget++===0){const e=S.getComponent(this.gameObject,yi);if(e&&!this.setLookTargetFromConstraint()){this.debugLog&&console.log("NO TARGET");const t=ee(e.threeCamera),i=Math.max(.01,t.length()),n=new b(0,0,-i).applyMatrix4(e.threeCamera.matrixWorld);zt&&B.DrawLine(t,n,5592575,10),this.setLookTargetPosition(n,!0)}if(!this.setLookTargetFromConstraint()){const t=new ks;t.screenPoint=new K(0,0),t.lineThreshold=.1;const i=this.context.physics.raycast(t);i.length>0&&this.setLookTargetPosition(i[0].point,!0),fR&&console.log("OrbitControls hits",...i)}}if(this.middleClickToFocus&&this.context.input.getPointerClicked(1)&&this.setTargetFromRaycast(),this._lookTargetLerpActive||this._cameraLerpActive||this._fovLerpActive){if(this._cameraLerpActive&&this._cameraObject)if(this._cameraLerp01+=this.context.time.deltaTime/this._cameraLerpDuration,this._cameraLerp01>=1)this._cameraObject.position.copy(this._cameraEndPosition),this._cameraLerpActive=!1,this.dispatchEvent(new Jc(this,"camera"));else{const e=D.easeInOutCubic(this._cameraLerp01);this._cameraObject.position.lerpVectors(this._cameraStartPosition,this._cameraEndPosition,e)}if(this._lookTargetLerpActive)if(this._lookTargetLerp01+=this.context.time.deltaTime/this._lookTargetLerpDuration,this._lookTargetLerp01>=1)this.lerpLookTarget(this._lookTargetEndPosition,this._lookTargetEndPosition,1),this._lookTargetLerpActive=!1,this.dispatchEvent(new Jc(this,"lookat"));else{const e=D.easeInOutCubic(this._lookTargetLerp01);this.lerpLookTarget(this._lookTargetStartPosition,this._lookTargetEndPosition,e)}if(this._fovLerpActive&&this._cameraObject){const e=this._cameraObject;if(this._fovLerp01+=this.context.time.deltaTime/this._fovLerpDuration,this._fovLerp01>=1)e.fov=this._fovLerpEndValue,this._fovLerpActive=!1;else{const t=D.easeInOutCubic(this._fovLerp01);e.fov=D.lerp(this._fovLerpStartValue,this._fovLerpEndValue,t)}e.updateProjectionMatrix()}}if(this.targetBounds){const e=this._controls.target,t=this.targetBounds.worldPosition,i=F(this.targetBounds.worldScale).multiplyScalar(.5),n=F(t).sub(i),s=F(t).add(i),r=F(this._controls.target).clamp(n,s),a=.1;e.lerp(r,this.context.time.deltaTime/a),this._lookTargetLerpActive&&this._lookTargetEndPosition.lerp(r,this.context.time.deltaTime/(a*5)),zt&&B.DrawWireBox(t,i.multiplyScalar(2),16755200)}if(this._controls){this.debugLog&&(this._controls.domElement=this.context.renderer.domElement);const e=1/(this.context.focusRectSettings?.zoom||1);if(this._controls.enabled=!this._shouldDisable&&this._camera===this.context.mainCameraComponent&&!this.context.isInXR&&!this._activePointerEvents.some(t=>t.used),this._controls.keys=this.enableKeys?Nf:yR,this._controls.autoRotate=this.autoRotate,this._controls.autoRotateSpeed=this.autoRotateSpeed,this._controls.enableZoom=this.enableZoom,this._controls.zoomSpeed=this.zoomSpeed,this._controls.zoomToCursor=this.zoomToCursor,this._controls.enableDamping=this.enableDamping,this._controls.dampingFactor=this.dampingFactor,this._controls.enablePan=this.enablePan,this._controls.panSpeed=e,this._controls.enableRotate=this.enableRotate,this._controls.minAzimuthAngle=this.minAzimuthAngle,this._controls.maxAzimuthAngle=this.maxAzimuthAngle,this._controls.minPolarAngle=this.minPolarAngle,this._controls.maxPolarAngle=this.maxPolarAngle,zf||(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 $u=="number"||$u===!0){this._controls.enableDamping=!0;const t=typeof $u=="number"?$u:.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||(!zf&&this.lookAtConstraint?.locked&&!this._lookTargetLerpActive&&this.setLookTargetFromConstraint(0,this.lookAtConstraint01),this._controls.update(this.context.time.deltaTime),zt&&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()||zt)&&console.warn("[OrbitControls] setCameraAndLookTarget target is null"),!1;if(!(e instanceof M)&&!(e instanceof yi))return(A()||zt)&&console.warn("[OrbitControls] setCameraAndLookTarget target is not an Object3D or Camera"),!1;e instanceof yi&&(e=e.gameObject);const i=e.worldPosition,n=e.worldForward;e instanceof cC&&(zt&&console.debug("[OrbitControls] setCameraAndLookTarget flip forward direction for camera"),n.multiplyScalar(-1));const s=new So(i,n);return zt&&B.DrawRay(s.origin,s.direction,16711680,10),this.setTargetFromRaycast(s,t)||this.setLookTargetPosition(s.at(2,F()),t),this.setCameraTargetPosition(i,t),!0}setCameraTargetPosition(e,t=!1){e&&(e instanceof M&&(e=ee(e)),this._cameraEndPosition||(this._cameraEndPosition=new b),this._cameraEndPosition.copy(e),t===!0?(this._cameraLerpActive=!1,this._cameraObject&&this._cameraObject.position.copy(this._cameraEndPosition)):this._cameraObject&&(this._cameraLerpActive=!0,this._cameraLerp01=0,this._cameraStartPosition.copy(this._cameraObject?.position),typeof t=="number"?this._cameraLerpDuration=t:this._cameraLerpDuration=this.targetLerpDuration))}get cameraLerpActive(){return this._cameraLerpActive}stopCameraLerp(){this._cameraLerpActive=!1}setFieldOfView(e,t=!1){if(!this._controls||typeof e!="number")return;const i=this._camera?.threeCamera;i&&(t===!0?i.fov=e:(this._fovLerpActive=!0,this._fovLerp01=0,this._fovLerpStartValue=i.fov,this._fovLerpEndValue=e,typeof t=="number"?this._fovLerpDuration=t:this._fovLerpDuration=this.targetLerpDuration))}setLookTargetPosition(e=null,t=!1){this._controls&&e&&(e instanceof M&&(e=ee(e)),this._lookTargetEndPosition.copy(e),this._didSetTarget++,zt&&(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 s=Ff(n.object);if(s&&s.canvas?.screenspace)break;return this.setLookTargetPosition(n.point,t),!0}return!1}fitCamera(e,t){let i;if(Array.isArray(e)||e&&"type"in e?i=e:e&&typeof e=="object"&&!(e instanceof M)&&!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=lx({objects:[...i],...t,autoApply:!1,context:this.context,camera:this._cameraObject,currentZoom:this._controls?.getDistance()||void 0,minZoom:this.minZoom,maxZoom:this.maxZoom});n&&(this.setLookTargetPosition(n.lookAt,t?.immediate||!1),this.setCameraTargetPosition(n.position,t?.immediate||!1),this.setFieldOfView(t?.fov,t?.immediate||!1),this.onBeforeRender())}_haveAttachedKeyboardEvents=!1}Me([u()],ge.prototype,"autoTarget",2),Me([u()],ge.prototype,"autoFit",2),Me([u()],ge.prototype,"enableRotate",2),Me([u()],ge.prototype,"autoRotate",2),Me([u()],ge.prototype,"autoRotateSpeed",2),Me([u()],ge.prototype,"minAzimuthAngle",2),Me([u()],ge.prototype,"maxAzimuthAngle",2),Me([u()],ge.prototype,"minPolarAngle",2),Me([u()],ge.prototype,"maxPolarAngle",2),Me([u()],ge.prototype,"enableKeys",2),Me([u()],ge.prototype,"enableDamping",2),Me([u()],ge.prototype,"dampingFactor",2),Me([u()],ge.prototype,"enableZoom",2),Me([u()],ge.prototype,"minZoom",2),Me([u()],ge.prototype,"maxZoom",2),Me([u()],ge.prototype,"zoomSpeed",2),Me([u()],ge.prototype,"enablePan",2),Me([u(Wr)],ge.prototype,"lookAtConstraint",2),Me([u()],ge.prototype,"lookAtConstraint01",2),Me([u()],ge.prototype,"allowInterrupt",2),Me([u()],ge.prototype,"middleClickToFocus",2),Me([u()],ge.prototype,"doubleClickToFocus",2),Me([u()],ge.prototype,"clickBackgroundToFitScene",2),Me([u()],ge.prototype,"targetLerpDuration",1),Me([u(M)],ge.prototype,"targetBounds",2);var bR=Object.defineProperty,_R=Object.getOwnPropertyDescriptor,ei=(o,e,t,i)=>{for(var n=i>1?void 0:i?_R(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&bR(e,t,n),n},$r=(o=>(o[o.None=0]="None",o[o.Skybox=1]="Skybox",o[o.SolidColor=2]="SolidColor",o[o.Uninitialized=4]="Uninitialized",o))($r||{});const js=w("debugcam"),gx=w("debugscreenpointtoray"),Nt=class md extends E{get isCamera(){return!0}get aspect(){return this._cam instanceof de?this._cam.aspect:this.context.domWidth/this.context.domHeight}set aspect(e){this._cam instanceof de&&this._cam.aspect!==e&&(this._cam.aspect=e,this._cam.updateProjectionMatrix())}get fieldOfView(){return this._cam instanceof de?this._cam.fov:this._fov}set fieldOfView(e){const t=this.fieldOfView!=e;if(this._fov=e,t&&this._cam&&this._cam instanceof de){if(this._fov===void 0){console.warn("Can not set undefined fov on PerspectiveCamera");return}this._cam.fov=this._fov,this._cam.updateProjectionMatrix()}}get nearClipPlane(){return this._nearClipPlane}set nearClipPlane(e){const t=this._nearClipPlane!=e;this._nearClipPlane=e,this._cam&&(t||this._cam.near!=e)&&(this._cam.near=e,this._cam.updateProjectionMatrix())}_nearClipPlane=.1;get farClipPlane(){return this._farClipPlane}set farClipPlane(e){const t=this._farClipPlane!=e;this._farClipPlane=e,this._cam&&(t||this._cam.far!=e)&&(this._cam.far=e,this._cam.updateProjectionMatrix())}_farClipPlane=1e3;applyClippingPlane(){this._cam&&(this._cam.near=this._nearClipPlane,this._cam.far=this._farClipPlane,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(e){if(typeof e=="string")switch(e){case"skybox":e=1;break;case"solidcolor":e=2;break;default:e=0;break}e!==this._clearFlags&&(this._clearFlags=e,this.applyClearFlagsIfIsActiveCamera())}orthographic=!1;orthographicSize=5;ARBackgroundAlpha=0;set cullingMask(e){this._cullingMask=e,this._cam&&(this._cam.layers.mask=e)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}_cullingMask=4294967295;set cullingLayer(e){this.cullingMask=(1<<e|0)>>>0}set backgroundBlurriness(e){e!==this._backgroundBlurriness&&(e===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(e,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}_backgroundBlurriness=void 0;set backgroundIntensity(e){e!==this._backgroundIntensity&&(e===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(e,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}_backgroundIntensity=void 0;set backgroundRotation(e){e!==this._backgroundRotation&&(e===void 0?this._backgroundRotation=void 0:this._backgroundRotation=e,this.applyClearFlagsIfIsActiveCamera())}get backgroundRotation(){return this._backgroundRotation}_backgroundRotation=void 0;set environmentIntensity(e){this._environmentIntensity=e}get environmentIntensity(){return this._environmentIntensity}_environmentIntensity=void 0;get backgroundColor(){return this._backgroundColor??null}set backgroundColor(e){e&&(this._backgroundColor||(this._backgroundColor=new se(1,1,1,1)),this._backgroundColor.copy(e),(!("alpha"in e)||e.alpha===void 0)&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera())}set targetTexture(e){this._targetTexture=e}get targetTexture(){return this._targetTexture}_targetTexture=null;_backgroundColor;_fov;_cam=null;_clearFlags=2;_skybox;get cam(){return this.threeCamera}get threeCamera(){return this.activeAndEnabled&&this.buildCamera(),this._cam}static _origin=new b;static _direction=new b;screenPointToRay(e,t,i){const n=this.threeCamera,s=md._origin;s.set(e,t,-1),this.context.input.convertScreenspaceToRaycastSpace(s),gx&&console.log("screenPointToRay",e.toFixed(2),t.toFixed(2),"now:",s.x.toFixed(2),s.y.toFixed(2),"isInXR:"+this.context.isInXR),s.z=-1,s.unproject(n);const r=md._direction.set(s.x,s.y,s.z),a=ee(n);return r.sub(a),r.normalize(),i?(i.set(a,r),i):new So(a.clone(),r.clone())}_frustum;getFrustum(){return this._frustum||(this._frustum=new Sb,this.updateFrustum()),this._frustum}updateFrustum(){this._frustum||(this._frustum=new Sb),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 J;awake(){gx&&window.addEventListener("pointerdown",e=>{const t=e.clientX,i=e.clientY;console.log("touch",t.toFixed(2),i.toFixed(2));const n=this.screenPointToRay(t,i),s="#"+Math.floor(Math.random()*16777215).toString(16);B.DrawRay(n.origin,n.direction,s,10)})}onEnable(){js&&console.log(`Camera enabled: "${this.name}". ClearFlags=${$r[this._clearFlags]}`,this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),wR(this)),this.applyClearFlagsIfIsActiveCamera({applySkybox:!0})}onDisable(){this.context.removeCamera(this)}onLeaveXR(e){this.fieldOfView=this._fov}onBeforeRender(){if(this._cam&&(this._frustum&&this.updateFrustum(),this._clearFlags===2&&this.applyClearFlagsIfIsActiveCamera(),this._targetTexture)){this.context.isManagedExternally&&(this._warnedAboutExternalRenderer||(this._warnedAboutExternalRenderer=!0,console.warn("Rendering with external renderer is not supported yet. This may not work or throw errors. Please remove the the target texture from your camera: "+this.name,this.targetTexture))),this.context.composer;const e=this.context.renderer;if(e){const t=this.context.mainCameraComponent;this.applyClearFlags(),this._targetTexture.render(this.context.scene,this._cam,e),t?.applyClearFlags()}}}buildCamera(){if(this._cam)return;const e=this.gameObject.isCamera;let t=null;if(e?(t=this.gameObject,t?.layers.enableAll(),t instanceof de&&(this._fov=t.fov)):t=this.gameObject.children[0],t&&t.isCamera)t instanceof de&&(this._fov&&(t.fov=this._fov),t.near=this._nearClipPlane,t.far=this._farClipPlane,t.updateProjectionMatrix());else if(!this.orthographic)t=new de(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),this.fieldOfView&&(t.fov=this.fieldOfView),this.gameObject.add(t);else{const i=this.orthographicSize*100;t=new Cd(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){js&&console.log("Camera does not exist (apply clear flags)");return}if(this.fieldOfView=this.fieldOfView,js){const i=`[Camera] Apply ClearFlags: ${$r[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(md.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:js&&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:js&&console.warn(`Camera "${this.name}" has no background intensity`);break;case 2:if(this._backgroundColor&&!t){let i=this._backgroundColor.alpha;md.backgroundShouldBeTransparent(this.context)&&(i=this.ARBackgroundAlpha??0),this.context.scene.background=null,this.context.xr?.isVR?this.context.renderer.setClearColor(y_(this._backgroundColor).convertLinearToSRGB()):this.context.renderer.setClearColor(this._backgroundColor,i)}else this._backgroundColor||js&&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 vR(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;js&&Oe("Environment blend mode: "+i+" on "+navigator.userAgent);let n=i==="additive"||i==="alpha-blend";if(e.isInAR&&i==="opaque"){if(navigator.userAgent?.includes("OculusBrowser"))n=!0;else if(navigator.userAgent?.includes("Mozilla")&&navigator.userAgent?.includes("Mobile WebXRViewer/v2"))n=!0;else if(I.isNeedleAppClip())return!0}return t._transparent=n,n}};ei([u()],Nt.prototype,"aspect",1),ei([u()],Nt.prototype,"fieldOfView",1),ei([u()],Nt.prototype,"nearClipPlane",1),ei([u()],Nt.prototype,"farClipPlane",1),ei([u()],Nt.prototype,"clearFlags",1),ei([u()],Nt.prototype,"orthographic",2),ei([u()],Nt.prototype,"orthographicSize",2),ei([u()],Nt.prototype,"ARBackgroundAlpha",2),ei([u()],Nt.prototype,"cullingMask",1),ei([u()],Nt.prototype,"backgroundBlurriness",1),ei([u()],Nt.prototype,"backgroundIntensity",1),ei([u(at)],Nt.prototype,"backgroundRotation",1),ei([u()],Nt.prototype,"environmentIntensity",1),ei([u(se)],Nt.prototype,"backgroundColor",1),ei([u(xo)],Nt.prototype,"targetTexture",1);let yi=Nt;class vR{_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");js&&console.debug(`[Camera] Apply Skybox ${this._skybox?.name} ${e} - "${this._camera.name}"`),e?.length||(this._skybox.mapping=ko,this.context.scene.background=this._skybox)}}}function wR(o){w("freecam")&&o.context.mainCameraComponent===o&&S.getOrAddComponent(o.gameObject,ge)}class Wo extends E{get listener(){return this._listener==null&&(this._listener=new hC),this._listener}_listener=null;onEnable(){Nn.registerWaitForInteraction(this.onInteraction),this.addListenerIfItExists()}onDisable(){Nn.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,yi);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 xR=Object.defineProperty,SR=Object.getOwnPropertyDescriptor,An=(o,e,t,i)=>{for(var n=i>1?void 0:i?SR(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&xR(e,t,n),n};const Mt=w("debugaudio"),en=class hr extends E{static get userInteractionRegistered(){return Nn.userInteractionRegistered}static registerWaitForAllowAudio(e){Nn.registerWaitForInteraction(e)}clip="";playOnAwake=!1;preload=!0;playInBackground=!0;get isPlaying(){return this.sound?.isPlaying??!1}get duration(){return this.sound?.buffer?.duration}get time01(){const e=this.duration;return e&&this.sound?this.sound?.context.currentTime/e:0}set time01(e){const t=this.duration;t&&this.sound&&(this.time=e*t)}get time(){return this.sound?.source?this.sound.source?.context.currentTime-this._lastContextTime+this.sound.offset:0}set time(e){if(this.sound){if(e===this.sound.offset)return;const t=this.isPlaying;this.stop(),this.sound.offset=e,t&&this.play()}}get loop(){return this.sound&&(this._loop=this.sound.getLoop()),this._loop}set loop(e){this._loop=e,this.sound&&this.sound.setLoop(e)}get spatialBlend(){return this._spatialBlend}set spatialBlend(e){e!==this._spatialBlend&&(this._spatialBlend=e,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(e){this._minDistance!==e&&(this._minDistance=e,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(e){this._maxDistance!==e&&(this._maxDistance=e,this._needUpdateSpatialDistanceSettings=!0)}_spatialBlend=0;_minDistance=1;_maxDistance=100;get volume(){return this._volume}set volume(e){this._volume=e,this.sound&&!this.context.application.muted&&(Mt&&console.log(this.name,"audio set volume",e),this.sound.setVolume(e))}_volume=1;set pitch(e){this.sound&&this.sound.setPlaybackRate(e)}get pitch(){return this.sound?this.sound.getPlaybackRate():1}rollOffMode=0;_loop=!1;sound=null;helper=null;wasPlaying=!1;audioLoader=null;shouldPlay=!1;_lastClipStartedLoading=null;_audioElement=null;get Sound(){if(!this.sound&&hr.userInteractionRegistered){let e=this.gameObject.getComponent(Wo)??this.context.mainCamera.getComponent(Wo)??tl(Wo,this.context,!1);!e&&this.context.mainCamera&&(e=this.context.mainCamera.addComponent(Wo)),e?.listener?(this.sound=new dC(e.listener),this.gameObject?.add(this.sound)):Mt&&console.warn("No audio listener found in scene - can not play audio")}return this.sound}get ShouldPlay(){return this.shouldPlay}get audioContext(){return this.sound?.context}awake(){Mt&&console.log("[AudioSource]",this),this.audioLoader=new Lm,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),hr.userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():hr.registerWaitForAllowAudio(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.onNewClip(this.clip)}),globalThis.addEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.addEventListener(Og.MuteChanged,this.onApplicationMuteChanged)}onDisable(){globalThis.removeEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.removeEventListener(Og.MuteChanged,this.onApplicationMuteChanged),this.pause()}onVisibilityChanged=()=>{switch(document.visibilityState){case"hidden":(this.playInBackground===!1||I.isMobileDevice())&&(this.wasPlaying=this.isPlaying,this.isPlaying&&this.pause());break;case"visible":Mt&&console.log("visible",this.enabled,this.playOnAwake,!this.isPlaying,hr.userInteractionRegistered,this.wasPlaying),this.enabled&&this.playOnAwake&&!this.isPlaying&&hr.userInteractionRegistered&&this.wasPlaying&&this.play();break}};onApplicationMuteChanged=()=>{this.context.application.muted?this.sound?.setVolume(0):this.sound?.setVolume(this.volume)};createAudio=e=>{if(this.destroyed){Mt&&console.warn("AudioSource destroyed, not creating audio",this.name);return}Mt&&console.log("AudioBuffer finished loading",e);const t=this.Sound;if(!t){Mt&&console.warn("Failed getting sound?",this.name);return}t.isPlaying&&t.stop(),e&&t.setBuffer(e),t.loop=this._loop,this.context.application.muted?t.setVolume(0):t.setVolume(this.volume),t.autoplay=this.shouldPlay&&hr.userInteractionRegistered,this.applySpatialDistanceSettings(),t.isPlaying&&t.stop(),hr.registerWaitForAllowAudio(this.__onAllowAudioCallback)};__onAllowAudioCallback=()=>{this.shouldPlay&&this.play()};applySpatialDistanceSettings(){const e=this.sound;if(!e)return;this._needUpdateSpatialDistanceSettings=!1;const t=D.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(Mt&&console.log(this.name,this._minDistance,this._maxDistance,this.spatialBlend,"Ref distance="+t),e.setRefDistance(t),e.setMaxDistance(Math.max(.01,this._maxDistance)),this.rollOffMode){case 0:e.setDistanceModel("exponential");break;case 1:e.setDistanceModel("linear");break;case 2:console.warn("Custom rolloff for AudioSource is not supported: "+this.name);break}this.spatialBlend>0?Mt&&!this.helper&&(this.helper=new fP(e,e.getRefDistance()),e.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}async onNewClip(e){if(e&&(this.clip=e),typeof e=="string")if(Mt&&console.log(e),e.endsWith(".mp3")||e.endsWith(".wav")){if(this.audioLoader||(this.audioLoader=new Lm),this.shouldPlay=!0,this._lastClipStartedLoading===e){Mt&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=e,Mt&&console.log("load audio",e);const t=await this.audioLoader.loadAsync(e).catch(console.error);if(this.destroyed)return;this._lastClipStartedLoading===e&&(this._lastClipStartedLoading=null),t&&this.createAudio(t)}else console.warn("Unsupported audio clip type",e);else this.shouldPlay=!0,this.createAudio()}play(e=void 0){!e&&this.clip&&(e=this.clip),e!==void 0&&typeof e!="string"&&!(e instanceof MediaStream)&&(A()&&console.warn("Called play on AudioSource with unknown argument type:",e+`
|
|
974
|
+
Could not find method ${r.method} on object ${l.name}`,l,typeof l[r.method])};if(typeof l[r.method]!="function"){let d=!1,p=l;for(;p;){const m=Object.getOwnPropertyDescriptor(p,r.method);if(m&&(m.writable===!0||m.set)){d=!0;break}p=Object.getPrototypeOf(p)}!d&&(A()||bt)&&h()}}if(l){let h=r.argument;if(h!==void 0?h=a(h):r.arguments!==void 0&&(h=r.arguments.map(a)),l[r.method]===void 0)console.warn(`EventList method not found: "${r.method}" on ${l?.name}`);else{h!==void 0&&!Array.isArray(h)&&(h=[h]);const d=new No(l,r.method,h,r.enabled);i.push(d)}}else A()&&console.warn(`[Dev] EventList: Could not find event listener in scene (${t.object?.name})`,r)}const n=new ae(i);bt&&console.log(n);const s=t.target;return s!==void 0&&t.path!==void 0&&n.setEventTarget(t.path,s),n}}}const lR=new aR,Nu=new WeakMap,cR=Se.prototype.clone;Se.prototype.clone=function(){const o=cR.call(this);return Nu.has(o)||Nu.set(o,this),o};class ux extends Zi{constructor(){super([xo,$n])}onSerialize(e,t){}onDeserialize(e,t){if(e instanceof Se&&t.type===xo){let i=e;Nu.has(i)&&(i=Nu.get(i)),i.isRenderTargetTexture=!0,i.flipY=!0,i.offset.y=1,i.repeat.y=-1,i.needsUpdate=!0,i.mipmaps=[],i instanceof lC&&(i.isCompressedTexture=!1,i.format=Md);const n=new xo(i.image.width,i.image.height,{colorSpace:Oo});return n.texture=i,n}}}new ux;class px extends Zi{constructor(){super([URL])}onSerialize(e,t){return null}onDeserialize(e,t){if(typeof e=="string"&&e.length>0)return Ao(t.gltfId,e)}}new px;var hR=Object.defineProperty,dR=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&hR(e,t,n),n};class Zc extends E{awake(){li.createIfNoneExists(this.context)}onEnable(){li.get(this.context)?.register(this)}onDisable(){li.get(this.context)?.unregister(this)}}class Ji extends Zc{targets=null;raycastHits=[];ignoreSkinnedMeshes=!1;start(){this.targets=[this.gameObject]}performRaycast(e=null){if(!this.targets)return null;e??=new ks,e.targets=this.targets,e.results=this.raycastHits,e.useAcceleratedRaycast=!0;const t=e.testObject;this.ignoreSkinnedMeshes&&(e.testObject=n=>n instanceof vs?"continue in children":t?t(n):!0);const i=this.context.physics.raycast(e);return e.testObject=t,i}}dR([u()],Ji.prototype,"ignoreSkinnedMeshes");class Wu extends Ji{constructor(){super(),this.ignoreSkinnedMeshes=!0}}class Ca extends Zc{static allow=!0;performRaycast(e){if(!Z.active||!Ca.allow||!e?.ray)return null;const t=e.ray.origin;return this.context.physics.sphereOverlap(t,.015,!1,!0)}}class Bf{static getObject(e){const t=e[Ai];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=Fr(e,s=>{if(s.isGraphic===!0)return s},!1);return t&&n?.isGraphic===!0&&(t.graphic=n),!(n?.raycastTarget===!1||n?.layer===2)}static tryFindCanvasGroup(e){if(!e)return null;const t=Fr(e,i=>{if(i.activeAndEnabled){const n=i;if(n.blocksRaycasts!==void 0&&n.interactable!==void 0)return n}},!1);return t!==void 0?t:this.tryFindCanvasGroup(e.parent)}}function Ff(o){return o[Ai]||(o.parent?Ff(o.parent):null)}function uR(o){return o.isUI===!0||typeof o[Ai]=="object"}function Vu(o,e){if(!o)return;const t=o.material;if(t?.isMaterial===!0){const i=o.parent;i&&i.isText,t.side=e.doubleSided??!0?Oi:ws,t.shadowSide=e.doubleSided?Oi:ws,o.castShadow=e.castShadows?e.castShadows:!1,o.receiveShadow=e.receiveShadows?e.receiveShadows:!1}for(const i of o.children)Vu(i,e)}function hl(o,e,t){o[e]===void 0&&console.warn("Field",e,"is undefined on",o);const i=Proxy.revocable(o[e],{set(r,a,l,c){const h=r[a],d=Reflect.set(r,a,l,c);return t(l,h),d}}),n=i.revoke,s=o[e];return i.revoke=()=>{o[e]=s,n()},o[e]=i.proxy,i}const mx=Symbol("Scheduled action");function pR(o,e,t=xe.OnBeforeRender){let i=o[mx];i||(i=o[mx]={});const n=e.name;i[t]||(i[t]={});const s=i[t];if(s[n])return;function*r(){e?.call(o),s[n]=null}const a=o.startCoroutine(r(),t);s[n]=a}const Ls=w("debugeventsystem");var Uf=(o=>(o.BeforeHandleInput="BeforeHandleInput",o.AfterHandleInput="AfterHandleInput",o))(Uf||{});Pf(o=>{li.createIfNoneExists(o)});class li extends E{static ensureUpdateMeshUI(e,t,i=!1){Kc.update(e,t,i)}static markUIDirty(e){Kc.markDirty()}static createIfNoneExists(e){e.scene.getComponent(li)||e.scene.addComponent(li)}static get(e){return this.createIfNoneExists(e),e.scene.getComponent(li)}static get instance(){return this.get(U.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(Zc)||this.context.scene.addComponent(Ji)}onEnable(){this.context.input.addEventListener(Ae.PointerDown,this.onPointerEvent),this.context.input.addEventListener(Ae.PointerUp,this.onPointerEvent),this.context.input.addEventListener(Ae.PointerMove,this.onPointerEvent)}onDisable(){this.context.input.removeEventListener(Ae.PointerDown,this.onPointerEvent),this.context.input.removeEventListener(Ae.PointerUp,this.onPointerEvent),this.context.input.removeEventListener(Ae.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 vd(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==Ae.PointerDown,t.isUp=e.type==Ae.PointerUp,t.isPressed=this.context.input.getPointerPressed(e.pointerId);const i=new ks;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(Ls&&(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})}Ls&&t.isClick&&Oe("EventSystem: "+t.pointerId+" - "+this.context.time.frame+" - Up:"+t.isUp+", Down:"+t.isDown);const s={sender:this,args:t,hasActiveUI:this.currentActiveMeshUIComponents.length>0};this.dispatchEvent(new CustomEvent("BeforeHandleInput",{detail:s})),this.handleIntersections(n,t),this.dispatchEvent(new CustomEvent("AfterHandleInput",{detail:s}))};_sortedHits=[];_testObjectsCache=new Map;_currentlyActiveRaycaster=null;_currentPointerEventName=null;shouldRaycastObject=e=>{const t=e&&"getComponent"in e?e.getComponent(Zc):null;if(t&&t!=this._currentlyActiveRaycaster)return!1;let i=null;if(uR(e)&&(i=e[Ai]?.gameObject),this._testObjectsCache.has(e)||i&&this._testObjectsCache.has(i))return this._testObjectsCache.get(e)===!1?"continue in children":!0;{let n=Fu(e,this._currentPointerEventName);if(!n&&i&&(n=Fu(i,this._currentPointerEventName)),n){this._testObjectsCache.set(e,!0);for(const s of e.children)this.shouldRaycastObject_AddToYesCache(s);return!0}return this._testObjectsCache.set(e,!1),"continue in children"}};shouldRaycastObject_AddToYesCache(e){this._testObjectsCache.set(e,!0);for(const t of e.children)this.shouldRaycastObject_AddToYesCache(t)}performRaycast(e){if(!this.raycaster)return null;this._testObjectsCache.clear(),this._sortedHits.length=0,e.testObject=this.shouldRaycastObject;for(const t of this.raycaster){if(!t.activeAndEnabled)continue;this._currentlyActiveRaycaster=t;const i=t.performRaycast(e);this._currentlyActiveRaycaster=null,i&&i.length>0&&this._sortedHits.push(...i)}return this._sortedHits.sort((t,i)=>t.distance-i.distance),this._sortedHits}assignHitInformation(e,t){t?(e.intersection=t,e.point=t.point,e.normal=t.normal,e.face=t.face,e.distance=t.distance,e.instanceId=t.instanceId):(e.intersection=void 0,e.point=void 0,e.normal=void 0,e.face=void 0,e.distance=void 0,e.instanceId=void 0)}handleIntersections(e,t){if(e?.length){e=this.sortCandidates(e);for(const n of e){if(t.event.immediatePropagationStopped)return!1;if(this.assignHitInformation(t,n),this.handleEventOnObject(n.object,t))return!0}}this.assignHitInformation(t,e?.[0]),this.invokePointerCapture(t);const i=this.hoveredByID.get(t.pointerId);return i&&this.propagatePointerExit(i.obj,i.data,null),this.hoveredByID.delete(t.pointerId),t.isUp&&(this.pressedByID.get(t.pointerId)?.handlers.forEach(n=>this.invokeOnPointerUp(t,n)),this.pressedByID.delete(t.pointerId)),!1}_sortingBuffer=[];_noDepthTestingResults=[];sortCandidates(e){this._sortingBuffer.length=0,this._noDepthTestingResults.length=0;for(let t=0;t<e.length;t++){const i=e[t],n=i.object;if(n.material&&n.material.depthTest===!1){this._noDepthTestingResults.push(i);continue}this._sortingBuffer.push(i)}for(const t of this._sortingBuffer)this._noDepthTestingResults.push(t);return this._noDepthTestingResults}out={};handleEventOnObject(e,t){if(!this.testIsVisible(e))return t.isClick&&Ls&&console.log("not allowed",e),!1;if(t.pointerId===void 0)return Ls&&console.error("Event without pointer can't be handled",t),!1;t.object=e;const i=e.parent,n=t.isClick??!1;let s=null;if(i&&i.isUI){const c=(t.isPressed||t.isClick)??!1;if(i[Ai]){const h=i[Ai].gameObject;if(h){if(!Bf.isInteractable(h,this.out))return!1;s=this.out.canvasGroup??null,this.handleMeshUIIntersection(e,c),e=h}}}n&&Ls&&console.log(this.context.time.frame,e);const r=this.hoveredByID.get(t.pointerId),a=r?.obj;a!==e&&a&&this.propagatePointerExit(a,r.data,e);const l=this.hoveredByID.get(t.pointerId);if(l?(l.obj=e,l.data=t):this.hoveredByID.set(t.pointerId,{obj:e,data:t}),t.isDown){const c=this.pressedByID.get(t.pointerId);c?(c.obj=e,c.data=t):this.pressedByID.set(t.pointerId,{obj:e,data:t,handlers:new Set})}return(s===null||s.interactable)&&this.handleMainInteraction(e,t,a??null),!0}propagate(e,t){for(;e;)S.foreachComponent(e,i=>{t(i)},!1),e=e.parent}handleMainInteraction(e,t,i){const n=this.pressedByID.get(t.pointerId),s=i!==e;let r=!0;switch(t.event.pointerType){case"mouse":case"touch":const a=this.context.input.getPointerPositionLastFrame(t.pointerId),l=this.context.input.getPointerPosition(t.pointerId);r=a&&!j.approximately(a,l);break}this.propagate(e,a=>{const l=a;l.interactable!==!1&&(!l.activeAndEnabled||!l.enabled||(l.onPointerEnter&&s&&this.handlePointerEnter(l,t),t.isDown&&l.onPointerDown&&(l.onPointerDown(t),n?.handlers.add(l),this.handlePointerCapture(t,l)),l.onPointerMove&&(r&&l.onPointerMove(t),this.handlePointerCapture(t,l)),t.isUp&&(l.onPointerUp&&(this.invokeOnPointerUp(t,l),n?.handlers.delete(l)),l.onPointerExit&&t.event?.pointerType===Yd.Touch&&(this.handlePointerExit(l,t),this.hoveredByID.delete(t.pointerId))),t.isClick&&l.onPointerClick&&l.onPointerClick(t)))}),t.isUp&&(n?.handlers.forEach(a=>{this.invokeOnPointerUp(t,a)}),this.pressedByID.delete(t.pointerId))}propagatePointerExit(e,t,i){this.propagate(e,n=>{if(!n.gameObject||n.destroyed)return;const s=n;if(s.onPointerExit||s.onPointerEnter){if(i&&this.isChild(i,n.gameObject))return;this.handlePointerExit(s,t)}})}invokeOnPointerUp(e,t){t.onPointerUp?.call(t,e),this.releasePointerCapture(e,t)}handlePointerEnter(e,t){e.onPointerEnter&&this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!0)&&e.onPointerEnter(t),this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!1)}handlePointerExit(e,t){e.onPointerExit&&this.updatePointerState(e,t.pointerId,this.pointerExitSymbol,!0)&&e.onPointerExit(t),this.updatePointerState(e,t.pointerId,this.pointerEnterSymbol,!1)}updatePointerState(e,t,i,n){let s=e[i];if(n)return s&&s.includes(t)?!1:(s=s||[],s.push(t),e[i]=s,!0);{if(!s||!s.includes(t))return!1;const r=s.indexOf(t);return r!==-1&&s.splice(r,1),!0}}_capturedPointer={};handlePointerCapture(e,t){if(e.z__pointer_ctured){e.z__pointer_ctured=!1;const i=e.pointerId;if(t.onPointerMove){const n=this._capturedPointer[i]||[];n.push(t),this._capturedPointer[i]=n}else A()&&!t.z__warned_no_pointermove&&(t.z__warned_no_pointermove=!0,console.warn("PointerCapture was requested but the component doesn't implement onPointerMove. It will not receive any pointer events"))}else e.z__pointer_cture_rleased&&(e.z__pointer_cture_rleased=!1,this.releasePointerCapture(e,t))}releasePointerCapture(e,t){const i=e.pointerId;if(this._capturedPointer[i]){const n=this._capturedPointer[i].indexOf(t);n!==-1&&(this._capturedPointer[i].splice(n,1),Ls&&console.log("released pointer capture",i,t,this._capturedPointer))}}invokePointerCapture(e){if(e.event.type===Ae.PointerMove){const t=e.pointerId,i=this._capturedPointer[t];if(i){Ls&&console.log("Captured",t,i);for(let n=0;n<i.length;n++){const s=i[n];if(s.destroyed){i.splice(n,1),n--;continue}s.onPointerMove?.call(s,e)}}}}pointerEnterSymbol=Symbol("pointerEnter");pointerExitSymbol=Symbol("pointerExit");isChild(e,t){return!e||!t?!1:e===t?!0:e.parent?this.isChild(e.parent,t):!1}handleMeshUiObjectWithoutShadowDom(e,t){return!e||!e.isUI?!0:this.handleMeshUIIntersection(e,t)}currentActiveMeshUIComponents=[];handleMeshUIIntersection(e,t){const i=Kc.updateState(e,t);return i&&this.currentActiveMeshUIComponents.push(i),i!==null}resetMeshUIStates(){if(this.context.input.getPointerPressedCount()>0&&Kc.resetLastSelected(),!(!this.currentActiveMeshUIComponents||this.currentActiveMeshUIComponents.length<=0)){for(let e=0;e<this.currentActiveMeshUIComponents.length;e++){const t=this.currentActiveMeshUIComponents[e];Kc.resetState(t)}this.currentActiveMeshUIComponents.length=0}}testIsVisible(e){return e?S.isActiveSelf(e)?this.testIsVisible(e.parent):!1:!0}}class Kc{static lastSelected=null;static lastUpdateFrame=[];static needsUpdate=!1;static markDirty(){this.needsUpdate=!0}static update(e,t,i=!1){if(i){e.update();return}const n=t.time.frameCount;for(const s of this.lastUpdateFrame)if(s.context===t){if(n===s.frame)return;s.frame=n;let r=this.needsUpdate||n<1;s.nextUpdate<=n&&(r=!0),r&&(Ls&&console.log("Update threemeshui"),this.needsUpdate=!1,s.nextUpdate=n+60,e.update());return}this.lastUpdateFrame=[{context:t,frame:n,nextUpdate:n+60}],e.update(),this.needsUpdate=!1}static updateState(e,t){let i=null;if(e&&(i=this.findBlockOrTextInParent(e),i&&i!==this.lastSelected)){if(i.interactable===!1)return null;this.needsUpdate=!0}return i}static resetLastSelected(){const e=this.lastSelected;e&&(this.lastSelected=null,this.resetState(e))}static resetState(e){e&&(this.needsUpdate=!0)}static findBlockOrTextInParent(e){return e?e.isBlock||e.isText?e:this.findBlockOrTextInParent(e.parent):null}}var mR=Object.defineProperty,gR=Object.getOwnPropertyDescriptor,Me=(o,e,t,i)=>{for(var n=i>1?void 0:i?gR(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&mR(e,t,n),n};const zt=w("debugorbit"),zf=w("freecam"),fR=w("debugcamerafit"),$u=w("smoothcam"),yR={LEFT:"",UP:"",RIGHT:"",BOTTOM:""};let Nf;class Jc extends CustomEvent{constructor(e,t){super("target-reached",{detail:{controls:e,type:t}})}}class ge extends E{get isCameraController(){return!0}get controls(){return this._controls}get controllerObject(){return this._cameraObject}onStartInteraction(e){this.controls?.addEventListener("start",e)}autoTarget=!0;autoFit=!1;enableRotate=!0;autoRotate=!1;autoRotateSpeed=1;minAzimuthAngle=1/0;maxAzimuthAngle=1/0;minPolarAngle=0;maxPolarAngle=Math.PI;enableKeys=!1;enableDamping=!0;dampingFactor=.1;enableZoom=!0;minZoom=0;maxZoom=1/0;zoomSpeed=1;zoomToCursor=!1;enablePan=!0;lookAtConstraint=null;lookAtConstraint01=1;allowInterrupt=!0;middleClickToFocus=!0;doubleClickToFocus=!0;clickBackgroundToFitScene=2;get targetElement(){return this._controls?.domElement??this._targetElement}set targetElement(e){this._targetElement=e,this._controls&&this._controls.domElement!==e&&(this._controls.disconnect(),this._controls.domElement=e,this._controls.connect())}_targetElement=null;debugLog=!1;get targetLerpSpeed(){return 5}set targetLerpSpeed(e){this.targetLerpDuration=1/e}get targetLerpDuration(){return this._lookTargetLerpDuration}set targetLerpDuration(e){this._lookTargetLerpDuration=e}_lookTargetLerpDuration=1;targetBounds=null;rotateLeft(e){this._controls?._rotateLeft(e)}rotateUp(e){this._controls?._rotateUp(e)}pan(e,t){this._controls?._pan(e,t)}zoomIn(e){e>0?this._controls?._dollyIn(1-e):e<0&&this._controls?._dollyOut(1+e)}_controls=null;_cameraObject=null;_lookTargetLerpActive=!1;_lookTargetStartPosition=new b;_lookTargetEndPosition=new b;_lookTargetLerp01=0;_cameraLerpActive=!1;_cameraStartPosition=new b;_cameraEndPosition=new b;_cameraLerp01=0;_cameraLerpDuration=0;_fovLerpActive=!1;_fovLerpStartValue=0;_fovLerpEndValue=0;_fovLerp01=0;_fovLerpDuration=0;_inputs=0;_enableTime=0;_startedListeningToKeyEvents=!1;_eventSystem;_afterHandleInputFn;_camera=null;_syncedTransform;_didSetTarget=0;awake(){zt&&console.debug("OrbitControls",this),this._didSetTarget=0,this._startedListeningToKeyEvents=!1,this.context.domElement.cameraControls===!1&&(this.enabled=!1)}start(){this._eventSystem=li.get(this.context)??void 0,this._eventSystem&&(this._afterHandleInputFn=this.afterHandleInput.bind(this),this._eventSystem.addEventListener(Uf.AfterHandleInput,this._afterHandleInputFn))}onDestroy(){this._controls?.dispose(),this._eventSystem?.removeEventListener(Uf.AfterHandleInput,this._afterHandleInputFn)}onEnable(){this._didSetTarget=0,this._enableTime=this.context.time.time;const e=S.getComponent(this.gameObject,yi);this._camera=e;let t=e?.threeCamera;if(!t&&this.gameObject instanceof de&&(t=this.gameObject),t&&sg(t,this,!0),!this._controls&&t instanceof M){this._cameraObject=t;const i=this.targetElement??this.context.renderer.domElement,n=t?.quaternion.clone();this._controls=new gP(t,i),t?.quaternion.copy(n),Nf===void 0&&(Nf={...this._controls.keys});const s=ee(t),r=this.gameObject.worldForward,a=s.clone().sub(r.multiplyScalar(2.5));this._controls.target.copy(a)}if(this._controls)if(zf&&(this.enablePan=!0,this.enableZoom=!0,this.middleClickToFocus=!0,I.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,Tn)??void 0,this.context.pre_render_callbacks.push(this.__onPreRender),this._activePointerEvents=[],this.context.input.addEventListener("pointerdown",this._onPointerDown,{queue:pi.Early}),this.context.input.addEventListener("pointerdown",this._onPointerDownLate,{queue:pi.Late}),this.context.input.addEventListener("pointerup",this._onPointerUp,{queue:pi.Early}),this.context.input.addEventListener("pointerup",this._onPointerUpLate,{queue:pi.Late})}onDisable(){if(this._camera?.threeCamera&&sg(this._camera.threeCamera,this,!1),this._controls){this._controls.enabled=!1,this._controls.autoRotate=!1,this._controls.removeEventListener("start",this.onControlsChangeStarted),this._controls.removeEventListener("endMovement",this.onControlsChangeEnded);try{this._controls.stopListenToKeyEvents()}catch{}this._startedListeningToKeyEvents=!1}this._activePointerEvents.length=0,this.context.input.removeEventListener("pointerdown",this._onPointerDown),this.context.input.removeEventListener("pointerdown",this._onPointerDownLate),this.context.input.removeEventListener("pointerup",this._onPointerUp),this.context.input.removeEventListener("pointerup",this._onPointerUpLate)}_activePointerEvents;_lastTimeClickOnBackground=-1;_clickOnBackgroundCount=0;_onPointerDown=e=>{this._activePointerEvents.push(e)};_onPointerDownLate=e=>{e.used&&this._controls&&(this._controls.enabled=!1)};_onPointerUp=e=>{for(let t=this._activePointerEvents.length-1;t>=0;t--){const i=this._activePointerEvents[t];if(i.pointerId===e.pointerId&&i.button===e.button){this._activePointerEvents.splice(t,1);break}}if(this.clickBackgroundToFitScene>0&&e.isClick&&e.button===0){if(e.hasRay||e.intersections.push(...this.context.physics.raycast()),e.intersections.length<=0){const t=this.context.time.time-this._lastTimeClickOnBackground;this._lastTimeClickOnBackground=this.context.time.time,this.clickBackgroundToFitScene<=1||t<this.clickBackgroundToFitScene*.15?(this._clickOnBackgroundCount+=1,this._clickOnBackgroundCount>=this.clickBackgroundToFitScene-1&&(this.autoRotate=!1,this.fitCamera({objects:this.context.scene,immediate:!1}))):this._clickOnBackgroundCount=0}zt&&console.log(this.clickBackgroundToFitScene,e.intersections.length,this._clickOnBackgroundCount)}};_onPointerUpLate=e=>{this.doubleClickToFocus&&e.isDoubleClick&&!e.used&&this.setTargetFromRaycast()};updateTargetNow(e){const t=new So(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?(zt&&B.DrawWireSphere(n.point,.1,16711680,2),this._controls?.target.copy(i[0].point)):zt&&console.log("OrbitControls: No hit found when updating target",{hits:[...i]})}_orbitStartAngle=0;_zoomStartDistance=0;onControlsChangeStarted=()=>{zt&&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(zt&&console.debug("OrbitControls: Change ended",{autoTarget:this.autoTarget}),this._controls&&this.autoTarget){const e=this._controls.getAzimuthalAngle()+this._controls.getPolarAngle()-this._orbitStartAngle;Math.abs(e)<.01?(zt&&console.debug("OrbitControls: Update target",{deltaAngle:e}),this.updateTargetNow({allowSlowRaycastFallback:!1})):zt&&console.debug("OrbitControls: No target update",{deltaAngle:e})}};_shouldDisable=!1;afterHandleInput(e){e.detail.args.pointerId===0&&(e.detail.args.isDown?this._controls&&this._eventSystem&&(this._shouldDisable=this._eventSystem.hasActiveUI):(!e.detail.args.isPressed||e.detail.args.isUp)&&(this._shouldDisable=!1))}onPausedChanged(e){this._controls&&e&&(this._controls.enabled=!1)}onBeforeRender(){if(!!this._controls){if(this._cameraObject!==this.context.mainCamera){this._controls.enabled=!1;return}if(this._controls.enabled=!0,(this.context.input.getPointerDown(1)||this.context.input.getPointerDown(2)||this.context.input.mouseWheelChanged||this.context.input.getPointerPressed(0)&&this.context.input.getPointerPositionDelta(0)?.length())&&(this._inputs+=1),this._inputs>0&&this.allowInterrupt&&(this.enableRotate&&(this.autoRotate=!1),this._cameraLerpActive=!1,this._lookTargetLerpActive=!1),this._inputs=0,this.autoTarget&&this._didSetTarget++===0){const e=S.getComponent(this.gameObject,yi);if(e&&!this.setLookTargetFromConstraint()){this.debugLog&&console.log("NO TARGET");const t=ee(e.threeCamera),i=Math.max(.01,t.length()),n=new b(0,0,-i).applyMatrix4(e.threeCamera.matrixWorld);zt&&B.DrawLine(t,n,5592575,10),this.setLookTargetPosition(n,!0)}if(!this.setLookTargetFromConstraint()){const t=new ks;t.screenPoint=new K(0,0),t.lineThreshold=.1;const i=this.context.physics.raycast(t);i.length>0&&this.setLookTargetPosition(i[0].point,!0),fR&&console.log("OrbitControls hits",...i)}}if(this.middleClickToFocus&&this.context.input.getPointerClicked(1)&&this.setTargetFromRaycast(),this._lookTargetLerpActive||this._cameraLerpActive||this._fovLerpActive){if(this._cameraLerpActive&&this._cameraObject)if(this._cameraLerp01+=this.context.time.deltaTime/this._cameraLerpDuration,this._cameraLerp01>=1)this._cameraObject.position.copy(this._cameraEndPosition),this._cameraLerpActive=!1,this.dispatchEvent(new Jc(this,"camera"));else{const e=j.easeInOutCubic(this._cameraLerp01);this._cameraObject.position.lerpVectors(this._cameraStartPosition,this._cameraEndPosition,e)}if(this._lookTargetLerpActive)if(this._lookTargetLerp01+=this.context.time.deltaTime/this._lookTargetLerpDuration,this._lookTargetLerp01>=1)this.lerpLookTarget(this._lookTargetEndPosition,this._lookTargetEndPosition,1),this._lookTargetLerpActive=!1,this.dispatchEvent(new Jc(this,"lookat"));else{const e=j.easeInOutCubic(this._lookTargetLerp01);this.lerpLookTarget(this._lookTargetStartPosition,this._lookTargetEndPosition,e)}if(this._fovLerpActive&&this._cameraObject){const e=this._cameraObject;if(this._fovLerp01+=this.context.time.deltaTime/this._fovLerpDuration,this._fovLerp01>=1)e.fov=this._fovLerpEndValue,this._fovLerpActive=!1;else{const t=j.easeInOutCubic(this._fovLerp01);e.fov=j.lerp(this._fovLerpStartValue,this._fovLerpEndValue,t)}e.updateProjectionMatrix()}}if(this.targetBounds){const e=this._controls.target,t=this.targetBounds.worldPosition,i=F(this.targetBounds.worldScale).multiplyScalar(.5),n=F(t).sub(i),s=F(t).add(i),r=F(this._controls.target).clamp(n,s),a=.1;e.lerp(r,this.context.time.deltaTime/a),this._lookTargetLerpActive&&this._lookTargetEndPosition.lerp(r,this.context.time.deltaTime/(a*5)),zt&&B.DrawWireBox(t,i.multiplyScalar(2),16755200)}if(this._controls){this.debugLog&&(this._controls.domElement=this.context.renderer.domElement);const e=1/(this.context.focusRectSettings?.zoom||1);if(this._controls.enabled=!this._shouldDisable&&this._camera===this.context.mainCameraComponent&&!this.context.isInXR&&!this._activePointerEvents.some(t=>t.used),this._controls.keys=this.enableKeys?Nf:yR,this._controls.autoRotate=this.autoRotate,this._controls.autoRotateSpeed=this.autoRotateSpeed,this._controls.enableZoom=this.enableZoom,this._controls.zoomSpeed=this.zoomSpeed,this._controls.zoomToCursor=this.zoomToCursor,this._controls.enableDamping=this.enableDamping,this._controls.dampingFactor=this.dampingFactor,this._controls.enablePan=this.enablePan,this._controls.panSpeed=e,this._controls.enableRotate=this.enableRotate,this._controls.minAzimuthAngle=this.minAzimuthAngle,this._controls.maxAzimuthAngle=this.maxAzimuthAngle,this._controls.minPolarAngle=this.minPolarAngle,this._controls.maxPolarAngle=this.maxPolarAngle,zf||(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 $u=="number"||$u===!0){this._controls.enableDamping=!0;const t=typeof $u=="number"?$u:.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||(!zf&&this.lookAtConstraint?.locked&&!this._lookTargetLerpActive&&this.setLookTargetFromConstraint(0,this.lookAtConstraint01),this._controls.update(this.context.time.deltaTime),zt&&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()||zt)&&console.warn("[OrbitControls] setCameraAndLookTarget target is null"),!1;if(!(e instanceof M)&&!(e instanceof yi))return(A()||zt)&&console.warn("[OrbitControls] setCameraAndLookTarget target is not an Object3D or Camera"),!1;e instanceof yi&&(e=e.gameObject);const i=e.worldPosition,n=e.worldForward;e instanceof cC&&(zt&&console.debug("[OrbitControls] setCameraAndLookTarget flip forward direction for camera"),n.multiplyScalar(-1));const s=new So(i,n);return zt&&B.DrawRay(s.origin,s.direction,16711680,10),this.setTargetFromRaycast(s,t)||this.setLookTargetPosition(s.at(2,F()),t),this.setCameraTargetPosition(i,t),!0}setCameraTargetPosition(e,t=!1){e&&(e instanceof M&&(e=ee(e)),this._cameraEndPosition||(this._cameraEndPosition=new b),this._cameraEndPosition.copy(e),t===!0?(this._cameraLerpActive=!1,this._cameraObject&&this._cameraObject.position.copy(this._cameraEndPosition)):this._cameraObject&&(this._cameraLerpActive=!0,this._cameraLerp01=0,this._cameraStartPosition.copy(this._cameraObject?.position),typeof t=="number"?this._cameraLerpDuration=t:this._cameraLerpDuration=this.targetLerpDuration))}get cameraLerpActive(){return this._cameraLerpActive}stopCameraLerp(){this._cameraLerpActive=!1}setFieldOfView(e,t=!1){if(!this._controls||typeof e!="number")return;const i=this._camera?.threeCamera;i&&(t===!0?i.fov=e:(this._fovLerpActive=!0,this._fovLerp01=0,this._fovLerpStartValue=i.fov,this._fovLerpEndValue=e,typeof t=="number"?this._fovLerpDuration=t:this._fovLerpDuration=this.targetLerpDuration))}setLookTargetPosition(e=null,t=!1){this._controls&&e&&(e instanceof M&&(e=ee(e)),this._lookTargetEndPosition.copy(e),this._didSetTarget++,zt&&(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 s=Ff(n.object);if(s&&s.canvas?.screenspace)break;return this.setLookTargetPosition(n.point,t),!0}return!1}fitCamera(e,t){let i;if(Array.isArray(e)||e&&"type"in e?i=e:e&&typeof e=="object"&&!(e instanceof M)&&!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=lx({objects:[...i],...t,autoApply:!1,context:this.context,camera:this._cameraObject,currentZoom:this._controls?.getDistance()||void 0,minZoom:this.minZoom,maxZoom:this.maxZoom});n&&(this.setLookTargetPosition(n.lookAt,t?.immediate||!1),this.setCameraTargetPosition(n.position,t?.immediate||!1),this.setFieldOfView(t?.fov,t?.immediate||!1),this.onBeforeRender())}_haveAttachedKeyboardEvents=!1}Me([u()],ge.prototype,"autoTarget",2),Me([u()],ge.prototype,"autoFit",2),Me([u()],ge.prototype,"enableRotate",2),Me([u()],ge.prototype,"autoRotate",2),Me([u()],ge.prototype,"autoRotateSpeed",2),Me([u()],ge.prototype,"minAzimuthAngle",2),Me([u()],ge.prototype,"maxAzimuthAngle",2),Me([u()],ge.prototype,"minPolarAngle",2),Me([u()],ge.prototype,"maxPolarAngle",2),Me([u()],ge.prototype,"enableKeys",2),Me([u()],ge.prototype,"enableDamping",2),Me([u()],ge.prototype,"dampingFactor",2),Me([u()],ge.prototype,"enableZoom",2),Me([u()],ge.prototype,"minZoom",2),Me([u()],ge.prototype,"maxZoom",2),Me([u()],ge.prototype,"zoomSpeed",2),Me([u()],ge.prototype,"enablePan",2),Me([u(Wr)],ge.prototype,"lookAtConstraint",2),Me([u()],ge.prototype,"lookAtConstraint01",2),Me([u()],ge.prototype,"allowInterrupt",2),Me([u()],ge.prototype,"middleClickToFocus",2),Me([u()],ge.prototype,"doubleClickToFocus",2),Me([u()],ge.prototype,"clickBackgroundToFitScene",2),Me([u()],ge.prototype,"targetLerpDuration",1),Me([u(M)],ge.prototype,"targetBounds",2);var bR=Object.defineProperty,_R=Object.getOwnPropertyDescriptor,ei=(o,e,t,i)=>{for(var n=i>1?void 0:i?_R(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&bR(e,t,n),n},$r=(o=>(o[o.None=0]="None",o[o.Skybox=1]="Skybox",o[o.SolidColor=2]="SolidColor",o[o.Uninitialized=4]="Uninitialized",o))($r||{});const js=w("debugcam"),gx=w("debugscreenpointtoray"),Nt=class md extends E{get isCamera(){return!0}get aspect(){return this._cam instanceof de?this._cam.aspect:this.context.domWidth/this.context.domHeight}set aspect(e){this._cam instanceof de&&this._cam.aspect!==e&&(this._cam.aspect=e,this._cam.updateProjectionMatrix())}get fieldOfView(){return this._cam instanceof de?this._cam.fov:this._fov}set fieldOfView(e){const t=this.fieldOfView!=e;if(this._fov=e,t&&this._cam&&this._cam instanceof de){if(this._fov===void 0){console.warn("Can not set undefined fov on PerspectiveCamera");return}this._cam.fov=this._fov,this._cam.updateProjectionMatrix()}}get nearClipPlane(){return this._nearClipPlane}set nearClipPlane(e){const t=this._nearClipPlane!=e;this._nearClipPlane=e,this._cam&&(t||this._cam.near!=e)&&(this._cam.near=e,this._cam.updateProjectionMatrix())}_nearClipPlane=.1;get farClipPlane(){return this._farClipPlane}set farClipPlane(e){const t=this._farClipPlane!=e;this._farClipPlane=e,this._cam&&(t||this._cam.far!=e)&&(this._cam.far=e,this._cam.updateProjectionMatrix())}_farClipPlane=1e3;applyClippingPlane(){this._cam&&(this._cam.near=this._nearClipPlane,this._cam.far=this._farClipPlane,this._cam.updateProjectionMatrix())}get clearFlags(){return this._clearFlags}set clearFlags(e){if(typeof e=="string")switch(e){case"skybox":e=1;break;case"solidcolor":e=2;break;default:e=0;break}e!==this._clearFlags&&(this._clearFlags=e,this.applyClearFlagsIfIsActiveCamera())}orthographic=!1;orthographicSize=5;ARBackgroundAlpha=0;set cullingMask(e){this._cullingMask=e,this._cam&&(this._cam.layers.mask=e)}get cullingMask(){return this._cam?this._cam.layers.mask:this._cullingMask}_cullingMask=4294967295;set cullingLayer(e){this.cullingMask=(1<<e|0)>>>0}set backgroundBlurriness(e){e!==this._backgroundBlurriness&&(e===void 0?this._backgroundBlurriness=void 0:this._backgroundBlurriness=Math.min(Math.max(e,0),1),this.applyClearFlagsIfIsActiveCamera())}get backgroundBlurriness(){return this._backgroundBlurriness}_backgroundBlurriness=void 0;set backgroundIntensity(e){e!==this._backgroundIntensity&&(e===void 0?this._backgroundIntensity=void 0:this._backgroundIntensity=Math.min(Math.max(e,0),10),this.applyClearFlagsIfIsActiveCamera())}get backgroundIntensity(){return this._backgroundIntensity}_backgroundIntensity=void 0;set backgroundRotation(e){e!==this._backgroundRotation&&(e===void 0?this._backgroundRotation=void 0:this._backgroundRotation=e,this.applyClearFlagsIfIsActiveCamera())}get backgroundRotation(){return this._backgroundRotation}_backgroundRotation=void 0;set environmentIntensity(e){this._environmentIntensity=e}get environmentIntensity(){return this._environmentIntensity}_environmentIntensity=void 0;get backgroundColor(){return this._backgroundColor??null}set backgroundColor(e){e&&(this._backgroundColor||(this._backgroundColor=new se(1,1,1,1)),this._backgroundColor.copy(e),(!("alpha"in e)||e.alpha===void 0)&&(this._backgroundColor.alpha=1),this.applyClearFlagsIfIsActiveCamera())}set targetTexture(e){this._targetTexture=e}get targetTexture(){return this._targetTexture}_targetTexture=null;_backgroundColor;_fov;_cam=null;_clearFlags=2;_skybox;get cam(){return this.threeCamera}get threeCamera(){return this.activeAndEnabled&&this.buildCamera(),this._cam}static _origin=new b;static _direction=new b;screenPointToRay(e,t,i){const n=this.threeCamera,s=md._origin;s.set(e,t,-1),this.context.input.convertScreenspaceToRaycastSpace(s),gx&&console.log("screenPointToRay",e.toFixed(2),t.toFixed(2),"now:",s.x.toFixed(2),s.y.toFixed(2),"isInXR:"+this.context.isInXR),s.z=-1,s.unproject(n);const r=md._direction.set(s.x,s.y,s.z),a=ee(n);return r.sub(a),r.normalize(),i?(i.set(a,r),i):new So(a.clone(),r.clone())}_frustum;getFrustum(){return this._frustum||(this._frustum=new Sb,this.updateFrustum()),this._frustum}updateFrustum(){this._frustum||(this._frustum=new Sb),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 J;awake(){gx&&window.addEventListener("pointerdown",e=>{const t=e.clientX,i=e.clientY;console.log("touch",t.toFixed(2),i.toFixed(2));const n=this.screenPointToRay(t,i),s="#"+Math.floor(Math.random()*16777215).toString(16);B.DrawRay(n.origin,n.direction,s,10)})}onEnable(){js&&console.log(`Camera enabled: "${this.name}". ClearFlags=${$r[this._clearFlags]}`,this),this.buildCamera(),(this.tag=="MainCamera"||!this.context.mainCameraComponent)&&(this.context.setCurrentCamera(this),wR(this)),this.applyClearFlagsIfIsActiveCamera({applySkybox:!0})}onDisable(){this.context.removeCamera(this)}onLeaveXR(e){this.fieldOfView=this._fov}onBeforeRender(){if(this._cam&&(this._frustum&&this.updateFrustum(),this._clearFlags===2&&this.applyClearFlagsIfIsActiveCamera(),this._targetTexture)){this.context.isManagedExternally&&(this._warnedAboutExternalRenderer||(this._warnedAboutExternalRenderer=!0,console.warn("Rendering with external renderer is not supported yet. This may not work or throw errors. Please remove the the target texture from your camera: "+this.name,this.targetTexture))),this.context.composer;const e=this.context.renderer;if(e){const t=this.context.mainCameraComponent;this.applyClearFlags(),this._targetTexture.render(this.context.scene,this._cam,e),t?.applyClearFlags()}}}buildCamera(){if(this._cam)return;const e=this.gameObject.isCamera;let t=null;if(e?(t=this.gameObject,t?.layers.enableAll(),t instanceof de&&(this._fov=t.fov)):t=this.gameObject.children[0],t&&t.isCamera)t instanceof de&&(this._fov&&(t.fov=this._fov),t.near=this._nearClipPlane,t.far=this._farClipPlane,t.updateProjectionMatrix());else if(!this.orthographic)t=new de(this.fieldOfView,window.innerWidth/window.innerHeight,this._nearClipPlane,this._farClipPlane),this.fieldOfView&&(t.fov=this.fieldOfView),this.gameObject.add(t);else{const i=this.orthographicSize*100;t=new Cd(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){js&&console.log("Camera does not exist (apply clear flags)");return}if(this.fieldOfView=this.fieldOfView,js){const i=`[Camera] Apply ClearFlags: ${$r[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(md.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:js&&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:js&&console.warn(`Camera "${this.name}" has no background intensity`);break;case 2:if(this._backgroundColor&&!t){let i=this._backgroundColor.alpha;md.backgroundShouldBeTransparent(this.context)&&(i=this.ARBackgroundAlpha??0),this.context.scene.background=null,this.context.xr?.isVR?this.context.renderer.setClearColor(y_(this._backgroundColor).convertLinearToSRGB()):this.context.renderer.setClearColor(this._backgroundColor,i)}else this._backgroundColor||js&&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 vR(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;js&&Oe("Environment blend mode: "+i+" on "+navigator.userAgent);let n=i==="additive"||i==="alpha-blend";if(e.isInAR&&i==="opaque"){if(navigator.userAgent?.includes("OculusBrowser"))n=!0;else if(navigator.userAgent?.includes("Mozilla")&&navigator.userAgent?.includes("Mobile WebXRViewer/v2"))n=!0;else if(I.isNeedleAppClip())return!0}return t._transparent=n,n}};ei([u()],Nt.prototype,"aspect",1),ei([u()],Nt.prototype,"fieldOfView",1),ei([u()],Nt.prototype,"nearClipPlane",1),ei([u()],Nt.prototype,"farClipPlane",1),ei([u()],Nt.prototype,"clearFlags",1),ei([u()],Nt.prototype,"orthographic",2),ei([u()],Nt.prototype,"orthographicSize",2),ei([u()],Nt.prototype,"ARBackgroundAlpha",2),ei([u()],Nt.prototype,"cullingMask",1),ei([u()],Nt.prototype,"backgroundBlurriness",1),ei([u()],Nt.prototype,"backgroundIntensity",1),ei([u(at)],Nt.prototype,"backgroundRotation",1),ei([u()],Nt.prototype,"environmentIntensity",1),ei([u(se)],Nt.prototype,"backgroundColor",1),ei([u(xo)],Nt.prototype,"targetTexture",1);let yi=Nt;class vR{_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");js&&console.debug(`[Camera] Apply Skybox ${this._skybox?.name} ${e} - "${this._camera.name}"`),e?.length||(this._skybox.mapping=ko,this.context.scene.background=this._skybox)}}}function wR(o){w("freecam")&&o.context.mainCameraComponent===o&&S.getOrAddComponent(o.gameObject,ge)}class Wo extends E{get listener(){return this._listener==null&&(this._listener=new hC),this._listener}_listener=null;onEnable(){Nn.registerWaitForInteraction(this.onInteraction),this.addListenerIfItExists()}onDisable(){Nn.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,yi);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 xR=Object.defineProperty,SR=Object.getOwnPropertyDescriptor,An=(o,e,t,i)=>{for(var n=i>1?void 0:i?SR(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&xR(e,t,n),n};const Mt=w("debugaudio"),en=class hr extends E{static get userInteractionRegistered(){return Nn.userInteractionRegistered}static registerWaitForAllowAudio(e){Nn.registerWaitForInteraction(e)}clip="";playOnAwake=!1;preload=!0;playInBackground=!0;get isPlaying(){return this.sound?.isPlaying??!1}get duration(){return this.sound?.buffer?.duration}get time01(){const e=this.duration;return e&&this.sound?this.sound?.context.currentTime/e:0}set time01(e){const t=this.duration;t&&this.sound&&(this.time=e*t)}get time(){return this.sound?.source?this.sound.source?.context.currentTime-this._lastContextTime+this.sound.offset:0}set time(e){if(this.sound){if(e===this.sound.offset)return;const t=this.isPlaying;this.stop(),this.sound.offset=e,t&&this.play()}}get loop(){return this.sound&&(this._loop=this.sound.getLoop()),this._loop}set loop(e){this._loop=e,this.sound&&this.sound.setLoop(e)}get spatialBlend(){return this._spatialBlend}set spatialBlend(e){e!==this._spatialBlend&&(this._spatialBlend=e,this._needUpdateSpatialDistanceSettings=!0)}get minDistance(){return this._minDistance}set minDistance(e){this._minDistance!==e&&(this._minDistance=e,this._needUpdateSpatialDistanceSettings=!0)}get maxDistance(){return this._maxDistance}set maxDistance(e){this._maxDistance!==e&&(this._maxDistance=e,this._needUpdateSpatialDistanceSettings=!0)}_spatialBlend=0;_minDistance=1;_maxDistance=100;get volume(){return this._volume}set volume(e){this._volume=e,this.sound&&!this.context.application.muted&&(Mt&&console.log(this.name,"audio set volume",e),this.sound.setVolume(e))}_volume=1;set pitch(e){this.sound&&this.sound.setPlaybackRate(e)}get pitch(){return this.sound?this.sound.getPlaybackRate():1}rollOffMode=0;_loop=!1;sound=null;helper=null;wasPlaying=!1;audioLoader=null;shouldPlay=!1;_lastClipStartedLoading=null;_audioElement=null;get Sound(){if(!this.sound&&hr.userInteractionRegistered){let e=this.gameObject.getComponent(Wo)??this.context.mainCamera.getComponent(Wo)??tl(Wo,this.context,!1);!e&&this.context.mainCamera&&(e=this.context.mainCamera.addComponent(Wo)),e?.listener?(this.sound=new dC(e.listener),this.gameObject?.add(this.sound)):Mt&&console.warn("No audio listener found in scene - can not play audio")}return this.sound}get ShouldPlay(){return this.shouldPlay}get audioContext(){return this.sound?.context}awake(){Mt&&console.log("[AudioSource]",this),this.audioLoader=new Lm,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),hr.userInteractionRegistered?this.playOnAwake&&this.context.application.isVisible&&this.play():hr.registerWaitForAllowAudio(()=>{this.enabled&&!this.destroyed&&this.shouldPlay&&this.onNewClip(this.clip)}),globalThis.addEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.addEventListener(Og.MuteChanged,this.onApplicationMuteChanged)}onDisable(){globalThis.removeEventListener("visibilitychange",this.onVisibilityChanged),this.context.application.removeEventListener(Og.MuteChanged,this.onApplicationMuteChanged),this.pause()}onVisibilityChanged=()=>{switch(document.visibilityState){case"hidden":(this.playInBackground===!1||I.isMobileDevice())&&(this.wasPlaying=this.isPlaying,this.isPlaying&&this.pause());break;case"visible":Mt&&console.log("visible",this.enabled,this.playOnAwake,!this.isPlaying,hr.userInteractionRegistered,this.wasPlaying),this.enabled&&this.playOnAwake&&!this.isPlaying&&hr.userInteractionRegistered&&this.wasPlaying&&this.play();break}};onApplicationMuteChanged=()=>{this.context.application.muted?this.sound?.setVolume(0):this.sound?.setVolume(this.volume)};createAudio=e=>{if(this.destroyed){Mt&&console.warn("AudioSource destroyed, not creating audio",this.name);return}Mt&&console.log("AudioBuffer finished loading",e);const t=this.Sound;if(!t){Mt&&console.warn("Failed getting sound?",this.name);return}t.isPlaying&&t.stop(),e&&t.setBuffer(e),t.loop=this._loop,this.context.application.muted?t.setVolume(0):t.setVolume(this.volume),t.autoplay=this.shouldPlay&&hr.userInteractionRegistered,this.applySpatialDistanceSettings(),t.isPlaying&&t.stop(),hr.registerWaitForAllowAudio(this.__onAllowAudioCallback)};__onAllowAudioCallback=()=>{this.shouldPlay&&this.play()};applySpatialDistanceSettings(){const e=this.sound;if(!e)return;this._needUpdateSpatialDistanceSettings=!1;const t=j.lerp(10*this._maxDistance/Math.max(1e-4,this.spatialBlend),this._minDistance,this.spatialBlend);switch(Mt&&console.log(this.name,this._minDistance,this._maxDistance,this.spatialBlend,"Ref distance="+t),e.setRefDistance(t),e.setMaxDistance(Math.max(.01,this._maxDistance)),this.rollOffMode){case 0:e.setDistanceModel("exponential");break;case 1:e.setDistanceModel("linear");break;case 2:console.warn("Custom rolloff for AudioSource is not supported: "+this.name);break}this.spatialBlend>0?Mt&&!this.helper&&(this.helper=new fP(e,e.getRefDistance()),e.add(this.helper)):this.helper&&this.helper.parent&&this.helper.removeFromParent()}async onNewClip(e){if(e&&(this.clip=e),typeof e=="string")if(Mt&&console.log(e),e.endsWith(".mp3")||e.endsWith(".wav")){if(this.audioLoader||(this.audioLoader=new Lm),this.shouldPlay=!0,this._lastClipStartedLoading===e){Mt&&console.log("Is currently loading:",this._lastClipStartedLoading,this);return}this._lastClipStartedLoading=e,Mt&&console.log("load audio",e);const t=await this.audioLoader.loadAsync(e).catch(console.error);if(this.destroyed)return;this._lastClipStartedLoading===e&&(this._lastClipStartedLoading=null),t&&this.createAudio(t)}else console.warn("Unsupported audio clip type",e);else this.shouldPlay=!0,this.createAudio()}play(e=void 0){!e&&this.clip&&(e=this.clip),e!==void 0&&typeof e!="string"&&!(e instanceof MediaStream)&&(A()&&console.warn("Called play on AudioSource with unknown argument type:",e+`
|
|
975
975
|
Using the assigned clip instead:`,this.clip),e=this.clip);let t=!this.sound||e&&e!==this.clip;if(typeof e=="string"&&!this.audioLoader&&(t=!0),(e instanceof MediaStream||typeof e=="string")&&(this.clip=e),t){this.shouldPlay=!0,this.onNewClip(e);return}if(this.shouldPlay=!0,this._hasEnded=!1,Mt&&console.log("play",this.sound?.getVolume(),this.sound),this.sound&&!this.sound.isPlaying){const i=this.context.application.muted;i&&this.sound.setVolume(0),this.gameObject?.add(this.sound),this.clip instanceof MediaStream?(this.sound.setMediaStreamSource(this.clip),this._audioElement||(this._audioElement=document.createElement("audio"),this._audioElement.style.display="none"),this._audioElement.parentNode||this.context.domElement.shadowRoot?.append(this._audioElement),this._audioElement.srcObject=this.clip,this._audioElement.autoplay=!1):(this._audioElement&&this._audioElement.remove(),this.sound.play(i?.1:0))}}pause(){Mt&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.isPlaying&&this.sound.source&&(this._lastContextTime=this.sound?.context.currentTime,this.sound.pause()),this._audioElement?.remove()}stop(){Mt&&console.log("Pause",this),this._hasEnded=!0,this.shouldPlay=!1,this.sound&&this.sound.source&&(this._lastContextTime=this.sound?.context.currentTime,Mt&&console.log(this._lastContextTime),this.sound.stop()),this._audioElement?.remove()}_lastContextTime=0;_hasEnded=!0;_needUpdateSpatialDistanceSettings=!1;update(){this.helper&&(this.isPlaying&&this.helper.update(),this.helper.visible=this.isPlaying),this._needUpdateSpatialDistanceSettings&&this.applySpatialDistanceSettings(),this.sound&&!this.sound.isPlaying&&this.shouldPlay&&!this._hasEnded&&(this._hasEnded=!0,Mt&&console.log("Audio clip ended",this.clip),this.dispatchEvent(new CustomEvent("ended",{detail:this})))}};An([u(URL)],en.prototype,"clip",2),An([u()],en.prototype,"playOnAwake",2),An([u()],en.prototype,"preload",2),An([u()],en.prototype,"playInBackground",2),An([u()],en.prototype,"loop",1),An([u()],en.prototype,"spatialBlend",1),An([u()],en.prototype,"minDistance",1),An([u()],en.prototype,"maxDistance",1),An([u()],en.prototype,"volume",1),An([u()],en.prototype,"pitch",1),An([u()],en.prototype,"rollOffMode",2);let ji=en;const CR=w("debugavatar");class Le extends E{static getAvatar(e){return e>=0&&e<Le.instances.length?Le.instances[e]:null}static instances=[];static onAvatarMarkerCreated(e){return Le._onNewAvatarMarkerAdded.push(e),e}static onAvatarMarkerDestroyed(e){return Le._onAvatarMarkerDestroyed.push(e),e}static _onNewAvatarMarkerAdded=[];static _onAvatarMarkerDestroyed=[];connectionId;avatar;awake(){Le.instances.push(this),CR&&console.log(this);for(const e of Le._onNewAvatarMarkerAdded)e({avatarMarker:this,gameObject:this.gameObject})}onDestroy(){Le.instances.splice(Le.instances.indexOf(this),1);for(const e of Le._onAvatarMarkerDestroyed)e({avatarMarker:this,gameObject:this.gameObject})}isLocalAvatar(){return this.connectionId===this.context.connection.connectionId}}class Hr{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??U.Current?.time.time;return}}}}class PR{guid;position=new b}class eh extends E{set controlledTarget(e){this.target=e;const t=C.get("MoveRandom");if(t&&this.target){const i=S.getComponent(this.target,t);i&&i.destroy()}}target=null;avatar=null;_model=null;_targetModel=new PR;_currentTargetObject=null;_lastUpdateTime=0;_lookDuration=0;_lastPoiChangedTime=0;awake(){if(this.avatar=S.getComponentInParent(this.gameObject,Le),this.avatar){const e=S.getComponentInParent(this.gameObject,Le);this._model=new Tg(this.context.connection,this.guid),e?.isLocalAvatar&&this._model.requestOwnership()}this.context.connection.beginListen("avatar-look-target-changed",e=>{this.target&&e&&e.guid===this.avatar?.guid&&yt(this.target,e.position)})}update(){if((!this.context.connection.isConnected||this._model?.hasOwnership)&&(Hr.LastChangeTime!==this._lastPoiChangedTime&&(this._lastPoiChangedTime=Hr.LastChangeTime,this._lookDuration=0),this.selectTarget(),this._currentTargetObject&&this.context.time.frameCount%10===0&&this.target)){const e=ee(this._currentTargetObject);yt(this.target,e),this.context.connection.isConnected&&this.avatar&&(this.context.connection.send("avatar-look-target-changed",this._targetModel),this._targetModel.guid=this.avatar.guid,this._targetModel.position.copy(e))}}selectTarget(){if(this.context.time.time-this._lastUpdateTime>this._lookDuration){this._lastUpdateTime=this.context.time.time,this._lookDuration=Math.random()*.5+.2;const e=Hr.Pois;if(e.length>0){const t=e[Math.floor(Math.random()*e.length)];if(t&&t.obj){if(t.avatar&&t.avatar===this.avatar)return;this._currentTargetObject=t.obj}}}}}const je=w("debugnetworkingstreams");var to=(o=>(o.Connected="peer-user-connected",o.StreamReceived="receive-stream",o.StreamEnded="call-ended",o.Disconnected="peer-user-disconnected",o.UserJoined="user-joined",o))(to||{});class Wf{type="call-ended";userId;direction;constructor(e,t){this.userId=e,this.direction=t}}class fx{type="receive-stream";userId;stream;target;constructor(e,t,i){this.userId=e,this.stream=t,this.target=i}}class OR{guid;peerId;dontSave=!0;constructor(e,t){this.guid=e.id,this.peerId=t}}var yx=(o=>(o.Incoming="incoming",o.Outgoing="outgoing",o))(yx||{});class kR extends jm{peerId;userId;direction;call;get stream(){return this._stream}_stream=null;_isDisposed=!1;close(){this._isDisposed||(this._isDisposed=!0,this.call.close(),io(this._stream))}get isOpen(){return this.call.peerConnection?.connectionState==="connected"}get isOpening(){return this.call.peerConnection?.connectionState==="connecting"}get isClosed(){return!this.isOpen||this._isDisposed}constructor(e,t,i,n=null){super(),this.peerId=t.peer,this.userId=e,this.call=t,this.direction=i,this._stream=n,t.on("stream",s=>{if(je&&console.log("Receive stream",`
|
|
976
976
|
Audio:`,s.getAudioTracks(),`
|
|
977
977
|
Video:`,s.getVideoTracks()),this._stream=s,i==="incoming"){const r=new fx(e,s,this);this.dispatchEvent(r)}}),t.on("close",()=>{this.dispatchEvent(new Wf(e,i))})}}function bx(o){return o=o.replace("a=fmtp:111 minptime=10;useinbandfec=1","a=fmtp:111 ptime=5;useinbandfec=1;stereo=1;maxplaybackrate=48000;maxaveragebitrat=128000;sprop-stereo=1"),o}class fs extends jm{static instances=new Map;static getOrCreate(e,t){if(fs.instances.has(t))return fs.instances.get(t);const i=new fs(e,t);return fs.instances.set(t,i),i}getMyPeerId(){if(this.context.connection.connectionId)return this.getPeerIdFromUserId(this.context.connection.connectionId)}getPeerIdFromUserId(e){return this.id+"-"+e}getUserIdFromPeerId(e){return e.substring(this.id.length+1)}makeCall(e,t){if(!t?.id){je?console.warn("Can not make a call: mediastream has no id or is undefined"):console.debug("Can not make a call: mediastream has no id or is undefined");return}const i={metadata:{userId:this.context.connection.connectionId,streamId:t.id},sdpTransform:s=>bx(s)},n=this._peer?.call(e,t,i);if(n){const s=this.registerCall(n,"outgoing",t);return je&&console.warn(`\u{1F4DE} CALL ${e}`,`
|
|
978
978
|
Outgoing:`,this._outgoingCalls,`
|
|
979
|
-
Incoming:`,this._incomingCalls),s}else je&&console.error("Failed to make call",e,t,this._peer)}closeAll(){for(const e of this._incomingCalls)e.close();for(const e of this._outgoingCalls)e.close();this.updateCalls()}updateCalls=()=>{for(let e=this._incomingCalls.length-1;e>=0;e--){const t=this._incomingCalls[e];t.isClosed&&!t.isOpening&&this._incomingCalls.splice(e,1)}for(let e=this._outgoingCalls.length-1;e>=0;e--){const t=this._outgoingCalls[e];let i=!1;t.isClosed&&!t.isOpening&&(t.stream?.active?je&&console.warn("!!! Stream is still active, don't remove call",t.userId,"Your id: "+this.context.connection.connectionId):(je&&console.warn("!!! Remove closed call",t.userId),i=!0)),this.context.connection.userIsInRoom(t.userId)===!1&&(je&&console.warn("!!! User is not in room anymore, remove call",t.userId),i=!0),i&&(t.close(),this._outgoingCalls.splice(e,1))}};get peer(){return this._peer}get incomingCalls(){return this._incomingCalls}id;context;_incomingCalls=[];_outgoingCalls=[];_peer;constructor(e,t){super(),this.context=e,this.id=t,this.setupPeer();const i=Object.getOwnPropertyDescriptor(navigator,"getUserMedia")?.writable;try{i?navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia:je&&console.warn("[PeerJs] getUserMedia is not writable")}catch(n){je&&console.error("[PeerJs] Error setting getUserMedia",n)}}_enabled=!1;_enabledPeer=!1;onConnectRoomFn=this.onConnectRoom.bind(this);enable(){this._enabled||(this._enabled=!0,this.context.connection.beginListen(ie.JoinedRoom,this.onConnectRoomFn),this.subscribePeerEvents())}disable(){this._enabled&&(this._enabled=!1,this.context.connection.stopListen(ie.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=lv(e):console.error("Failed to setup peerjs because we dont have a connection id",this.context.connection.connectionId)}this._enabled&&this.subscribePeerEvents()}}subscribePeerEvents(){this._peer&&(this._peer.on("open",this.onPeerConnect),this._peer.on("close",this.onPeerClose),this._peer.on("call",this.onPeerReceivingCall),this._peer.on("disconnected",this.onPeerDisconnected),this._peer.on("error",this.onPeerError))}unsubscribePeerEvents(){this._peer&&(this._peer.off("open",this.onPeerConnect),this._peer.off("close",this.onPeerClose),this._peer.off("call",this.onPeerReceivingCall),this._peer.off("disconnected",this.onPeerDisconnected),this._peer.off("error",this.onPeerError))}onPeerConnect=e=>{if(je&&console.log("PEER opened as",e),e===null){console.error("Peer connection failed",e);return}this.context.connection.send("peer-user-connected",new OR(this,e))};onPeerClose=()=>{je&&console.log("PEER closed"),this.updateCalls()};onPeerDisconnected=()=>{je&&console.log("PEER disconnected"),this.updateCalls()};onPeerError=e=>{je&&console.error("PEER error",e)};onPeerReceivingCall=e=>{e.answer(void 0,{sdpTransform:t=>bx(t)}),this.registerCall(e,"incoming",null)};registerCall(e,t,i){const n=e.metadata;(!n||!n.userId)&&console.error("Missing call metadata",e);const s=n.userId;t==="incoming"&&je?console.warn("\u2190 Receive call from",e.metadata,e.connectionId):je&&console.warn("\u2192 Make call to",e.metadata);const r=t==="incoming"?this._incomingCalls:this._outgoingCalls,a=new kR(s,e,t,i);return r.push(a),e.on("error",l=>{console.error("Call error",l)}),e.on("close",()=>{je&&console.log("Call ended",e.metadata);const l=r.indexOf(a);l!==-1&&r.splice(l,1),a.close(),this.dispatchEvent(new Wf(s,t))}),a.addEventListener("call-ended",l=>{this.dispatchEvent(l)}),t==="incoming"&&(a.addEventListener("receive-stream",l=>{this.dispatchEvent(l)}),e.on("stream",()=>{je&&console.log("Received stream for call",e.metadata);let l=0;const c=setInterval(()=>{const h=l===0;!a.isOpen&&h&&(je&&console.warn("Close call because stream is not active",e.metadata),l+=1,clearInterval(c),a.close())},2e3)})),a}}class wd extends jm{static create(e,t){const i=fs.getOrCreate(e.context,t||e.context.connection.connectionId||e.guid);return new wd(e.context,i)}context;peer;_sendingStreams=new Map;debug=!1;constructor(e,t){if(super(),vg(e)){const i=e;e=i.context,t=fs.getOrCreate(i.context,i.guid)}else typeof t=="string"&&(t=fs.getOrCreate(e,t));if(e){if(!(e instanceof U))throw new Error("Failed to create NetworkedStreams because context is not an instance of Context")}else throw new Error("Failed to create NetworkedStreams because context is undefined");if(!t)throw new Error("Failed to create NetworkedStreams because peer is undefined");this.context=e,this.peer=t,je&&(this.debug=!0)}startSendingStream(e){this._sendingStreams.has(e)?console.warn("Received start sending stream with stream that is already being sent"):(this._sendingStreams.set(e,[]),this.updateSendingCalls())}stopSendingStream(e){if(e){const t=this._sendingStreams.get(e);if(t){for(const i of t)i.close();t.length=0}this._sendingStreams.delete(e),t&&this.debug&&this.debugLogCurrentState()}this.updateSendingCalls()}_enabled=!1;get enabled(){return this._enabled}enable(){this._enabled||(this._enabled=!0,this.peer.enable(),this.peer.addEventListener("receive-stream",this.onCallStreamReceived),this.peer.addEventListener("call-ended",this.onCallEnded),this.context.connection.beginListen("peer-user-connected",this.onUserConnected),this.context.connection.beginListen(ie.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(ie.UserJoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(ie.UserLeftRoom,this.onUserLeft),this.context.connection.beginListen(ie.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(ie.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(ie.UserJoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(ie.UserLeftRoom,this.onUserLeft),this.context.connection.stopListen(ie.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;if(!t)return;this.peer.makeCall(e.peerId,t)}else je&&console.log("Unknown user connected",e.guid,e.peerId)};onUserLeft=e=>{this.debug&&console.log("User left room: "+e.userId),this.stopCallsToUsersThatAreNotInTheRoomAnymore()};updateSendingCalls(){const e=this.context.connection.connectionId;for(const t of this._sendingStreams.keys()){const i=this._sendingStreams.get(t)||[];for(const n of this.context.connection.usersInRoom()){if(n===e)continue;const s=this.peer.getPeerIdFromUserId(n);if(i.find(r=>r.peerId===s&&r.direction==="outgoing"&&!r.isClosed&&r.stream?.active))je&&console.debug("Already have a call with user "+n+" / peer "+s);else{const r=this.peer.makeCall(s,t);r&&i.push(r)}}this._sendingStreams.set(t,i)}this.stopCallsToUsersThatAreNotInTheRoomAnymore()}stopCallsToUsersThatAreNotInTheRoomAnymore(){for(const e of this._sendingStreams.keys()){const t=this._sendingStreams.get(e);if(t)for(let i=t.length-1;i>=0;i--){const n=t[i];this.context.connection.userIsInRoom(n.userId)?je&&(this.context.connection.connectionId===n.userId?console.warn(`You are still in the room [${i}] ${n.userId}`):console.log(`User is still in room [${i}] ${n.userId}`)):(je&&console.log(`Remove call ${[i]} to user that is not in room anymore ${n.userId}`),n.close(),t.splice(i,1))}}this.peer.updateCalls(),this.debug&&this.debugLogCurrentState()}debugLogCurrentState(){console.warn(`You (${this.context.connection.connectionId}) are currently sending ${this._sendingStreams.size} and receiving ${this.peer.incomingCalls.length} calls (${this.peer.incomingCalls.map(e=>e.userId).join(", ")})`,this.peer.incomingCalls)}}function io(o){if(o&&o instanceof MediaStream)for(const e of o.getTracks())e.stop()}var MR=Object.defineProperty,Vf=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&MR(e,t,n),n};const ER="noVoip",RR=w("debugvoip");class Ds extends E{autoConnect=!0;runInBackground=!0;createMenuButton=!0;debug=!1;_net;_menubutton;awake(){RR&&(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=wd.create(this)),this.debug&&(this._net.debug=!0),this._net.addEventListener(to.StreamReceived,this.onReceiveStream),this._net.addEventListener(to.StreamEnded,this.onStreamEnded),this._net.enable(),this.autoConnect&&this.context.connection.isConnected&&this.connect(),this.context.connection.beginListen(ie.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(ie.LeftRoom,this.onLeftRoom),this.onEnabledChanged(),this.updateButton(),window.addEventListener("visibilitychange",this.onVisibilityChanged)}onDisable(){this._net&&(this._net.stopSendingStream(this._outputStream),this._net.removeEventListener(to.StreamReceived,this.onReceiveStream),this._net.removeEventListener(to.StreamEnded,this.onStreamEnded),this._net?.disable()),this.context.connection.stopListen(ie.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(ie.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 I.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),io(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 I.microphonePermissionsGranted()?console.error("VOIP: Could not get audio stream - please make sure to connect an audio device and grant microphone permissions"):_c("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),io(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(),I.microphonePermissionsGranted().then(e=>{e||be("<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 I.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()&&be("VOIP: getFrequency is currently not supported"),console.warn("VOIP: getFrequency is currently not supported")),null}async getAudioStream(e){if(!navigator.mediaDevices.getUserMedia)return console.error("No getDisplayMedia support"),null;const t=async n=>await navigator.mediaDevices.getUserMedia({audio:n??!0,video:!1}).catch(s=>(console.warn("VOIP failed getting audio stream",s),null)),i=await t(e);if(!i)return null;if(I.isiOS()&&e?.deviceId===void 0){const n=(await navigator.mediaDevices.enumerateDevices()).find(s=>(s.kind==="audioinput"||s.kind==="audiooutput")&&!s.label.includes("iPhone"));if(n){const s=Object.assign({},e);return s.deviceId=n.deviceId,await t(s)}}return i}onJoinedRoom=async()=>{this.debug&&console.log("VOIP: Joined room"),await To(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())io(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"),Nn.registerWaitForInteraction(()=>{n?.play().catch(s=>{console.error("VOIP: Failed to play audio",s)})})};onStreamEnded=e=>{const t=this._incomingStreams.get(e.userId);io(t?.srcObject),this._incomingStreams.delete(e.userId)};onEnabledChanged=()=>{for(const e of this._incomingStreams){const t=e[1];t.muted=!this.enabled}};onVisibilityChanged=()=>{if(this.runInBackground)return;const e=document.visibilityState!=="visible";this.setMuted(e);for(const t of this._incomingStreams){const i=t[1];i.muted=e}}}Vf([u()],Ds.prototype,"autoConnect"),Vf([u()],Ds.prototype,"runInBackground"),Vf([u()],Ds.prototype,"createMenuButton");var TR=Object.defineProperty,_x=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&TR(e,t,n),n};const AR=w("debugmouth");class th extends E{idle=[];talking=[];marker=null;voip=null;lastMouthChangeTime=0;mouthChangeLength=0;awake(){setTimeout(()=>{this.voip=S.findObjectOfType(Ds,this.context),this.marker||(this.marker=S.getComponentInParent(this.gameObject,Le))},3e3)}update(){if(!this.voip||this.context.time.frameCount%10!==0)return;let e=this.marker?.connectionId??null;if(!e){AR&&(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)}}}}_x([u(M)],th.prototype,"idle"),_x([u(M)],th.prototype,"talking");class $f extends E{voip=null;marker=null;_startPosition=null;awake(){this.voip=S.findObjectOfType(Ds,this.context),this.marker=S.getComponentInParent(this.gameObject,Le)}update(){if(!this.voip||!this.marker||this.context.time.frameCount%10!==0)return;const e=this.marker.connectionId,t=this.voip.getFrequency(e);if(t==null)return;this._startPosition||(this._startPosition=this.gameObject.position.clone());const i=t/100;this.gameObject.position.y=this._startPosition.y+i*.07}}var IR=Object.defineProperty,LR=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&IR(e,t,n),n};const dl=w("debugxrflags"),vx=w("disablexrflags");vx&&console.warn("XRFlags are disabled");var no=(o=>(o[o.Never=0]="Never",o[o.Browser=1]="Browser",o[o.AR=2]="AR",o[o.VR=4]="VR",o[o.FirstPerson=8]="FirstPerson",o[o.ThirdPerson=16]="ThirdPerson",o[o.All=4294967295]="All",o))(no||{});class ai{static Global=new ai;Mask=17;Has(e){return(this.Mask&e)!==0}Set(e){dl&&console.warn("Set XR flag state to",e),this.Mask=e,tn.Apply()}Enable(e){this.Mask|=e,tn.Apply()}Disable(e){this.Mask&=~e,tn.Apply()}Toggle(e){this.Mask^=e,tn.Apply()}EnableAll(){this.Mask=-1,tn.Apply()}DisableAll(){this.Mask=0,tn.Apply()}}const wx=class ds extends E{static registry=[];static Apply(){for(const e of this.registry)e.UpdateVisible(ai.Global)}static firstApply;static buffer=new ai;visibleIn;awake(){ds.registry.push(this)}onEnable(){ds.firstApply?this.UpdateVisible(ai.Global):(ds.firstApply=!0,ds.Apply())}onDestroy(){const e=ds.registry.indexOf(this);e>=0&&ds.registry.splice(e,1)}get isOn(){return this.gameObject.visible}UpdateVisible(e=null){if(vx)return;let t;const i=e;if(i&&typeof i=="number"&&(console.assert(typeof i=="number","XRFlag.UpdateVisible: state must be a number",i),dl&&console.log(i),ds.buffer.Mask=i,e=ds.buffer),e instanceof ai?(dl&&console.warn(this.name,"use passed in mask",e.Mask,this.visibleIn),t=e.Has(this.visibleIn)):(dl&&console.log(this.name,"use global mask"),ai.Global.Has(this.visibleIn)),t!==void 0)if(t)dl&&console.log(this.name,"is visible",this.gameObject.uuid),S.setActive(this.gameObject,!0);else{if(dl&&console.log(this.name,"is not visible",this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}};LR([u()],wx.prototype,"visibleIn");let tn=wx;var jR=Object.defineProperty,Hu=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&jR(e,t,n),n};class Gr extends E{eyes=[];lastBlinkTime=0;blinkLength=0;eyesOpen=!0;state=null;awake(){this.state=S.getComponentInParent(this.gameObject,tn)}update(){if(!(!this.gameObject||!this.gameObject.visible||!this.eyes||!Array.isArray(this.eyes)||this.eyes.length===0)&&this.context.time.time-this.lastBlinkTime>this.blinkLength){if(this.lastBlinkTime=this.context.time.time,this.state&&!this.state.isOn||!this.activeAndEnabled)return;if(this.eyesOpen=!this.eyesOpen,this.blinkLength=Math.random(),this.eyesOpen?(this.blinkLength*=3,this.blinkLength+=.5,Math.random()<.1&&(this.blinkLength=.1+Math.random()*.2)):(this.blinkLength*=Math.random()*.2,this.blinkLength+=.1),Math.random()<.1&&(this.blinkLength*=3),this.blinkLength=Math.max(.2,this.blinkLength),this.blinkLength=Math.min(3,this.blinkLength),this.eyes)for(const e of this.eyes)e&&(e.visible=this.eyesOpen)}}}Hu([u(M)],Gr.prototype,"eyes"),Hu([u()],Gr.prototype,"lastBlinkTime"),Hu([u()],Gr.prototype,"blinkLength"),Hu([u()],Gr.prototype,"eyesOpen");var DR=Object.defineProperty,Hf=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&DR(e,t,n),n};const Gu=class jS extends E{head=null;eyes=null;target=null;brain=null;awake(){this.brain||(this.brain=S.getComponentInParent(this.gameObject,eh)),this.brain||(this.brain=S.addComponent(this.gameObject,eh)),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}vec=new b;static forward=new b(0,0,1);currentTargetPoint=new b;update(){const e=this.target;if(e&&this.head){const t=this.eyes;if(t){const i=ee(e);this.currentTargetPoint.lerp(i,this.context.time.deltaTime/.1);const n=ee(this.head),s=this.vec.copy(this.currentTargetPoint).sub(n).normalize();if(s.length()<.1)return;const r=jS.forward;if(r.set(0,0,1),r.applyQuaternion(_e(this.head)),r.dot(s)>.45)for(let a=0;a<t.length;a++)t[a].lookAt(this.currentTargetPoint)}}}};Hf([u(M)],Gu.prototype,"head"),Hf([u(M)],Gu.prototype,"eyes"),Hf([u(M)],Gu.prototype,"target");let Gf=Gu;var BR=Object.defineProperty,qf=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&BR(e,t,n),n};class ul extends E{length=1;depthTest=!0;isGizmo=!1;_axes=null;onEnable(){if(this.isGizmo&&!jc)return;this._axes||(this._axes=new Pi(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)}}qf([u()],ul.prototype,"length"),qf([u()],ul.prototype,"depthTest"),qf([u()],ul.prototype,"isGizmo");class Xf extends E{from;to;hint;desiredDistance=1;onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;const e=ee(this.to).clone(),t=ee(this.from).clone(),i=e.distanceTo(t),n=e.clone();n.sub(t);const s=t.clone();s.add(e),s.multiplyScalar(.5);const r=ee(this.hint).clone();r.sub(s);const a=new b;a.crossVectors(r,n),a.crossVectors(n,a),a.normalize();const l=i*.5,c=Math.max(this.desiredDistance,l),h=Math.sqrt(c*c-l*l),d=a.clone();d.multiplyScalar(h),d.add(s),yt(this.gameObject,d);const p=s.clone();p.sub(a),this.gameObject.lookAt(p)}}const FR=w("gizmos"),UR=w("debugboxhelper");class Bt extends E{box=null;static testBox=new Yt;_lastMatrixUpdateFrame=-1;static _position=new b;static _size=new b(.01,.01,.01);static _emptyObjectSize=new b(.01,.01,.01);isInBox(e){if(!e)return;if(this.box||(this.box=new Yt),di([e],void 0,void 0,Bt.testBox),Bt.testBox.isEmpty()){const i=ee(e,Bt._position);Bt.testBox.setFromCenterAndSize(i,Bt._emptyObjectSize)}this.updateBox();const t=this.box?.intersectsBox(Bt.testBox);return t&&UR&&B.DrawWireBox3(Bt.testBox,16711680,5),t}intersects(e){return e?this.updateBox(!1).intersectsBox(e):!1}updateBox(e=!1){if(this.box||(this.box=new Yt),e||this.context.time.frameCount!=this._lastMatrixUpdateFrame){const t=this._lastMatrixUpdateFrame<0;this._lastMatrixUpdateFrame=this.context.time.frameCount;const i=t,n=ee(this.gameObject,Bt._position,i),s=$e(this.gameObject,Bt._size);this.box.setFromCenterAndSize(n,s)}return this.box}_helper=null;_color=null;awake(){this._helper=null,this._color=null,this.box=null}showHelper(e=null,t=!1){if(!(!FR&&!t)){if(this._helper){e&&this._color?.set(e),this.gameObject.add(this._helper);return}this._helper=iu(e),this.gameObject.add(this._helper)}}}var zR=Object.defineProperty,bi=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&zR(e,t,n),n};class nn extends E{get isCollider(){return!0}attachedRigidbody=null;isTrigger=!1;sharedMaterial;membership=[0];filter;awake(){super.awake(),this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Ke))}start(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Ke))}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Ke))}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)}}bi([u(Ke)],nn.prototype,"attachedRigidbody"),bi([u()],nn.prototype,"isTrigger"),bi([u()],nn.prototype,"sharedMaterial"),bi([u()],nn.prototype,"membership"),bi([u()],nn.prototype,"filter");class pl extends nn{radius=.5;center=new b(0,0,0);onEnable(){super.onEnable(),this.context.physics.engine?.addSphereCollider(this),Bd(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),Qm(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}}bi([kt(),u()],pl.prototype,"radius"),bi([u(b)],pl.prototype,"center");const Qf=class DS extends nn{static add(e,t){const i=Mn(e,DS);return i.autoFit(),t?.rigidbody===!0&&Mn(e,Ke,{isKinematic:!1}),i}size=new b(1,1,1);center=new b(0,0,0);onEnable(){super.onEnable(),this.context.physics.engine?.addBoxCollider(this,this.size),Bd(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),Qm(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}autoFit(e){const t=this.gameObject,i=t.position.clone(),n=t.quaternion.clone(),s=t.scale.clone(),r=t.parent;t.position.set(0,0,0),t.quaternion.set(0,0,0,1),t.scale.set(1,1,1),t.parent=null,t.updateMatrix();const a=di([t]);t.position.copy(i),t.quaternion.copy(n),t.scale.copy(s),t.parent=r,e?.debug===!0&&B.DrawWireBox3(a,16768256,20),this.size=a.getSize(new b)||new b(1,1,1),this.center=a.getCenter(new b)||new b(0,0,0),this.size.length()<=0&&this.size.set(.01,.01,.01)}};bi([kt(),u(b)],Qf.prototype,"size"),bi([u(b)],Qf.prototype,"center");let qu=Qf;class Bs extends nn{sharedMesh;convex=!1;onEnable(){if(super.onEnable(),!this.context.physics.engine)return;this.sharedMesh?.isMesh||(this.gameObject instanceof H||this.gameObject instanceof Po)&&(this.sharedMesh=this.gameObject);const e=0;if(this.sharedMesh?.isMesh)this.context.physics.engine.addMeshCollider(this,this.sharedMesh,this.convex),Ve.assignMeshLOD(this.sharedMesh,e).then(t=>{t&&this.activeAndEnabled&&this.context.physics.engine&&this.sharedMesh&&(this.context.physics.engine.removeBody(this),this.sharedMesh.geometry=t,this.context.physics.engine.addMeshCollider(this,this.sharedMesh,this.convex))});else{const t=this.sharedMesh;if(t?.isGroup){console.warn(`MeshCollider mesh is a group "${this.sharedMesh?.name||this.gameObject.name}", adding all children as colliders. This is currently not fully supported (colliders can not be removed from world again)`,this);const i=new Array;for(const n in t.children){const s=t.children[n];s.isMesh&&(this.context.physics.engine.addMeshCollider(this,s,this.convex),i.push(Ve.assignMeshLOD(s,e)))}Promise.all(i).then(n=>{if(n.some(r=>r)==!1)return;this.context.physics.engine?.removeBody(this);const s=new H;for(const r of n)r&&this.activeAndEnabled&&(s.geometry=r,this.context.physics.engine?.addMeshCollider(this,s,this.convex))})}else(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)}}}bi([u(H)],Bs.prototype,"sharedMesh"),bi([u()],Bs.prototype,"convex");class Vo extends nn{center=new b(0,0,0);radius=.5;height=2;onEnable(){super.onEnable(),this.context.physics.engine?.addCapsuleCollider(this,this.height,this.radius)}}bi([u(b)],Vo.prototype,"center"),bi([u()],Vo.prototype,"radius"),bi([u()],Vo.prototype,"height");var NR=Object.defineProperty,$o=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&NR(e,t,n),n};const xx=w("debugcharactercontroller");class qr extends E{center=new b(0,0,0);radius=.5;height=2;_rigidbody=null;get rigidbody(){return this._rigidbody?this._rigidbody:(this._rigidbody=this.gameObject.getComponent(Ke),this._rigidbody||(this._rigidbody=this.gameObject.addComponent(Ke)),this.rigidbody)}_activeGroundCollisions;awake(){this._activeGroundCollisions=new Set}onEnable(){const e=this.rigidbody;let t=this.gameObject.getComponent(Vo);t||(t=this.gameObject.addComponent(Vo)),t.center.copy(this.center),t.radius=this.radius,t.height=this.height;const i=new b(0,0,1),n=new b(1,0,0),s=new b(0,1,0),r=this.gameObject.getWorldDirection(new b);r.y=0;const a=n.dot(r)<0?-1:1,l=i.angleTo(r)*a;this.gameObject.setRotationFromAxisAngle(s,l),e.lockRotationX=!0,e.lockRotationY=!0,e.lockRotationZ=!0}move(e){this.gameObject.position.add(e)}onCollisionEnter(e){(e.contacts.length==0||e.contacts.some(t=>t.normal.y>.2))&&(this._activeGroundCollisions.add(e),xx&&console.log(`Collision(${this._activeGroundCollisions.size}): ${e.contacts.map(t=>t.normal.y.toFixed(2)).join(", ")} - ${this.isGrounded}`))}onCollisionExit(e){this._activeGroundCollisions.delete(e),xx&&console.log(`Collision(${this._activeGroundCollisions.size}) - ${this.isGrounded}`)}get isGrounded(){return this._activeGroundCollisions.size>0}_contactVelocity=new b;get contactVelocity(){this._contactVelocity.set(0,0,0);for(const e of this._activeGroundCollisions){const t=this.context.physics.engine?.getLinearVelocity(e.collider);t&&(this._contactVelocity.x+=t.x,this._contactVelocity.y+=t.y,this._contactVelocity.z+=t.z)}return this._contactVelocity}}$o([u(b)],qr.prototype,"center"),$o([u()],qr.prototype,"radius"),$o([u()],qr.prototype,"height");class Ho extends E{controller;movementSpeed=2;rotationSpeed=2;jumpForce=1;doubleJumpForce=2;animator;lookForward=!0;awake(){this._currentRotation=new N}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 K(0,0);moveInput=new K(0,0);jumpInput=!1;onBeforeRender(){this.handleInput(this.moveInput,this.lookInput,this.jumpInput),this.lookInput.set(0,0),this.moveInput.set(0,0),this.jumpInput=!1}_currentSpeed=new b(0,0,0);_currentAngularSpeed=new b(0,0,0);_temp=new b(0,0,0);_jumpCount=0;_currentRotation;handleInput(e,t,i){if(this.controller?.isGrounded&&(this._jumpCount=0,this.doubleJumpForce>0&&this.animator?.setBool("doubleJump",!1)),this._currentSpeed.z+=e.y*this.movementSpeed*this.context.time.deltaTime,this.animator?.setBool("running",e.length()>.01),this.animator?.setBool("jumping",this.controller?.isGrounded===!0&&i),this._temp.copy(this._currentSpeed),this._temp.applyQuaternion(this.gameObject.quaternion),this.controller?this.controller.move(this._temp):this.gameObject.position.add(this._temp),this._currentAngularSpeed.y+=D.toRadians(-t.x*this.rotationSpeed)*this.context.time.deltaTime,this.lookForward&&Math.abs(this._currentAngularSpeed.y)<.01){const n=this.context.mainCameraComponent.forward;n.y=0,n.normalize(),this._currentRotation.setFromUnitVectors(new b(0,0,1),n),this.gameObject.quaternion.slerp(this._currentRotation,this.context.time.deltaTime*10)}if(this.gameObject.rotateY(this._currentAngularSpeed.y),this._currentSpeed.multiplyScalar(1-this.context.time.deltaTime*10),this._currentAngularSpeed.y*=1-this.context.time.deltaTime*10,this.controller&&i&&this.jumpForce>0){let n=this.controller?.isGrounded;if(this.doubleJumpForce>0&&!this.controller?.isGrounded&&this._jumpCount===1&&(n=!0,this.animator?.setBool("doubleJump",!0)),n){this._jumpCount+=1;const s=this.controller.rigidbody,r=this._jumpCount===2?this.doubleJumpForce:this.jumpForce;s.applyImpulse(new b(0,1,0).multiplyScalar(r))}}if(this.controller){const n=this.controller?.rigidbody.getVelocity().y;if(n<-1){this._raycastOptions.ray||(this._raycastOptions.ray=new So),this._raycastOptions.ray.origin.copy(ee(this.gameObject)),this._raycastOptions.ray.direction.set(0,-1,0);const s=this.layer;this.gameObject.layers.disableAll(),this.gameObject.layers.set(2);const r=this.context.physics.raycast(this._raycastOptions);this.gameObject.layers.set(s),(r.length&&r[0].distance>2||n<-10)&&this.animator?.setBool("falling",!0)}else this.animator?.setBool("falling",!1)}}_raycastOptions=new ks}$o([u(qr)],Ho.prototype,"controller"),$o([u()],Ho.prototype,"movementSpeed"),$o([u()],Ho.prototype,"rotationSpeed"),$o([u()],Ho.prototype,"jumpForce"),$o([u()],Ho.prototype,"doubleJumpForce"),$o([u(_t)],Ho.prototype,"animator");var WR=Object.defineProperty,ml=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&WR(e,t,n),n};const ih=w("debugcontactshadows");Ru(o=>{const e=o.domElement.getAttribute("contactshadows")||o.domElement.getAttribute("contact-shadows");if(e!=null&&e!="0"&&e!="false"){console.debug("Auto-creating ContactShadows because of `contactshadows` attribute");const t=nh.auto(o),i=parseFloat(e);isNaN(i)||(t.opacity=i,t.darkness=i)}});const Xr=class gd extends E{static _instances=new Map;static auto(e,t){if(e||(e=U.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 M;n.name="ContactShadows",i=Mn(n,gd,{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 M;shadowCamera;shadowGroup=new Po;renderTarget;renderTargetBlur;plane;occluderMesh;blurPlane;planeMaterial;depthMaterial;horizontalBlurMaterial;verticalBlurMaterial;textureSize=512;fitShadows(e={}){ih&&console.warn("Fitting shadows to scene"),Nd(this.shadowsRoot,!1);const t=e.object||this.context.scene,i=di(t,[this.shadowsRoot]),n=Math.max(1,this.blur/32),s=i.max.x-i.min.x,r=i.max.z-i.min.z;i.expandByVector(new b(n*s,0,n*r)),ih&&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,ih&&console.log("Fitted shadows to scene",this.shadowsRoot.scale.clone())}awake(){gd._instances.set(this.context,this),this.shadowsRoot.hideFlags=Gd.DontExport,Nd(this.shadowsRoot,!1)}start(){ih&&console.log("Create ContactShadows on "+this.gameObject.name,this),this.gameObject.add(this.shadowsRoot),this.shadowsRoot.add(this.shadowGroup),this.renderTarget=new $n(this.textureSize,this.textureSize),this.renderTarget.texture.generateMipmaps=!1,this.renderTargetBlur=new $n(this.textureSize,this.textureSize),this.renderTargetBlur.texture.generateMipmaps=!1;const e=new vn(1,1).rotateX(Math.PI/2);this.gameObject instanceof H&&(console.warn("ContactShadows can not be added to a Mesh. Please add it to a Group or an empty Object"),Fo(this.gameObject,!1));const t=this.planeMaterial=new Ce({map:this.renderTarget.texture,opacity:this.opacity,color:0,transparent:!0,depthWrite:!1,side:ws});this.plane=new H(e,t),this.plane.scale.y=-1,this.plane.layers.set(2),this.shadowsRoot.add(this.plane),this.plane&&(this.plane.renderOrder=1),this.occluderMesh=new H(this.plane.geometry,new Ce({depthWrite:!0,stencilWrite:!0,colorWrite:!1,side:Id})).translateY(-1e-4),this.occluderMesh.renderOrder=-100,this.occluderMesh.layers.set(2),this.shadowsRoot.add(this.occluderMesh),this.blurPlane=new H(e),this.blurPlane.visible=!1,this.shadowGroup.add(this.blurPlane);const i=0,n=1;this.shadowCamera=new Cd(-1/2,1/2,1/2,-1/2,i,n),this.shadowCamera.layers.enableAll(),this.shadowCamera.rotation.x=Math.PI/2,this.shadowCamera.matrixWorldAutoUpdate=!1,this.shadowGroup.add(this.shadowCamera),this.shadowCamera.updateMatrix(),this.depthMaterial=new uC,this.depthMaterial.userData.darkness={value:this.darkness},this.depthMaterial.blending=pC,this.depthMaterial.blendEquation=mC,this.depthMaterial.onBeforeCompile=s=>{this.depthMaterial&&(s.uniforms.darkness=this.depthMaterial.userData.darkness,s.fragmentShader=`
|
|
979
|
+
Incoming:`,this._incomingCalls),s}else je&&console.error("Failed to make call",e,t,this._peer)}closeAll(){for(const e of this._incomingCalls)e.close();for(const e of this._outgoingCalls)e.close();this.updateCalls()}updateCalls=()=>{for(let e=this._incomingCalls.length-1;e>=0;e--){const t=this._incomingCalls[e];t.isClosed&&!t.isOpening&&this._incomingCalls.splice(e,1)}for(let e=this._outgoingCalls.length-1;e>=0;e--){const t=this._outgoingCalls[e];let i=!1;t.isClosed&&!t.isOpening&&(t.stream?.active?je&&console.warn("!!! Stream is still active, don't remove call",t.userId,"Your id: "+this.context.connection.connectionId):(je&&console.warn("!!! Remove closed call",t.userId),i=!0)),this.context.connection.userIsInRoom(t.userId)===!1&&(je&&console.warn("!!! User is not in room anymore, remove call",t.userId),i=!0),i&&(t.close(),this._outgoingCalls.splice(e,1))}};get peer(){return this._peer}get incomingCalls(){return this._incomingCalls}id;context;_incomingCalls=[];_outgoingCalls=[];_peer;constructor(e,t){super(),this.context=e,this.id=t,this.setupPeer();const i=Object.getOwnPropertyDescriptor(navigator,"getUserMedia")?.writable;try{i?navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia:je&&console.warn("[PeerJs] getUserMedia is not writable")}catch(n){je&&console.error("[PeerJs] Error setting getUserMedia",n)}}_enabled=!1;_enabledPeer=!1;onConnectRoomFn=this.onConnectRoom.bind(this);enable(){this._enabled||(this._enabled=!0,this.context.connection.beginListen(ie.JoinedRoom,this.onConnectRoomFn),this.subscribePeerEvents())}disable(){this._enabled&&(this._enabled=!1,this.context.connection.stopListen(ie.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=lv(e):console.error("Failed to setup peerjs because we dont have a connection id",this.context.connection.connectionId)}this._enabled&&this.subscribePeerEvents()}}subscribePeerEvents(){this._peer&&(this._peer.on("open",this.onPeerConnect),this._peer.on("close",this.onPeerClose),this._peer.on("call",this.onPeerReceivingCall),this._peer.on("disconnected",this.onPeerDisconnected),this._peer.on("error",this.onPeerError))}unsubscribePeerEvents(){this._peer&&(this._peer.off("open",this.onPeerConnect),this._peer.off("close",this.onPeerClose),this._peer.off("call",this.onPeerReceivingCall),this._peer.off("disconnected",this.onPeerDisconnected),this._peer.off("error",this.onPeerError))}onPeerConnect=e=>{if(je&&console.log("PEER opened as",e),e===null){console.error("Peer connection failed",e);return}this.context.connection.send("peer-user-connected",new OR(this,e))};onPeerClose=()=>{je&&console.log("PEER closed"),this.updateCalls()};onPeerDisconnected=()=>{je&&console.log("PEER disconnected"),this.updateCalls()};onPeerError=e=>{je&&console.error("PEER error",e)};onPeerReceivingCall=e=>{e.answer(void 0,{sdpTransform:t=>bx(t)}),this.registerCall(e,"incoming",null)};registerCall(e,t,i){const n=e.metadata;(!n||!n.userId)&&console.error("Missing call metadata",e);const s=n.userId;t==="incoming"&&je?console.warn("\u2190 Receive call from",e.metadata,e.connectionId):je&&console.warn("\u2192 Make call to",e.metadata);const r=t==="incoming"?this._incomingCalls:this._outgoingCalls,a=new kR(s,e,t,i);return r.push(a),e.on("error",l=>{console.error("Call error",l)}),e.on("close",()=>{je&&console.log("Call ended",e.metadata);const l=r.indexOf(a);l!==-1&&r.splice(l,1),a.close(),this.dispatchEvent(new Wf(s,t))}),a.addEventListener("call-ended",l=>{this.dispatchEvent(l)}),t==="incoming"&&(a.addEventListener("receive-stream",l=>{this.dispatchEvent(l)}),e.on("stream",()=>{je&&console.log("Received stream for call",e.metadata);let l=0;const c=setInterval(()=>{const h=l===0;!a.isOpen&&h&&(je&&console.warn("Close call because stream is not active",e.metadata),l+=1,clearInterval(c),a.close())},2e3)})),a}}class wd extends jm{static create(e,t){const i=fs.getOrCreate(e.context,t||e.context.connection.connectionId||e.guid);return new wd(e.context,i)}context;peer;_sendingStreams=new Map;debug=!1;constructor(e,t){if(super(),vg(e)){const i=e;e=i.context,t=fs.getOrCreate(i.context,i.guid)}else typeof t=="string"&&(t=fs.getOrCreate(e,t));if(e){if(!(e instanceof U))throw new Error("Failed to create NetworkedStreams because context is not an instance of Context")}else throw new Error("Failed to create NetworkedStreams because context is undefined");if(!t)throw new Error("Failed to create NetworkedStreams because peer is undefined");this.context=e,this.peer=t,je&&(this.debug=!0)}startSendingStream(e){this._sendingStreams.has(e)?console.warn("Received start sending stream with stream that is already being sent"):(this._sendingStreams.set(e,[]),this.updateSendingCalls())}stopSendingStream(e){if(e){const t=this._sendingStreams.get(e);if(t){for(const i of t)i.close();t.length=0}this._sendingStreams.delete(e),t&&this.debug&&this.debugLogCurrentState()}this.updateSendingCalls()}_enabled=!1;get enabled(){return this._enabled}enable(){this._enabled||(this._enabled=!0,this.peer.enable(),this.peer.addEventListener("receive-stream",this.onCallStreamReceived),this.peer.addEventListener("call-ended",this.onCallEnded),this.context.connection.beginListen("peer-user-connected",this.onUserConnected),this.context.connection.beginListen(ie.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(ie.UserJoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(ie.UserLeftRoom,this.onUserLeft),this.context.connection.beginListen(ie.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(ie.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(ie.UserJoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(ie.UserLeftRoom,this.onUserLeft),this.context.connection.stopListen(ie.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;if(!t)return;this.peer.makeCall(e.peerId,t)}else je&&console.log("Unknown user connected",e.guid,e.peerId)};onUserLeft=e=>{this.debug&&console.log("User left room: "+e.userId),this.stopCallsToUsersThatAreNotInTheRoomAnymore()};updateSendingCalls(){const e=this.context.connection.connectionId;for(const t of this._sendingStreams.keys()){const i=this._sendingStreams.get(t)||[];for(const n of this.context.connection.usersInRoom()){if(n===e)continue;const s=this.peer.getPeerIdFromUserId(n);if(i.find(r=>r.peerId===s&&r.direction==="outgoing"&&!r.isClosed&&r.stream?.active))je&&console.debug("Already have a call with user "+n+" / peer "+s);else{const r=this.peer.makeCall(s,t);r&&i.push(r)}}this._sendingStreams.set(t,i)}this.stopCallsToUsersThatAreNotInTheRoomAnymore()}stopCallsToUsersThatAreNotInTheRoomAnymore(){for(const e of this._sendingStreams.keys()){const t=this._sendingStreams.get(e);if(t)for(let i=t.length-1;i>=0;i--){const n=t[i];this.context.connection.userIsInRoom(n.userId)?je&&(this.context.connection.connectionId===n.userId?console.warn(`You are still in the room [${i}] ${n.userId}`):console.log(`User is still in room [${i}] ${n.userId}`)):(je&&console.log(`Remove call ${[i]} to user that is not in room anymore ${n.userId}`),n.close(),t.splice(i,1))}}this.peer.updateCalls(),this.debug&&this.debugLogCurrentState()}debugLogCurrentState(){console.warn(`You (${this.context.connection.connectionId}) are currently sending ${this._sendingStreams.size} and receiving ${this.peer.incomingCalls.length} calls (${this.peer.incomingCalls.map(e=>e.userId).join(", ")})`,this.peer.incomingCalls)}}function io(o){if(o&&o instanceof MediaStream)for(const e of o.getTracks())e.stop()}var MR=Object.defineProperty,Vf=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&MR(e,t,n),n};const ER="noVoip",RR=w("debugvoip");class Ds extends E{autoConnect=!0;runInBackground=!0;createMenuButton=!0;debug=!1;_net;_menubutton;awake(){RR&&(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=wd.create(this)),this.debug&&(this._net.debug=!0),this._net.addEventListener(to.StreamReceived,this.onReceiveStream),this._net.addEventListener(to.StreamEnded,this.onStreamEnded),this._net.enable(),this.autoConnect&&this.context.connection.isConnected&&this.connect(),this.context.connection.beginListen(ie.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(ie.LeftRoom,this.onLeftRoom),this.onEnabledChanged(),this.updateButton(),window.addEventListener("visibilitychange",this.onVisibilityChanged)}onDisable(){this._net&&(this._net.stopSendingStream(this._outputStream),this._net.removeEventListener(to.StreamReceived,this.onReceiveStream),this._net.removeEventListener(to.StreamEnded,this.onStreamEnded),this._net?.disable()),this.context.connection.stopListen(ie.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(ie.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 I.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),io(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 I.microphonePermissionsGranted()?console.error("VOIP: Could not get audio stream - please make sure to connect an audio device and grant microphone permissions"):_c("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),io(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(),I.microphonePermissionsGranted().then(e=>{e||be("<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 I.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()&&be("VOIP: getFrequency is currently not supported"),console.warn("VOIP: getFrequency is currently not supported")),null}async getAudioStream(e){if(!navigator.mediaDevices.getUserMedia)return console.error("No getDisplayMedia support"),null;const t=async n=>await navigator.mediaDevices.getUserMedia({audio:n??!0,video:!1}).catch(s=>(console.warn("VOIP failed getting audio stream",s),null)),i=await t(e);if(!i)return null;if(I.isiOS()&&e?.deviceId===void 0){const n=(await navigator.mediaDevices.enumerateDevices()).find(s=>(s.kind==="audioinput"||s.kind==="audiooutput")&&!s.label.includes("iPhone"));if(n){const s=Object.assign({},e);return s.deviceId=n.deviceId,await t(s)}}return i}onJoinedRoom=async()=>{this.debug&&console.log("VOIP: Joined room"),await To(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())io(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"),Nn.registerWaitForInteraction(()=>{n?.play().catch(s=>{console.error("VOIP: Failed to play audio",s)})})};onStreamEnded=e=>{const t=this._incomingStreams.get(e.userId);io(t?.srcObject),this._incomingStreams.delete(e.userId)};onEnabledChanged=()=>{for(const e of this._incomingStreams){const t=e[1];t.muted=!this.enabled}};onVisibilityChanged=()=>{if(this.runInBackground)return;const e=document.visibilityState!=="visible";this.setMuted(e);for(const t of this._incomingStreams){const i=t[1];i.muted=e}}}Vf([u()],Ds.prototype,"autoConnect"),Vf([u()],Ds.prototype,"runInBackground"),Vf([u()],Ds.prototype,"createMenuButton");var TR=Object.defineProperty,_x=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&TR(e,t,n),n};const AR=w("debugmouth");class th extends E{idle=[];talking=[];marker=null;voip=null;lastMouthChangeTime=0;mouthChangeLength=0;awake(){setTimeout(()=>{this.voip=S.findObjectOfType(Ds,this.context),this.marker||(this.marker=S.getComponentInParent(this.gameObject,Le))},3e3)}update(){if(!this.voip||this.context.time.frameCount%10!==0)return;let e=this.marker?.connectionId??null;if(!e){AR&&(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)}}}}_x([u(M)],th.prototype,"idle"),_x([u(M)],th.prototype,"talking");class $f extends E{voip=null;marker=null;_startPosition=null;awake(){this.voip=S.findObjectOfType(Ds,this.context),this.marker=S.getComponentInParent(this.gameObject,Le)}update(){if(!this.voip||!this.marker||this.context.time.frameCount%10!==0)return;const e=this.marker.connectionId,t=this.voip.getFrequency(e);if(t==null)return;this._startPosition||(this._startPosition=this.gameObject.position.clone());const i=t/100;this.gameObject.position.y=this._startPosition.y+i*.07}}var IR=Object.defineProperty,LR=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&IR(e,t,n),n};const dl=w("debugxrflags"),vx=w("disablexrflags");vx&&console.warn("XRFlags are disabled");var no=(o=>(o[o.Never=0]="Never",o[o.Browser=1]="Browser",o[o.AR=2]="AR",o[o.VR=4]="VR",o[o.FirstPerson=8]="FirstPerson",o[o.ThirdPerson=16]="ThirdPerson",o[o.All=4294967295]="All",o))(no||{});class ai{static Global=new ai;Mask=17;Has(e){return(this.Mask&e)!==0}Set(e){dl&&console.warn("Set XR flag state to",e),this.Mask=e,tn.Apply()}Enable(e){this.Mask|=e,tn.Apply()}Disable(e){this.Mask&=~e,tn.Apply()}Toggle(e){this.Mask^=e,tn.Apply()}EnableAll(){this.Mask=-1,tn.Apply()}DisableAll(){this.Mask=0,tn.Apply()}}const wx=class ds extends E{static registry=[];static Apply(){for(const e of this.registry)e.UpdateVisible(ai.Global)}static firstApply;static buffer=new ai;visibleIn;awake(){ds.registry.push(this)}onEnable(){ds.firstApply?this.UpdateVisible(ai.Global):(ds.firstApply=!0,ds.Apply())}onDestroy(){const e=ds.registry.indexOf(this);e>=0&&ds.registry.splice(e,1)}get isOn(){return this.gameObject.visible}UpdateVisible(e=null){if(vx)return;let t;const i=e;if(i&&typeof i=="number"&&(console.assert(typeof i=="number","XRFlag.UpdateVisible: state must be a number",i),dl&&console.log(i),ds.buffer.Mask=i,e=ds.buffer),e instanceof ai?(dl&&console.warn(this.name,"use passed in mask",e.Mask,this.visibleIn),t=e.Has(this.visibleIn)):(dl&&console.log(this.name,"use global mask"),ai.Global.Has(this.visibleIn)),t!==void 0)if(t)dl&&console.log(this.name,"is visible",this.gameObject.uuid),S.setActive(this.gameObject,!0);else{if(dl&&console.log(this.name,"is not visible",this.gameObject.uuid),!this.gameObject.visible)return;this.gameObject.visible=!1}}};LR([u()],wx.prototype,"visibleIn");let tn=wx;var jR=Object.defineProperty,Hu=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&jR(e,t,n),n};class Gr extends E{eyes=[];lastBlinkTime=0;blinkLength=0;eyesOpen=!0;state=null;awake(){this.state=S.getComponentInParent(this.gameObject,tn)}update(){if(!(!this.gameObject||!this.gameObject.visible||!this.eyes||!Array.isArray(this.eyes)||this.eyes.length===0)&&this.context.time.time-this.lastBlinkTime>this.blinkLength){if(this.lastBlinkTime=this.context.time.time,this.state&&!this.state.isOn||!this.activeAndEnabled)return;if(this.eyesOpen=!this.eyesOpen,this.blinkLength=Math.random(),this.eyesOpen?(this.blinkLength*=3,this.blinkLength+=.5,Math.random()<.1&&(this.blinkLength=.1+Math.random()*.2)):(this.blinkLength*=Math.random()*.2,this.blinkLength+=.1),Math.random()<.1&&(this.blinkLength*=3),this.blinkLength=Math.max(.2,this.blinkLength),this.blinkLength=Math.min(3,this.blinkLength),this.eyes)for(const e of this.eyes)e&&(e.visible=this.eyesOpen)}}}Hu([u(M)],Gr.prototype,"eyes"),Hu([u()],Gr.prototype,"lastBlinkTime"),Hu([u()],Gr.prototype,"blinkLength"),Hu([u()],Gr.prototype,"eyesOpen");var DR=Object.defineProperty,Hf=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&DR(e,t,n),n};const Gu=class jS extends E{head=null;eyes=null;target=null;brain=null;awake(){this.brain||(this.brain=S.getComponentInParent(this.gameObject,eh)),this.brain||(this.brain=S.addComponent(this.gameObject,eh)),this.brain&&this.target&&(this.brain.controlledTarget=this.target)}vec=new b;static forward=new b(0,0,1);currentTargetPoint=new b;update(){const e=this.target;if(e&&this.head){const t=this.eyes;if(t){const i=ee(e);this.currentTargetPoint.lerp(i,this.context.time.deltaTime/.1);const n=ee(this.head),s=this.vec.copy(this.currentTargetPoint).sub(n).normalize();if(s.length()<.1)return;const r=jS.forward;if(r.set(0,0,1),r.applyQuaternion(_e(this.head)),r.dot(s)>.45)for(let a=0;a<t.length;a++)t[a].lookAt(this.currentTargetPoint)}}}};Hf([u(M)],Gu.prototype,"head"),Hf([u(M)],Gu.prototype,"eyes"),Hf([u(M)],Gu.prototype,"target");let Gf=Gu;var BR=Object.defineProperty,qf=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&BR(e,t,n),n};class ul extends E{length=1;depthTest=!0;isGizmo=!1;_axes=null;onEnable(){if(this.isGizmo&&!jc)return;this._axes||(this._axes=new Pi(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)}}qf([u()],ul.prototype,"length"),qf([u()],ul.prototype,"depthTest"),qf([u()],ul.prototype,"isGizmo");class Xf extends E{from;to;hint;desiredDistance=1;onEnable(){}update(){if(!this.from||!this.to||!this.hint)return;const e=ee(this.to).clone(),t=ee(this.from).clone(),i=e.distanceTo(t),n=e.clone();n.sub(t);const s=t.clone();s.add(e),s.multiplyScalar(.5);const r=ee(this.hint).clone();r.sub(s);const a=new b;a.crossVectors(r,n),a.crossVectors(n,a),a.normalize();const l=i*.5,c=Math.max(this.desiredDistance,l),h=Math.sqrt(c*c-l*l),d=a.clone();d.multiplyScalar(h),d.add(s),yt(this.gameObject,d);const p=s.clone();p.sub(a),this.gameObject.lookAt(p)}}const FR=w("gizmos"),UR=w("debugboxhelper");class Bt extends E{box=null;static testBox=new Yt;_lastMatrixUpdateFrame=-1;static _position=new b;static _size=new b(.01,.01,.01);static _emptyObjectSize=new b(.01,.01,.01);isInBox(e){if(!e)return;if(this.box||(this.box=new Yt),di([e],void 0,void 0,Bt.testBox),Bt.testBox.isEmpty()){const i=ee(e,Bt._position);Bt.testBox.setFromCenterAndSize(i,Bt._emptyObjectSize)}this.updateBox();const t=this.box?.intersectsBox(Bt.testBox);return t&&UR&&B.DrawWireBox3(Bt.testBox,16711680,5),t}intersects(e){return e?this.updateBox(!1).intersectsBox(e):!1}updateBox(e=!1){if(this.box||(this.box=new Yt),e||this.context.time.frameCount!=this._lastMatrixUpdateFrame){const t=this._lastMatrixUpdateFrame<0;this._lastMatrixUpdateFrame=this.context.time.frameCount;const i=t,n=ee(this.gameObject,Bt._position,i),s=$e(this.gameObject,Bt._size);this.box.setFromCenterAndSize(n,s)}return this.box}_helper=null;_color=null;awake(){this._helper=null,this._color=null,this.box=null}showHelper(e=null,t=!1){if(!(!FR&&!t)){if(this._helper){e&&this._color?.set(e),this.gameObject.add(this._helper);return}this._helper=iu(e),this.gameObject.add(this._helper)}}}var zR=Object.defineProperty,bi=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&zR(e,t,n),n};class nn extends E{get isCollider(){return!0}attachedRigidbody=null;isTrigger=!1;sharedMaterial;membership=[0];filter;awake(){super.awake(),this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Ke))}start(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Ke))}onEnable(){this.attachedRigidbody||(this.attachedRigidbody=this.gameObject.getComponentInParent(Ke))}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)}}bi([u(Ke)],nn.prototype,"attachedRigidbody"),bi([u()],nn.prototype,"isTrigger"),bi([u()],nn.prototype,"sharedMaterial"),bi([u()],nn.prototype,"membership"),bi([u()],nn.prototype,"filter");class pl extends nn{radius=.5;center=new b(0,0,0);onEnable(){super.onEnable(),this.context.physics.engine?.addSphereCollider(this),Bd(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),Qm(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}}bi([kt(),u()],pl.prototype,"radius"),bi([u(b)],pl.prototype,"center");const Qf=class DS extends nn{static add(e,t){const i=Mn(e,DS);return i.autoFit(),t?.rigidbody===!0&&Mn(e,Ke,{isKinematic:!1}),i}size=new b(1,1,1);center=new b(0,0,0);onEnable(){super.onEnable(),this.context.physics.engine?.addBoxCollider(this,this.size),Bd(this.gameObject.scale,this.updateProperties)}onDisable(){super.onDisable(),Qm(this.gameObject.scale,this.updateProperties)}onValidate(){this.updateProperties()}autoFit(e){const t=this.gameObject,i=t.position.clone(),n=t.quaternion.clone(),s=t.scale.clone(),r=t.parent;t.position.set(0,0,0),t.quaternion.set(0,0,0,1),t.scale.set(1,1,1),t.parent=null,t.updateMatrix();const a=di([t]);t.position.copy(i),t.quaternion.copy(n),t.scale.copy(s),t.parent=r,e?.debug===!0&&B.DrawWireBox3(a,16768256,20),this.size=a.getSize(new b)||new b(1,1,1),this.center=a.getCenter(new b)||new b(0,0,0),this.size.length()<=0&&this.size.set(.01,.01,.01)}};bi([kt(),u(b)],Qf.prototype,"size"),bi([u(b)],Qf.prototype,"center");let qu=Qf;class Bs extends nn{sharedMesh;convex=!1;onEnable(){if(super.onEnable(),!this.context.physics.engine)return;this.sharedMesh?.isMesh||(this.gameObject instanceof H||this.gameObject instanceof Po)&&(this.sharedMesh=this.gameObject);const e=0;if(this.sharedMesh?.isMesh)this.context.physics.engine.addMeshCollider(this,this.sharedMesh,this.convex),Ve.assignMeshLOD(this.sharedMesh,e).then(t=>{t&&this.activeAndEnabled&&this.context.physics.engine&&this.sharedMesh&&(this.context.physics.engine.removeBody(this),this.sharedMesh.geometry=t,this.context.physics.engine.addMeshCollider(this,this.sharedMesh,this.convex))});else{const t=this.sharedMesh;if(t?.isGroup){console.warn(`MeshCollider mesh is a group "${this.sharedMesh?.name||this.gameObject.name}", adding all children as colliders. This is currently not fully supported (colliders can not be removed from world again)`,this);const i=new Array;for(const n in t.children){const s=t.children[n];s.isMesh&&(this.context.physics.engine.addMeshCollider(this,s,this.convex),i.push(Ve.assignMeshLOD(s,e)))}Promise.all(i).then(n=>{if(n.some(r=>r)==!1)return;this.context.physics.engine?.removeBody(this);const s=new H;for(const r of n)r&&this.activeAndEnabled&&(s.geometry=r,this.context.physics.engine?.addMeshCollider(this,s,this.convex))})}else(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)}}}bi([u(H)],Bs.prototype,"sharedMesh"),bi([u()],Bs.prototype,"convex");class Vo extends nn{center=new b(0,0,0);radius=.5;height=2;onEnable(){super.onEnable(),this.context.physics.engine?.addCapsuleCollider(this,this.height,this.radius)}}bi([u(b)],Vo.prototype,"center"),bi([u()],Vo.prototype,"radius"),bi([u()],Vo.prototype,"height");var NR=Object.defineProperty,$o=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&NR(e,t,n),n};const xx=w("debugcharactercontroller");class qr extends E{center=new b(0,0,0);radius=.5;height=2;_rigidbody=null;get rigidbody(){return this._rigidbody?this._rigidbody:(this._rigidbody=this.gameObject.getComponent(Ke),this._rigidbody||(this._rigidbody=this.gameObject.addComponent(Ke)),this.rigidbody)}_activeGroundCollisions;awake(){this._activeGroundCollisions=new Set}onEnable(){const e=this.rigidbody;let t=this.gameObject.getComponent(Vo);t||(t=this.gameObject.addComponent(Vo)),t.center.copy(this.center),t.radius=this.radius,t.height=this.height;const i=new b(0,0,1),n=new b(1,0,0),s=new b(0,1,0),r=this.gameObject.getWorldDirection(new b);r.y=0;const a=n.dot(r)<0?-1:1,l=i.angleTo(r)*a;this.gameObject.setRotationFromAxisAngle(s,l),e.lockRotationX=!0,e.lockRotationY=!0,e.lockRotationZ=!0}move(e){this.gameObject.position.add(e)}onCollisionEnter(e){(e.contacts.length==0||e.contacts.some(t=>t.normal.y>.2))&&(this._activeGroundCollisions.add(e),xx&&console.log(`Collision(${this._activeGroundCollisions.size}): ${e.contacts.map(t=>t.normal.y.toFixed(2)).join(", ")} - ${this.isGrounded}`))}onCollisionExit(e){this._activeGroundCollisions.delete(e),xx&&console.log(`Collision(${this._activeGroundCollisions.size}) - ${this.isGrounded}`)}get isGrounded(){return this._activeGroundCollisions.size>0}_contactVelocity=new b;get contactVelocity(){this._contactVelocity.set(0,0,0);for(const e of this._activeGroundCollisions){const t=this.context.physics.engine?.getLinearVelocity(e.collider);t&&(this._contactVelocity.x+=t.x,this._contactVelocity.y+=t.y,this._contactVelocity.z+=t.z)}return this._contactVelocity}}$o([u(b)],qr.prototype,"center"),$o([u()],qr.prototype,"radius"),$o([u()],qr.prototype,"height");class Ho extends E{controller;movementSpeed=2;rotationSpeed=2;jumpForce=1;doubleJumpForce=2;animator;lookForward=!0;awake(){this._currentRotation=new N}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 K(0,0);moveInput=new K(0,0);jumpInput=!1;onBeforeRender(){this.handleInput(this.moveInput,this.lookInput,this.jumpInput),this.lookInput.set(0,0),this.moveInput.set(0,0),this.jumpInput=!1}_currentSpeed=new b(0,0,0);_currentAngularSpeed=new b(0,0,0);_temp=new b(0,0,0);_jumpCount=0;_currentRotation;handleInput(e,t,i){if(this.controller?.isGrounded&&(this._jumpCount=0,this.doubleJumpForce>0&&this.animator?.setBool("doubleJump",!1)),this._currentSpeed.z+=e.y*this.movementSpeed*this.context.time.deltaTime,this.animator?.setBool("running",e.length()>.01),this.animator?.setBool("jumping",this.controller?.isGrounded===!0&&i),this._temp.copy(this._currentSpeed),this._temp.applyQuaternion(this.gameObject.quaternion),this.controller?this.controller.move(this._temp):this.gameObject.position.add(this._temp),this._currentAngularSpeed.y+=j.toRadians(-t.x*this.rotationSpeed)*this.context.time.deltaTime,this.lookForward&&Math.abs(this._currentAngularSpeed.y)<.01){const n=this.context.mainCameraComponent.forward;n.y=0,n.normalize(),this._currentRotation.setFromUnitVectors(new b(0,0,1),n),this.gameObject.quaternion.slerp(this._currentRotation,this.context.time.deltaTime*10)}if(this.gameObject.rotateY(this._currentAngularSpeed.y),this._currentSpeed.multiplyScalar(1-this.context.time.deltaTime*10),this._currentAngularSpeed.y*=1-this.context.time.deltaTime*10,this.controller&&i&&this.jumpForce>0){let n=this.controller?.isGrounded;if(this.doubleJumpForce>0&&!this.controller?.isGrounded&&this._jumpCount===1&&(n=!0,this.animator?.setBool("doubleJump",!0)),n){this._jumpCount+=1;const s=this.controller.rigidbody,r=this._jumpCount===2?this.doubleJumpForce:this.jumpForce;s.applyImpulse(new b(0,1,0).multiplyScalar(r))}}if(this.controller){const n=this.controller?.rigidbody.getVelocity().y;if(n<-1){this._raycastOptions.ray||(this._raycastOptions.ray=new So),this._raycastOptions.ray.origin.copy(ee(this.gameObject)),this._raycastOptions.ray.direction.set(0,-1,0);const s=this.layer;this.gameObject.layers.disableAll(),this.gameObject.layers.set(2);const r=this.context.physics.raycast(this._raycastOptions);this.gameObject.layers.set(s),(r.length&&r[0].distance>2||n<-10)&&this.animator?.setBool("falling",!0)}else this.animator?.setBool("falling",!1)}}_raycastOptions=new ks}$o([u(qr)],Ho.prototype,"controller"),$o([u()],Ho.prototype,"movementSpeed"),$o([u()],Ho.prototype,"rotationSpeed"),$o([u()],Ho.prototype,"jumpForce"),$o([u()],Ho.prototype,"doubleJumpForce"),$o([u(_t)],Ho.prototype,"animator");var WR=Object.defineProperty,ml=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&WR(e,t,n),n};const ih=w("debugcontactshadows");Ru(o=>{const e=o.domElement.getAttribute("contactshadows")||o.domElement.getAttribute("contact-shadows");if(e!=null&&e!="0"&&e!="false"){console.debug("Auto-creating ContactShadows because of `contactshadows` attribute");const t=nh.auto(o),i=parseFloat(e);isNaN(i)||(t.opacity=i,t.darkness=i)}});const Xr=class gd extends E{static _instances=new Map;static auto(e,t){if(e||(e=U.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 M;n.name="ContactShadows",i=Mn(n,gd,{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 M;shadowCamera;shadowGroup=new Po;renderTarget;renderTargetBlur;plane;occluderMesh;blurPlane;planeMaterial;depthMaterial;horizontalBlurMaterial;verticalBlurMaterial;textureSize=512;fitShadows(e={}){ih&&console.warn("Fitting shadows to scene"),Nd(this.shadowsRoot,!1);const t=e.object||this.context.scene,i=di(t,[this.shadowsRoot]),n=Math.max(1,this.blur/32),s=i.max.x-i.min.x,r=i.max.z-i.min.z;i.expandByVector(new b(n*s,0,n*r)),ih&&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,ih&&console.log("Fitted shadows to scene",this.shadowsRoot.scale.clone())}awake(){gd._instances.set(this.context,this),this.shadowsRoot.hideFlags=Gd.DontExport,Nd(this.shadowsRoot,!1)}start(){ih&&console.log("Create ContactShadows on "+this.gameObject.name,this),this.gameObject.add(this.shadowsRoot),this.shadowsRoot.add(this.shadowGroup),this.renderTarget=new $n(this.textureSize,this.textureSize),this.renderTarget.texture.generateMipmaps=!1,this.renderTargetBlur=new $n(this.textureSize,this.textureSize),this.renderTargetBlur.texture.generateMipmaps=!1;const e=new vn(1,1).rotateX(Math.PI/2);this.gameObject instanceof H&&(console.warn("ContactShadows can not be added to a Mesh. Please add it to a Group or an empty Object"),Fo(this.gameObject,!1));const t=this.planeMaterial=new Ce({map:this.renderTarget.texture,opacity:this.opacity,color:0,transparent:!0,depthWrite:!1,side:ws});this.plane=new H(e,t),this.plane.scale.y=-1,this.plane.layers.set(2),this.shadowsRoot.add(this.plane),this.plane&&(this.plane.renderOrder=1),this.occluderMesh=new H(this.plane.geometry,new Ce({depthWrite:!0,stencilWrite:!0,colorWrite:!1,side:Id})).translateY(-1e-4),this.occluderMesh.renderOrder=-100,this.occluderMesh.layers.set(2),this.shadowsRoot.add(this.occluderMesh),this.blurPlane=new H(e),this.blurPlane.visible=!1,this.shadowGroup.add(this.blurPlane);const i=0,n=1;this.shadowCamera=new Cd(-1/2,1/2,1/2,-1/2,i,n),this.shadowCamera.layers.enableAll(),this.shadowCamera.rotation.x=Math.PI/2,this.shadowCamera.matrixWorldAutoUpdate=!1,this.shadowGroup.add(this.shadowCamera),this.shadowCamera.updateMatrix(),this.depthMaterial=new uC,this.depthMaterial.userData.darkness={value:this.darkness},this.depthMaterial.blending=pC,this.depthMaterial.blendEquation=mC,this.depthMaterial.onBeforeCompile=s=>{this.depthMaterial&&(s.uniforms.darkness=this.depthMaterial.userData.darkness,s.fragmentShader=`
|
|
980
980
|
uniform float darkness;
|
|
981
981
|
${s.fragmentShader.replace("gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );","gl_FragColor = vec4( vec3( 1.0 ), ( 1.0 - fragCoordZ ) * darkness * opacity * (gl_FrontFacing ? 1.0 : 0.66) );")}
|
|
982
982
|
`)},this.depthMaterial.depthTest=!1,this.depthMaterial.depthWrite=!1,this.horizontalBlurMaterial=new Vn(yP),this.horizontalBlurMaterial.depthTest=!1,this.verticalBlurMaterial=new Vn(bP),this.verticalBlurMaterial.depthTest=!1,this.shadowGroup.visible=!1,this.autoFit?this.fitShadows():this.applyMinSize()}onEnable(){this._needsUpdate=!0}onDestroy(){gd._instances.get(this.context)===this&&gd._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||!this.planeMaterial){ih&&console.error("ContactShadows: not initialized yet");return}this.depthMaterial.userData.darkness.value=this.darkness,this.planeMaterial.opacity=this.opacity;const t=this.context.scene,i=this.context.renderer,n=i.getRenderTarget();this.shadowGroup.visible=!0,this.occluderMesh&&(this.occluderMesh.visible=!1);const s=this.plane.visible;this.plane.visible=!1,this.gameObject instanceof H&&Fo(this.gameObject,!1);const r=t.background;t.background=null,t.overrideMaterial=this.depthMaterial,this.backfaceShadows?this.depthMaterial.side=Oi:this.depthMaterial.side=ws;const a=i.getClearAlpha();i.setClearAlpha(0);const l=i.xr.enabled;i.xr.enabled=!1;const c=this.context.scene.matrixWorldAutoUpdate;this.context.scene.matrixWorldAutoUpdate=!1;const h=i.renderLists.get(t,0),d=h.transparent;Sx.length=0,h.transparent=Sx,Yf.length=0;for(const m of h.opaque){if(!m.object.visible)continue;const g=m.material;let f=m.material.colorWrite==!1||g.wireframe===!0||k_(m.object)===!1;!f&&m.material.isLineMaterial&&(f=!0),!f&&m.material.isPointsMaterial&&(f=!0),f&&(Yf.push(m.object),m.object["needle:visible"]=m.object.visible,m.object.visible=!1)}this.shadowCamera.parent?this.shadowCamera.matrixWorld.multiplyMatrices(this.shadowCamera.parent.matrixWorld,this.shadowCamera.matrix):this.shadowCamera.matrixWorld.copy(this.shadowCamera.matrix),this.shadowCamera.matrixWorldInverse.copy(this.shadowCamera.matrixWorld).invert(),i.setRenderTarget(this.renderTarget),i.clear(),i.render(t,this.shadowCamera),h.transparent=d;for(const m of Yf)m["needle:visible"]!=null&&(m.visible=m["needle:visible"]);t.overrideMaterial=null;const p=Math.max(this.blur,.05);this.blurShadow(p*2),this.blurShadow(p*.5),this.shadowGroup.visible=!1,this.occluderMesh&&(this.occluderMesh.visible=this.occludeBelowGround),this.plane.visible=s,i.setRenderTarget(n),i.setClearAlpha(a),t.background=r,i.xr.enabled=l,this.context.scene.matrixWorldAutoUpdate=c}blurShadow(e){if(!this.blurPlane||!this.shadowCamera||!this.renderTarget||!this.renderTargetBlur||!this.horizontalBlurMaterial||!this.verticalBlurMaterial)return;this.blurPlane.visible=!0;const t=this.shadowsRoot.worldScale,i=(t.x+t.z)/2,n=t.z/i,s=t.x/i;this.blurPlane.material=this.horizontalBlurMaterial,this.blurPlane.material.uniforms.tDiffuse.value=this.renderTarget.texture,this.horizontalBlurMaterial.uniforms.h.value=e*1/this.textureSize*n;const r=this.context.renderer,a=r.getRenderTarget();r.setRenderTarget(this.renderTargetBlur),r.render(this.blurPlane,this.shadowCamera),this.blurPlane.material=this.verticalBlurMaterial,this.blurPlane.material.uniforms.tDiffuse.value=this.renderTargetBlur.texture,this.verticalBlurMaterial.uniforms.v.value=e*1/this.textureSize*s,r.setRenderTarget(this.renderTarget),r.render(this.blurPlane,this.shadowCamera),this.blurPlane.visible=!1,r.setRenderTarget(a)}applyMinSize(){this.minSize&&this.shadowsRoot.scale.set(Math.max(this.minSize.x||0,this.shadowsRoot.scale.x),Math.max(this.minSize.y||0,this.shadowsRoot.scale.y),Math.max(this.minSize.z||0,this.shadowsRoot.scale.z))}};ml([u()],Xr.prototype,"autoFit"),ml([u()],Xr.prototype,"darkness"),ml([u()],Xr.prototype,"opacity"),ml([u()],Xr.prototype,"blur"),ml([u()],Xr.prototype,"occludeBelowGround"),ml([u()],Xr.prototype,"backfaceShadows");let nh=Xr;const Sx=[],Yf=new Array,VR=w("logstats");class Zf extends E{onEnable(){console.log(this),VR&&this.startCoroutine(this.run(),xe.OnAfterRender)}*run(){for(;this.enabled;){const e=this.context.renderer.info;console.log(e.memory,e.render,e.programs),yield}}}class oh extends E{isUsed=!0;usedBy=null}class Kf extends E{}const Cx=w("debugdeletable");class gr extends Bt{static _instances=[];onEnable(){gr._instances.push(this)}onDisable(){const e=gr._instances.indexOf(this);e>=0&&gr._instances.splice(e,1)}}class Jf extends E{update(){for(const e of gr._instances){const t=this.gameObject;if(e.isInBox(t)===!0){const i=S.getComponentInParent(this.gameObject,oh);if(i)Cx&&console.warn("DeleteBox: Not deleting object with usage marker",this.guid,i);else{if(Cx)try{if(e.box){const n=e.box,s=Bt.testBox;B.DrawWireBox3(n,16711680,5),B.DrawWireBox3(s,255,5),console.log("DeleteBox: Destroying",this.gameObject,{deleteBoxArea:n,deletedObjectArea:s})}else console.log("DeleteBox: Destroying",this.gameObject)}catch{}Lc(this.gameObject,this.context.connection)}}}}}var $R=Object.defineProperty,HR=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&$R(e,t,n),n};class Xu extends E{visibleOn;onEnable(){this.apply()}apply(){this.test()||S.setActive(this.gameObject,!1)}test(){return this.visibleOn<0?!0:I.isMobileDevice()?(this.visibleOn&2)!==0:(this.visibleOn&1)!==0}}HR([u()],Xu.prototype,"visibleOn");var GR=Object.defineProperty,Qr=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&GR(e,t,n),n};const oo=w("debugdrag"),ey=[];var ty=(o=>(o[o.XZPlane=0]="XZPlane",o[o.Attached=1]="Attached",o[o.HitNormal=2]="HitNormal",o[o.DynamicViewAngle=3]="DynamicViewAngle",o[o.SnapToSurfaces=4]="SnapToSurfaces",o[o.None=5]="None",o))(ty||{});const Fs=class dn extends E{static get HasAnySelected(){return this._active>0}static _active=0;static get CurrentlySelected(){ey.length=0;for(const e of this._instances)e._isDragging&&ey.push(e);return ey}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,Ke),this._rigidbody?.isKinematic===!1&&(this._rigidbody.isKinematic=!0,this._rigidbody[t]=!1))}_rigidbody=null;_targetObject=null;_dragHelper=null;static lastHovered;_draggingRigidbodies=[];_potentialDragStartEvt=null;_dragHandlers=new Map;_totalMovement=new b;_marker=null;_isDragging=!1;_didDrag=!1;awake(){this._potentialDragStartEvt=null,this._dragHandlers=new Map,this._totalMovement=new b,this._marker=null,this._isDragging=!1,this._didDrag=!1,this._dragHelper=null,this._draggingRigidbodies=[]}start(){this.gameObject.getComponentInParent(Ji)||this.gameObject.addComponent(Ji)}onEnable(){dn._instances.push(this),this.context.accessibility.updateElement(this,{role:"button",label:"Drag "+(this.gameObject.name||"object"),hidden:!1})}onDisable(){this.context.accessibility.updateElement(this,{hidden:!0}),dn._instances=dn._instances.filter(e=>e!==this)}onDestroy(){this.context.accessibility.removeElement(this)}allowEdit(e=null){return this.context.connection.allowEditing}onPointerEnter(e){if(!this.allowEdit(this.gameObject)||e.mode!=="screen"||(e.event.mode==="tracked-pointer"||e.event.mode==="transient-pointer"?this.xrDragMode:this.dragMode)===5)return;const t=S.getComponentInParent(e.object,dn);!t||t!==this||(dn.lastHovered=e.object,this.context.domElement.style.cursor="pointer",this.context.accessibility.hover(this,`Draggable ${e.object?.name}`))}onPointerMove(e){(this._isDragging||this._potentialDragStartEvt!==null)&&e.use()}onPointerExit(e){this.allowEdit(this.gameObject)&&e.mode==="screen"&&dn.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)&&(dn.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),dn._active+=1;const t=new iy(this,this._targetObject);if(this._dragHandlers.set(e.event.space,t),t.onDragStart(e),this._dragHandlers.size===2){const i=this._dragHandlers.values(),n=i.next().value,s=i.next().value;if(n instanceof iy&&s instanceof iy){const r=new qR(this,this._targetObject,n,s);this._dragHandlers.set(this.gameObject,r),r.onDragStart(e)}else console.error("Attempting to construct a MultiTouchDragHandler with invalid DragPointerHandlers. This is likely a bug.",{a:n,b:s})}e.use(),this.context.accessibility.updateElement(this,{role:"button",label:"Dragging "+(this.gameObject.name||"object"),hidden:!1,busy:!0}),this.context.accessibility.focus(this)}}onPointerUp(e){if(oo&&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&&(dn._active>0&&(dn._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()),this.context.accessibility.unfocus(this),this.context.accessibility.updateElement(this,{busy:!1})}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,dn);if(!t||t!==this&&t._isDragging)return;const i=this._targetObject||this.gameObject;if(!i)return;this._isDragging=!0;const n=S.getComponentInChildren(i,Tn);oo&&console.log("DRAG START",n,i),n&&(n.fastMode=!0,n?.requestOwnership()),this._marker=S.addComponent(i,oh),this._draggingRigidbodies.length=0;const s=S.getComponentsInChildren(i,Ke);s&&this._draggingRigidbodies.push(...s),i.matrixAutoUpdate===!1&&!globalThis["DragControls:MatrixWarningShown"]&&(globalThis["DragControls:MatrixWarningShown"]=!0,console.warn("Dragging an object with matrixAutoUpdate=false can lead to unexpected behavior. Consider enabling matrixAutoUpdate or updating the matrix manually during dragging."))}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;pn.markDirty(e)}onLastDragEnd(e){if(!this||!this._isDragging)return;this._isDragging=!1;for(const i of this._draggingRigidbodies)i.setVelocity(i.smoothedVelocity.multiplyScalar(this.context.time.deltaTime));if(this._draggingRigidbodies.length=0,this._targetObject=null,e?.object){const i=S.getComponentInChildren(e.object,Tn);i&&(i.fastMode=!1)}if(this._marker&&this._marker.destroy(),!this._dragHelper)return;const t=this._dragHelper.selected;oo&&console.log("DRAG END",t,t?.visible),this._dragHelper.setSelected(null,this.context)}};Qr([u()],Fs.prototype,"dragMode"),Qr([u()],Fs.prototype,"snapGridResolution"),Qr([u()],Fs.prototype,"keepRotation"),Qr([u()],Fs.prototype,"xrDragMode"),Qr([u()],Fs.prototype,"xrKeepRotation"),Qr([u()],Fs.prototype,"xrDistanceDragFactor"),Qr([u()],Fs.prototype,"showGizmo");let Yr=Fs;class qR{handlerA;handlerB;context;settings;gameObject;_handlerAAttachmentPoint=new b;_handlerBAttachmentPoint=new b;_followObject;_manipulatorObject;_deviceMode;_followObjectStartWorldQuaternion=new N;constructor(e,t,i,n){this.context=e.context,this.settings=e,this.gameObject=t,this.handlerA=i,this.handlerB=n,this._followObject=new M,this._manipulatorObject=new M,this.context.scene.add(this._manipulatorObject);const s=Z.active?.rig?.gameObject;if(!this.handlerA||!this.handlerB||!this.handlerA.hitPointInLocalSpace||!this.handlerB.hitPointInLocalSpace){console.error("Invalid: MultiTouchDragHandler needs two valid DragPointerHandlers with hitPointInLocalSpace set.");return}if(this._tempVec1.copy(this.handlerA.hitPointInLocalSpace),this._tempVec2.copy(this.handlerB.hitPointInLocalSpace),this.gameObject.localToWorld(this._tempVec1),this.gameObject.localToWorld(this._tempVec2),s&&(s.worldToLocal(this._tempVec1),s.worldToLocal(this._tempVec2)),this._initialDistance=this._tempVec1.distanceTo(this._tempVec2),this._initialDistance<.02?(oo&&console.log("Finding alternative drag attachment points since initial distance is too low: "+this._initialDistance.toFixed(2)),this.handlerA.followObject.parent.getWorldPosition(this._tempVec1),this.handlerB.followObject.parent.getWorldPosition(this._tempVec2),this._handlerAAttachmentPoint.copy(this._tempVec1),this._handlerBAttachmentPoint.copy(this._tempVec2),this.gameObject.worldToLocal(this._handlerAAttachmentPoint),this.gameObject.worldToLocal(this._handlerBAttachmentPoint),this._initialDistance=this._tempVec1.distanceTo(this._tempVec2),this._initialDistance<.001&&(console.warn("Not supported right now \u2013 controller drag points for multitouch are too close!"),this._initialDistance=1)):(this._handlerAAttachmentPoint.copy(this.handlerA.hitPointInLocalSpace),this._handlerBAttachmentPoint.copy(this.handlerB.hitPointInLocalSpace)),this._tempVec3.lerpVectors(this._tempVec1,this._tempVec2,.5),this._initialScale.copy(t.scale),oo){this._followObject.add(new Pi(2)),this._manipulatorObject.add(new Pi(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)+`
|
|
983
983
|
`+r(this._tempVec1)+`
|
|
984
|
-
`+r(this._tempVec2),.03,5)}}onDragStart(e){this.gameObject.add(this._followObject),this._followObject.matrixAutoUpdate=!1,this._followObject.matrix.identity(),this._deviceMode=e.mode,this._followObjectStartWorldQuaternion.copy(this._followObject.worldQuaternion),this.alignManipulator(),this._manipulatorObject.attach(this._followObject),this._manipulatorPosOffset.copy(this._followObject.position),this._manipulatorRotOffset.copy(this._followObject.quaternion),this._manipulatorScaleOffset.copy(this._followObject.scale)}onDragEnd(e){if(!this.handlerA||!this.handlerB){console.error("onDragEnd called on MultiTouchDragHandler without valid handlers. This is likely a bug.");return}this.handlerA.recenter(),this.handlerB.recenter(),this._manipulatorObject.removeFromParent(),this._followObject.removeFromParent(),this._manipulatorObject.destroy(),this._followObject.destroy()}_manipulatorPosOffset=new b;_manipulatorRotOffset=new N;_manipulatorScaleOffset=new b;_tempVec1=new b;_tempVec2=new b;_tempVec3=new b;tempLookMatrix=new J;_initialScale=new b;_initialDistance=0;alignManipulator(){if(!this.handlerA||!this.handlerB){console.error("alignManipulator called on MultiTouchDragHandler without valid handlers. This is likely a bug.",this);return}if(!this.handlerA.followObject||!this.handlerB.followObject){console.error("alignManipulator called on MultiTouchDragHandler without valid follow objects. This is likely a bug.",this.handlerA,this.handlerB);return}this._tempVec1.copy(this._handlerAAttachmentPoint),this._tempVec2.copy(this._handlerBAttachmentPoint),this.handlerA.followObject.localToWorld(this._tempVec1),this.handlerB.followObject.localToWorld(this._tempVec2),this._tempVec3.lerpVectors(this._tempVec1,this._tempVec2,.5),this._manipulatorObject.position.copy(this._tempVec3);const e=this.context.mainCamera;this.tempLookMatrix.lookAt(this._tempVec3,this._tempVec2,e.worldUp),this._manipulatorObject.quaternion.setFromRotationMatrix(this.tempLookMatrix);const t=this._tempVec1.distanceTo(this._tempVec2);this._manipulatorObject.scale.copy(this._initialScale).multiplyScalar(t/this._initialDistance),this._manipulatorObject.updateMatrix(),this._manipulatorObject.updateMatrixWorld(!0),oo&&(B.DrawLabel(this._tempVec3.clone().add(new b(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 s=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer"?this.settings.xrKeepRotation:this.settings.keepRotation;if(this.settings.snapGridResolution>0){const h=this._followObject.worldPosition,d=this.settings.snapGridResolution;h.x=Math.round(h.x/d)*d,h.y=Math.round(h.y/d)*d,h.z=Math.round(h.z/d)*d,this._followObject.worldPosition=h,this._followObject.updateMatrix()}s&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion,this._followObject.updateMatrix());const r=D.clamp01(this.context.time.deltaTime*e*t),a=i.worldPosition;a.lerp(n.worldPosition,r),i.worldPosition=a;const l=i.worldQuaternion;l.slerp(n.worldQuaternion,r),i.worldQuaternion=l;const c=i.worldScale;c.lerp(n.worldScale,r),i.worldScale=c,i.matrixAutoUpdate===!1&&i.updateMatrix()}setTargetObject(e){this.gameObject=e}}class iy{getTotalMovement(){return this._totalMovement}get followObject(){return this._followObject}get hitPointInLocalSpace(){return this._hitPointInLocalSpace}context;gameObject;settings;_lastRig=void 0;_followObject;_totalMovement=new b;_totalMovementAlongRayDirection=0;_grabStartDistance=0;_deviceMode;_followObjectStartPosition=new b;_followObjectStartQuaternion=new N;_followObjectStartWorldQuaternion=new N;_lastDragPosRigSpace;_tempVec=new b;_tempMat=new J;_hitPointInLocalSpace=new b;_hitNormalInLocalSpace=new b;_bottomCenter=new b;_backCenter=new b;_backBottomCenter=new b;_bounds=new Yt;_dragPlane=new _r(new b(0,1,0));_draggedOverObject=null;_draggedOverObjectLastSetUp=null;_draggedOverObjectLastNormal=new b;_draggedOverObjectDuration=0;setTargetObject(e){this.gameObject=e}constructor(e,t){this.settings=e,this.context=e.context,this.gameObject=t,this._followObject=new M}recenter(){if(!this._followObject.parent){console.warn("Error: space follow object doesn't have parent but recenter() is called. This is likely a bug");return}if(!this.gameObject){console.warn("Error: space follow object doesn't have a gameObject");return}const e=this._followObject.parent;this.gameObject.add(this._followObject),this._followObject.matrixAutoUpdate=!1,this._followObject.position.set(0,0,0),this._followObject.quaternion.set(0,0,0,1),this._followObject.scale.set(1,1,1),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0),e.attach(this._followObject),this._followObjectStartPosition.copy(this._followObject.position),this._followObjectStartQuaternion.copy(this._followObject.quaternion),this._followObjectStartWorldQuaternion.copy(this._followObject.worldQuaternion),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);const t=this._hitPointInLocalSpace.clone();this.gameObject.localToWorld(t),this._grabStartDistance=t.distanceTo(e.worldPosition);const i=Z.active?.rig?.gameObject?.worldScale.x||1;this._grabStartDistance/=i,this._totalMovementAlongRayDirection=0,this._lastDragPosRigSpace=void 0,oo&&(B.DrawLine(t,e.worldPosition,65280,.5,!1),B.DrawLabel(e.worldPosition.add(new b(0,.1,0)),this._grabStartDistance.toFixed(2),.03,.5))}onDragStart(e){if(!this.gameObject){console.warn("Error: space follow object doesn't have a gameObject");return}if(e.event.space.add(this._followObject),this._lastDragPosRigSpace=void 0,e.point&&e.normal)this._hitPointInLocalSpace.copy(e.point),this.gameObject.worldToLocal(this._hitPointInLocalSpace),this._hitNormalInLocalSpace.copy(e.normal);else if(e){const m=e.event.space,g=m.worldPosition;this.gameObject.worldToLocal(g),this._hitPointInLocalSpace.copy(g);const f=m.worldUp;this._tempMat.copy(this.gameObject.matrixWorld).invert(),f.transformDirection(this._tempMat),this._hitNormalInLocalSpace.copy(f)}this.recenter(),this._totalMovement.set(0,0,0),this._deviceMode=e.mode;const t=this._followObject.parent.worldForward,i=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer"?this.settings.xrDragMode:this.settings.dragMode,n=this._hitPointInLocalSpace.clone();switch(this.gameObject.localToWorld(n),i){case 0:const m=new b(0,1,0);this.gameObject.parent&&m.transformDirection(this.gameObject.parent.matrixWorld.clone().invert()),this._dragPlane.setFromNormalAndCoplanarPoint(m,n);break;case 2:const g=this._hitNormalInLocalSpace.clone();g.transformDirection(this.gameObject.matrixWorld),this._dragPlane.setFromNormalAndCoplanarPoint(g,n);break;case 1:this._dragPlane.setFromNormalAndCoplanarPoint(t,n);break;case 3:this.setPlaneViewAligned(n,!0);break;case 4:this.setPlaneViewAligned(n,!1);break}const s=this.gameObject.parent,r=this.gameObject.position.clone(),a=this.gameObject.quaternion.clone(),l=this.gameObject.scale.clone(),c=this.gameObject.matrixWorld.clone();s&&s.remove(this.gameObject),this.gameObject.position.set(0,0,0),this.gameObject.quaternion.set(0,0,0,1),this.gameObject.scale.set(1,1,1);const h=di([this.gameObject]);h.expandByPoint(this.gameObject.worldPosition);const d=new b;h.getCenter(d);const p=new b;h.getSize(p),this._bottomCenter.copy(d.clone().add(new b(0,-p.y/2,0))),this._backCenter.copy(d.clone().add(new b(0,0,p.z/2))),this._backBottomCenter.copy(d.clone().add(new b(0,-p.y/2,p.z/2))),this._bounds.copy(h),s&&s.add(this.gameObject),this.gameObject.position.copy(r),this.gameObject.quaternion.copy(a),this.gameObject.scale.copy(l),this.gameObject.matrixWorld.copy(c),this._draggedOverObject=null,this._draggedOverObjectLastSetUp=null,this._draggedOverObjectLastNormal.set(0,1,0),this._draggedOverObjectDuration=0}collectMovementInfo(){if(!this._followObject.parent)return;const e=this._followObject.parent;this._followObject.updateMatrix();const t=e.worldPosition,i=Z.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),oo){let s=t;i&&(s=s.clone(),s.transformDirection(i.matrixWorld)),B.DrawRay(s,n,255)}}onDragUpdate(e){if(e>1)return;const t=this.gameObject;if(!t||!this._followObject){console.warn("Warning: DragPointerHandler doesn't have a dragged object. This is likely a bug.");return}const i=this._followObject.parent;if(!i){console.warn("Warning: DragPointerHandler doesn't have a drag source. This is likely a bug.");return}this._followObject.updateMatrix();const n=i.worldPosition,s=i.worldForward,r=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer",a=r?this.settings.xrKeepRotation:this.settings.keepRotation,l=r?this.settings.xrDragMode:this.settings.dragMode;if(l===5)return;const c=10;a&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);let h=1,d=2;if(r&&this._grabStartDistance>.5){const v=1+this._totalMovementAlongRayDirection*(2*this.settings.xrDistanceDragFactor);h=Math.max(0,v),h=h*h*h}else this._grabStartDistance<=.5&&(d=3);this._followObject.position.copy(this._followObjectStartPosition),a||this._followObject.quaternion.copy(this._followObjectStartQuaternion),this._followObject.position.multiplyScalar(h),this._followObject.updateMatrix();const p=this._hasLastSurfaceHitPoint;this._hasLastSurfaceHitPoint=!1;const m=new So(n,s);if(l==4){const v=this.context.physics.raycastFromRay(m,{testObject:P=>P!==this.followObject&&P!==i&&P!==t});if(v.length>0){const P=v[0];if(this._draggedOverObject===P.object?this._draggedOverObjectDuration+=this.context.time.deltaTime:(this._draggedOverObject=P.object,this._draggedOverObjectDuration=0),P.face){this._hasLastSurfaceHitPoint=!0,this._lastSurfaceHitPoint.copy(P.point);const k=this._draggedOverObjectDuration>=.15,O=this._totalMovement.length()>=.001,j=F(P.normal||P.face.normal).applyQuaternion(P.object.worldQuaternion);if((k||O)&&(this._draggedOverObjectLastSetUp!==this._draggedOverObject||this._draggedOverObjectLastNormal.dot(j)<.999999||this.context.time.frame%60===0)){this._draggedOverObjectLastSetUp=this._draggedOverObject,this._draggedOverObjectLastNormal.copy(P.face.normal);const L=F(),V=F();this._bounds.getCenter(L),this._bounds.getSize(V),L.sub(V.multiplyScalar(.5).multiply(j)),this._hitPointInLocalSpace.copy(L),this._hitNormalInLocalSpace.copy(P.face.normal),this._bounds.getCenter(L),this._bounds.getSize(V),L.add(V.multiplyScalar(.5).multiply(P.face.normal));const W=F(this._hitPointInLocalSpace).add(L);this._followObject.localToWorld(W);const G=P.point;this._dragPlane.setFromNormalAndCoplanarPoint(j,G)}else if(!(k||O))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=F(this._hitPointInLocalSpace);this._followObject.localToWorld(v),oo&&B.DrawLine(v,this._tempVec,65535,0,!1),this._followObject.worldPosition=this._tempVec.multiplyScalar(2).sub(v),this._followObject.updateMatrix(),this._followObject.updateMatrix()}if(this.settings.snapGridResolution>0){const v=this._followObject.worldPosition,P=this.settings.snapGridResolution;v.x=Math.round(v.x/P)*P,v.y=Math.round(v.y/P)*P,v.z=Math.round(v.z/P)*P,this._followObject.worldPosition=v,this._followObject.updateMatrix()}a&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion,this._followObject.updateMatrix());const g=D.clamp01(this.context.time.deltaTime*c*d),f=D.clamp01(this.context.time.deltaTime*c*.5*d),y=t.worldPosition;y.lerp(this._followObject.worldPosition,g),t.worldPosition=y;const _=t.worldQuaternion;if(_.slerp(this._followObject.worldQuaternion,f),t.worldQuaternion=_,t.matrixAutoUpdate===!1&&t.updateMatrix(),oo){const v=this._hitPointInLocalSpace.clone();t.localToWorld(v),B.DrawSphere(v,.02,16711680);const P=this._hitNormalInLocalSpace.clone();P.applyQuaternion(_),B.DrawRay(v,P,16711680),B.DrawLabel(y.add(new b(0,.25,0)),`Distance: ${this._totalMovement.length().toFixed(2)}
|
|
984
|
+
`+r(this._tempVec2),.03,5)}}onDragStart(e){this.gameObject.add(this._followObject),this._followObject.matrixAutoUpdate=!1,this._followObject.matrix.identity(),this._deviceMode=e.mode,this._followObjectStartWorldQuaternion.copy(this._followObject.worldQuaternion),this.alignManipulator(),this._manipulatorObject.attach(this._followObject),this._manipulatorPosOffset.copy(this._followObject.position),this._manipulatorRotOffset.copy(this._followObject.quaternion),this._manipulatorScaleOffset.copy(this._followObject.scale)}onDragEnd(e){if(!this.handlerA||!this.handlerB){console.error("onDragEnd called on MultiTouchDragHandler without valid handlers. This is likely a bug.");return}this.handlerA.recenter(),this.handlerB.recenter(),this._manipulatorObject.removeFromParent(),this._followObject.removeFromParent(),this._manipulatorObject.destroy(),this._followObject.destroy()}_manipulatorPosOffset=new b;_manipulatorRotOffset=new N;_manipulatorScaleOffset=new b;_tempVec1=new b;_tempVec2=new b;_tempVec3=new b;tempLookMatrix=new J;_initialScale=new b;_initialDistance=0;alignManipulator(){if(!this.handlerA||!this.handlerB){console.error("alignManipulator called on MultiTouchDragHandler without valid handlers. This is likely a bug.",this);return}if(!this.handlerA.followObject||!this.handlerB.followObject){console.error("alignManipulator called on MultiTouchDragHandler without valid follow objects. This is likely a bug.",this.handlerA,this.handlerB);return}this._tempVec1.copy(this._handlerAAttachmentPoint),this._tempVec2.copy(this._handlerBAttachmentPoint),this.handlerA.followObject.localToWorld(this._tempVec1),this.handlerB.followObject.localToWorld(this._tempVec2),this._tempVec3.lerpVectors(this._tempVec1,this._tempVec2,.5),this._manipulatorObject.position.copy(this._tempVec3);const e=this.context.mainCamera;this.tempLookMatrix.lookAt(this._tempVec3,this._tempVec2,e.worldUp),this._manipulatorObject.quaternion.setFromRotationMatrix(this.tempLookMatrix);const t=this._tempVec1.distanceTo(this._tempVec2);this._manipulatorObject.scale.copy(this._initialScale).multiplyScalar(t/this._initialDistance),this._manipulatorObject.updateMatrix(),this._manipulatorObject.updateMatrixWorld(!0),oo&&(B.DrawLabel(this._tempVec3.clone().add(new b(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 s=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer"?this.settings.xrKeepRotation:this.settings.keepRotation;if(this.settings.snapGridResolution>0){const h=this._followObject.worldPosition,d=this.settings.snapGridResolution;h.x=Math.round(h.x/d)*d,h.y=Math.round(h.y/d)*d,h.z=Math.round(h.z/d)*d,this._followObject.worldPosition=h,this._followObject.updateMatrix()}s&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion,this._followObject.updateMatrix());const r=j.clamp01(this.context.time.deltaTime*e*t),a=i.worldPosition;a.lerp(n.worldPosition,r),i.worldPosition=a;const l=i.worldQuaternion;l.slerp(n.worldQuaternion,r),i.worldQuaternion=l;const c=i.worldScale;c.lerp(n.worldScale,r),i.worldScale=c,i.matrixAutoUpdate===!1&&i.updateMatrix()}setTargetObject(e){this.gameObject=e}}class iy{getTotalMovement(){return this._totalMovement}get followObject(){return this._followObject}get hitPointInLocalSpace(){return this._hitPointInLocalSpace}context;gameObject;settings;_lastRig=void 0;_followObject;_totalMovement=new b;_totalMovementAlongRayDirection=0;_grabStartDistance=0;_deviceMode;_followObjectStartPosition=new b;_followObjectStartQuaternion=new N;_followObjectStartWorldQuaternion=new N;_lastDragPosRigSpace;_tempVec=new b;_tempMat=new J;_hitPointInLocalSpace=new b;_hitNormalInLocalSpace=new b;_bottomCenter=new b;_backCenter=new b;_backBottomCenter=new b;_bounds=new Yt;_dragPlane=new _r(new b(0,1,0));_draggedOverObject=null;_draggedOverObjectLastSetUp=null;_draggedOverObjectLastNormal=new b;_draggedOverObjectDuration=0;setTargetObject(e){this.gameObject=e}constructor(e,t){this.settings=e,this.context=e.context,this.gameObject=t,this._followObject=new M}recenter(){if(!this._followObject.parent){console.warn("Error: space follow object doesn't have parent but recenter() is called. This is likely a bug");return}if(!this.gameObject){console.warn("Error: space follow object doesn't have a gameObject");return}const e=this._followObject.parent;this.gameObject.add(this._followObject),this._followObject.matrixAutoUpdate=!1,this._followObject.position.set(0,0,0),this._followObject.quaternion.set(0,0,0,1),this._followObject.scale.set(1,1,1),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0),e.attach(this._followObject),this._followObjectStartPosition.copy(this._followObject.position),this._followObjectStartQuaternion.copy(this._followObject.quaternion),this._followObjectStartWorldQuaternion.copy(this._followObject.worldQuaternion),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);const t=this._hitPointInLocalSpace.clone();this.gameObject.localToWorld(t),this._grabStartDistance=t.distanceTo(e.worldPosition);const i=Z.active?.rig?.gameObject?.worldScale.x||1;this._grabStartDistance/=i,this._totalMovementAlongRayDirection=0,this._lastDragPosRigSpace=void 0,oo&&(B.DrawLine(t,e.worldPosition,65280,.5,!1),B.DrawLabel(e.worldPosition.add(new b(0,.1,0)),this._grabStartDistance.toFixed(2),.03,.5))}onDragStart(e){if(!this.gameObject){console.warn("Error: space follow object doesn't have a gameObject");return}if(e.event.space.add(this._followObject),this._lastDragPosRigSpace=void 0,e.point&&e.normal)this._hitPointInLocalSpace.copy(e.point),this.gameObject.worldToLocal(this._hitPointInLocalSpace),this._hitNormalInLocalSpace.copy(e.normal);else if(e){const m=e.event.space,g=m.worldPosition;this.gameObject.worldToLocal(g),this._hitPointInLocalSpace.copy(g);const f=m.worldUp;this._tempMat.copy(this.gameObject.matrixWorld).invert(),f.transformDirection(this._tempMat),this._hitNormalInLocalSpace.copy(f)}this.recenter(),this._totalMovement.set(0,0,0),this._deviceMode=e.mode;const t=this._followObject.parent.worldForward,i=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer"?this.settings.xrDragMode:this.settings.dragMode,n=this._hitPointInLocalSpace.clone();switch(this.gameObject.localToWorld(n),i){case 0:const m=new b(0,1,0);this.gameObject.parent&&m.transformDirection(this.gameObject.parent.matrixWorld.clone().invert()),this._dragPlane.setFromNormalAndCoplanarPoint(m,n);break;case 2:const g=this._hitNormalInLocalSpace.clone();g.transformDirection(this.gameObject.matrixWorld),this._dragPlane.setFromNormalAndCoplanarPoint(g,n);break;case 1:this._dragPlane.setFromNormalAndCoplanarPoint(t,n);break;case 3:this.setPlaneViewAligned(n,!0);break;case 4:this.setPlaneViewAligned(n,!1);break}const s=this.gameObject.parent,r=this.gameObject.position.clone(),a=this.gameObject.quaternion.clone(),l=this.gameObject.scale.clone(),c=this.gameObject.matrixWorld.clone();s&&s.remove(this.gameObject),this.gameObject.position.set(0,0,0),this.gameObject.quaternion.set(0,0,0,1),this.gameObject.scale.set(1,1,1);const h=di([this.gameObject]);h.expandByPoint(this.gameObject.worldPosition);const d=new b;h.getCenter(d);const p=new b;h.getSize(p),this._bottomCenter.copy(d.clone().add(new b(0,-p.y/2,0))),this._backCenter.copy(d.clone().add(new b(0,0,p.z/2))),this._backBottomCenter.copy(d.clone().add(new b(0,-p.y/2,p.z/2))),this._bounds.copy(h),s&&s.add(this.gameObject),this.gameObject.position.copy(r),this.gameObject.quaternion.copy(a),this.gameObject.scale.copy(l),this.gameObject.matrixWorld.copy(c),this._draggedOverObject=null,this._draggedOverObjectLastSetUp=null,this._draggedOverObjectLastNormal.set(0,1,0),this._draggedOverObjectDuration=0}collectMovementInfo(){if(!this._followObject.parent)return;const e=this._followObject.parent;this._followObject.updateMatrix();const t=e.worldPosition,i=Z.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),oo){let s=t;i&&(s=s.clone(),s.transformDirection(i.matrixWorld)),B.DrawRay(s,n,255)}}onDragUpdate(e){if(e>1)return;const t=this.gameObject;if(!t||!this._followObject){console.warn("Warning: DragPointerHandler doesn't have a dragged object. This is likely a bug.");return}const i=this._followObject.parent;if(!i){console.warn("Warning: DragPointerHandler doesn't have a drag source. This is likely a bug.");return}this._followObject.updateMatrix();const n=i.worldPosition,s=i.worldForward,r=this._deviceMode==="tracked-pointer"||this._deviceMode==="transient-pointer",a=r?this.settings.xrKeepRotation:this.settings.keepRotation,l=r?this.settings.xrDragMode:this.settings.dragMode;if(l===5)return;const c=10;a&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion),this._followObject.updateMatrix(),this._followObject.updateMatrixWorld(!0);let h=1,d=2;if(r&&this._grabStartDistance>.5){const v=1+this._totalMovementAlongRayDirection*(2*this.settings.xrDistanceDragFactor);h=Math.max(0,v),h=h*h*h}else this._grabStartDistance<=.5&&(d=3);this._followObject.position.copy(this._followObjectStartPosition),a||this._followObject.quaternion.copy(this._followObjectStartQuaternion),this._followObject.position.multiplyScalar(h),this._followObject.updateMatrix();const p=this._hasLastSurfaceHitPoint;this._hasLastSurfaceHitPoint=!1;const m=new So(n,s);if(l==4){const v=this.context.physics.raycastFromRay(m,{testObject:P=>P!==this.followObject&&P!==i&&P!==t});if(v.length>0){const P=v[0];if(this._draggedOverObject===P.object?this._draggedOverObjectDuration+=this.context.time.deltaTime:(this._draggedOverObject=P.object,this._draggedOverObjectDuration=0),P.face){this._hasLastSurfaceHitPoint=!0,this._lastSurfaceHitPoint.copy(P.point);const k=this._draggedOverObjectDuration>=.15,O=this._totalMovement.length()>=.001,D=F(P.normal||P.face.normal).applyQuaternion(P.object.worldQuaternion);if((k||O)&&(this._draggedOverObjectLastSetUp!==this._draggedOverObject||this._draggedOverObjectLastNormal.dot(D)<.999999||this.context.time.frame%60===0)){this._draggedOverObjectLastSetUp=this._draggedOverObject,this._draggedOverObjectLastNormal.copy(P.face.normal);const L=F(),V=F();this._bounds.getCenter(L),this._bounds.getSize(V),L.sub(V.multiplyScalar(.5).multiply(D)),this._hitPointInLocalSpace.copy(L),this._hitNormalInLocalSpace.copy(P.face.normal),this._bounds.getCenter(L),this._bounds.getSize(V),L.add(V.multiplyScalar(.5).multiply(P.face.normal));const W=F(this._hitPointInLocalSpace).add(L);this._followObject.localToWorld(W);const G=P.point;this._dragPlane.setFromNormalAndCoplanarPoint(D,G)}else if(!(k||O))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=F(this._hitPointInLocalSpace);this._followObject.localToWorld(v),oo&&B.DrawLine(v,this._tempVec,65535,0,!1),this._followObject.worldPosition=this._tempVec.multiplyScalar(2).sub(v),this._followObject.updateMatrix(),this._followObject.updateMatrix()}if(this.settings.snapGridResolution>0){const v=this._followObject.worldPosition,P=this.settings.snapGridResolution;v.x=Math.round(v.x/P)*P,v.y=Math.round(v.y/P)*P,v.z=Math.round(v.z/P)*P,this._followObject.worldPosition=v,this._followObject.updateMatrix()}a&&(this._followObject.worldQuaternion=this._followObjectStartWorldQuaternion,this._followObject.updateMatrix());const g=j.clamp01(this.context.time.deltaTime*c*d),f=j.clamp01(this.context.time.deltaTime*c*.5*d),y=t.worldPosition;y.lerp(this._followObject.worldPosition,g),t.worldPosition=y;const _=t.worldQuaternion;if(_.slerp(this._followObject.worldQuaternion,f),t.worldQuaternion=_,t.matrixAutoUpdate===!1&&t.updateMatrix(),oo){const v=this._hitPointInLocalSpace.clone();t.localToWorld(v),B.DrawSphere(v,.02,16711680);const P=this._hitNormalInLocalSpace.clone();P.applyQuaternion(_),B.DrawRay(v,P,16711680),B.DrawLabel(y.add(new b(0,.25,0)),`Distance: ${this._totalMovement.length().toFixed(2)}
|
|
985
985
|
|
|
986
986
|
Along Ray: ${this._totalMovementAlongRayDirection.toFixed(2)}
|
|
987
987
|
|
|
@@ -989,7 +989,7 @@ Incoming:`,this._incomingCalls),s}else je&&console.error("Failed to make call",e
|
|
|
989
989
|
|
|
990
990
|
Device: ${this._deviceMode}
|
|
991
991
|
|
|
992
|
-
`,.03);const k=this._bottomCenter.clone(),O=this._backCenter.clone(),
|
|
992
|
+
`,.03);const k=this._bottomCenter.clone(),O=this._backCenter.clone(),D=this._backBottomCenter.clone();t.localToWorld(k),t.localToWorld(O),t.localToWorld(D),B.DrawSphere(k,.01,65280,0,!1),B.DrawSphere(O,.01,255,0,!1),B.DrawSphere(D,.01,16711935,0,!1),B.DrawLine(k,D,65535,0,!1),B.DrawLine(D,O,65535,0,!1)}}onDragEnd(e){console.assert(this._followObject.parent===e.event.space,"Drag end: _followObject is not parented to the space object"),this._followObject.removeFromParent(),this._followObject.destroy(),this._lastDragPosRigSpace=void 0}_hasLastSurfaceHitPoint=!1;_lastSurfaceHitPoint=new b;setPlaneViewAligned(e,t){if(!this._followObject.parent)return!1;const i=this._followObject.parent.worldForward,n=F(0,1,0),s=i,r=n.angleTo(s),a=.5;return t&&(r>Math.PI/2+a||r<Math.PI/2-a)?this._dragPlane.setFromNormalAndCoplanarPoint(n,e):this._dragPlane.setFromNormalAndCoplanarPoint(i,e),!0}}class BS{showGizmo=!0;useViewAngle=!0;get hasSelected(){return this._selected!==null&&this._selected!==void 0}get selected(){return this._selected}_selected=null;_context=null;_camera;_cameraPlane=new _r;_hasGroundPlane=!1;_groundPlane=new _r;_groundOffset=new b;_groundOffsetFactor=0;_groundDistance=0;_groundPlanePoint=new b;_raycaster=new Od;_cameraPlaneOffset=new b;_intersection=new b;_worldPosition=new b;_inverseMatrix=new J;_rbs=[];_groundLine;_groundMarker;static geometry=new wn().setFromPoints([new b(0,0,0),new b(0,-1,0)]);constructor(e){this._camera=e;const t=new Ia(BS.geometry),i=t.material;i.color=new oe(.4,.4,.4),t.layers.set(2),t.name="line",t.scale.y=1,this._groundLine=t;const n=new Pd(.5,22,22),s=new Ce({color:i.color}),r=new H(n,s);r.visible=!1,r.layers.set(2),this._groundMarker=r}setSelected(e,t){if(this._selected&&t)for(const i of this._rbs)i.wakeUp(),i.setVelocity(0,0,0);if(this._selected&&Hr.Remove(t,this._selected),this._selected=e,this._context=t,this._rbs.length=0,e?(t.scene.add(this._groundLine),t.scene.add(this._groundMarker)):(this._groundLine.removeFromParent(),this._groundMarker.removeFromParent()),this._selected){if(!t){console.error("DragHelper: no context");return}Hr.Add(t,this._selected,null),this._groundOffsetFactor=0,this._hasGroundPlane=!0,this._groundOffset.set(0,0,0),this._requireUpdateGroundPlane=!0,this.onUpdateScreenSpacePlane()}}_groundOffsetVector=new b(0,1,0);_requireUpdateGroundPlane=!0;_didDragOnGroundPlaneLastFrame=!1;onUpdate(e){this._selected}onUpdateWorldPosition(e,t,i){if(this._selected){if(i){const n=ee(this._selected);n.y=e.y,e=n}if(yt(this._selected,e),yt(this._groundLine,e),this._hasGroundPlane?this._groundLine.scale.y=this._groundDistance:this._groundLine.scale.y=1e3,this._groundLine.visible=this.showGizmo,this._groundMarker.visible=t!==null&&this.showGizmo,t){const n=ee(this._camera).distanceTo(t)*.01;this._groundMarker.scale.set(n,n,n),yt(this._groundMarker,t)}}}onUpdateScreenSpacePlane(){if(!this._selected||!this._context)return;const e=this._context.input.getPointerPositionRC(0);e&&(this._raycaster.setFromCamera(e,this._camera),this._cameraPlane.setFromNormalAndCoplanarPoint(this._camera.getWorldDirection(this._cameraPlane.normal),this._worldPosition.setFromMatrixPosition(this._selected.matrixWorld)),this._raycaster.ray.intersectPlane(this._cameraPlane,this._intersection)&&this._selected.parent&&(this._inverseMatrix.copy(this._selected.parent.matrixWorld).invert(),this._cameraPlaneOffset.copy(this._intersection).sub(this._worldPosition.setFromMatrixPosition(this._selected.matrixWorld))))}onUpdateGroundPlane(){if(!this._selected||!this._context)return;const e=ee(this._selected),t=new So(F(0,.1,0).add(e),F(0,-1,0)),i=new ks;i.testObject=s=>s!==this._selected;const n=this._context.physics.raycastFromRay(t,i);for(let s=0;s<n.length;s++){const r=n[s];if(!r.face||this.contains(this._selected,r.object))continue;const a=F(0,1,0);this._groundPlane.setFromNormalAndCoplanarPoint(a,r.point);break}this._hasGroundPlane=!0,this._groundPlane.setFromNormalAndCoplanarPoint(t.direction.multiplyScalar(-1),t.origin),this._raycaster.ray.intersectPlane(this._groundPlane,this._intersection),this._groundDistance=this._intersection.distanceTo(e),this._groundOffset.copy(this._intersection).sub(e)}contains(e,t){if(e===t)return!0;if(e.children){for(const i of e.children)if(this.contains(i,t))return!0}return!1}}var Px=(o=>(o.File_Spawned="file-spawned",o))(Px||{});class XR{guid;file_name;file_hash;file_size;position;scale;seed;sender;downloadUrl;parentGuid;boundsSize;constructor(e,t,i,n,s,r,a,l,c){this.seed=t,this.guid=i,this.file_name=n,this.file_hash=s,this.file_size=r,this.position=a,this.scale=l,this.sender=e,this.downloadUrl=c}}var Us;(o=>{const e=new Map;function t(n){e.has(n.guid)&&i(n.guid);const s=new M;e.set(n.guid,s);const r=new M;r.position.y=-.5,s.add(r);const a=new H(new Aa(1,1,1,1,1,1),new Ce({color:14540253,wireframe:!0,transparent:!0,opacity:.3}));a.position.y=.5,r.add(a);const l=new M;r.add(l);const c=new H(new Aa(1,1,1,1,1,1),new Ce({color:12307660,transparent:!0,opacity:.4}));c.position.y=.5,l.scale.y=.01,l.add(c);const h=new H(new vn(1,1,1,1),new Ce({color:34,transparent:!0,opacity:.05,depthTest:!1}));return h.rotateX(-Math.PI/2),h.position.y=.51,c.add(h),n.parent.add(s),s.rotateY(Math.PI/2),n.position&&s.position?.copy(n.position),n.size&&(s.worldScale=new b().copy(n.size)),s.position.y=s.scale.y/2,{object:s,onProgress:d=>{l instanceof M&&l.scale.set(1,d,1)}}}o.addPreview=t;function i(n){const s=e.get(n);s&&(e.delete(n),s.removeFromParent())}o.removePreview=i})(Us||(Us={}));const gl=[],Qu=[];var ny;(o=>{function e(i,n){const s={name:n?.name,priority:n?.priority??0,callback:i};return gl.push(s),gl.sort((r,a)=>r.priority===a.priority?0:r.priority>a.priority?-1:1),()=>{const r=gl.indexOf(s);r>=0&&gl.splice(r,1)}}o.onCreateCustomModelLoader=e;function t(i){return Qu.push(i),()=>{const n=Qu.indexOf(i);n>=0&&Qu.splice(n,1)}}o.onDetermineModelMimetype=t})(ny||(ny={}));const sh=w("debugfileformat");function Ox(o){switch((o.split(".").pop()||o).toUpperCase()){case"GLTF":return"model/gltf+json";case"VRM":return"model/vrm";case"GLB":return"model/gltf-binary";case"FBX":return"model/fbx";case"USD":return"model/vnd.usd+zip";case"USDA":return"model/vnd.usda+zip";case"USDZ":return"model/vnd.usdz+zip";case"OBJ":return"model/obj";default:return null}}async function kx(o,e){const{useExtension:t=!0}=e;if(t){const s=o,r=new URL(s,globalThis.location.href);let a=null;const l=r.searchParams.get("filetype");switch(l&&(a=l.toUpperCase()),a?.length||(a=r.pathname.split(".").pop()?.toUpperCase()),sh&&console.warn(`[Needle Engine] Try to use file extension to determine type: '${a}'`),a){case"GLTF":return"model/gltf+json";case"VRM":return"model/vrm";case"GLB":return"model/gltf-binary";case"FBX":return"model/fbx";case"USD":return"model/vnd.usd+zip";case"USDA":return"model/vnd.usda+zip";case"USDZ":return"model/vnd.usdz+zip";case"OBJ":return"model/obj";case"MTLX":return"application/materialx+xml"}}const i=o;if(!o.startsWith("blob:")){const s=new URL(o,globalThis.location.href);s.searchParams.append("range","true"),o=s.toString()}const n=await fetch(o,{method:"GET",headers:{range:"bytes=0-32"}}).catch(s=>null);if(n?.ok){const s=await n.arrayBuffer(),r=Mx(i,s,n);return sh&&console.log("[Needle Engine] Determined file type from header: "+r),r}return"unknown"}function Mx(o,e,t){if(e.byteLength<4)return"unknown";const i=new Uint8Array(e);sh&&console.warn(`[Needle Engine] Trying to determine file type from binary data
|
|
993
993
|
`,'"'+new TextDecoder().decode(e)+`"
|
|
994
994
|
`,i);const n=new TextDecoder().decode(e).replace(/\s/g,"");if(n[0]==="{"&&n[1]==='"')return console.debug("GLTF detected"),"model/gltf+json";if(i[0]==103&&i[1]==108&&i[2]==84&&i[3]==70&&(i[4]==10||i[4]===2))return console.debug("GLTF .bin detected"),"model/gltf+json";if(i[0]==103&&i[1]==108&&i[2]==84&&i[3]==70&&i[4]==98)return console.debug("GLB detected"),"model/gltf-binary";if(i[0]==80&&i[1]==75&&i[2]==3&&i[3]==4)return console.debug("USDZ detected"),"model/vnd.usdz+zip";if(i[0]==80&&i[1]==88&&i[2]==82&&i[3]==45&&i[4]==85&&i[5]==83&&i[6]==68&&i[7]==67)return console.debug("Binary USD detected"),"model/vnd.usd";if(i[0]==35&&i[1]==117&&i[2]==115&&i[3]==100&&i[4]==97)return console.debug("ASCII USD detected"),"model/vnd.usda";if(i[0]==75&&i[1]==97&&i[2]==121&&i[3]==100&&i[4]==97&&i[5]==114&&i[6]==97&&i[7]==32)return console.debug("Binary FBX detected"),"model/fbx";if(i[0]==59&&i[1]==32&&i[2]==70&&i[3]==66&&i[4]==88&&i[5]==32)return console.debug("ASCII FBX detected"),"model/fbx";if(i[0]==35&&i[1]==32&&i[2]==66&&i[3]==108&&i[4]==101&&i[5]==110&&i[6]==100&&i[7]==101&&i[8]==114&&i[9]==32||i[0]==35&&i[1]==32&&i[2]==65&&i[3]==108&&i[4]==105&&i[5]==97&&i[6]==115&&i[7]==32&&i[8]==79&&i[9]==66&&i[10]==74)return console.debug("OBJ detected"),"model/obj";if(t.headers.has("content-type")){const s=t.headers.get("content-type");if(s?.startsWith("image/"))return console.debug("Image detected, not a model file"),"unsupported";switch(console.debug("Content-Type: "+s),s){case"model/gltf+json":case"model/gltf-binary":case"model/vrm":case"model/vnd.usdz+zip":case"model/vnd.usd+zip":case"model/vnd.usd":case"model/vnd.usda+zip":case"model/vnd.usda":case"model/vnd.usdc":case"model/fbx":case"model/vnd.autodesk.fbx":case"model/obj":case"application/materialx+xml":return s}}if(i[0]==118&&i[1]==32||i[0]==102&&i[1]==32)return console.debug("OBJ detected (the file has no header and starts with vertex or face)"),"obj";if(i[0]==35&&i[1]==32&&i[2]==70&&i[3]==105&&i[4]==108&&i[5]==101&&i[6]==32&&i[7]==101&&i[8]==120&&i[9]==112&&i[10]==111&&i[11]==114&&i[12]==116&&i[13]==101&&i[14]==100&&i[15]==32&&i[16]==98&&i[17]==121&&i[18]==32&&i[19]==90&&i[20]==66&&i[21]==114&&i[22]==117&&i[23]==115&&i[24]==104)return console.debug("OBJ detected (exported by ZBrush)"),"obj";if(i[0]==109&&i[1]==116&&i[2]==108&&i[3]==108&&i[4]==105&&i[5]==98)return console.debug("OBJ detected (mtllib)"),"obj";for(const s of Qu){const r=s({url:o,response:t,contentType:t.headers.get("content-type"),bytes:i});if(r)return sh&&console.debug(`Mimetype callback returned: ${r}`),r}if(A()||sh){const s=new TextDecoder().decode(e.slice(0,Math.min(e.byteLength,32)));console.warn(`Could not determine file type.
|
|
995
995
|
|
|
@@ -998,7 +998,7 @@ Consider registering a custom loader via the 'onCreateCustomModelLoader' callbac
|
|
|
998
998
|
Content-Type: "${t.headers.get("content-type")}"
|
|
999
999
|
"Text: "${s}"
|
|
1000
1000
|
Binary:`,i)}else console.debug("Could not determine file type from binary data");return"unknown"}const oy=w("debugstencil");function QR(o,e){return(o&1<<e.layer)!=0}const YR=Symbol("stencils");class mr{get name(){return"NEEDLE_render_objects"}static stencils={};static applyStencil(e){if(!e)return;const t=e.sourceId;if(oy&&console.log(t,mr.stencils),!t)return;const i=mr.stencils[t];if(i)for(let n=i.length-1;n>=0;n--){const s=i[n];if(QR(s.layer,e)){oy&&console.log(s),setTimeout(()=>{Mi()&&bu(e.gameObject)&&(be("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[YR]=!0,a.stencilWrite=!0,a.stencilWriteMask=255,a.stencilFuncMask=255,a.stencilRef=s.value,a.stencilFunc=s.compareFunc,a.stencilZPass=s.passOp,a.stencilFail=s.failOp,a.stencilZFail=s.zFailOp,e.sharedMaterials[r]=a)}e.gameObject.renderOrder=s.event*1e3+s.index*50;break}}}parser;source;constructor(e,t){this.parser=e,this.source=t}afterRoot(e){const t=this.parser.json.extensions;if(t){const i=t[KR];if(i){oy&&console.log(i);const n=i.stencil;if(n&&Array.isArray(n))for(const s of n){const r={...s};r.compareFunc=ZR(r.compareFunc),r.passOp=sy(r.passOp),r.failOp=sy(r.failOp),r.zFailOp=sy(r.zFailOp),mr.stencils[this.source]||(mr.stencils[this.source]=[]),mr.stencils[this.source].push(r)}}}return null}}function sy(o){switch(o){case 0:return EC;case 1:return MC;case 2:return kC;case 3:return OC;case 4:return PC;case 6:return CC;case 7:return SC;case 5:return xC}return 0}function ZR(o){switch(o){case 1:return Cb;case 2:return wC;case 3:return vC;case 4:return _C;case 5:return bC;case 6:return yC;case 7:return fC;case 8:return gC}return Cb}const KR="NEEDLE_render_objects";class JR{objectToBlock=new WeakMap;meshToOwners=new WeakMap;meshToOriginalCallbacks=new WeakMap;getBlock(e){return this.objectToBlock.get(e)}setBlock(e,t){this.objectToBlock.set(e,t)}deleteBlock(e){this.objectToBlock.delete(e)}isHooked(e,t){return this.meshToOwners.get(e)?.has(t)??!1}addHook(e,t){let i=this.meshToOwners.get(e);i||(i=new Set,this.meshToOwners.set(e,i)),i.add(t)}removeHook(e,t){const i=this.meshToOwners.get(e);i&&(i.delete(t),i.size===0&&this.meshToOwners.delete(e))}getOriginalCallbacks(e){return this.meshToOriginalCallbacks.get(e)}setOriginalCallbacks(e,t){this.meshToOriginalCallbacks.set(e,t)}}const Go=new JR;class ms{_overrides=[];_defines={};_object=null;get object(){return this._object}constructor(e=null){this._object=e}static get(e){let t=Go.getBlock(e);return t||(t=new ms(e),Go.setBlock(e,t),iT(e,t)),t}static hasOverrides(e){const t=Go.getBlock(e);return t?t.hasOverrides():!1}dispose(){this._object&&Go.deleteBlock(this._object),this._overrides=[],this._object=null}setOverride(e,t,i){const n=this._overrides.find(s=>s.name===e);n?(n.value=t,n.textureTransform=i):this._overrides.push({name:e,value:t,textureTransform:i})}getOverride(e){return this._overrides.find(t=>t.name===e)}removeOveride(e){const t=this._overrides.findIndex(i=>i.name===e);t>=0&&this._overrides.splice(t,1)}clearAllOverrides(){this._overrides=[]}get overrides(){return this._overrides}hasOverrides(){return this._overrides.length>0}setDefine(e,t){this._defines[e]=t}clearDefine(e){this._defines[e]=void 0}getDefines(){return this._defines}getCacheKey(){const e=[],t=Object.keys(this._defines).sort();for(const i of t){const n=this._defines[i];n!==void 0&&e.push(`d:${i}=${n}`)}for(const i of this._overrides){if(i.value===null)continue;let n="";if(i.value instanceof Se){if(n=i.value.uuid||"texture",i.textureTransform){const s=i.textureTransform;s.offset&&(n+=`;to:${s.offset.x},${s.offset.y}`),s.repeat&&(n+=`;tr:${s.repeat.x},${s.repeat.y}`)}}else if(Array.isArray(i.value))n=i.value.join(",");else if(i.value&&typeof i.value=="object"&&"r"in i.value){const s=i.value;n=`${s.r},${s.g},${s.b},${s.a!==void 0?s.a:""}`}else if(i.value&&typeof i.value=="object"&&"x"in i.value){const s=i.value;n=`${s.x},${s.y}${s.z!==void 0?`,${s.z}`:""}${s.w!==void 0?`,${s.w}`:""}`}else n=String(i.value);e.push(`${i.name}=${n}`)}return e.join(";")}}const Yu=Symbol("originalValues"),Zu=Symbol("savedTextureTransforms");function Ex(o){let e=Go.getBlock(o);if(e)return{block:e,owner:o};if(o.parent&&o.parent.type==="Group"&&(e=Go.getBlock(o.parent),e))return{block:e,owner:o.parent}}const fl=Symbol("beforeRenderingFlag"),ry=new WeakMap,ay=new WeakMap,eT=function(o,e,t,i){const n=Go.getBlock(o);if(n&&n.hasOverrides()){const s=n.getOverride("transmission")?.value,r=n.getOverride("transparent")?.value;s!==void 0&&typeof s=="number"&&"transmission"in t&&s!==t.transmission&&(ay.set(this,t.transmission),t.transmission=s),r!==void 0&&typeof r=="boolean"&&r!==t.transparent&&(ry.set(this,t.transparent),t.transparent=r)}},tT=function(o,e,t,i){const n=ry.get(o);n!==void 0&&(ry.delete(o),t.transparent=n);const s=ay.get(o);s!==void 0&&(ay.delete(o),t.transmission=s)},Rx=function(o,e,t,i,n,s){const r=this.material;if(!r)return;if(Array.isArray(r)){if(!r.includes(n))return}else if(r!==n)return;this[fl]===void 0&&(this[fl]=new WeakSet),this[fl].add(n);const a=Ex(this);if(!a)return;const{block:l,owner:c}=a,h=l.overrides,d=n,p=l.getDefines(),m=Object.keys(p);if(m.length>0){d.defines||(d.defines={});for(const y of m){const _=p[y];_!==void 0&&(d.defines[y]=_)}}if(h.length===0&&m.length===0)return;let g=m.length>0;d[Yu]||(d[Yu]=[]);const f=d[Yu];for(const y of h){if(y.value===null)continue;const _=d[y.name],v=f.find(P=>P.name===y.name);if(v?v.value=_:f.push({name:y.name,value:_}),!g&&!!_!=!!y.value&&(g=!0),d[y.name]=y.value,y.textureTransform&&y.value instanceof Se){const P=y.value;d[Zu]||(d[Zu]=[]),d[Zu].push({name:y.name,offsetX:P.offset.x,offsetY:P.offset.y,repeatX:P.repeat.x,repeatY:P.repeat.y});const k=y.textureTransform;k.offset&&P.offset.copy(k.offset),k.repeat&&P.repeat.copy(k.repeat)}}g&&(d.needsUpdate=!0),d._forceRefresh=!0},Tx=function(o,e,t,i,n,s){if(this[fl]===void 0||!this[fl].has(n))return;this[fl].delete(n);const r=Ex(this);if(!r)return;const{block:a,owner:l}=r,c=a.overrides,h=n,d=h[Yu],p=a.getDefines(),m=Object.keys(p);let g=!1;if(m.length>0&&h.defines){for(const y of m)delete h.defines[y];g=!0}if(c.length===0){g&&(h.needsUpdate=!0,h._forceRefresh=!0);return}if(!d)return;const f=h[Zu];if(f&&f.length>0){for(const y of f){const _=c.find(v=>v.name===y.name);_?.value instanceof Se&&(_.value.offset.set(y.offsetX,y.offsetY),_.value.repeat.set(y.repeatX,y.repeatY))}f.length=0}for(const y of c){const _=d.find(v=>v.name===y.name);_&&(!g&&!!y.value!=!!_.value&&(g=!0),h[y.name]=_.value)}g&&(h.needsUpdate=!0),h._forceRefresh=!0};function iT(o,e){o.type==="Group"?o.children.forEach(t=>{(t.type==="Mesh"||t.type==="SkinnedMesh")&&Ax(t,o,e)}):(o.type==="Mesh"||o.type==="SkinnedMesh")&&Ax(o,o,e)}function Ax(o,e,t){if(!Go.isHooked(o,e)){if(Go.addHook(o,e),o["needle:materialPropertyBlock"]=t,!o.onBeforeRender)o.onBeforeRender=Rx;else{const i=o.onBeforeRender;o.onBeforeRender=function(n,s,r,a,l,c){i.call(this,n,s,r,a,l,c),Rx.call(this,n,s,r,a,l,c)}}if(!o.onAfterRender)o.onAfterRender=Tx;else{const i=o.onAfterRender;o.onAfterRender=function(n,s,r,a,l,c){Tx.call(this,n,s,r,a,l,c),i.call(this,n,s,r,a,l,c)}}o.onBeforeRenderListPush=eT,o.onAfterRenderListPush=tT}}const Ku=new Map;function ly(o,e){if(Ku.has(o))return Ku.get(o);const t=new URL(o,window.location.href),i=nT(t,e);return Ku.set(o,i),i.finally(()=>{Ku.delete(o)}),i}async function nT(o,e){if(!o)return Promise.resolve(null);const t=o.pathname,i=o.toString().toLowerCase().includes("pmrem")||o.searchParams.get("pmrem")!=null,n=t.endsWith(".exr"),s=t.endsWith(".hdr"),r=t.endsWith(".ktx2");let a;if(n)a=new zm;else if(s)a=new jb;else if(r){const{ktx2Loader:c}=Um(e);a=c}else a=new br;const l=o.toString();return await a.loadAsync(l).then(c=>{if(c){const h=t.lastIndexOf("/");c.name=t.substring(h>=0?h+1:0),i&&(c.mapping=Pb),a instanceof br&&(c.colorSpace=Mo)}return c}).catch(c=>(console.warn("Failed to load texture from url:",o),null))}var oT=Object.defineProperty,sT=Object.getOwnPropertyDescriptor,Ju=(o,e,t,i)=>{for(var n=i>1?void 0:i?sT(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&oT(e,t,n),n};const yl=w("debugreflectionprobe"),Ix=w("noreflectionprobe");let ep=null;const rT=new N,aT=Symbol("reflectionProbeKey"),rh=class zn extends E{static _probes=new Map;static testBox=new Yt;static isUsingReflectionProbe(e){return!!e[aT]}static onEnabled=new ae;static onDisabled=new ae;static get(e,t,i,n){if(!e||e.isObject3D!==!0||Ix)return null;const s=zn._probes.get(t);if(s){for(const r of s)if(r.__didAwake||r.__internalAwake(),r.activeAndEnabled){if(n){if(r.gameObject===n)return r}else if(r.isInBox(e))return yl&&console.log("Found reflection probe",e.name,r.name),r}}return yl&&console.debug("Did not find reflection probe",e.name,i,e),null}_texture;_textureUrlInFlight;set texture(e){if(this._texture!==e){if(typeof e=="string"){yl&&console.debug(`[ReflectionProbe] Loading reflection probe texture from URL: ${e}`),this._textureUrlInFlight=e;const t=Ao(this.sourceId,e);ly(t,this.context.renderer).then(i=>{this._textureUrlInFlight===e&&i&&(this._textureUrlInFlight=void 0,yl&&console.debug(`[ReflectionProbe] Successfully loaded reflection probe texture: ${e}`),this.texture=i)});return}this.__didAwake&&(this._textureUrlInFlight=void 0),this._texture=e,yl&&console.debug("[ReflectionProbe] Set reflection probe texture "+(e?.name||"(removed)")),e&&(e instanceof Ob||e.mapping!==ko&&(e.mapping=ko),e.colorSpace=Oo,e.needsUpdate=!0)}}get texture(){return this._texture}intensity=1;center=new b;size=new b(1,1,1);__lightmapIntensityScale=!0;isInBox(e){return ep??=new Yt,ep.setFromCenterAndSize(this.gameObject.worldPosition.add(this.center),this.gameObject.worldScale.multiply(this.size)),di([e],void 0,void 0,zn.testBox),zn.testBox.isEmpty()?ep.containsPoint(e.worldPosition):ep?.intersectsBox(zn.testBox)}constructor(){super(),zn._probes.has(this.context)||zn._probes.set(this.context,[]),zn._probes.get(this.context)?.push(this)}_gizmo=null;_color=null;awake(){yl&&(this._gizmo=iu(5592320),this.gameObject.add(this._gizmo)),this._texture&&(this._texture.mapping=ko,this._texture.colorSpace=Oo,this._texture.needsUpdate=!0)}update(){this._gizmo&&(this.center&&this._gizmo.position.copy(this.center),this.size&&this._gizmo.scale.copy(this.size),this._gizmo.worldQuaternion=rT.identity())}onEnable(){zn.onEnabled?.invoke(this)}onDisable(){zn.onDisabled?.invoke(this)}start(){this._texture||console.warn(`[ReflectionProbe] Missing texture. Please assign a custom cubemap texture. To use reflection probes assign them to your renderer's "anchor" property.`)}onDestroy(){const e=zn._probes.get(this.context);if(e){const t=e.indexOf(this);t>=0&&e.splice(t,1)}}apply(e){if(Ix||!this.enabled||!this.texture)return;const t=ms.get(e);t.setOverride("envMap",this.texture),t.setOverride("envMapRotation",this.gameObject.rotation);let i=this.intensity;this.__lightmapIntensityScale&&t.getOverride("lightMap")&&(i/=Math.PI),t.setOverride("envMapIntensity",i)}unapply(e){const t=ms.get(e);t&&t.getOverride("envMap")?.value===this.texture&&t.removeOveride("envMap")}};Ju([u([Se,String])],rh.prototype,"texture",1),Ju([u()],rh.prototype,"intensity",2),Ju([u(b)],rh.prototype,"center",2),Ju([u(b)],rh.prototype,"size",2);let qo=rh;const cy=w("debugexr");class lT{get name(){return"EXT_texture_exr"}parser;constructor(e){this.parser=e,cy&&console.log(e)}loadTexture(e){const t=this.name,i=this.parser,n=i.json.textures[e];if(cy&&console.log("EXT_texture_exr.loadTexture",e,n),!n.extensions||!n.extensions[t])return null;const s=n.extensions[t],r=new zm(i.options.manager);return cy&&console.log("EXT_texture_exr.loadTexture",s),i.loadTextureImage(e,s.source,r)}}typeof window<"u"&&window.addEventListener("unhandledrejection",o=>{});const so=bt,tp="$___Export_Components",cT="NEEDLE_components";class hT{[Mr]}class dT{node;nodeIndex;nodeDef;constructor(e,t,i){this.node=e,this.nodeIndex=t,this.nodeDef=i}}class Lx{get name(){return cT}exportContext;objectToNodeMap={};context;writer;registerExport(e){e.register(t=>{if("serializeUserData"in t){const i=t.serializeUserData.bind(t);this.writer=t,t.serializeUserData=(n,s)=>{try{this.serializeUserData(n,s)&&(t.extensionsUsed[this.name]=!0),i(n,s)}finally{this.afterSerializeUserData(n,s)}}}return this})}beforeParse(){this.exportContext={},this.objectToNodeMap={}}serializeUserData(e,t){const i=e.userData?.components;return!i||i.length<=0?!1:(delete e.userData.components,e[tp]=i,!0)}afterSerializeUserData(e,t){if(e.type==="Scene"&&so&&console.log("DONE",JSON.stringify(t)),e[tp]===void 0)return;const i=e[tp];delete e[tp],i!==null&&(e.userData.components=i)}writeNode(e,t){const i=this.writer.json.nodes.length;so&&console.log(e.name,i,e.uuid);const n=new dT(e,i,t);this.exportContext[i]=n,this.objectToNodeMap[e.uuid]=i}afterParse(e){so&&console.log("AFTER",e);for(const t in this.exportContext){const i=this.exportContext[t],n=i.node,s=i.nodeDef,r=i.nodeIndex,a=n.userData?.components;if(!a||a.length<=0)continue;const l=new hT;s.extensions=s.extensions||{},s.extensions[this.name]=l,this.context.object=n,this.context.nodeId=r,this.context.objectToNode=this.objectToNodeMap;const c=[];for(const h of a){this.context.target=h;const d=Cn().writeBuiltinComponentData(h,this.context);d!==null&&c.push(d)}c.length>0&&(l[Mr]=c,so&&console.log("DID WRITE",n,"nodeIndex",r,c))}}parser;nodeToObjectMap={};gltf=null;beforeRoot(){return so&&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];so&&console.log("After root",e,this.parser,i);const s=[];if(n===!0){const r=t.json.nodes;if(r){for(let a=0;a<r.length;a++){const l=await t.getDependency("node",a);this.nodeToObjectMap[a]=l}for(let a=0;a<r.length;a++){const l=r[a],c=a,h=l.extensions;if(!h)continue;const d=h[this.name];if(!d)continue;so&&console.log("NODE",l);const p=this.nodeToObjectMap[c];if(!p){console.error("Could not find object for node index: "+c,l,t);continue}fu(p),s.push(this.createComponents(e,l,p,d))}}}await Promise.all(s);for(const r of t.associations.keys()){const a=t.associations.get(r);if(a?.materials!=null){const l="/materials/"+a.materials;OM(r,l)}}}async createComponents(e,t,i,n){if(!n)return;const s=n[Mr];if(s){const r=new Array;so&&console.log(i.name,s);for(const a in s){const l=s[a];if(so&&console.log("Serialized data",JSON.parse(JSON.stringify(l))),(l?.name==="MeshRenderer"||l?.name==="SkinnedMeshRenderer")&&!l.sharedMaterials){let c=!1;if("mesh"in t){const h=t.mesh;if(typeof h=="number"&&e.parser){const d=e.parser.json.meshes?.[h];d?.primitives&&(l.sharedMaterials=d.primitives.map(p=>"/materials/"+(p.material??0)),c=!0)}}!c&&(so||A())&&console.warn(`[NEEDLE_components] Component '${l.name}' on object '${i.name}' is not added to a mesh or failed to retrieve materials from glTF.`)}l&&this.parser&&r.push(nf(this.parser,l).catch(c=>console.error(`Error while resolving references (see console for details)
|
|
1001
|
-
`,c,i,l))),i.userData=i.userData||{},i.userData[Mr]=i.userData[Mr]||[],i.userData[Mr].push(l)}await Promise.all(r).catch(a=>{console.error("Error while loading components",a)})}}}const jx="NEEDLE_gameobject_data";class uT{get name(){return jx}parser;constructor(e){this.parser=e}afterRoot(e){const t=[];for(let i=0;i<this.parser.json.nodes?.length;i++){const n=this.parser.json.nodes[i];if(n&&n.extensions){const s=n.extensions[jx];if(s){const r=this.findAndApplyExtensionData(i,s);t.push(r)}}}return Promise.all(t).then(()=>null)}async findAndApplyExtensionData(e,t){const i=await this.parser.getDependency("node",e);i&&this.applyExtensionData(i,t)}applyExtensionData(e,t){t.layers===void 0&&(t.layers=0),e.userData.layer=t.layers,e.layers.disableAll(),e.layers.set(t.layers),e.userData.tag=t.tag??"none",e.hideFlags=0,e.userData.static=t.static??!1,e.visible=t.activeSelf??!0,e.guid=t.guid}}const Dx="NEEDLE_lighting_settings",bl=w("debugenvlight");class pT{get name(){return Dx}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[Dx];if(i){bl&&console.log('Loaded "'+this.name+'", src: "'+this.sourceId+'"',i);let n;if(e.scene.children.length===1){const s=e.scene.children[0];n=S.addComponent(s,ip,{},{callAwake:!1})}else{const s=new M;s.name="LightSettings "+this.sourceId,e.scene.add(s),n=S.addComponent(s,ip,{},{callAwake:!1})}n.sourceId=this.sourceId,n.ambientIntensity=i.ambientIntensity,n.ambientLight=new oe().fromArray(i.ambientLight),Array.isArray(i.ambientTrilight)&&(n.ambientTrilight=i.ambientTrilight.map(s=>new oe().fromArray(s))),n.ambientMode=i.ambientMode,n.environmentReflectionSource=i.environmentReflectionSource}}return null}}pe.registerCallback(ue.ContextCreated,o=>{const e=o.context,t=S.findObjectOfType(ip,e);t?.sourceId&&(t.enabled=!0)});class ip extends E{ambientMode=rl.Skybox;ambientLight;ambientTrilight;ambientIntensity=1;environmentReflectionSource=Pu.Skybox;_hasReflection=!1;_ambientLightObj;_hemisphereLightObj;awake(){if(this.sourceId){const t=this.environmentReflectionSource===Pu.Skybox?Yn.Skybox:Yn.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),bl&&window.addEventListener("keydown",t=>{this.destroyed||t.key==="l"&&(this.enabled=!this.enabled)});const e=this.gameObject.userData?.components;if(e){const t=e.indexOf(this);e.splice(t,1),e.push(this)}}onDestroy(){this.context.sceneLighting.internalUnregisterSceneLightSettings(this)}calculateIntensityFactor(e){const t=Math.max(e.r,e.g,e.b);return 2.2*D.lerp(0,1.33,t)}onEnable(){if(bl&&console.warn("\u{1F4A1}\u{1F7E1} >>> Enable lighting",this.sourceId,this.enabled,this),this.ambientMode==rl.Flat){if(this.ambientLight&&!this._ambientLightObj){const e=this.calculateIntensityFactor(this.ambientLight);this._ambientLightObj=new RC(this.ambientLight,this.ambientIntensity*e),bl&&console.log("Created ambient light",this.sourceId,this._ambientLightObj,this.ambientIntensity,e)}this._ambientLightObj&&this.gameObject.add(this._ambientLightObj)}else if(this.ambientMode===rl.Trilight){if(this.ambientTrilight){const e=this.ambientTrilight[0],t=this.ambientTrilight[this.ambientTrilight.length-1],i=this.calculateIntensityFactor(t);this._hemisphereLightObj=new TC(t,e,this.ambientIntensity*i),this.gameObject.add(this._hemisphereLightObj),bl&&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(){bl&&console.warn("\u{1F4A1}\u26AB <<< Disable lighting:",this.sourceId,this),this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._hemisphereLightObj&&this._hemisphereLightObj.removeFromParent(),this.sourceId&&this.context.sceneLighting.internalDisableReflection(this.sourceId)}}var np;(o=>{async function e(t,i){if(!t)throw new Error("URL or XML string is required to load a MaterialX material");const n=await T.MaterialX.load(),s=t.trimStart().startsWith("<"),r=s?t:await fetch(t).then(c=>c.text()).catch(console.error);if(!r)return console.warn("Failed to load MaterialX file from url",t),null;let a;if(i?.url||!s){const c=(i?.url||t).split("/");c.pop(),a=c.join("/")}const l=new br;return n.Experimental_API.createMaterialXMaterial(r,i?.materialNameOrIndex??0,{getTexture:async c=>(!c.startsWith("http")&&!c.startsWith("data:")&&!c.startsWith("blob:")&&!c.startsWith("file:")&&a&&(c=a+"/"+c),l.loadAsync(c).catch(h=>{console.warn(`Failed to load texture for MaterialX material ${c}`,h)}))},{cacheKey:t})}o.loadFromUrl=e})(np||(np={}));class mT extends AC{loadAsync(e,t){return new Promise((i,n)=>{this.load(e,i,t,n)})}load(e,t,i,n){i?.({type:"progress",loaded:0,total:0}),np.loadFromUrl(e,{}).then(s=>{s?t(this.onLoaded(s)):n?.(new Error("Failed to load MaterialX material from url: "+e))})}onLoaded(e){return Os.createPrimitive("ShaderBall",{material:e})}}class gT{constructor(e,t,i,n){this.context=e,this.loader=t,this.url=i,this.parser=n}get name(){return"materialx-loading-helper"}mtlxLoader;async beforeRoot(){if(this.parser.json.extensions?.NEEDLE_materials_mtlx){const e=await T.MaterialX.load();try{this.mtlxLoader=new e.MaterialXLoader(this.parser,{cacheKey:`${this.url}:materialx`,parameters:{precision:this.context.renderer?.capabilities.precision}},{getFrame:()=>this.context.time.frame,getTime:()=>this.context.time.time})}catch(t){console.error(t)}}}loadMaterial(e){return this.mtlxLoader?this.mtlxLoader.loadMaterial(e):null}}var Bx=(o=>(o[o.INT=5124]="INT",o[o.FLOAT=5126]="FLOAT",o[o.FLOAT_VEC2=35664]="FLOAT_VEC2",o[o.FLOAT_VEC3=35665]="FLOAT_VEC3",o[o.FLOAT_VEC4=35666]="FLOAT_VEC4",o[o.INT_VEC2=35667]="INT_VEC2",o[o.INT_VEC3=35668]="INT_VEC3",o[o.INT_VEC4=35669]="INT_VEC4",o[o.BOOL=35670]="BOOL",o[o.BOOL_VEC2=35671]="BOOL_VEC2",o[o.BOOL_VEC3=35672]="BOOL_VEC3",o[o.BOOL_VEC4=35673]="BOOL_VEC4",o[o.FLOAT_MAT2=35674]="FLOAT_MAT2",o[o.FLOAT_MAT3=35675]="FLOAT_MAT3",o[o.FLOAT_MAT4=35676]="FLOAT_MAT4",o[o.SAMPLER_2D=35678]="SAMPLER_2D",o[o.SAMPLER_3D=35680]="SAMPLER_3D",o[o.SAMPLER_CUBE=35681]="SAMPLER_CUBE",o[o.UNKNOWN=0]="UNKNOWN",o))(Bx||{});const ro=w("debugcustomshader"),_l="NEEDLE_techniques_webgl";class fT{objectToWorldMatrix=new J;worldToObjectMatrix=new J;objectToWorld=new Array;worldToObject=new Array;updateFrom(e){this.objectToWorldMatrix.copy(e.matrixWorld),Cu(this.objectToWorldMatrix,this.objectToWorld),this.worldToObjectMatrix.copy(e.matrixWorld).invert(),Cu(this.worldToObjectMatrix,this.worldToObject)}}class Te extends kb{identifier;onBeforeRenderSceneCallback=this.onBeforeRenderScene.bind(this);clone(){const e=super.clone();return Fx(e),e}constructor(e,...t){super(...t),this.identifier=e,ro&&console.log(this),this.type="NEEDLE_CUSTOM_SHADER",this.uniforms[this._objToWorldName]||(this.uniforms[this._objToWorldName]={value:[]}),this.uniforms[this._worldToObjectName]||(this.uniforms[this._worldToObjectName]={value:[]}),this.uniforms[this._viewProjectionName]||(this.uniforms[this._viewProjectionName]={value:[]}),this.uniforms[this._sphericalHarmonicsName],(this.depthTextureUniform||this.opaqueTextureUniform)&&U.Current.pre_render_callbacks.push(this.onBeforeRenderSceneCallback)}dispose(){super.dispose();const e=U.Current.pre_render_callbacks.indexOf(this.onBeforeRenderSceneCallback);e>=0&&U.Current.pre_render_callbacks.splice(e,1)}_sphericalHarmonicsName="unity_SpecCube0";_objToWorldName="hlslcc_mtx4x4unity_ObjectToWorld";_worldToObjectName="hlslcc_mtx4x4unity_WorldToObject";static viewProjection=new J;static _viewProjectionValues=[];_viewProjectionName="hlslcc_mtx4x4unity_MatrixVP";static viewMatrix=new J;static _viewMatrixValues=[];_viewMatrixName="hlslcc_mtx4x4unity_MatrixV";static _worldSpaceCameraPosName="_WorldSpaceCameraPos";static _worldSpaceCameraPos=new b;static _mainLightColor=new ye;static _mainLightPosition=new b;static _lightData=new ye;_rendererData=new fT;get depthTextureUniform(){if(this.uniforms)return this.uniforms._CameraDepthTexture}get opaqueTextureUniform(){if(this.uniforms)return this.uniforms._CameraOpaqueTexture}onBeforeRenderScene(){this.opaqueTextureUniform&&U.Current.setRequireColor(!0),this.depthTextureUniform&&U.Current.setRequireDepth(!0)}onBeforeRender(e,t,i,n,s,r){n.attributes.tangent||n.computeTangents(),this.onUpdateUniforms(i,s)}onUpdateUniforms(e,t){const i=U.Current;if(e&&(Te.viewProjection&&this.uniforms[this._viewProjectionName]&&(Te.viewProjection.copy(e.projectionMatrix).multiply(e.matrixWorldInverse),Cu(Te.viewProjection,Te._viewProjectionValues)),Te.viewMatrix&&this.uniforms[this._viewMatrixName]&&(Te.viewMatrix.copy(e.matrixWorldInverse),Cu(Te.viewMatrix,Te._viewMatrixValues)),this.uniforms[Te._worldSpaceCameraPosName]&&Te._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=ee(n.gameObject,Te._mainLightPosition);this.uniforms._MainLightPosition={value:a.normalize()},Te._mainLightColor.set(n.color.r,n.color.g,n.color.b,0),this.uniforms._MainLightColor={value:Te._mainLightColor};const l=n.intensity;Te._lightData.z=l,this.uniforms.unity_LightData={value:Te._lightData}}if(e&&(Te.viewProjection&&this.uniforms[this._viewProjectionName]&&(this.uniforms[this._viewProjectionName].value=Te._viewProjectionValues),Te.viewMatrix&&this.uniforms[this._viewMatrixName]&&(this.uniforms[this._viewMatrixName].value=Te._viewMatrixValues),this.uniforms[Te._worldSpaceCameraPosName]&&(this.uniforms[Te._worldSpaceCameraPosName]={value:Te._worldSpaceCameraPos}),i.mainCameraComponent)){if(this.uniforms._ProjectionParams){const a=this.uniforms._ProjectionParams.value;a.x=1,a.y=i.mainCameraComponent.nearClipPlane,a.z=i.mainCameraComponent.farClipPlane,a.w=1/a.z,this.uniforms._ProjectionParams.value=a}if(this.uniforms._ZBufferParams){const a=this.uniforms._ZBufferParams.value,l=i.mainCameraComponent;a.x=1-l.farClipPlane/l.nearClipPlane,a.y=l.farClipPlane/l.nearClipPlane,a.z=a.x/l.farClipPlane,a.w=a.y/l.farClipPlane,this.uniforms._ZBufferParams.value=a}if(this.uniforms._ScreenParams){const a=this.uniforms._ScreenParams.value;a.x=i.domWidth,a.y=i.domHeight,a.z=1+1/a.x,a.w=1+1/a.y,this.uniforms._ScreenParams.value=a}if(this.uniforms._ScaledScreenParams){const a=this.uniforms._ScaledScreenParams.value;a.x=i.domWidth,a.y=i.domHeight,a.z=1+1/a.x,a.w=1+1/a.y,this.uniforms._ScaledScreenParams.value=a}}const s=this.depthTextureUniform;s&&(s.value=i.depthTexture);const r=this.opaqueTextureUniform;if(r&&(r.value=i.opaqueColorTexture),t){const a=this._rendererData;a.updateFrom(t),this.uniforms[this._worldToObjectName].value=a.worldToObject,this.uniforms[this._objToWorldName].value=a.objectToWorld}this.uniformsNeedUpdate=!0}}class yT{get name(){return _l}parser;identifier;constructor(e,t){this.parser=e,this.identifier=t}loadMaterial(e){const t=this.parser.json.materials[e];if(!t)return ro&&console.log(e,this.parser.json.materials),null;if(!t.extensions||!t.extensions[_l])return ro&&console.log(`Material ${e} does not use NEEDLE_techniques_webgl`),null;ro&&console.log(`Material ${e} uses NEEDLE_techniques_webgl`,t);const i=t.extensions[_l].technique;if(i<0)return console.debug(`Material ${e} does not have a valid technique index`),null;const n=this.parser.json.extensions[_l];if(!n)return ro?console.error("Missing shader data",this.parser.json.extensions):console.debug("Missing custom shader data in parser.json.extensions"),null;ro&&console.log(n);const s=n.techniques[i];return s?new Promise(async(r,a)=>{const l=await rE(n,s.program),c=l?.fragmentShader,h=l?.vertexShader;if(!c||!h)return a();ro&&console.log("loadMaterial",t,l);const d={},p=s.uniforms;(h.includes("_Time")||c.includes("_Time"))&&(d._Time={value:new ye(0,0,0,0)}),(h.includes("_SinTime")||c.includes("_SinTime"))&&(d._SinTime={value:new ye(0,0,0,0)}),(h.includes("_CosTime")||c.includes("_CosTime"))&&(d._CosTime={value:new ye(0,0,0,0)}),(h.includes("unity_DeltaTime")||c.includes("unity_DeltaTime"))&&(d.unity_DeltaTime={value:new ye(0,0,0,0)});for(const f in p){const y=f;switch(y){case"_TimeParameters":const _=new ye;d[y]={value:_};break;case"hlslcc_mtx4x4unity_MatrixV":case"hlslcc_mtx4x4unity_MatrixVP":d[y]={value:[]};break;case"_MainLightPosition":case"_MainLightColor":case"_WorldSpaceCameraPos":d[y]={value:[0,0,0,1]};break;case"unity_OrthoParams":break;case"unity_SpecCube0":d[y]={value:null};break;default:case"_ScreenParams":case"_ZBufferParams":case"_ProjectionParams":d[y]={value:[0,0,0,0]};break;case"_CameraOpaqueTexture":case"_CameraDepthTexture":d[y]={value:null};break}}let m=!1;if(t.extensions&&t.extensions[_l]){const f=t.extensions[_l];if(f.technique===i){ro&&console.log(t.name,"Material Properties",f);for(const y in f.values){const _=f.values[y];if(typeof _=="string"){if(_.startsWith("/textures/")){const v=_.substring(10),P=Number.parseInt(v);if(P>=0){const k=await this.parser.getDependency("texture",P);k instanceof Se&&(k.colorSpace=Oo,k.needsUpdate=!0),d[y]={value:k};continue}}if(y==="alphaMode"){_==="BLEND"&&(m=!0);continue}}if(Array.isArray(_)&&_.length===4){d[y]={value:new ye(_[0],_[1],_[2],_[3])};continue}d[y]={value:_}}}}const g=new Te(this.identifier,{name:t.name??"",uniforms:d,vertexShader:h,fragmentShader:c,lights:!1});switch(g.glslVersion=IC,g.vertexShader=g.vertexShader.replace("#version 300 es",""),g.fragmentShader=g.fragmentShader.replace("#version 300 es",""),d._Cull?.value){case 0:g.side=Oi;break;case 1:g.side=Id;break;case 2:g.side=ws;break;default:g.side=ws;break}switch(d._ZTest?.value){case 3:g.depthTest=!0,g.depthFunc=zC;break;case 6:g.depthTest=!0,g.depthFunc=UC;break;case 2:g.depthTest=!0,g.depthFunc=FC;break;case 4:g.depthTest=!0,g.depthFunc=BC;break;case 5:g.depthTest=!0,g.depthFunc=DC;break;case 7:g.depthTest=!0,g.depthFunc=jC;break;case 8:g.depthTest=!1,g.depthFunc=LC;break}g.transparent=m,m&&(g.depthWrite=!1),oE(d),g.onUpdateUniforms();for(const f in p){const y=f,_=p[f].type;d[y]?.value===void 0&&(_===Bx.SAMPLER_2D?(d[y]={value:iE},console.warn("Missing/unassigned texture, fallback to white: "+y)):y==="unity_OrthoParams"||console.warn("TODO: EXPECTED UNIFORM / fallback NOT SET: "+y,p[f]))}ro&&console.log(g.uuid,d),Fx(g),r(g)}):null}}function Fx(o){if(o.uniforms){ro&&console.log("Uniforms:",o.uniforms);for(const t in o.uniforms)switch(e(t,t),t){case"_Color":e("color",t);break;case"_map":e("map",t);break}}function e(t,i){Object.getOwnPropertyDescriptor(o,t)||Object.defineProperty(o,t,{get:()=>o.uniforms[i].value,set:n=>{o.uniforms[i].value=n,o.needsUpdate=!0}})}}const bT=w("debugextensions");let op;const _T=import("./vendor-DZ45lcA8.min.js").then(o=>o.index$2).then(async o=>(op=o.GLTFAnimationPointerExtension,op)).catch(o=>{console.warn("Failed to import GLTFLoaderAnimationPointer. Please use @needle-tools/three-animationpointer for full KHR_animation support",o)}),Zr=new Array;function vT(o){Zr.includes(o)||Zr.push(o)}function wT(o){const e=Zr.indexOf(o);e>=0&&Zr.splice(e,1)}function hy(o){if(o instanceof Eo){const e=new Lx;return o.register(t=>(e.parser=t,e)),e}return null}class xT{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 sp(o,e,t,i){const n=t.indexOf("?");n>=0&&(t=t.substring(0,n)),i||(i=t),(i.startsWith("blob:")||i.startsWith("data:"))&&console.debug("[GLTFLoader] Suspicious sourceId detected"),o.register(s=>new uT(s)),o.register(s=>new MM(s)),o.register(s=>new KM(s,e.lightmaps,i)),o.register(s=>new pT(s,i,e)),o.register(s=>new yT(s,i)),o.register(s=>new mr(s,i)),o.register(s=>new Ve(s)),o.register(s=>new lT(s)),o.register(s=>new gT(e,o,t,s)),Rv()&&o.register(s=>new sc(s)),await _T.catch(s=>{}),o.register(s=>{if(op){const r=new op(s);return r.setAnimationPointerResolver.bind(r)(new xT),r}else return(bT||A())&&console.error("Missing KHR_animation_pointer extension..."),{name:"KHR_animation_pointer_NOT_AVAILABLE"}});for(const s of Zr)s.onImport&&s.onImport(o,t,e)}function dy(o,e){for(const t of Zr)t.onExport&&t.onExport(o,e)}function Ux(o,e,t){for(const i of Zr)i.onLoaded&&i.onLoaded(o,e,t)}const Wt=w("debuginstancing");class Oa{static instance=new Oa;static getStartInstanceCount=e=>4;objs=[];setup(e,t,i,n,s,r=0){e.applySettings(t);const a=this.tryCreateOrAddInstance(t,i,s);if(a){n===null&&(n=[]),n.push(a);const l=a.object.material;Array.isArray(l)?l.forEach(d=>Ve.assignTextureLOD(d,0)):Ve.assignTextureLOD(l,0);const c=a.object,h=c.geometry;Ve.assignMeshLOD(c,0).then(d=>{d&&h!=d&&a.setGeometry(d)})}else if(r<=0&&t.type!=="Mesh"){const l=r+1;for(const c of t.children)n=this.setup(e,c,i,n,s,l)}return r===0&&s.useMatrixWorldAutoUpdate&&n&&n.length>=0&&this.autoUpdateInstanceMatrix(t),n}tryCreateOrAddInstance(e,t,i){if(e.type==="Mesh"){const n=i.foundMeshes;if(i.foundMeshes+=1,!i.rend.enableInstancing)return null;if(i.rend.enableInstancing!==!0){if(n>=i.rend.enableInstancing.length)return Wt&&console.error("Something is wrong with instance setup",e,i.rend.enableInstancing,n),null;if(!i.rend.enableInstancing[n])return null}const s=e,r=s.material;for(const h of this.objs)if(!!h.canAdd(s.geometry,r))return h.addInstance(s);let a=Oa.getStartInstanceCount(e);(!a||a<0)&&(a=4);let l=e.name;l?.length||(l=t_());const c=new ST(l,s.geometry,r,a,t);return this.objs.push(c),c.addInstance(s)}return null}autoUpdateInstanceMatrix(e){const t=e.matrixWorld.multiplyMatrices.bind(e.matrixWorld),i=e.matrixWorld.clone(),n=(s,r)=>{const a=t(s,r);return(e[Rc]||i.equals(a)===!1)&&(i.copy(a),e[Rc]=!0),a};e.matrixWorld.multiplyMatrices=n}}class Ra{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[Dv]=t,this.meshInformation=Kr(e.geometry),Ra.all.push(this)}updateMeshInformation(){const e=Kr(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()||Wt)&&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=Ra.all.indexOf(this);t>=0&&Ra.all.splice(t,1)}}}class ST{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(),Wt&&this._batchedMesh.boundingSphere){const i=this._batchedMesh.boundingSphere;B.DrawWireSphere(i.center,i.radius,65280)}}_context;_batchedMesh;_handles=[];_geometryIds=new WeakMap;_maxInstanceCount;_currentInstanceCount=0;_currentVertexCount=0;_currentIndexCount=0;_maxVertexCount;_maxIndexCount;static nullMatrix=new J;canAdd(e,t){return this._maxVertexCount>1e7||t!==this.material||!this.validateGeometry(e)?!1:!!(!this.mustGrow(e)||this.allowResize)}_needUpdateBounds=!1;_debugMaterial=null;getBatchedMeshName(){return this.name?`${this.name} (BatchedMesh)`:"BatchedMesh"}constructor(e,t,i,n,s){this.name=e,this.geometry=t,this.material=i,this._context=s,this._maxInstanceCount=Math.max(2,n),Wt&&(this._debugMaterial=zx());const r=this.tryEstimateVertexCountSize(this._maxInstanceCount,[t],n);this._maxVertexCount=r.vertexCount,this._maxIndexCount=r.indexCount,this._batchedMesh=new Mb(this._maxInstanceCount,this._maxVertexCount,this._maxIndexCount,this._debugMaterial??this.material),this._batchedMesh.name=this.getBatchedMeshName(),this._batchedMesh[Tc]=!0,this._batchedMesh.visible=!0,this._context.scene.add(this._batchedMesh),i instanceof kb&&(i.defines.USE_INSTANCING=!0,i.needsUpdate=!0),s.pre_render_callbacks.push(this.onBeforeRender),s.post_render_callbacks.push(this.onAfterRender),Wt&&console.log(`Instanced renderer (${this.name}) created with ${this._maxInstanceCount} instances, ${this._maxVertexCount} max vertices and ${this._maxIndexCount} max indices for "${e}"`)}dispose(){Wt&&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 Ra(e,this);e.castShadow===!0&&this._batchedMesh.castShadow===!1&&(this._batchedMesh.castShadow=!0),e.receiveShadow===!0&&this._batchedMesh.receiveShadow===!1&&(this._batchedMesh.receiveShadow=!0);try{this.add(t)}catch(i){if(console.error(`Failed adding mesh to instancing (object name: "${e.name}", instances: ${this._currentInstanceCount.toLocaleString()}/${this._maxInstanceCount.toLocaleString()}, vertices: ${this._currentVertexCount.toLocaleString()}/${this._maxVertexCount.toLocaleString()}, indices: ${this._currentIndexCount.toLocaleString()}/${this._maxIndexCount.toLocaleString()})
|
|
1001
|
+
`,c,i,l))),i.userData=i.userData||{},i.userData[Mr]=i.userData[Mr]||[],i.userData[Mr].push(l)}await Promise.all(r).catch(a=>{console.error("Error while loading components",a)})}}}const jx="NEEDLE_gameobject_data";class uT{get name(){return jx}parser;constructor(e){this.parser=e}afterRoot(e){const t=[];for(let i=0;i<this.parser.json.nodes?.length;i++){const n=this.parser.json.nodes[i];if(n&&n.extensions){const s=n.extensions[jx];if(s){const r=this.findAndApplyExtensionData(i,s);t.push(r)}}}return Promise.all(t).then(()=>null)}async findAndApplyExtensionData(e,t){const i=await this.parser.getDependency("node",e);i&&this.applyExtensionData(i,t)}applyExtensionData(e,t){t.layers===void 0&&(t.layers=0),e.userData.layer=t.layers,e.layers.disableAll(),e.layers.set(t.layers),e.userData.tag=t.tag??"none",e.hideFlags=0,e.userData.static=t.static??!1,e.visible=t.activeSelf??!0,e.guid=t.guid}}const Dx="NEEDLE_lighting_settings",bl=w("debugenvlight");class pT{get name(){return Dx}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[Dx];if(i){bl&&console.log('Loaded "'+this.name+'", src: "'+this.sourceId+'"',i);let n;if(e.scene.children.length===1){const s=e.scene.children[0];n=S.addComponent(s,ip,{},{callAwake:!1})}else{const s=new M;s.name="LightSettings "+this.sourceId,e.scene.add(s),n=S.addComponent(s,ip,{},{callAwake:!1})}n.sourceId=this.sourceId,n.ambientIntensity=i.ambientIntensity,n.ambientLight=new oe().fromArray(i.ambientLight),Array.isArray(i.ambientTrilight)&&(n.ambientTrilight=i.ambientTrilight.map(s=>new oe().fromArray(s))),n.ambientMode=i.ambientMode,n.environmentReflectionSource=i.environmentReflectionSource}}return null}}pe.registerCallback(ue.ContextCreated,o=>{const e=o.context,t=S.findObjectOfType(ip,e);t?.sourceId&&(t.enabled=!0)});class ip extends E{ambientMode=rl.Skybox;ambientLight;ambientTrilight;ambientIntensity=1;environmentReflectionSource=Pu.Skybox;_hasReflection=!1;_ambientLightObj;_hemisphereLightObj;awake(){if(this.sourceId){const t=this.environmentReflectionSource===Pu.Skybox?Yn.Skybox:Yn.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),bl&&window.addEventListener("keydown",t=>{this.destroyed||t.key==="l"&&(this.enabled=!this.enabled)});const e=this.gameObject.userData?.components;if(e){const t=e.indexOf(this);e.splice(t,1),e.push(this)}}onDestroy(){this.context.sceneLighting.internalUnregisterSceneLightSettings(this)}calculateIntensityFactor(e){const t=Math.max(e.r,e.g,e.b);return 2.2*j.lerp(0,1.33,t)}onEnable(){if(bl&&console.warn("\u{1F4A1}\u{1F7E1} >>> Enable lighting",this.sourceId,this.enabled,this),this.ambientMode==rl.Flat){if(this.ambientLight&&!this._ambientLightObj){const e=this.calculateIntensityFactor(this.ambientLight);this._ambientLightObj=new RC(this.ambientLight,this.ambientIntensity*e),bl&&console.log("Created ambient light",this.sourceId,this._ambientLightObj,this.ambientIntensity,e)}this._ambientLightObj&&this.gameObject.add(this._ambientLightObj)}else if(this.ambientMode===rl.Trilight){if(this.ambientTrilight){const e=this.ambientTrilight[0],t=this.ambientTrilight[this.ambientTrilight.length-1],i=this.calculateIntensityFactor(t);this._hemisphereLightObj=new TC(t,e,this.ambientIntensity*i),this.gameObject.add(this._hemisphereLightObj),bl&&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(){bl&&console.warn("\u{1F4A1}\u26AB <<< Disable lighting:",this.sourceId,this),this._ambientLightObj&&this._ambientLightObj.removeFromParent(),this._hemisphereLightObj&&this._hemisphereLightObj.removeFromParent(),this.sourceId&&this.context.sceneLighting.internalDisableReflection(this.sourceId)}}var np;(o=>{async function e(t,i){if(!t)throw new Error("URL or XML string is required to load a MaterialX material");const n=await T.MaterialX.load(),s=t.trimStart().startsWith("<"),r=s?t:await fetch(t).then(c=>c.text()).catch(console.error);if(!r)return console.warn("Failed to load MaterialX file from url",t),null;let a;if(i?.url||!s){const c=(i?.url||t).split("/");c.pop(),a=c.join("/")}const l=new br;return n.Experimental_API.createMaterialXMaterial(r,i?.materialNameOrIndex??0,{getTexture:async c=>(!c.startsWith("http")&&!c.startsWith("data:")&&!c.startsWith("blob:")&&!c.startsWith("file:")&&a&&(c=a+"/"+c),l.loadAsync(c).catch(h=>{console.warn(`Failed to load texture for MaterialX material ${c}`,h)}))},{cacheKey:t})}o.loadFromUrl=e})(np||(np={}));class mT extends AC{loadAsync(e,t){return new Promise((i,n)=>{this.load(e,i,t,n)})}load(e,t,i,n){i?.({type:"progress",loaded:0,total:0}),np.loadFromUrl(e,{}).then(s=>{s?t(this.onLoaded(s)):n?.(new Error("Failed to load MaterialX material from url: "+e))})}onLoaded(e){return Os.createPrimitive("ShaderBall",{material:e})}}class gT{constructor(e,t,i,n){this.context=e,this.loader=t,this.url=i,this.parser=n}get name(){return"materialx-loading-helper"}mtlxLoader;async beforeRoot(){if(this.parser.json.extensions?.NEEDLE_materials_mtlx){const e=await T.MaterialX.load();try{this.mtlxLoader=new e.MaterialXLoader(this.parser,{cacheKey:`${this.url}:materialx`,parameters:{precision:this.context.renderer?.capabilities.precision}},{getFrame:()=>this.context.time.frame,getTime:()=>this.context.time.time})}catch(t){console.error(t)}}}loadMaterial(e){return this.mtlxLoader?this.mtlxLoader.loadMaterial(e):null}}var Bx=(o=>(o[o.INT=5124]="INT",o[o.FLOAT=5126]="FLOAT",o[o.FLOAT_VEC2=35664]="FLOAT_VEC2",o[o.FLOAT_VEC3=35665]="FLOAT_VEC3",o[o.FLOAT_VEC4=35666]="FLOAT_VEC4",o[o.INT_VEC2=35667]="INT_VEC2",o[o.INT_VEC3=35668]="INT_VEC3",o[o.INT_VEC4=35669]="INT_VEC4",o[o.BOOL=35670]="BOOL",o[o.BOOL_VEC2=35671]="BOOL_VEC2",o[o.BOOL_VEC3=35672]="BOOL_VEC3",o[o.BOOL_VEC4=35673]="BOOL_VEC4",o[o.FLOAT_MAT2=35674]="FLOAT_MAT2",o[o.FLOAT_MAT3=35675]="FLOAT_MAT3",o[o.FLOAT_MAT4=35676]="FLOAT_MAT4",o[o.SAMPLER_2D=35678]="SAMPLER_2D",o[o.SAMPLER_3D=35680]="SAMPLER_3D",o[o.SAMPLER_CUBE=35681]="SAMPLER_CUBE",o[o.UNKNOWN=0]="UNKNOWN",o))(Bx||{});const ro=w("debugcustomshader"),_l="NEEDLE_techniques_webgl";class fT{objectToWorldMatrix=new J;worldToObjectMatrix=new J;objectToWorld=new Array;worldToObject=new Array;updateFrom(e){this.objectToWorldMatrix.copy(e.matrixWorld),Cu(this.objectToWorldMatrix,this.objectToWorld),this.worldToObjectMatrix.copy(e.matrixWorld).invert(),Cu(this.worldToObjectMatrix,this.worldToObject)}}class Te extends kb{identifier;onBeforeRenderSceneCallback=this.onBeforeRenderScene.bind(this);clone(){const e=super.clone();return Fx(e),e}constructor(e,...t){super(...t),this.identifier=e,ro&&console.log(this),this.type="NEEDLE_CUSTOM_SHADER",this.uniforms[this._objToWorldName]||(this.uniforms[this._objToWorldName]={value:[]}),this.uniforms[this._worldToObjectName]||(this.uniforms[this._worldToObjectName]={value:[]}),this.uniforms[this._viewProjectionName]||(this.uniforms[this._viewProjectionName]={value:[]}),this.uniforms[this._sphericalHarmonicsName],(this.depthTextureUniform||this.opaqueTextureUniform)&&U.Current.pre_render_callbacks.push(this.onBeforeRenderSceneCallback)}dispose(){super.dispose();const e=U.Current.pre_render_callbacks.indexOf(this.onBeforeRenderSceneCallback);e>=0&&U.Current.pre_render_callbacks.splice(e,1)}_sphericalHarmonicsName="unity_SpecCube0";_objToWorldName="hlslcc_mtx4x4unity_ObjectToWorld";_worldToObjectName="hlslcc_mtx4x4unity_WorldToObject";static viewProjection=new J;static _viewProjectionValues=[];_viewProjectionName="hlslcc_mtx4x4unity_MatrixVP";static viewMatrix=new J;static _viewMatrixValues=[];_viewMatrixName="hlslcc_mtx4x4unity_MatrixV";static _worldSpaceCameraPosName="_WorldSpaceCameraPos";static _worldSpaceCameraPos=new b;static _mainLightColor=new ye;static _mainLightPosition=new b;static _lightData=new ye;_rendererData=new fT;get depthTextureUniform(){if(this.uniforms)return this.uniforms._CameraDepthTexture}get opaqueTextureUniform(){if(this.uniforms)return this.uniforms._CameraOpaqueTexture}onBeforeRenderScene(){this.opaqueTextureUniform&&U.Current.setRequireColor(!0),this.depthTextureUniform&&U.Current.setRequireDepth(!0)}onBeforeRender(e,t,i,n,s,r){n.attributes.tangent||n.computeTangents(),this.onUpdateUniforms(i,s)}onUpdateUniforms(e,t){const i=U.Current;if(e&&(Te.viewProjection&&this.uniforms[this._viewProjectionName]&&(Te.viewProjection.copy(e.projectionMatrix).multiply(e.matrixWorldInverse),Cu(Te.viewProjection,Te._viewProjectionValues)),Te.viewMatrix&&this.uniforms[this._viewMatrixName]&&(Te.viewMatrix.copy(e.matrixWorldInverse),Cu(Te.viewMatrix,Te._viewMatrixValues)),this.uniforms[Te._worldSpaceCameraPosName]&&Te._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=ee(n.gameObject,Te._mainLightPosition);this.uniforms._MainLightPosition={value:a.normalize()},Te._mainLightColor.set(n.color.r,n.color.g,n.color.b,0),this.uniforms._MainLightColor={value:Te._mainLightColor};const l=n.intensity;Te._lightData.z=l,this.uniforms.unity_LightData={value:Te._lightData}}if(e&&(Te.viewProjection&&this.uniforms[this._viewProjectionName]&&(this.uniforms[this._viewProjectionName].value=Te._viewProjectionValues),Te.viewMatrix&&this.uniforms[this._viewMatrixName]&&(this.uniforms[this._viewMatrixName].value=Te._viewMatrixValues),this.uniforms[Te._worldSpaceCameraPosName]&&(this.uniforms[Te._worldSpaceCameraPosName]={value:Te._worldSpaceCameraPos}),i.mainCameraComponent)){if(this.uniforms._ProjectionParams){const a=this.uniforms._ProjectionParams.value;a.x=1,a.y=i.mainCameraComponent.nearClipPlane,a.z=i.mainCameraComponent.farClipPlane,a.w=1/a.z,this.uniforms._ProjectionParams.value=a}if(this.uniforms._ZBufferParams){const a=this.uniforms._ZBufferParams.value,l=i.mainCameraComponent;a.x=1-l.farClipPlane/l.nearClipPlane,a.y=l.farClipPlane/l.nearClipPlane,a.z=a.x/l.farClipPlane,a.w=a.y/l.farClipPlane,this.uniforms._ZBufferParams.value=a}if(this.uniforms._ScreenParams){const a=this.uniforms._ScreenParams.value;a.x=i.domWidth,a.y=i.domHeight,a.z=1+1/a.x,a.w=1+1/a.y,this.uniforms._ScreenParams.value=a}if(this.uniforms._ScaledScreenParams){const a=this.uniforms._ScaledScreenParams.value;a.x=i.domWidth,a.y=i.domHeight,a.z=1+1/a.x,a.w=1+1/a.y,this.uniforms._ScaledScreenParams.value=a}}const s=this.depthTextureUniform;s&&(s.value=i.depthTexture);const r=this.opaqueTextureUniform;if(r&&(r.value=i.opaqueColorTexture),t){const a=this._rendererData;a.updateFrom(t),this.uniforms[this._worldToObjectName].value=a.worldToObject,this.uniforms[this._objToWorldName].value=a.objectToWorld}this.uniformsNeedUpdate=!0}}class yT{get name(){return _l}parser;identifier;constructor(e,t){this.parser=e,this.identifier=t}loadMaterial(e){const t=this.parser.json.materials[e];if(!t)return ro&&console.log(e,this.parser.json.materials),null;if(!t.extensions||!t.extensions[_l])return ro&&console.log(`Material ${e} does not use NEEDLE_techniques_webgl`),null;ro&&console.log(`Material ${e} uses NEEDLE_techniques_webgl`,t);const i=t.extensions[_l].technique;if(i<0)return console.debug(`Material ${e} does not have a valid technique index`),null;const n=this.parser.json.extensions[_l];if(!n)return ro?console.error("Missing shader data",this.parser.json.extensions):console.debug("Missing custom shader data in parser.json.extensions"),null;ro&&console.log(n);const s=n.techniques[i];return s?new Promise(async(r,a)=>{const l=await rE(n,s.program),c=l?.fragmentShader,h=l?.vertexShader;if(!c||!h)return a();ro&&console.log("loadMaterial",t,l);const d={},p=s.uniforms;(h.includes("_Time")||c.includes("_Time"))&&(d._Time={value:new ye(0,0,0,0)}),(h.includes("_SinTime")||c.includes("_SinTime"))&&(d._SinTime={value:new ye(0,0,0,0)}),(h.includes("_CosTime")||c.includes("_CosTime"))&&(d._CosTime={value:new ye(0,0,0,0)}),(h.includes("unity_DeltaTime")||c.includes("unity_DeltaTime"))&&(d.unity_DeltaTime={value:new ye(0,0,0,0)});for(const f in p){const y=f;switch(y){case"_TimeParameters":const _=new ye;d[y]={value:_};break;case"hlslcc_mtx4x4unity_MatrixV":case"hlslcc_mtx4x4unity_MatrixVP":d[y]={value:[]};break;case"_MainLightPosition":case"_MainLightColor":case"_WorldSpaceCameraPos":d[y]={value:[0,0,0,1]};break;case"unity_OrthoParams":break;case"unity_SpecCube0":d[y]={value:null};break;default:case"_ScreenParams":case"_ZBufferParams":case"_ProjectionParams":d[y]={value:[0,0,0,0]};break;case"_CameraOpaqueTexture":case"_CameraDepthTexture":d[y]={value:null};break}}let m=!1;if(t.extensions&&t.extensions[_l]){const f=t.extensions[_l];if(f.technique===i){ro&&console.log(t.name,"Material Properties",f);for(const y in f.values){const _=f.values[y];if(typeof _=="string"){if(_.startsWith("/textures/")){const v=_.substring(10),P=Number.parseInt(v);if(P>=0){const k=await this.parser.getDependency("texture",P);k instanceof Se&&(k.colorSpace=Oo,k.needsUpdate=!0),d[y]={value:k};continue}}if(y==="alphaMode"){_==="BLEND"&&(m=!0);continue}}if(Array.isArray(_)&&_.length===4){d[y]={value:new ye(_[0],_[1],_[2],_[3])};continue}d[y]={value:_}}}}const g=new Te(this.identifier,{name:t.name??"",uniforms:d,vertexShader:h,fragmentShader:c,lights:!1});switch(g.glslVersion=IC,g.vertexShader=g.vertexShader.replace("#version 300 es",""),g.fragmentShader=g.fragmentShader.replace("#version 300 es",""),d._Cull?.value){case 0:g.side=Oi;break;case 1:g.side=Id;break;case 2:g.side=ws;break;default:g.side=ws;break}switch(d._ZTest?.value){case 3:g.depthTest=!0,g.depthFunc=zC;break;case 6:g.depthTest=!0,g.depthFunc=UC;break;case 2:g.depthTest=!0,g.depthFunc=FC;break;case 4:g.depthTest=!0,g.depthFunc=BC;break;case 5:g.depthTest=!0,g.depthFunc=DC;break;case 7:g.depthTest=!0,g.depthFunc=jC;break;case 8:g.depthTest=!1,g.depthFunc=LC;break}g.transparent=m,m&&(g.depthWrite=!1),oE(d),g.onUpdateUniforms();for(const f in p){const y=f,_=p[f].type;d[y]?.value===void 0&&(_===Bx.SAMPLER_2D?(d[y]={value:iE},console.warn("Missing/unassigned texture, fallback to white: "+y)):y==="unity_OrthoParams"||console.warn("TODO: EXPECTED UNIFORM / fallback NOT SET: "+y,p[f]))}ro&&console.log(g.uuid,d),Fx(g),r(g)}):null}}function Fx(o){if(o.uniforms){ro&&console.log("Uniforms:",o.uniforms);for(const t in o.uniforms)switch(e(t,t),t){case"_Color":e("color",t);break;case"_map":e("map",t);break}}function e(t,i){Object.getOwnPropertyDescriptor(o,t)||Object.defineProperty(o,t,{get:()=>o.uniforms[i].value,set:n=>{o.uniforms[i].value=n,o.needsUpdate=!0}})}}const bT=w("debugextensions");let op;const _T=import("./vendor-DZ45lcA8.min.js").then(o=>o.index$2).then(async o=>(op=o.GLTFAnimationPointerExtension,op)).catch(o=>{console.warn("Failed to import GLTFLoaderAnimationPointer. Please use @needle-tools/three-animationpointer for full KHR_animation support",o)}),Zr=new Array;function vT(o){Zr.includes(o)||Zr.push(o)}function wT(o){const e=Zr.indexOf(o);e>=0&&Zr.splice(e,1)}function hy(o){if(o instanceof Eo){const e=new Lx;return o.register(t=>(e.parser=t,e)),e}return null}class xT{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 sp(o,e,t,i){const n=t.indexOf("?");n>=0&&(t=t.substring(0,n)),i||(i=t),(i.startsWith("blob:")||i.startsWith("data:"))&&console.debug("[GLTFLoader] Suspicious sourceId detected"),o.register(s=>new uT(s)),o.register(s=>new MM(s)),o.register(s=>new KM(s,e.lightmaps,i)),o.register(s=>new pT(s,i,e)),o.register(s=>new yT(s,i)),o.register(s=>new mr(s,i)),o.register(s=>new Ve(s)),o.register(s=>new lT(s)),o.register(s=>new gT(e,o,t,s)),Rv()&&o.register(s=>new sc(s)),await _T.catch(s=>{}),o.register(s=>{if(op){const r=new op(s);return r.setAnimationPointerResolver.bind(r)(new xT),r}else return(bT||A())&&console.error("Missing KHR_animation_pointer extension..."),{name:"KHR_animation_pointer_NOT_AVAILABLE"}});for(const s of Zr)s.onImport&&s.onImport(o,t,e)}function dy(o,e){for(const t of Zr)t.onExport&&t.onExport(o,e)}function Ux(o,e,t){for(const i of Zr)i.onLoaded&&i.onLoaded(o,e,t)}const Wt=w("debuginstancing");class Oa{static instance=new Oa;static getStartInstanceCount=e=>4;objs=[];setup(e,t,i,n,s,r=0){e.applySettings(t);const a=this.tryCreateOrAddInstance(t,i,s);if(a){n===null&&(n=[]),n.push(a);const l=a.object.material;Array.isArray(l)?l.forEach(d=>Ve.assignTextureLOD(d,0)):Ve.assignTextureLOD(l,0);const c=a.object,h=c.geometry;Ve.assignMeshLOD(c,0).then(d=>{d&&h!=d&&a.setGeometry(d)})}else if(r<=0&&t.type!=="Mesh"){const l=r+1;for(const c of t.children)n=this.setup(e,c,i,n,s,l)}return r===0&&s.useMatrixWorldAutoUpdate&&n&&n.length>=0&&this.autoUpdateInstanceMatrix(t),n}tryCreateOrAddInstance(e,t,i){if(e.type==="Mesh"){const n=i.foundMeshes;if(i.foundMeshes+=1,!i.rend.enableInstancing)return null;if(i.rend.enableInstancing!==!0){if(n>=i.rend.enableInstancing.length)return Wt&&console.error("Something is wrong with instance setup",e,i.rend.enableInstancing,n),null;if(!i.rend.enableInstancing[n])return null}const s=e,r=s.material;for(const h of this.objs)if(!!h.canAdd(s.geometry,r))return h.addInstance(s);let a=Oa.getStartInstanceCount(e);(!a||a<0)&&(a=4);let l=e.name;l?.length||(l=t_());const c=new ST(l,s.geometry,r,a,t);return this.objs.push(c),c.addInstance(s)}return null}autoUpdateInstanceMatrix(e){const t=e.matrixWorld.multiplyMatrices.bind(e.matrixWorld),i=e.matrixWorld.clone(),n=(s,r)=>{const a=t(s,r);return(e[Rc]||i.equals(a)===!1)&&(i.copy(a),e[Rc]=!0),a};e.matrixWorld.multiplyMatrices=n}}class Ra{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[Dv]=t,this.meshInformation=Kr(e.geometry),Ra.all.push(this)}updateMeshInformation(){const e=Kr(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()||Wt)&&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=Ra.all.indexOf(this);t>=0&&Ra.all.splice(t,1)}}}class ST{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(),Wt&&this._batchedMesh.boundingSphere){const i=this._batchedMesh.boundingSphere;B.DrawWireSphere(i.center,i.radius,65280)}}_context;_batchedMesh;_handles=[];_geometryIds=new WeakMap;_maxInstanceCount;_currentInstanceCount=0;_currentVertexCount=0;_currentIndexCount=0;_maxVertexCount;_maxIndexCount;static nullMatrix=new J;canAdd(e,t){return this._maxVertexCount>1e7||t!==this.material||!this.validateGeometry(e)?!1:!!(!this.mustGrow(e)||this.allowResize)}_needUpdateBounds=!1;_debugMaterial=null;getBatchedMeshName(){return this.name?`${this.name} (BatchedMesh)`:"BatchedMesh"}constructor(e,t,i,n,s){this.name=e,this.geometry=t,this.material=i,this._context=s,this._maxInstanceCount=Math.max(2,n),Wt&&(this._debugMaterial=zx());const r=this.tryEstimateVertexCountSize(this._maxInstanceCount,[t],n);this._maxVertexCount=r.vertexCount,this._maxIndexCount=r.indexCount,this._batchedMesh=new Mb(this._maxInstanceCount,this._maxVertexCount,this._maxIndexCount,this._debugMaterial??this.material),this._batchedMesh.name=this.getBatchedMeshName(),this._batchedMesh[Tc]=!0,this._batchedMesh.visible=!0,this._context.scene.add(this._batchedMesh),i instanceof kb&&(i.defines.USE_INSTANCING=!0,i.needsUpdate=!0),s.pre_render_callbacks.push(this.onBeforeRender),s.post_render_callbacks.push(this.onAfterRender),Wt&&console.log(`Instanced renderer (${this.name}) created with ${this._maxInstanceCount} instances, ${this._maxVertexCount} max vertices and ${this._maxIndexCount} max indices for "${e}"`)}dispose(){Wt&&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 Ra(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()})
|
|
1002
1002
|
`,i),A()){_c("Failed instancing mesh. See the browser console for details.");debugger}return null}return t}add(e){const t=e.object.geometry;if(!t||!t.attributes)return console.error("Cannot add object to instancing without geometry",e.name),!1;if(this._currentInstanceCount+1>this._maxInstanceCount||this.mustGrow(t))if(this.allowResize)this.grow(t);else return console.error("Cannot add instance, max count reached",this.name,this.count,this._maxInstanceCount),!1;return e.object.updateWorldMatrix(!0,!0),this.addGeometry(e),this._handles[e.__instanceIndex]=e,this._currentInstanceCount+=1,this.markNeedsUpdate(),this._currentInstanceCount>0&&(this._batchedMesh.visible=!0),!0}remove(e,t){e&&(e.__instanceIndex<0||this._handles[e.__instanceIndex]!=e||this._currentInstanceCount<=0||(this.removeGeometry(e,t),this._handles[e.__instanceIndex]=null,e.__instanceIndex=-1,this._currentInstanceCount>0&&(this._currentInstanceCount-=1),this._currentInstanceCount<=0&&(this._batchedMesh.visible=!1),this.markNeedsUpdate()))}updateInstance(e,t){this._batchedMesh.setMatrixAt(t,e),this.markNeedsUpdate()}updateGeometry(e,t){return this.validateGeometry(e)?(this.mustGrow()&&this.grow(e),Wt&&console.debug("[Instancing] UPDATE GEOMETRY at "+t,this._batchedMesh._geometryCount,e.name,Kr(e),e.attributes.position.count,e.index?e.index.count:0),this._batchedMesh.setGeometryAt(t,e),this._geometryIds.set(e,t),this.markNeedsUpdate(),!0):!1}onBeforeRender=()=>{this._batchedMesh.layers.enableAll(),this._needUpdateBounds&&this._batchedMesh[Tc]===!0&&(Wt==="verbose"&&console.log("Update instancing bounds",this.name,this._batchedMesh.matrixWorldNeedsUpdate),this.updateBounds())};onAfterRender=()=>{this._batchedMesh.layers.disableAll()};validateGeometry(e){const t=this.geometry;for(const i in t.attributes)if(i!=="batchId"&&!e.hasAttribute(i))return A()&&console.warn(`BatchedMesh: Added geometry missing "${i}". All geometries must have consistent attributes.`),!1;return!0}markNeedsUpdate(){Wt==="verbose"&&console.warn("Marking instanced mesh dirty",this.name),this._needUpdateBounds=!0}mustGrow(e){if(this.count>=this._maxInstanceCount)return!0;if(!e||!e.attributes||this._geometryIds.has(e))return!1;const t=Kr(e),i=t.vertexCount,n=t.indexCount;return this._currentVertexCount+i>this._maxVertexCount||this._currentIndexCount+n>this._maxIndexCount}_growId=0;grow(e){const t=++this._growId,i=this.count>=this._maxInstanceCount?Math.ceil(this._maxInstanceCount*2):this._maxInstanceCount,n=this.tryEstimateVertexCountSize(i,[e]),s=1.25,r=Math.max(this._maxVertexCount,Math.ceil(n.vertexCount*s)),a=Math.max(this._maxIndexCount,Math.ceil(n.indexCount*s));if(Wt){const h=Kr(e);console.warn(`[Instancing] Growing Buffer
|
|
1003
1003
|
Mesh: "${this.name}${e.name?.length?"/"+e.name:""}" (${h.vertexCount.toLocaleString()} vertices, ${h.indexCount.toLocaleString()} indices)
|
|
1004
1004
|
Max count ${this._maxInstanceCount.toLocaleString()} \u2192 ${i.toLocaleString()}
|
|
@@ -1199,7 +1199,7 @@ def "${i}_doubleSided" (
|
|
|
1199
1199
|
def "Materials"
|
|
1200
1200
|
{
|
|
1201
1201
|
${i.join("")}
|
|
1202
|
-
}`}function on(o){return Di(o.name)+"_"+(o.source?.id??o.id)}function zs(o,e,t,i,n,s,r=void 0,a=void 0){const l=on(o),c=l+(a!==void 0&&a!==1?"_"+a:""),h=t&&a!==void 0&&a!==1,d=h?new ye(1,1,1,a):void 0;a===void 0&&(a=1),h&&(a=1),d&&d.w<=.05&&(d.w=.05),i[c]={texture:o,scale:d};const p=o.channel>0?"st"+o.channel:"st";s.add(o.channel);const m=My.includes(o.format),g={1e3:"repeat",1001:"clamp",1002:"mirror"},f=o.repeat.clone(),y=o.offset.clone(),_=o.rotation,v=Math.sin(_),P=Math.cos(_);y.y=1-y.y-f.y,t?(f.x===0&&(f.x=1e-4),f.y===0&&(f.y=1e-4),y.x=y.x/f.x,y.y=y.y/f.y,y.x+=v/f.x,y.y+=P-1):(y.x+=v*f.x,y.y+=(1-P)*f.y);const k=fp(n),O=f.x!=1||f.y!=1||y.x!=0||y.y!=0||_!=0,
|
|
1202
|
+
}`}function on(o){return Di(o.name)+"_"+(o.source?.id??o.id)}function zs(o,e,t,i,n,s,r=void 0,a=void 0){const l=on(o),c=l+(a!==void 0&&a!==1?"_"+a:""),h=t&&a!==void 0&&a!==1,d=h?new ye(1,1,1,a):void 0;a===void 0&&(a=1),h&&(a=1),d&&d.w<=.05&&(d.w=.05),i[c]={texture:o,scale:d};const p=o.channel>0?"st"+o.channel:"st";s.add(o.channel);const m=My.includes(o.format),g={1e3:"repeat",1001:"clamp",1002:"mirror"},f=o.repeat.clone(),y=o.offset.clone(),_=o.rotation,v=Math.sin(_),P=Math.cos(_);y.y=1-y.y-f.y,t?(f.x===0&&(f.x=1e-4),f.y===0&&(f.y=1e-4),y.x=y.x/f.x,y.y=y.y/f.y,y.x+=v/f.x,y.y+=P-1):(y.x+=v*f.x,y.y+=(1-P)*f.y);const k=fp(n),O=f.x!=1||f.y!=1||y.x!=0||y.y!=0||_!=0,D=`${ii}/${k}/${"uvReader_"+p}.outputs:result>`,L=`${ii}/${k}/Transform2d_${e}.outputs:result>`,V=e!=="normal"&&r&&(r.r!==1||r.g!==1||r.b!==1||a!==1)||!1,W=e==="normal",G=n instanceof gt&&n.normalScale?n.normalScale.x*2:2,X=G.toFixed(Ee),R=(-1*(G/2)).toFixed(Ee),$=(1-G).toFixed(Ee);return`
|
|
1203
1203
|
${O?`def Shader "Transform2d_${e}" (
|
|
1204
1204
|
sdrMetadata = {
|
|
1205
1205
|
string role = "math"
|
|
@@ -1207,7 +1207,7 @@ ${i.join("")}
|
|
|
1207
1207
|
)
|
|
1208
1208
|
{
|
|
1209
1209
|
uniform token info:id = "UsdTransform2d"
|
|
1210
|
-
float2 inputs:in.connect = ${
|
|
1210
|
+
float2 inputs:in.connect = ${D}
|
|
1211
1211
|
float2 inputs:scale = ${m1(f)}
|
|
1212
1212
|
float2 inputs:translation = ${m1(y)}
|
|
1213
1213
|
float inputs:rotation = ${(_/Math.PI*180).toFixed(Ee)}
|
|
@@ -1219,7 +1219,7 @@ ${i.join("")}
|
|
|
1219
1219
|
uniform token info:id = "UsdUVTexture"
|
|
1220
1220
|
asset inputs:file = @textures/${c}.${m?"png":"jpg"}@
|
|
1221
1221
|
token inputs:sourceColorSpace = "${o.colorSpace==="srgb"?"sRGB":"raw"}"
|
|
1222
|
-
float2 inputs:st.connect = ${O?L:
|
|
1222
|
+
float2 inputs:st.connect = ${O?L:D}
|
|
1223
1223
|
${V?`
|
|
1224
1224
|
float4 inputs:scale = (${r?r.r+", "+r.g+", "+r.b:"1, 1, 1"}, ${a})
|
|
1225
1225
|
`:""}
|
|
@@ -1286,7 +1286,7 @@ ${r.join(`
|
|
|
1286
1286
|
`)}`:""}
|
|
1287
1287
|
}`}function p1(o){return`(${o.r}, ${o.g}, ${o.b})`}function m1(o){return`(${o.x}, ${o.y})`}const My=[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 jt{static global_id=0;id;trigger;action;exclusive=!1;makeExclusive(e){return this.exclusive=e,this}constructor(e,t,i){this.id="Behavior_"+Di(e)+"_"+jt.global_id++,this.trigger=t,this.action=i}writeTo(e,t,i){if(!this.trigger||!this.action)return;i.beginBlock(`def Preliminary_Behavior "${this.id}"`);let n="";if(Array.isArray(this.trigger)){n="[";for(let s=0;s<this.trigger.length;s++){const r=this.trigger[s];n+="<"+r.id+">",s+1<this.trigger.length&&(n+=", ")}n+="]"}else n=`<${this.trigger.id}>`;if(i.appendLine(`rel triggers = ${n}`),i.appendLine(`rel actions = <${this.action.id}>`),i.appendLine(`uniform bool exclusive = ${this.exclusive?1:0}`),i.appendLine(),Array.isArray(this.trigger))for(const s of this.trigger)s.writeTo(t,i),i.appendLine();else this.trigger.writeTo(t,i);i.appendLine(),this.action.writeTo(t,i),i.closeBlock()}}const Pl=new Set;function Ey(o,e){let t="";if(Array.isArray(o)){Pl.clear();let i="[ ";for(let n=0;n<o.length;n++){let s=o[n];if(!s){console.warn("Invalid target object in behavior",o+". Is the object exported?");continue}if(typeof s=="string"){if(Pl.has(s))continue;i+=s,Pl.add(s)}else if(typeof s=="object"){if(s.isObject3D&&(s=e.findById(s.uuid),!s)){console.warn("Invalid target object in behavior",o+". Is the object exported?");continue}const r=s.getPath?.call(s);if(Pl.has(r))continue;i+=r,Pl.add(r)}n+1<o.length&&(i+=", ")}i+=" ]",t=i,Pl.clear()}else if(typeof o=="object"){const i=o;if(i.isObject3D&&(o=e.findById(i.uuid)),!o)throw console.error("Invalid target object in behavior, the target object is likely missing from USDZ export. Is the object exported?",i),new Error(`Invalid target object in behavior, the target object is likely missing from USDZ export. Please report a bug. uuid: ${i.uuid}.`);t=o.getPath?.call(o)}return t}class dr{static global_id=0;id;targetId;tokenId;type;distance;constructor(e,t){e&&(this.targetId=e),t?this.id=t:this.id="Trigger_"+dr.global_id++}writeTo(e,t){t.beginBlock(`def Preliminary_Trigger "${this.id}"`),this.targetId&&(typeof this.targetId!="string"&&(this.targetId=Ey(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 g1(o,e={direct:!0,indirect:!0}){const t=rt.createEmpty();t.name="InputTarget_"+t.name,t.displayName=void 0,t.type="RealityKitComponent",t.onSerialize=i=>{i.appendLine("bool allowsDirectInput = "+(e.direct?1:0)),i.appendLine("bool allowsIndirectInput = "+(e.indirect?1:0)),i.appendLine('uniform token info:id = "RealityKit.InputTarget"')},o.add(t)}class $t{static __sceneStartTrigger;static sceneStartTrigger(){if(this.__sceneStartTrigger!==void 0)return this.__sceneStartTrigger;const e=new dr(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 dr(e);if(Array.isArray(e)&&e.length>1)for(const n of e)n instanceof rt&&g1(n,t);else e instanceof rt&&g1(e,t);return i.tokenId="TapGesture",i}static isTapTrigger(e){return e?.tokenId==="TapGesture"}static proximityToCameraTrigger(e,t){const i=new dr(e);return i.tokenId="ProximityToCamera",i.distance=t,i}}class Jr{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 Ci{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 Ci,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+="_"+Ci.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=Ey(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=Ey(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 bn{x=0;y=0;z=0;constructor(e,t,i){this.x=e,this.y=t,this.z=i}static get up(){return new bn(0,1,0)}static get right(){return new bn(1,0,0)}static get forward(){return new bn(0,0,1)}static get back(){return new bn(0,0,-1)}static get zero(){return new bn(0,0,0)}}class fe{static sequence(...e){return new Jr("Group_"+Jr.getId(),e).makeSequence()}static parallel(...e){return new Jr("Group_"+Jr.getId(),e).makeParallel()}static fadeAction(e,t,i){const n=new Ci(e);return n.tokenId="Visibility",n.type=i?"show":"hide",n.duration=t,n.style="basic",n.motionType="none",n.moveDistance=0,n.easeType="none",n}static startAnimationAction(e,t,i=!1,n=!1){const s=new Ci(e);s.tokenId="StartAnimation";const r=t.start,a=t.duration,l=t.speed,c=t.clipName;if(s.comment=`Animation: ${c}, start=${r*60}, length=${a*60}, end=${(r+a)*60}`,s.animationName=c,s.start=r,s.duration=a,s.animationSpeed=l,s.reversed=i,s.pingPong=n,s.multiplePerformOperation="allow",i&&(s.start-=a),n){s.pingPong=!1;const h=s.clone();return h.reversed=!i,h.start=s.start,h.reversed&&(h.start-=a),fe.sequence(s,h)}return s}static waitAction(e){const t=new Ci;return t.tokenId="Wait",t.duration=e,t.motionType=void 0,t}static lookAtCameraAction(e,t,i,n){const s=new Ci(e);return s.tokenId="LookAtCamera",s.duration=t===void 0?9999999999999:t,s.front=i??bn.forward,s.up=n??bn.up,s}static emphasize(e,t,i="bounce",n=1,s="basic"){const r=new Ci(e);return r.tokenId="Emphasize",r.duration=t,r.style=s??"basic",r.motionType=i,r.moveDistance=n,r}static transformAction(e,t,i,n,s="inout"){const r=new Ci(e);return r.tokenId="Transform",r.duration=i,r.duration=Math.max(1e-6,i),r.type=n,r.easeType=i>0?s:"none",Array.isArray(t)&&console.error("Transform target must not be an array",t),r.xFormTarget=t,r}static playAudioAction(e,t,i="play",n=1,s="spatial"){const r=new Ci(e);return r.tokenId="Audio",r.type=i,r.audio=t,r.gain=n,r.auralMode=s,r.multiplePerformOperation="allow",r}static impulseAction(e,t){const i=new Ci(e);return i.tokenId="Impulse",i.velocity=t,i}}class iA{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 Ry extends iA{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||rt.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=fe.fadeAction(this.object,0,!0),this._enableAction)}disable(){return this._disableAction?this._disableAction:(this._disableAction=fe.fadeAction(this.object,0,!1),this._disableAction)}}class f1{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 lo=w("debugusdzanimation"),Ty=w("debugusdzanimationserialization");class fr{_start;get start(){return this._start===void 0&&(this._start=this.ext.getStartTimeByClip(this.clip)),this._start}get duration(){return this.clip?.duration??Ne.restPoseClipDuration}get nearestAnimatedRoot(){return this._nearestAnimatedRoot}get clipName(){return this.clip?.name??"rest"}ext;root;_nearestAnimatedRoot=void 0;clip;speed;constructor(e,t,i){this.ext=e,this.root=t,this.clip=i,this._nearestAnimatedRoot=this.getNearestAnimatedRoot()}static isDescendantOf(e,t){let i=t;if(!i||!e)return!1;for(;i;){if(!i)return!1;if(i===e)return!0;i=i.parent}return!1}getNearestAnimatedRoot(){let e;try{for(const t of this.clip?.tracks??[]){const i=La.parseTrackName(t.name);let n=La.findNode(this.root,i.nodeName);if(n)if(!e)e=n;else{if(n===e||fr.isDescendantOf(e,n))continue;if(!fr.isDescendantOf(n,e)){for(;!fr.isDescendantOf(n,e)&&n.parent;)n=n.parent;fr.isDescendantOf(n,e)||console.error("USDZExporter: Animation clip targets multiple roots that are not parent/child. Please report a bug",this.root,this.clip,e,n)}e=n}}}catch(t){console.error("USDZExporter: Exception when trying to find nearest animated root. Please report a bug",t),e=void 0}return e}}class Ne{clip;pos;rot;scale;root;target;duration=0;useRootMotion=!1;static frameRate=60;static animationDurationPadding=6/60;static restPoseClipDuration=6/60;constructor(e,t,i){if(this.root=e,this.target=t,this.clip=i,i?this.duration=i.duration:this.duration=Ne.restPoseClipDuration,i&&i.tracks){const s=Math.max(...i.tracks.map(r=>r.times[r.times.length-1]));s!==this.duration&&(console.warn("USDZExporter: Animation clip duration does not match the maximum time value in the tracks.",i,s,this.duration),this.duration=s)}const n=S.getComponent(e,_t);n&&(this.useRootMotion=n.applyRootMotion)}addTrack(e){if(!this.clip){console.error("This is a rest clip but you're trying to add tracks to it \u2013 this is likely a bug");return}e.name.endsWith("position")?this.pos=e:e.name.endsWith("quaternion")?this.rot=e:e.name.endsWith("scale")?this.scale=e:(e.name.endsWith("activeSelf")?console.warn("[USDZ] Animation of enabled/disabled state is not supported for USDZ export and will NOT be exported: "+e.name+" on "+(this.root?.name??this.target.name)+". Animate scale 0/1 instead."):console.warn("[USDZ] Animation track type not supported for USDZ export and will NOT be exported: "+e.name+" on "+(this.root?.name??this.target.name)+". Only .position, .rotation, .scale are supported."),A()&&be("[USDZ] Some animations can't be exported. See console for details."))}getFrames(){return this.clip?Math.max(this.pos?.times?.length??0,this.rot?.times?.length??0,this.scale?.times?.length??0):2}getDuration(){return this.duration}getSortedTimesArray(e=!0,t=!0,i=!0){if(!this.clip)return[0,this.duration];const n=this.pos?.times,s=this.rot?.times,r=this.scale?.times,a=[];if(e&&n)for(const l of n)a.push(l);if(t&&s)for(const l of s)a.push(l);if(i&&r)for(const l of r)a.push(l);return a.includes(0)||a.push(0),a.sort((l,c)=>l-c),[...new Set(a)]}*getValues(e,t=!0,i=!0,n=!0){const s=new b,r=new N,a=new b(1,1,1),l=this.target,c=t?this.pos?.createInterpolant():void 0,h=i?this.rot?.createInterpolant():void 0,d=n?this.scale?.createInterpolant():void 0;c||s.set(l.position.x,l.position.y,l.position.z),h||r.set(l.quaternion.x,l.quaternion.y,l.quaternion.z,l.quaternion.w),d||a.set(l.scale.x,l.scale.y,l.scale.z),c&&c.valueSize!==3&&(c.valueSize=3),h&&h.valueSize!==4&&(h.valueSize=4),d&&d.valueSize!==3&&(d.valueSize=3);const p=0;for(let m=0-p;m<e.length+p;m++){let g=0,f=0;if(m<0?(g=e[0],f=g-Ne.animationDurationPadding/2+1/60):m>=e.length?(g=e[e.length-1],f=g+Ne.animationDurationPadding/2-1/60):(g=e[m],f=g),c){const y=c.evaluate(g);s.set(y[0],y[1],y[2])}if(h){const y=h.evaluate(g);r.set(y[0],y[1],y[2],y[3])}if(d){const y=d.evaluate(g);a.set(y[0],y[1],y[2])}if(this.useRootMotion&&l===this.root){const y=new J;y.compose(s,r,a),y.multiply(l.matrix),y.decompose(s,r,a)}yield{time:f,translation:s,rotation:r,scale:a,index:m}}}}class _p{get extensionName(){return"animation"}get animationData(){return this.dict}get registeredClips(){return this.clipToStartTime.keys()}get animatedRoots(){return this.rootTargetMap.keys()}get holdClipMap(){return this.clipToHoldClip}dict=new Map;rootTargetMap=new Map;rootAndClipToRegisteredAnimationMap=new Map;rootToRegisteredClip=new Map;lastClipEndTime=0;clipToStartTime=new Map;clipToHoldClip=new Map;serializers=[];injectRestPoses=!1;injectImplicitBehaviours=!1;constructor(e){this.injectRestPoses=e,this.injectImplicitBehaviours=e}getStartTimeCode(){return!this.injectRestPoses||this.rootAndClipToRegisteredAnimationMap.size===0?0:(Ne.restPoseClipDuration+Ne.animationDurationPadding)*60}getEndTimeCode(){let e=0;for(const[t,i]of this.rootAndClipToRegisteredAnimationMap){const n=i.start+i.duration;n>e&&(e=n)}return e*60}getClipCount(e){return this.rootToRegisteredClip.get(e)?.length??0??0}getStartTimeByClip(e){return e?this.clipToStartTime.has(e)?this.clipToStartTime.get(e):(console.error("USDZExporter: Missing start time for clip \u2013 please report a bug.",e),0):0}registerAnimation(e,t){if(!e)return null;this.rootTargetMap.has(e)||this.rootTargetMap.set(e,[]);const i=e.uuid+(t?.uuid??"-rest");if(this.rootAndClipToRegisteredAnimationMap.has(i))return this.rootAndClipToRegisteredAnimationMap.get(i);lo&&console.log("registerAnimation",e,t);const n=this.injectRestPoses?1:0,s=(this.rootToRegisteredClip.get(e)?.length??0)+n,r=this.rootTargetMap.get(e),a=new Set(r);if(t&&t.tracks)for(const c of t.tracks){const h=La.parseTrackName(c.name),d=La.findNode(e,h.nodeName);if(!d){console.warn("no object found for track",c.name,"using "+e.name+" instead");continue}this.dict.has(d)||this.dict.set(d,[]);const p=this.dict.get(d);if(!p){console.warn("no transform data found for target ",d,"at slot "+s+", this is likely a bug");continue}a.delete(d),this.injectRestPoses&&!p[0]&&(console.log("Injecting rest pose",d,t,"at slot",s),p[0]=new Ne(null,d,null));let m=p[s];m||(m=new Ne(e,d,t),p[s]=m),m.addTrack(c),r?.includes(d)||r?.push(d)}lo&&console.log("Unregistered nodes for this clip",a,"clip",t,"at slot",s,"for root",e,"targets",r);for(const c of a){const h=this.dict.get(c);if(!h)continue;if(this.injectRestPoses&&!h[0]){console.warn("Adding rest pose for ",c,t,"at slot",s,"This is likely a bug, should have been added earlier.");const p=new Ne(null,c,null);h[0]=p}let d=h[s];d||(lo&&console.log("Adding padding clip for ",c,t,"at slot",s),d=new Ne(e,c,t),h[s]=d)}const l=new fr(this,e,t);if(this.rootAndClipToRegisteredAnimationMap.set(i,l),lo&&console.log({root:e,clip:t,info:l}),t){const c=this.rootToRegisteredClip.get(e);if(c?c.push(t):this.rootToRegisteredClip.set(e,[t]),!this.clipToStartTime.get(t)){this.lastClipEndTime==null&&(this.lastClipEndTime=Ne.restPoseClipDuration);let h=this.lastClipEndTime+Ne.animationDurationPadding,d=h+t.duration;const p=Math.round(h*60)/60,m=Math.round(d*60)/60;Math.abs(p-h)<.01&&(h=p),Math.abs(m-d)<.01&&(d=m),h=Math.ceil(h),d=h+t.duration,this.clipToStartTime.set(t,h),this.lastClipEndTime=d}}return l}onAfterHierarchy(e){lo&&console.log("Animation clips per animation target node",this.dict)}onAfterBuildDocument(e){lo&&console.log("Animation data",{dict:this.dict,rootTargetMap:this.rootTargetMap,rootToRegisteredClip:this.rootToRegisteredClip});for(const t of this.rootTargetMap.keys()){const i=this.rootTargetMap.get(t);if(!i)continue;let n;const s=[];for(const r of i){const a=this.dict.get(r);if(!a){console.error("No data found for target on USDZ export \u2013 please report a bug!",r);continue}n===void 0&&(n=a?.length),n!==a?.length&&console.error("Different array lengths for targets \u2013 please report a bug!",a);for(let l=0;l<a.length;l++){let c=a[l];if(!c){const d=l-(this.injectRestPoses?1:0);a[l]=new Ne(null,r,this.rootToRegisteredClip.get(t)[d]),c=a[l]}const h=c.getDuration();if(s[l]===void 0)s[l]=h;else if(s[l]!==h){console.error("Error during UDSZ export: Encountered different animation durations for animated targets. Please report a bug!",{datas:a,target:r}),s[l]=h;continue}}}}for(const t of this.serializers){const i=t.model?.parent,n=i?.isDynamic===!0;Ty&&console.log(n,t.model?.parent),n&&t.registerCallback(i)}}onExportObject(e,t,i){S.foreachComponent(e,s=>{const r=s;typeof r.createAnimation=="function"&&r.createAnimation(this,t,i)},!1);const n=new nA(e,this);this.serializers.push(n),n.registerCallback(t)}}class nA{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)),Ty&&console.log("REPARENT",e),this.model=e,this.callback&&this.model.addEventListener("serialize",this.callback)}skinnedMeshExport(e,t,i){const n=this.model,s=this.animationData;if(n&&n.skinnedMesh){let r=function(R){const $=[];for(const[q,he]of R){let re=`${q} : [`;const me=[];for(const te of he)me.push(`(${ce(te.x)}, ${ce(te.y)}, ${ce(te.z)})`);re=re.concat(me.join(", ")),re=re.concat("],"),$.push(re)}return $},a=function(R){const $=[];for(const[q,he]of R){let re=`${q} : [`;const me=[];for(const te of he)me.push(`(${ce(te.w)}, ${ce(te.x)}, ${ce(te.y)}, ${ce(te.z)})`);re=re.concat(me.join(", ")),re=re.concat("],"),$.push(re)}return $},l=function(R){let $,q=!0;const he=new Map;for(const[me,te]of R){$===void 0&&($=te.length),$!==te.length&&(q=!1);let We=0;for(const ci of te)We++,ci||(he.has(me)||he.set(me,[]),he.get(me).push(We))}lo&&console.log("Bone count: ",R.size,"TransformData entries per bone: ",$,"Undefined bone entries: ",he),console.assert(q,"All bones should have the same number of TransformData entries",R),console.assert(he.size===0,"All TransformData entries should be set",he);const re=[];for(const[me,te]of R)for(let We=0;We<te.length;We++){const ci=te[We],Sd=i.getStartTimeByClip(ci.clip);re.length<=We&&re.push({pos:[],rot:[],scale:[],timeOffset:Sd});const bs=re[We];bs.pos.push(...ci.getSortedTimesArray(!0,!1,!1)),bs.rot.push(...ci.getSortedTimesArray(!1,!0,!1)),bs.scale.push(...ci.getSortedTimesArray(!1,!1,!0))}for(const me of re)me.pos.sort((te,We)=>te-We),me.rot.sort((te,We)=>te-We),me.scale.sort((te,We)=>te-We),me.pos=[...new Set(me.pos)],me.rot=[...new Set(me.rot)],me.scale=[...new Set(me.scale)];return re},c=function(R,$,q){const he=new Map,re=new Map,me=new Map,te=$.length;for(const We of q){const ci=R.get(We);let Sd;ci?console.assert(ci.length===te,"We should have the same number of TransformData entries for each bone",ci,$):Sd=new Ne(null,We,null);for(let bs=0;bs<te;bs++){const Om=ci?ci[bs]:Sd,Ta=$[bs];for(const{time:cc,translation:hc}of Om.getValues(Ta.pos,!0,!1,!1)){const _n=(cc+Ta.timeOffset)*60;he.has(_n)||he.set(_n,new Array),he.get(_n).push(hc.clone())}for(const{time:cc,rotation:hc}of Om.getValues(Ta.rot,!1,!0,!1)){const _n=(cc+Ta.timeOffset)*60;re.has(_n)||re.set(_n,new Array),re.get(_n).push(hc.clone())}for(const{time:cc,scale:hc}of Om.getValues(Ta.scale,!1,!1,!0)){const _n=(cc+Ta.timeOffset)*60;me.has(_n)||me.set(_n,new Array),me.get(_n).push(hc.clone())}}}return{position:he.size==0?void 0:he,quaternion:re.size==0?void 0:re,scale:me.size==0?void 0:me}},h=function(R){const $=[];for(const q of R)$.push(`(${ce(q.x)}, ${ce(q.y)}, ${ce(q.z)})`);return $.join(", ")},d=function(R){const $=[];for(const q of R)$.push(`(${ce(q.w)}, ${ce(q.x)}, ${ce(q.y)}, ${ce(q.z)})`);return $.join(", ")},p=function(R){const $=new Map;if(lo){const q=new Array;for(const[he,re]of s)q.push(he.uuid+": "+re.length+" "+re.map(me=>me.clip?.uuid.substring(0,6)).join(" "));console.log(`getPerBoneTransformData
|
|
1288
1288
|
`+q.join(`
|
|
1289
|
-
`))}for(const q of R){const he=s.get(q);he&&$.set(q,he)}return $},m=function(R){const $=p(R),q=l($);return c($,q,R)};const g=n.skinnedMesh.skeleton,f=new Array,y=[],_=[];for(const R of g.bones){y.push(R),_.push(R.uuid);const $=g.boneInverses[g.bones.indexOf(R)];f.push({bone:R,inverse:$})}let v=1e4;for(;_.length<g.bones.length&&v-- >0;)for(const R of y){const $=R.children;for(const q of $)if(_.indexOf(q.uuid)===-1&&g.bones.indexOf(q)!==-1){y.push(q),_.push(q.uuid);const he=g.boneInverses[g.bones.indexOf(q)];f.push({bone:q,inverse:he})}}v<=0&&console.error("Failed to sort bones in skinned mesh",n.skinnedMesh,g.bones,_);for(const R of Kx(g.bones))f.push({bone:R,inverse:R.matrixWorld.clone().invert()});const P=f[0].bone.parent;P||console.error("No bone parent found for skinned mesh during USDZ export",n.skinnedMesh),f.sort((R,$)=>Cl(R.bone,P)>Cl($.bone,P)?1:-1);const k=t.quickLookCompatible,O=[],j=[],L=[],V=[];for(const{bone:R}of f){if(k){const $=R.scale;$.x==0&&($.x=1e-5),$.y==0&&($.y=1e-5),$.z==0&&($.z=1e-5),O.push(new J().compose(R.position,R.quaternion,R.scale))}else O.push(R.matrix.clone());j.push(R.position),L.push(R.quaternion),V.push(R.scale)}const W=f.map(R=>'"'+Cl(R.bone,P)+'"').join(", "),G=f.map(R=>h1(R.inverse.clone().invert())).join(", ");e.beginBlock('def Skeleton "Rig"'),e.appendLine(`uniform matrix4d[] bindTransforms = [${G}]`),e.appendLine(`uniform token[] joints = [${W}]`),e.appendLine('uniform token purpose = "guide"'),e.appendLine(`uniform matrix4d[] restTransforms = [${O.map(R=>h1(R)).join(", ")}]`);const X=m(f.map(R=>R.bone));if(lo){let R=1e7,$=0;for(const q of X.position?.keys()??[])R=Math.min(R,q),$=Math.max($,q);console.log("Time samples",R,$,X)}if(e.beginBlock('def SkelAnimation "_anim"'),e.appendLine(`uniform token[] joints = [${W}]`),e.appendLine(`quatf[] rotations = [${d(L)}]`),X&&X.quaternion){e.beginBlock("quatf[] rotations.timeSamples = {","");const R=a(X.quaternion);for(const $ of R)e.appendLine($);e.closeBlock()}if(e.appendLine(`half3[] scales = [${h(V)}]`),X&&X.scale){e.beginBlock("half3[] scales.timeSamples = {","");const R=r(X.scale);for(const $ of R)e.appendLine($);e.closeBlock()}if(e.appendLine(`float3[] translations = [${h(j)}]`),X&&X.position){e.beginBlock("float3[] translations.timeSamples = {","");const R=r(X.position);for(const $ of R)e.appendLine($);e.closeBlock()}e.closeBlock(),e.closeBlock()}}onSerialize(e,t){if(!this.model)return;const i=this.animationData.get(this.object);if(i)for(let h=0;h<i.length;h++)i[h]===void 0&&(i[h]=new Ne(null,this.object,null));const n=this.ext;this.skinnedMeshExport(e,t,n);const s=this.object,r=this.model,a=this.animationData.get(s);if(!a||s.isSkinnedMesh)return;Ty&&console.log("SERIALIZE",this.model.name,this.object.type,a);const l=Intl.NumberFormat("en-US",{maximumFractionDigits:3,minimumFractionDigits:0,useGrouping:!1});function c(h,d){if(h.some(p=>p&&{position:p.pos,rotation:p.rot,scale:p.scale}[d])){switch(d){case"position":r.needsTranslate=!0,e.beginBlock("double3 xformOp:translate.timeSamples = {","");break;case"rotation":r.needsOrient=!0,e.beginBlock("quatf xformOp:orient.timeSamples = {","");break;case"scale":r.needsScale=!0,e.beginBlock("double3 xformOp:scale.timeSamples = {","");break}for(let p=0;p<h.length;p++){const m=h[p];if(!m)continue;const g=n.getStartTimeByClip(m.clip),f=m.getSortedTimesArray(d==="position",d==="rotation",d==="scale");if(!f||f.length===0){console.error("got an animated object but no time values?",s,m);continue}const y=!m.clip,_=d==="position"&&(m.pos||y),v=d==="rotation"&&(m.rot||y),P=d==="scale"&&(m.scale||y);if(_||v||P){const k=m.clip?.name??"rest",O=m.getDuration();lo&&console.log("Write .timeSamples:",k,g,O,h),e.appendLine("# "+k+": start="+l.format(g*Ne.frameRate)+", length="+l.format(O*Ne.frameRate)+", frames="+m.getFrames())}if(_)for(const{time:k,translation:O}of m.getValues(f,!0,!1,!1)){const j=`${l.format((g+k)*Ne.frameRate)}: (${ce(O.x)}, ${ce(O.y)}, ${ce(O.z)}),`;e.appendLine(j)}if(v)for(const{time:k,rotation:O}of m.getValues(f,!1,!0,!1)){const j=`${l.format((g+k)*Ne.frameRate)}: (${ce(O.w)}, ${ce(O.x)}, ${ce(O.y)}, ${ce(O.z)}),`;e.appendLine(j)}if(P)for(const{time:k,scale:O}of m.getValues(f,!1,!1,!0)){const j=`${l.format((g+k)*Ne.frameRate)}: (${ce(O.x)}, ${ce(O.y)}, ${ce(O.z)}),`;e.appendLine(j)}}e.closeBlock()}}c(a,"position"),c(a,"rotation"),c(a,"scale")}}const oA=w("debugusdz");class Pa{static getName(e){const t=e.split(".").pop();let i=e.split(".").slice(0,-1).join(".").split("/").pop()?.replace(".","_");return i||(i="Audio_"+Math.random().toString(36).substring(2,15)),Di(i)+"."+t}get extensionName(){return"Audio"}files=new Array;onExportObject(e,t,i){const n=S.getComponents(e,ji);if(n.length)for(const s of n){if(!s.clip||typeof s.clip!="string"||!s.playOnAwake)continue;const r=s.clip.split("/").pop()||"Audio",a=Pa.getName(s.clip),l=Di(a);if(!this.files.some(c=>c.path===s.clip)){this.files.push({path:s.clip,name:a});const c=a.toLowerCase();i.quickLookCompatible&&!c.endsWith(".mp3")&&!c.endsWith(".wav")&&!c.endsWith(".m4a")&&console.error("Audio file "+s.clip+" from "+s.name+" is not an MP3 or WAV file. QuickLook may not support playing it.")}i.quickLookCompatible||t.addEventListener("serialize",(c,h)=>{c.appendLine(),c.beginBlock(`def SpatialAudio "${l}"`,"(",!1),c.appendLine(`displayName = "${r}"`),c.closeBlock(")"),c.beginBlock(),c.appendLine(`uniform asset filePath = @audio/${a}@`),c.appendLine(`uniform token auralMode = "${s.spatialBlend>0?"spatial":"nonSpatial"}"`),c.appendLine(`uniform token playbackMode = "${s.loop?"loopFromStage":"onceFromStart"}"`),c.appendLine(`uniform float gain = ${s.volume}`),c.closeBlock()})}}async onAfterSerialize(e){for(const t of this.files){const i="audio/"+t.name;if(e.files[i]){oA&&console.warn("Audio file with name "+i+" already exists in the context. Skipping.");continue}const n=await(await(await fetch(t.path)).blob()).arrayBuffer(),s=new Uint8Array(n);e.files[i]=s}}}var sA=Object.defineProperty,Be=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&sA(e,t,n),n};const y1=w("debugusdzbehaviours");class ea extends E{object;target;duration=1;relativeMotion=!1;coroutine=null;targetPos=new b;targetRot=new N;targetScale=new b;onEnable(){this.context.accessibility.updateElement(this,{role:"button",label:"Move "+(this.object?.name||"object")+" to "+(this.target?.name||"target")+" on click",hidden:!1})}onDisable(){this.context.accessibility.updateElement(this,{hidden:!0})}onDestroy(){this.context.accessibility.removeElement(this)}onPointerEnter(){this.context.input.setCursor("pointer")}onPointerExit(){this.context.input.unsetCursor("pointer")}onPointerClick(e){const t=this.object?.getComponentsInChildren(Ke);if(t)for(const i of t)i.resetVelocities(),i.resetForcesAndTorques();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=ee(this.object).clone(),t=ee(this.target).clone(),i=_e(this.object).clone(),n=_e(this.target).clone(),s=$e(this.object).clone(),r=$e(this.target).clone(),a=e.distanceTo(t),l=i.angleTo(n),c=s.distanceTo(r);if(a<.01&&l<.01&&c<.01){yt(this.object,t),Sn(this.object,n),za(this.object,r),this.coroutine=null;return}let h=0,d=0;for(;h<1;)h+=this.context.time.deltaTime/this.duration,h>1&&(h=1),d=h<.5?4*h*h*h:1-Math.pow(-2*h+2,3)/2,this.targetPos.lerpVectors(e,t,d),this.targetRot.slerpQuaternions(i,n,d),this.targetScale.lerpVectors(s,r,d),yt(this.object,this.targetPos),Sn(this.object,this.targetRot),za(this.object,this.targetScale),yield;this.coroutine=null}*moveRelative(){if(!this.target||!this.object)return;const e=this.object.position.clone(),t=this.object.quaternion.clone(),i=this.object.scale.clone(),n=this.target.position.clone(),s=this.target.quaternion.clone(),r=this.target.scale.clone();n.applyQuaternion(this.object.quaternion),this.targetPos.copy(this.object.position).add(n),this.targetRot.copy(this.object.quaternion).multiply(s),this.targetScale.copy(this.object.scale).multiply(r);let a=0,l=0;for(;a<1;)a+=this.context.time.deltaTime/this.duration,a>1&&(a=1),l=a<.5?4*a*a*a:1-Math.pow(-2*a+2,3)/2,this.object.position.lerpVectors(e,this.targetPos,l),this.object.quaternion.slerpQuaternions(t,this.targetRot,l),this.object.scale.lerpVectors(i,this.targetScale,l),yield;this.coroutine=null}beforeCreateDocument(e){if(this.target&&this.object&&this.gameObject){const t=new jt("Move to "+this.target?.name,$t.tapTrigger(this.gameObject),fe.transformAction(this.object,this.target,this.duration,this.relativeMotion?"relative":"absolute"));e.addBehavior(t)}}}Be([u(M)],ea.prototype,"object"),Be([u(M)],ea.prototype,"target"),Be([u()],ea.prototype,"duration"),Be([u()],ea.prototype,"relativeMotion");const vp=class ri extends E{materialToSwitch;variantMaterial;fadeDuration=0;start(){this._objectsWithThisMaterial=this.objectsWithThisMaterial,A()&&this._objectsWithThisMaterial.length<=0&&console.warn('ChangeMaterialOnClick: No objects found with material "'+this.materialToSwitch?.name+'"')}onEnable(){this.context.accessibility.updateElement(this,{role:"button",label:"Change material to "+(this.variantMaterial?.name||"unknown material"),hidden:!1})}onDisable(){this.context.accessibility.updateElement(this,{hidden:!0})}onDestroy(){this.context.accessibility.removeElement(this)}onPointerEnter(e){this.context.input.setCursor("pointer")}onPointerExit(e){this.context.input.unsetCursor("pointer")}onPointerClick(e){if(e.use(),!!this.variantMaterial)for(let t=0;t<this.objectsWithThisMaterial.length;t++){const i=this.objectsWithThisMaterial[t];i.material=this.variantMaterial}}_objectsWithThisMaterial=null;get objectsWithThisMaterial(){return this._objectsWithThisMaterial!=null?this._objectsWithThisMaterial:(this._objectsWithThisMaterial=[],this.variantMaterial&&this.materialToSwitch&&this.context.scene.traverse(e=>{if(e instanceof H)if(Array.isArray(e.material)){for(const t of e.material)if(t===this.materialToSwitch){this.objectsWithThisMaterial.push(e);break}}else e.material===this.materialToSwitch?this.objectsWithThisMaterial.push(e):Zv(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=[],ri._materialTriggersPerId={},ri.variantSwitchIndex=0,this.materialToSwitch&&await Ve.assignTextureLOD(this.materialToSwitch,0),this.variantMaterial&&await Ve.assignTextureLOD(this.variantMaterial,0)}createBehaviours(e,t,i){this.objectsWithThisMaterial.find(n=>n.uuid===t.uuid)&&this.targetModels.push(t),this.gameObject.uuid===t.uuid&&(this.selfModel=t,this.materialToSwitch&&(ri._materialTriggersPerId[this.materialToSwitch.uuid]||(ri._materialTriggersPerId[this.materialToSwitch.uuid]=[]),ri._materialTriggersPerId[this.materialToSwitch.uuid].push(this)))}afterCreateDocument(e,t){if(!this.materialToSwitch)return;const i=ri._materialTriggersPerId[this.materialToSwitch.uuid];if(i){const n={};for(const s of i){const r=s.createVariants();r&&r.length>0&&(n[s.selfModel.uuid]=r)}for(const s of i){const r=[];for(const a in n)a!==s.selfModel.uuid&&r.push(...n[a]);s.createAndAttachBehaviors(e,n[s.selfModel.uuid],r)}}delete ri._materialTriggersPerId[this.materialToSwitch.uuid]}createAndAttachBehaviors(e,t,i){const n=[],s=Math.max(0,this.fadeDuration);n.push(fe.fadeAction([...this.targetModels,...i],s,!1)),n.push(fe.fadeAction(t,s,!0)),e.addBehavior(new jt("Select_"+this.selfModel.name,$t.tapTrigger(this.selfModel),fe.parallel(...n))),ri._parallelStartHiddenActions.push(...t),ri._startHiddenBehaviour||(ri._startHiddenBehaviour=new jt("StartHidden_"+this.selfModel.name,$t.sceneStartTrigger(),fe.fadeAction(ri._parallelStartHiddenActions,s,!1)),e.addBehavior(ri._startHiddenBehaviour))}static getMaterialName(e){return Di(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_"+ri.variantSwitchIndex+++"_"+ri.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())&&rt.createEmptyParent(t),t.parent&&t.parent.add(i),e.push(i)}return e}};Be([u(we)],vp.prototype,"materialToSwitch"),Be([u(we)],vp.prototype,"variantMaterial"),Be([u()],vp.prototype,"fadeDuration");let Ay=vp;const ch=class ze extends E{target;toggleOnClick=!1;targetState=!0;hideSelf=!0;onPointerEnter(){this.context.input.setCursor("pointer")}onPointerExit(){this.context.input.unsetCursor("pointer")}onPointerClick(e){e.use(),!this.toggleOnClick&&this.hideSelf&&(this.gameObject.visible=!1),this.target&&(this.target.visible=this.toggleOnClick?!this.target.visible:this.targetState)}selfModel;selfModelClone;targetModel;toggleModel;createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&(this.selfModel=t,this.selfModelClone=t.clone())}stateBeforeCreatingDocument=!1;targetStateBeforeCreatingDocument=!1;static clonedToggleIndex=0;static wasVisible=Symbol("usdz_SetActiveOnClick_wasVisible");static toggleClone=Symbol("clone for toggling");static reverseToggleClone=Symbol("clone for reverse toggling");beforeCreateDocument(){this.target&&(this.gameObject[ze.wasVisible]===void 0&&(this.gameObject[ze.wasVisible]=this.gameObject.activeSelf),this.target[ze.wasVisible]===void 0&&(this.target[ze.wasVisible]=this.target.activeSelf),this.stateBeforeCreatingDocument=this.gameObject[ze.wasVisible],this.targetStateBeforeCreatingDocument=this.target[ze.wasVisible],this.gameObject.visible=!0,this.target.visible=!0)}afterCreateDocument(e,t){if(!this.target)return;this.targetModel=t.document.findById(this.target.uuid);const i=this.selfModel;if(this.selfModel&&this.targetModel){let n=this.selfModel,s=this.targetState;if(this.toggleOnClick)if(s=!this.targetStateBeforeCreatingDocument,!this.selfModelClone.geometry)(!this.selfModel.parent||this.selfModel.parent.isEmpty())&&xy.createEmptyParent(this.selfModel),this.toggleModel=this.selfModel.deepClone(),this.toggleModel.name+="_toggle",this.selfModel.parent.add(this.toggleModel);else{if(!this.gameObject[ze.toggleClone]){const l=this.selfModelClone.clone();l.setMatrix(new J),l.name+="_toggle"+ze.clonedToggleIndex++,i.add(l),this.gameObject[ze.toggleClone]=l,console.warn("USDZExport: Toggle "+this.gameObject.name+" doesn't have geometry. It will be deep cloned and nested behaviours will likely not work.")}const a=this.gameObject[ze.toggleClone];if(!this.gameObject[ze.reverseToggleClone]){const l=this.selfModelClone.clone();l.setMatrix(new J),l.name+="_toggleReverse"+ze.clonedToggleIndex++,i.add(l),this.gameObject[ze.reverseToggleClone]=l}this.toggleModel=this.gameObject[ze.reverseToggleClone],(!this.toggleModel.geometry||!a.geometry)&&console.error("triggers without childs and without geometry won't work!",this,i.geometry),n=a,i.geometry=null,i.material=null}if(this.toggleModel){if(this.toggleOnClick){const a=[];a.push(fe.fadeAction(n,0,!1)),a.push(fe.fadeAction(this.toggleModel,0,!0)),a.push(fe.fadeAction(this.targetModel,0,s)),e.addBehavior(new jt("Toggle_"+n.name+"_ToggleTo"+(s?"On":"Off"),$t.tapTrigger(n),fe.parallel(...a)));const l=[];l.push(fe.fadeAction(this.toggleModel,0,!1)),l.push(fe.fadeAction(n,0,!0)),l.push(fe.fadeAction(this.targetModel,0,!s)),e.addBehavior(new jt("Toggle_"+n.name+"_ToggleTo"+(s?"Off":"On"),$t.tapTrigger(this.toggleModel),fe.parallel(...l)))}}else{const a=[];this.hideSelf&&a.push(fe.fadeAction(n,0,!1)),a.push(fe.fadeAction(this.targetModel,0,s)),e.addBehavior(new jt("Toggle_"+n.name+"_ToggleTo"+(s?"On":"Off"),$t.tapTrigger(n),a.length>1?fe.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),fn.add(r,e)}}afterSerialize(e,t){this.gameObject[ze.wasVisible]!==void 0&&(this.gameObject.visible=this.gameObject[ze.wasVisible],delete this.gameObject[ze.wasVisible]),this.target&&this.target[ze.wasVisible]!==void 0&&(this.target.visible=this.target[ze.wasVisible],delete this.target[ze.wasVisible]),delete this.gameObject[ze.toggleClone],delete this.gameObject[ze.reverseToggleClone]}};Be([u(M)],ch.prototype,"target"),Be([u()],ch.prototype,"toggleOnClick"),Be([u()],ch.prototype,"targetState"),Be([u()],ch.prototype,"hideSelf");let Iy=ch;class fn extends E{static _fadeBehaviour;static _fadeObjects=[];static add(e,t){const i=Array.isArray(e)?e:[e];for(const n of i)fn._fadeObjects.includes(n)||(console.log("adding hide on start",n),fn._fadeObjects.push(n));fn._fadeBehaviour===void 0&&(fn._fadeBehaviour=new jt("HideOnStart",$t.sceneStartTrigger(),fe.fadeAction(fn._fadeObjects,0,!1)),t.addBehavior(fn._fadeBehaviour))}start(){S.setActive(this.gameObject,!1)}createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&(this.wasVisible||fn.add(t,e))}wasVisible=!1;beforeCreateDocument(){this.wasVisible=S.isActiveSelf(this.gameObject)}}class Ol extends E{target;duration=.5;motionType="bounce";onEnable(){this.context.accessibility.updateElement(this,{role:"button",label:"Emphasize "+this.target?.name+" on click",hidden:!1})}onDisable(){this.context.accessibility.updateElement(this,{hidden:!0})}onDestroy(){this.context.accessibility.removeElement(this)}beforeCreateDocument(){}createBehaviours(e,t,i){if(this.target&&t.uuid===this.gameObject.uuid){const n=new jt("emphasize "+this.name,$t.tapTrigger(this.gameObject),fe.emphasize(this.target,this.duration,this.motionType,void 0,"basic"));e.addBehavior(n)}}afterCreateDocument(e,t){}}Be([u()],Ol.prototype,"target"),Be([u()],Ol.prototype,"duration"),Be([u()],Ol.prototype,"motionType");class Ns extends E{target;clip="";toggleOnClick=!1;trigger="tap";ensureAudioSource(){if(!this.target){const e=this.gameObject.addComponent(ji);e&&(this.target=e,e.spatialBlend=1,e.volume=1,e.loop=!1,e.preload=!0)}}onEnable(){this.context.accessibility.updateElement(this,{role:"button",label:"Play audio: "+(this.clip||this.target?.clip||"unknown clip"),hidden:!1})}onDisable(){this.context.accessibility.updateElement(this,{hidden:!0})}onDestroy(){this.context.accessibility.removeElement(this)}onPointerEnter(){this.context.input.setCursor("pointer")}onPointerExit(){this.context.input.unsetCursor("pointer")}onPointerClick(e){e.use(),!(!this.target?.clip&&!this.clip)&&(this.ensureAudioSource(),this.target&&(this.target.isPlaying&&this.toggleOnClick?this.target.stop():(!this.toggleOnClick&&this.target.isPlaying&&this.target.stop(),this.clip?this.target.play(this.clip):this.target.play())))}createBehaviours(e,t,i){if(!(!this.target&&!this.clip)&&t.uuid===this.gameObject.uuid){const n=this.clip?this.clip:this.target?this.target.clip:void 0;if(!n||typeof n!="string")return;const s=this.target?this.target.gameObject:this.gameObject;Pa.getName(n);const r=this.target?this.target.volume:1,a=this.target&&this.target.spatialBlend==0?"nonSpatial":"spatial";let l=!1;this.gameObject.traverse(p=>{p instanceof H&&p.visible&&(l=!0)}),l=!0;const c=e.addAudioClip(n);let h=fe.playAudioAction(s,c,"play",r,a);this.target&&this.target.loop&&(h=fe.sequence(h).makeLooping());const d=this.name?"_"+this.name:"";if(l&&this.trigger==="tap"){this.toggleOnClick&&(h.multiplePerformOperation="stop");const p=new jt("playAudio"+d,$t.tapTrigger(t),h);e.addBehavior(p)}if(this.target&&this.target.playOnAwake&&this.target.enabled)if(l&&this.trigger==="tap")console.warn("USDZExport: Audio sources that are played on tap can't also auto-play at scene start due to a QuickLook bug.");else{const p=new jt("playAudioOnStart"+d,$t.sceneStartTrigger(),h);e.addBehavior(p)}}}}Be([u(ji)],Ns.prototype,"target"),Be([u(URL)],Ns.prototype,"clip"),Be([u()],Ns.prototype,"toggleOnClick");const Ly=class vo extends E{animator;stateName;trigger="tap";animation;get target(){return this.animator?.gameObject||this.animation?.gameObject}onEnable(){this.context.accessibility.updateElement(this,{role:"button",label:"Plays animation "+(this.stateName||"")+" on "+(this.target?this.target.name:""),hidden:!1})}onDisable(){this.context.accessibility.updateElement(this,{hidden:!0})}onDestroy(){this.context.accessibility.removeElement(this)}onPointerEnter(){this.context.input.setCursor("pointer"),this.context.accessibility.hover(this,"Click to play animation "+(this.stateName||"")+" on "+(this.target?this.target.name:""))}onPointerExit(){this.context.input.unsetCursor("pointer")}onPointerClick(e){e.use(),this.target&&this.stateName&&(this.context.accessibility.focus(this),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(vo.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()&&be(e),console.warn(e,...vo.rootsWithExclusivePlayback)}vo.animationActions=[],vo.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 _p);if(!n)return;const s=n.getClipCount(this.target)>1;s&&(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."),vo.rootsWithExclusivePlayback.add(this.target));const r=this.name?this.name:"";i.traverse(a=>{if(a.uuid===this.target?.uuid){const l=vo.getActionForSequences(i,a,this.animationSequence,this.animationLoopAfterSequence,this.randomOffsetNormalized),c=new jt(this.trigger+"_"+r+"_toPlayAnimation_"+this.stateName+"_on_"+this.target?.name,this.trigger=="tap"?$t.tapTrigger(this.selfModel):$t.sceneStartTrigger(),l);s&&c.makeExclusive(!0),e.addBehavior(c)}})}static getActionForSequences(e,t,i,n,s){const r=(l,c)=>{let h=vo.animationActions.find(d=>d.affectedObjects==l&&d.start==c.start&&d.duration==c.duration&&d.animationSpeed==c.speed);return h||(h=fe.startAnimationAction(l,c),vo.animationActions.push(h)),h},a=fe.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:fe.sequence();for(const c of n)l.addAction(r(t,c));l.makeLooping(),a!==l&&a.addAction(l)}return s&&s>0&&a.actions.unshift(fe.waitAction(s)),a}static getAndRegisterAnimationSequences(e,t,i){if(!t)return;const n=t.getComponent(_t),s=t.getComponent(Ut);if(!n&&!s)return;if(n&&!i)throw new Error("PlayAnimationOnClick: No stateName specified for animator "+n.name+" on "+t.name);let r=[],a=[];if(s){const g=e.registerAnimation(t,s.clip);g&&(s.loop?a.push(g):r.push(g));let f=0;if(s.minMaxOffsetNormalized){const y=s.minMaxOffsetNormalized.x,_=s.minMaxOffsetNormalized.y;f=(s.clip?.duration||1)*(y+Math.random()*(_-y))}return{animationSequence:r,animationLoopAfterSequence:a,randomTimeOffset:f}}const l=n?.runtimeAnimatorController;let c=l?.findState(i),h=[],d=[];if(l&&c){const g=new Array;g.push(c);let f=!1;for(;g.length<100;){if(!c||c===null||!c.transitions||c.transitions.length===0){c.motion?.isLooping&&(f=!0);break}const y=c.transitions.find(v=>v.conditions.length===0),_=y?l.getState(y.destinationState,0):null;if(_&&g.includes(_)){c=_,f=!0;break}else if(y){if(c=_,!c)break;g.push(c)}else{f=c.motion?.isLooping??!1;break}}if(f&&c){const y=g.indexOf(c);h=g.slice(0,y),d=g.slice(y),y1&&console.log("found loop from "+i,"states until loop",h,"states looping",d)}else h=g,d=[],y1&&console.log("found no loop from "+i,"states",h);if(!d.length){const y=h[h.length-1],_=y.motion?.clip;if(_){let v;if(e.holdClipMap.has(_))v=e.holdClipMap.get(_);else{const P=y.name+"_hold";v=_.clone(),v.duration=1,v.name=P;const k=_.duration;v.tracks=_.tracks.map(O=>{const j=O.clone();j.times=new Float32Array([0,k]);const L=O.values.length,V=O.getValueSize(),W=O.values.slice(L-V,L);return j.values=new Float32Array(2*V),j.values.set(W,0),j.values.set(W,V),j}),v.name=P,e.holdClipMap.set(_,v)}if(v){const P={name:v.name,motion:{clip:v,isLooping:!1,name:v.name},speed:1,transitions:[],behaviours:[],hash:y.hash+1};d.push(P)}}}}if(h.length===1&&(!h[0].motion?.clip||h[0].motion?.clip.tracks?.length===0)){r=new Array;const g=e.registerAnimation(t,null);g&&r.push(g);return}if(h=h.filter(g=>g.motion?.clip&&g.motion?.clip.tracks?.length>0),d=d.filter(g=>g.motion?.clip&&g.motion?.clip.tracks?.length>0),h.length===0&&d.length===0){console.warn("No clips found for state "+i+" on "+n?.name+", can't export animation data");return}const p=(g,f)=>{if(!t)return;const y=e.registerAnimation(t,g.motion.clip??null);y?(y.speed=g.speed,f.push(y)):console.warn("Couldn't register animation for state "+g.name+" on "+n?.name)};if(h.length>0){r=new Array;for(const g of h)p(g,r)}if(d.length>0){a=new Array;for(const g of d)p(g,a)}let m=0;if(n&&l&&n.minMaxOffsetNormalized){const g=n.minMaxOffsetNormalized.x,f=n.minMaxOffsetNormalized.y;m=((h.length?h[0]:d.length?d[0]:null)?.motion.clip?.duration||1)*(g+Math.random()*(f-g))}return{animationSequence:r,animationLoopAfterSequence:a,randomTimeOffset:m}}createAnimation(e,t,i){if(!this.target||!this.animator&&!this.animation)return;const n=vo.getAndRegisterAnimationSequences(e,this.target,this.stateName);n&&(this.animationSequence=n.animationSequence,this.animationLoopAfterSequence=n.animationLoopAfterSequence,this.randomOffsetNormalized=n.randomTimeOffset,this.stateAnimationModel=t)}};Be([u(_t)],Ly.prototype,"animator"),Be([u()],Ly.prototype,"stateName");let hh=Ly;class kl extends E{getType(){}target;getDuration(){}}Be([u(M)],kl.prototype,"target");class dh extends E{target}Be([u(kl)],dh.prototype,"target");class uh extends kl{type=1;duration=1;getType(){switch(this.type){case 1:return"hide";case 0:return"show"}}getDuration(){return this.duration}}Be([u()],uh.prototype,"type"),Be([u()],uh.prototype,"duration");class jy extends dh{}const rA=100,aA=200,lA=300;class ur{static _instance;static create(){return new ur}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 mn.getOrCreate().createQRCode()}createQuicklookButton(){if(this._quicklookButton)return this._quicklookButton;const e=document.createElement("button");this._quicklookButton=e,e.dataset.needle="quicklook-button";const t=I.supportsQuickLookAR();let i="View in AR";I.isVisionOS()?i="View in AR":(t||I.isiOS())&&(i="Open in Quicklook"),e.innerText=i,e.prepend(Pt("view_in_ar")),Es.setElementPriority(e,aA);let n=!1,s=null;return e.addEventListener("click",()=>{s=tl(uo),s||(n=!0,s=new uo),n&&(s.objectToExport=U.Current.scene),s?(e.classList.add("this-mode-is-requested"),s.exportAndOpen().then(()=>{e.classList.remove("this-mode-is-requested")}).catch(r=>{e.classList.remove("this-mode-is-requested"),console.error(r)})):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",()=>Z.start(t,e)),Es.setElementPriority(i,lA),this.updateSessionSupported(i,t),this.listenToXRSessionState(i,t),this.hideElementDuringXRSession(i),this.isSecureConnection||(i.disabled=!0,i.title="WebXR requires a secure connection (HTTPS)"),I.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",()=>Z.start(t,e)),Es.setElementPriority(i,rA),this.updateSessionSupported(i,t),this.listenToXRSessionState(i,t),this.hideElementDuringXRSession(i),this.isSecureConnection||(i.disabled=!0,i.title="WebXR requires a secure connection (HTTPS)"),I.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&&Oe("This page doesn't allow popups. Please paste "+n+" into your browser.")}),this.listenToXRSessionState(t),this.hideElementDuringXRSession(t),I.isMozillaXR()||navigator.xr?.addEventListener("devicechange",()=>{navigator.xr?.isSessionSupported("immersive-vr")?t.style.display="none":t.style.display=""}),t}createQRCode(){return mn.getOrCreate().createQRCode()}updateSessionSupported(e,t){if(!(t==="immersive-ar"&&I.isiOS()&&!I.isVisionOS())){if(!("xr"in navigator)){e.style.display="none";return}Z.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){Qd(t=>{e["previous-display"]=e.style.display,e.style.setProperty("display","none","important")}),Cg(t=>{e["previous-display"]!=null&&(e.style.display=e["previous-display"])})}listenToXRSessionState(e,t){t&&(Z.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"))}),Z.onSessionRequestEnd(i=>{e.classList.remove("this-mode-is-requested"),e.classList.remove("other-mode-is-requested"),e.disabled=e["was-disabled"]}))}}var cA=Object.defineProperty,hA=Object.getOwnPropertyDescriptor,wt=(o,e,t,i)=>{for(var n=i>1?void 0:i?hA(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&cA(e,t,n),n};const ph=w("debugspriterenderer"),dA=w("wireframe");class ka{static cache={};static getOrCreateGeometry(e){if(e.__cached_geometry)return e.__cached_geometry;if(e.guid&&ka.cache[e.guid])return ph&&console.log("Take cached geometry for sprite",e.guid),ka.cache[e.guid];const t=new wn;e.__cached_geometry=t;const i=new Float32Array(e.triangles.length*3),n=new Float32Array(e.triangles.length*2);for(let s=0;s<e.triangles.length;s+=1){const r=e.triangles[s];i[s*3]=-e.vertices[r].x,i[s*3+1]=e.vertices[r].y,i[s*3+2]=0;const a=e.uv[r];n[s*2]=a.x,n[s*2+1]=1-a.y}return t.setAttribute("position",new ft(i,3)),t.setAttribute("uv",new ft(n,2)),e.guid&&(this.cache[e.guid]=t),ph&&console.log("Built sprite geometry",e,t),t}}class uA{x;y}function b1(o){o&&(o.colorSpace!=Mo&&(o.colorSpace=Mo,o.needsUpdate=!0),o.minFilter==Ad&&o.magFilter==Ad&&(o.anisotropy=1,o.needsUpdate=!0))}let Zo=class{constructor(o){o&&(this.texture=o,this.triangles=[0,1,2,0,2,3],this.uv=[{x:0,y:0},{x:1,y:0},{x:1,y:1},{x:0,y:1}],this.vertices=[{x:-.5,y:-.5},{x:.5,y:-.5},{x:.5,y:.5},{x:-.5,y:.5}])}guid;texture;triangles;uv;vertices;__cached_geometry;get mesh(){return this._mesh||(this._mesh=new H(ka.getOrCreateGeometry(this),this.material)),this._mesh}_mesh;get material(){return this._material||(this.texture&&b1(this.texture),this._material=new Ce({map:this.texture,color:16777215,side:Oi,transparent:!0})),this._material}_material;getGeometry(){return ka.getOrCreateGeometry(this)}};wt([u()],Zo.prototype,"guid",2),wt([u(Se)],Zo.prototype,"texture",2),wt([Ye()],Zo.prototype,"triangles",2),wt([Ye()],Zo.prototype,"uv",2),wt([Ye()],Zo.prototype,"vertices",2);const Dy=Symbol("spriteOwner");class Ml{sprites;constructor(){this.sprites=[]}}wt([u(Zo)],Ml.prototype,"sprites",2);const By=class db{static create(){const e=new db;return e.spriteSheet=new Ml,e}constructor(){}clone(){const e=new db;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 Ml,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&&(b1(n),!i.__hasLoadedProgressive)){i.__hasLoadedProgressive=!0;const s=n;Ve.assignTextureLOD(n,0).then(r=>{r instanceof Se&&(i.texture=r,e?.map===s&&(e.map=r,e.needsUpdate=!0))})}}};wt([u(Ml)],By.prototype,"spriteSheet",2),wt([u()],By.prototype,"index",2);let El=By;class _i extends E{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=El.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);ph&&console.log("[SpriteSheet] Set index to "+t+" (was "+this.spriteIndex+")",e),this.spriteIndex=t}else e instanceof Zo?(this._spriteSheet||(this._spriteSheet=El.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=El.create(),ph&&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 ph&&console.warn("Sprite not found",this.spriteIndex,t.spriteSheet.sprites),!1;if(this._currentSprite)this._currentSprite.geometry=ka.getOrCreateGeometry(i),this._currentSprite.material.map=i.texture;else{const n=new Ce({color:16777215,side:Oi});if(dA&&(n.wireframe=!0),this.color&&(n.color||(n.color=new oe),n.color.copy(this.color),n.opacity=this.color.alpha),n.transparent=!0,n.toneMapped=this.toneMapped,n.depthWrite=!1,i.texture&&!n.wireframe){let s=i.texture;s[Dy]!==void 0&&s[Dy]!==this&&this.spriteFrames>1&&(s=i.texture=s.clone()),s[Dy]=this,n.map=s}this.sharedMaterial=n,this._currentSprite=new H(ka.getOrCreateGeometry(i),n),this._currentSprite.renderOrder=Math.round(this.renderOrder),Ve.assignTextureLOD(n,0)}return this._currentSprite.parent!==this.gameObject&&(this.drawMode===2&&this._currentSprite.scale.set(this.size.x,this.size.y,1),this.gameObject&&this.gameObject.add(this._currentSprite)),this._currentSprite&&this._currentSprite.layers.set(this.layer),this.sharedMaterial&&(this.sharedMaterial.alphaTest=this.cutoutThreshold,this.sharedMaterial.transparent=this.transparent),this._currentSprite.castShadow=this.castShadows,t?.update(this.sharedMaterial),!0}}wt([u()],_i.prototype,"drawMode",2),wt([u(uA)],_i.prototype,"size",2),wt([u(se)],_i.prototype,"color",2),wt([u(we)],_i.prototype,"sharedMaterial",2),wt([u()],_i.prototype,"transparent",2),wt([u()],_i.prototype,"cutoutThreshold",2),wt([u()],_i.prototype,"castShadows",2),wt([u()],_i.prototype,"renderOrder",2),wt([u()],_i.prototype,"toneMapped",2),wt([u(El)],_i.prototype,"sprite",1);const _1=w("debugwebxr"),pA=new J().makeRotationY(Math.PI);class yn extends E{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 J;_createdPlacementObject=null;_reparentedComponents=[];_placementScene=new Hi;_reticle=[];_hits=[];_placementStartTime=-1;_rigPlacementMatrix;_anchor=null;userInput;onEnable(){this.customReticle?.preload()}supportsXR(e){return e==="immersive-ar"}onEnterXR(e){_1&&console.log("ENTER WEBXR: SessionRoot start..."),this._anchor=null,yn._hasPlaced=!1,this.gameObject.updateMatrixWorld(),this._startOffset.copy(this.gameObject.matrixWorld);const t=new M;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=di(this._placementScene.children),n=i.getCenter(new b),s=i.getSize(new b),r=new J;r.makeTranslation(n.x,n.y-s.y*.5,n.z),this._startOffset.multiply(r)}this._reparentedComponents.length=0,this._reparentedComponents.push({comp:this,originalObject:this.gameObject}),S.addComponent(t,this);for(const i of this._reticle)Ii(i);this._reticle.length=0,this._isPlacing=!0,this.context.input.addEventListener("pointerup",this.onPlaceScene,{queue:pi.Early})}onLeaveXR(){this.context.input.removeEventListener("pointerup",this.onPlaceScene,{queue:pi.Early}),this.onRevertSceneChanges(),this._anchor=null,yn._hasPlaced=!1,this._rigPlacementMatrix=void 0}onUpdateXR(e){if(e.xr.isTrackingImages){for(const t of this._reticle)t.visible=!1;return}if(this._isPlacing){const t=e.xr.rig?.gameObject;t&&t.parent!==this.context.scene&&this.context.scene.add(t);let i=!1;if(e.xr.isPassThrough&&e.xr.controllers.length>0&&!this.autoPlace)for(const n of e.xr.controllers){const s=n.getHitTest();s&&(i=!0,this.updateReticleAndHits(e.xr,n.index,s,e.xr.rigScale))}if(!i){const n=e.xr.getHitTest();n&&this.updateReticleAndHits(e.xr,0,n,e.xr.rigScale)}}else{if(this._anchor&&e.xr.referenceSpace){const t=e.xr.frame.getPose(this._anchor.anchorSpace,e.xr.referenceSpace);if(t&&this.context.time.frame%20===0){const i=e.xr.convertSpace(t.transform),n=this._reticle[0];n&&(n.position.copy(i.position),n.quaternion.copy(i.quaternion),this.onApplyPose(n))}}if(this.arTouchTransform?(this.userInput||(this.userInput=new Pm(this.context)),this.userInput?.enable()):this.userInput?.disable(),this.arTouchTransform&&this.userInput?.hasChanged){if(e.xr.rig){const t=e.xr.rig.gameObject;this.userInput.applyMatrixTo(t.matrix,!0),t.matrix.decompose(t.position,t.quaternion,t.scale),this.userInput.factor=t.scale.x}this.userInput.reset()}}}updateReticleAndHits(e,t,i,n){this._hits[t]=i.hit;let s=this._reticle[t];if(!s){if(this.customReticle)if(this.customReticle.asset)s=Ur(this.customReticle.asset);else{this.customReticle.loadAssetAsync();return}else s=new H(new WC(.07,.09,32).rotateX(-Math.PI/2),new Ce({side:Oi,depthTest:!1,depthWrite:!1,transparent:!0,opacity:1,color:15658734})),s.name="AR Placement Reticle";if(_1){const r=new Pi(1);r.position.y+=.01,s.add(r)}this._reticle[t]=s,s.matrixAutoUpdate=!1,s.visible=!1}if(s.lastPos=s.lastPos||i.position.clone(),s.lastQuat=s.lastQuat||i.quaternion.clone(),s.position.copy(s.lastPos.lerp(i.position,this.context.time.deltaTime/.1)),s.lastPos.copy(s.position),s.quaternion.copy(s.lastQuat.slerp(i.quaternion,this.context.time.deltaTime/.05)),s.lastQuat.copy(s.quaternion),s.scale.set(n,n,n),this.customReticle&&this.applyViewBasedTransform(s),s.updateMatrix(),s.visible=!0,s.parent!==this.context.scene&&this.context.scene.add(s),this._placementStartTime<0&&(this._placementStartTime=this.context.time.realtimeSinceStartup),this.autoPlace)if(this.upVec.set(0,1,0).applyQuaternion(s.quaternion),this.upVec.dot(F(0,1,0))>.9){let r=s["autoplace:timer"]||0;r>=1?(s.visible=!1,this.onPlaceScene(null)):(r+=this.context.time.deltaTime,s["autoplace:timer"]=r)}else s["autoplace:timer"]=0}onPlaceScene=e=>{if(this._isPlacing==!1||e?.used)return;let t=this._reticle[0];if(!t){console.warn("No reticle to place...");return}if(!t.visible&&!this.autoPlace){console.warn("Reticle is not visible (can not place)");return}if(Z.active?.isTrackingImages){console.warn("Scene Placement is disabled while images are being tracked");return}let i=this._hits[0];if(e&&e.origin instanceof Pg){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),yn._hasPlaced=!0,this.useXRAnchor&&this.onCreateAnchor(Z.active,i),this.context.xr)for(const n of this.context.xr.controllers)n.cancelHitTestSource()};onSetScale(){if(!yn._hasPlaced)return;const e=Z.active?.rig?.gameObject;if(e){const t=Z.active?.rigScale||1,i=1/this._arScale*t,n=new J().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()&&be("Hit does not support creating an anchor");return}else{const i=await t.createAnchor(e.viewerPose.transform);e.running&&i&&(this._anchor=i)}}upVec=new b(0,1,0);lookPoint=new b;worldUpVec=new b(0,1,0);applyViewBasedTransform(e){const t=this.context.mainCamera,i=e,n=t.worldPosition,s=i.worldPosition;this.upVec.set(0,1,0).applyQuaternion(e.quaternion);const r=t.worldPosition;r&&e.position.clone().sub(r).angleTo(this.upVec)<Math.PI/2&&this.upVec.negate();const a=this.upVec.angleTo(this.worldUpVec)*180/Math.PI,l=30;a>l&&a<180-l||a<-l&&a>-180+l?(this.lookPoint.copy(e.position).add(this.upVec),this.lookPoint.y=e.position.y,e.lookAt(this.lookPoint)):(n.y=s.y,e.lookAt(n))}onApplyPose(e){const t=Z.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(pA),t.matrix.premultiply(this._startOffset),t.matrix.decompose(t.position,t.quaternion,t.scale),i.add(t)}}class Pm{static up=new b(0,1,0);static zero=new b(0,0,0);static one=new b(1,1,1);oneFingerDrag=!0;twoFingerRotate=!0;twoFingerScale=!0;factor=1;context;offset;plane;_scale=1;_hasChanged=!1;get scale(){return this._scale}constructor(e){this.context=e,this.offset=new J,this.plane=new _r,this.plane.setFromNormalAndCoplanarPoint(Pm.up,Pm.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:pi.Early}),this.context.input.addEventListener("pointerdown",this.onPointerDownLate,{queue:pi.Late}),this.context.input.addEventListener("pointerup",this.onPointerUpEarly,{queue:pi.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:pi.Early}),this.context.input.removeEventListener("pointerdown",this.onPointerDownLate,{queue:pi.Late}),this.context.input.removeEventListener("pointerup",this.onPointerUpEarly,{queue:pi.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=I.isAndroidDevice()&&i.clientY<window.innerHeight*.1;this.prev.has(i.identifier)||this.prev.set(i.identifier,{ignore:n,x:0,z:0,screenx:0,screeny:0});const s=this.prev.get(i.identifier);if(s){const r=this.getPositionOnPlane(i.clientX,i.clientY);s.x=r.x,s.z=r.z,s.screenx=i.clientX,s.screeny=i.clientY}}};touchEnd=e=>{e.touches.length<=0&&(this._didMultitouch=!1);for(let t=0;t<e.changedTouches.length;t++){const i=e.changedTouches[t];this.prev.delete(i.identifier)}};touchMove=e=>{if(!e.defaultPrevented&&this.isActive){if(e.touches.length===1){if(this._didMultitouch)return;const t=e.touches[0],i=this.prev.get(t.identifier);if(!i||i.ignore)return;const n=this.getPositionOnPlane(t.clientX,t.clientY),s=n.x-i.x,r=n.z-i.z;if(s===0&&r===0)return;this.oneFingerDrag&&this.addMovement(s,r),i.x=n.x,i.z=n.z,i.screenx=t.clientX,i.screeny=t.clientY;return}else if(e.touches.length===2){this._didMultitouch=!0;const t=e.touches[0],i=e.touches[1],n=this.prev.get(t.identifier),s=this.prev.get(i.identifier);if(!n||!s)return;if(this.twoFingerRotate){const r=Math.atan2(t.clientY-i.clientY,t.clientX-i.clientX),a=Math.atan2(n.screeny-s.screeny,n.screenx-s.screenx),l=r-a;Math.abs(l)>.001&&this.addRotation(l)}if(this.twoFingerScale){const r=t.clientX-i.clientX,a=t.clientY-i.clientY,l=Math.sqrt(r*r+a*a),c=n.screenx-s.screenx,h=n.screeny-s.screeny,d=Math.sqrt(c*c+h*h),p=l-d;Math.abs(p)>2&&this.addScale(p)}n.screenx=t.clientX,n.screeny=t.clientY,s.screenx=i.clientX,s.screeny=i.clientY}}};_raycaster=new Od;_intersection=new b;_screenPos=new b;getPositionOnPlane(e,t){const i=this.context.mainCamera;return this._screenPos.x=e/window.innerWidth*2-1,this._screenPos.y=-(t/window.innerHeight)*2+1,this._screenPos.z=1,this._screenPos.unproject(i),this._raycaster.set(i.position,this._screenPos.sub(i.position)),this._raycaster.ray.intersectPlane(this.plane,this._intersection),this._intersection}addMovement(e,t){e/=this._scale,t/=this._scale,e*=this.factor,t*=this.factor,this.offset.elements[12]+=e,this.offset.elements[14]+=t,(e!==0||t!==0)&&(this._hasChanged=!0)}_tempMatrix=new J;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 Ws=w("debugautosync"),Fy=Symbol("syncerId");class mA{_syncers={};getOrCreateSyncer(e){if(!e.guid)return null;if(this._syncers[e.guid])return this._syncers[e.guid];const t=new gA(e);return t[Fy]=e.guid,this._syncers[t[Fy]]=t,t}removeSyncer(e){delete this._syncers[e[Fy]]}}const Uy=new mA;class gA{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||(Ws&&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];Ws&&console.log("SEND",this.comp.guid,this.networkingKey),e.send(this.networkingKey,{guid:this.comp.guid,property:t,data:i},Pn.Queued),delete this.changedProperties[t]}};onHandleReceiving=e=>{if(Ws&&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 fA(o,e){let t=e!==o;return!t&&o&&e&&(Array.isArray(o)&&Array.isArray(e)||typeof o=="object"&&typeof e=="object")&&(t=!0),t}const mh=Symbol("AutoSyncHandler");function yA(o){if(o[mh])return o[mh];const e=Uy.getOrCreateSyncer(o);return e?.init(o),o[mh]=e,e}function bA(o){const e=o[mh];e&&(Uy.removeSyncer(e),e.destroy(),delete o[mh])}const zy=function(o=null){return function(e,t){let i="";typeof t=="string"?i=t:i=t.name;let n=null,s;typeof o=="string"?s=e[o]:typeof o=="function"&&(s=o),s==null&&(A()||Ws)&&o!=null&&console.warn('syncField: no callback function found for property "'+i+'"','"'+o+'"');const r=e,a=r.__internalAwake;if(typeof a!="function"){(Ws||A())&&console.error('@syncField can currently only used on Needle Engine Components, custom object of type "'+e?.constructor?.name+'" is not supported',e);return}Ws&&console.log(i);const l=Symbol(i);r.__internalAwake=function(){if(this[l]===void 0){if(this[l]=this[i],n=Uy.getOrCreateSyncer(this),Object.getOwnPropertyDescriptor(this,i)?.set===void 0){let h=!1;Object.defineProperty(this,i,{set:function(d){const p=this[l];if(this[l]=d,h){(A()||Ws)&&console.warn("Recursive call detected",i);return}h=!0;try{const m=fA(d,p);Ws&&console.log("SyncField assignment",i,"changed?",m,d,s),m&&s?.call(this,d,p)!==!1&&yA(this)?.notifyChanged(i,d)}finally{h=!1}},get:function(){return this[l]},configurable:!0,enumerable:!0})}n?.init(this),a.call(this)}};const c=r.__internalDestroy;r.__internalDestroy=function(){bA(this),c.call(this)}}};var _A=Object.defineProperty,wp=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&_A(e,t,n),n};const oi=w("debugplayersync"),xp=class US extends E{static async setupFrom(e,t){const i=ne.getOrCreateFromUrl(e);if(!i.asset){const r=await i.loadAssetAsync();r&&S.getOrAddComponent(r,sn)}const n=new US;n._internalInit(t),n.asset=i;const s=new M;return s.guid=e,S.addComponent(s,n),n}autoSync=!0;asset;onPlayerSpawned;_localInstance;awake(){this.watchTabVisible(),this.onPlayerSpawned||(this.onPlayerSpawned=new ae)}onEnable(){this.context.connection.beginListen(ie.RoomStateSent,this.onJoinedRoom),this.context.connection.beginListen(ie.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(ie.LeftRoom,this.destroyInstance),this.context.connection.isInRoom&&this.onJoinedRoom()}onDisable(){this.context.connection.stopListen(ie.RoomStateSent,this.onJoinedRoom),this.context.connection.stopListen(ie.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(ie.LeftRoom,this.destroyInstance)}onJoinedRoom=()=>{oi&&console.log("PlayerSync.joinedRoom. autoSync is set to "+this.autoSync),this.autoSync&&this.getInstance()};async getInstance(){if(this._localInstance)return this._localInstance;if(oi&&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,sn);if(oi&&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=>{oi&&console.log("PlayerSync.destroyInstance",e),Lc(e,this.context.connection,!0,{saveInRoom:!1})}),this._localInstance=void 0};watchTabVisible(){window.addEventListener("visibilitychange",e=>{if(document.visibilityState==="visible")for(let t=sn.all.length-1;t>=0;t--){const i=sn.all[t];(!i.owner||!this.context.connection.userIsInRoom(i.owner))&&i.doDestroy()}})}};wp([u()],xp.prototype,"autoSync"),wp([u(ne)],xp.prototype,"asset"),wp([u(ae)],xp.prototype,"onPlayerSpawned");let Ny=xp;var v1=(o=>(o.OwnerChanged="ownerChanged",o))(v1||{});const Wy=class It extends E{static _all=[];static get all(){return It._all}static _local=[];static get local(){return It._local}static getFor(e){if(e instanceof M)return S.getComponentInParent(e,It);if(e instanceof E)return S.getComponentInParent(e.gameObject,It)}static isLocalPlayer(e){return It.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 ae;onFirstOwnerChangeEvent=new ae;hasOwner=!1;owner;dontDestroy=!1;get isLocalPlayer(){return this.owner===this.context.connection.connectionId}onOwnerChange(e,t){oi&&console.log(`PlayerSync.onOwnerChange: ${t} \u2192 ${e} (me: ${this.context.connection.connectionId})`);const i=It._local.indexOf(this);i>=0&&It._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){It._local.push(this);const r=new CustomEvent("local-owner-changed",{detail:n});this.dispatchEvent(r)}const s=new CustomEvent("owner-changed",{detail:n});this.dispatchEvent(s),It.dispatchEvent("ownerChanged",s)}awake(){It.all.push(this),oi&&console.log("Registered new PlayerState",this.guid,It.all.length-1,It.all),this.context.connection.beginListen(ie.UserLeftRoom,this.onUserLeftRoom)}async start(){oi&&console.log("PLAYERSTATE.START, owner: "+this.owner,this.context.connection.usersInRoom([])),this.owner?(this.context.connection.isInRoom||await To(300),this.context.connection.userIsInRoom(this.owner)==!1&&(oi&&console.log(`PlayerSync.start \u2192 doDestroy "${this.name}" because user "${this.owner}" is not in room anymore...`,"Currently in room:",...this.context.connection.usersInRoom()),this.doDestroy())):this.owner||(oi&&console.warn("PlayerState.start \u2192 owner is undefined!",this.name),setTimeout(()=>{!this.destroyed&&!this.owner?this.dontDestroy?oi&&console.warn("PlayerState.start \u2192 owner is still undefined but dontDestroy is set to true",this.name):(oi&&console.warn(`PlayerState.start \u2192 owner is still undefined: destroying "${this.name}" instance now`),this.doDestroy()):oi&&console.log("PlayerState.start \u2192 owner is assigned",this.owner)},2e3))}doDestroy(){oi&&console.log("PlayerSync.doDestroy \u2192 syncDestroy",this.name),Lc(this.gameObject,this.context.connection,!0,{saveInRoom:!1})}onDestroy(){if(oi&&console.warn("PlayerState.onDestroy",this.owner),this.context.connection.stopListen(ie.UserLeftRoom,this.onUserLeftRoom),It.all.splice(It.all.indexOf(this),1),this.isLocalPlayer){const e=It._local.indexOf(this);e>=0&&It._local.splice(e,1)}}onUserLeftRoom=e=>{if(e.userId===this.owner){oi&&console.log("PLAYERSYNC LEFT",this.owner),this.doDestroy();return}}};wp([zy(Wy.prototype.onOwnerChange)],Wy.prototype,"owner");let sn=Wy;var vA=Object.defineProperty,Rl=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&vA(e,t,n),n};class co extends E{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&&(I.isMobileDevice()||this.context.menu.showQRCodeButton(!0))}}Rl([u()],co.prototype,"position"),Rl([u()],co.prototype,"showNeedleLogo"),Rl([u()],co.prototype,"showSpatialMenu"),Rl([u()],co.prototype,"createFullscreenButton"),Rl([u()],co.prototype,"createMuteButton"),Rl([u()],co.prototype,"createQRCodeButton");var wA=Object.defineProperty,Vy=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&wA(e,t,n),n};const gh=w("debugwebxr"),w1=new N().setFromAxisAngle(new b(0,1,0),Math.PI);class Vs extends E{head;leftHand;rightHand;_leftHandMeshes;_rightHandMeshes;_syncTransforms;async onEnterXR(e){if(!this.activeAndEnabled)return;gh&&console.warn("AVATAR ENTER XR",this.guid,this.sourceId,this,this.activeAndEnabled),this._syncTransforms&&(this._syncTransforms.length=0),await this.prepareAvatar();const t=sn.getFor(this);if(t?.owner){const i=this.gameObject.addComponent(Le);i.avatar=this.gameObject,i.connectionId=t.owner,this.context.players.setPlayerView(t.owner,this.head?.asset,Uo.Headset)}else this.context.connection.isConnected?console.error("No player state found for avatar",this):t&&!this.context.connection.isConnected&&(t.dontDestroy=!0)}onLeaveXR(e){const t=this.gameObject.getComponent(Le);t&&t.destroy()}onUpdateXR(e){if(!this.activeAndEnabled)return;const t=sn.isLocalPlayer(this);if(!t)return;const i=e.xr;if(i.rig&&i.rig.gameObject!==this.gameObject.parent&&(this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),this.gameObject.scale.set(1,1,1),i.rig.gameObject.add(this.gameObject)),this._syncTransforms&&t)for(const l of this._syncTransforms)l.fastMode=!0,l.isOwned()||l.requestOwnership();if(this.head&&this.context.mainCamera){const l=this.head.asset;if(l.position.copy(this.context.mainCamera.position),l.position.x*=-1,l.position.z*=-1,l.quaternion.copy(this.context.mainCamera.quaternion),l.quaternion.x*=-1,this.context.time.frameCount%10===0&&this.head.asset){const c=S.getComponentsInChildren(this.head.asset,tn);for(const h of c)h.enabled=!1,h.gameObject.visible=!1}}const n=e.xr.leftController,s=this.leftHand?.asset;n&&s?(s.position.copy(n.gripPosition),s.quaternion.copy(n.gripQuaternion),s.quaternion.multiply(w1),s.visible=n.isTracking,this.updateHandVisibility(n,s,this._leftHandMeshes)):s&&s.visible&&(s.visible=!1);const r=e.xr.rightController,a=this.rightHand?.asset;r&&a?(a.position.copy(r.gripPosition),a.quaternion.copy(r.gripQuaternion),a.quaternion.multiply(w1),a.visible=r.isTracking,this.updateHandVisibility(r,a,this._rightHandMeshes)):a&&a.visible&&(a.visible=!1)}onBeforeRender(){this.context.xr&&this.context.time.frame%10===0&&this.updateRemoteAvatarVisibility()}updateHandVisibility(e,t,i){if(i){const n=e.model&&e.model.visible&&e.model!==t;i.forEach(s=>{Fo(s,!n)})}}updateRemoteAvatarVisibility(){if(this.context.connection.isConnected){const e=sn.getFor(this);if(e&&e.isLocalPlayer==!1){const t=Z.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,tn);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};xv.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 M&&(this.head=new ne("",this.sourceId,this.head));else{const e=new M;e.name="Head";const t=Os.createPrimitive(Qa.Cube);e.add(t),this.gameObject.add(e),this.head=new ne("",this.sourceId,e),gh&&console.log("Create head",e)}if(this.rightHand)this.rightHand instanceof M&&(this.rightHand=new ne("",this.sourceId,this.rightHand));else{const e=new M;e.name="Right Hand",this.gameObject.add(e),this.rightHand=new ne("",this.sourceId,e),gh&&console.log("Create right hand",e)}if(this.leftHand)this.leftHand instanceof M&&(this.leftHand=new ne("",this.sourceId,this.leftHand));else{const e=new M;e.name="Left Hand",this.gameObject.add(e),this.leftHand=new ne("",this.sourceId,e),gh&&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)}),sn.isLocalPlayer(this.gameObject)&&(this._syncTransforms=S.getComponentsInChildren(this.gameObject,Tn))}async loadAvatarObjects(e,t,i){const n=e.loadAssetAsync(),s=t.loadAssetAsync(),r=i.loadAssetAsync(),a=new Array;n&&a.push(n),s&&a.push(s),r&&a.push(r);const l=await Jm(a);gh&&console.log("Avatar loaded results:",l)}}Vy([u(ne)],Vs.prototype,"head"),Vy([u(ne)],Vs.prototype,"leftHand"),Vy([u(ne)],Vs.prototype,"rightHand");var xA=Object.defineProperty,Sp=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&xA(e,t,n),n};const $s=w("debugwebxr"),Hs=new Array;class Ko extends E{createControllerModel=!0;createHandModel=!0;customLeftHand;customRightHand;static factory=new vP;supportsXR(e){return e==="immersive-vr"||e==="immersive-ar"}_models=new Array;async onXRControllerAdded(e){if(!(e.xr.isVR||e.xr.isPassThrough))return;console.debug("XR Controller Added",e.controller.side,e.controller.index);const{controller:t}=e;if(this.createControllerModel||this.createHandModel){if(t.hand){if(this.createHandModel){const i=await this.loadHandModel(this,t);if(!i||!t.connected||!t.isHand){i?.handObject&&nl(i.handObject,!1),i?.handObject?.destroy();return}this._models.push({controller:t,model:i.handObject,handmesh:i.handmesh}),this._models.sort((n,s)=>n.controller.index-s.controller.index),this.scene.add(i.handObject),t.model=i.handObject}}else if(this.createControllerModel){const i=await t.getModelUrl();if(i){const n=await this.loadModel(t,i);if(!n||!t.connected||t.isHand)return;this._models.push({controller:t,model:n}),this._models.sort((s,r)=>s.controller.index-r.controller.index),this.scene.add(n),n.traverse(s=>{s.layers.set(2),s.matrixAutoUpdate=!1,s.updateMatrix()}),t.model=n}else t.targetRayMode!=="transient-pointer"&&console.warn("XRControllerModel: no model found for "+t.side)}}}onXRControllerRemoved(e){console.debug("XR Controller Removed",e.controller.side,e.controller.index);const t=this._models.findIndex(n=>n.controller===e.controller),i=this._models[t];i&&(this._models.splice(t,1),i.model&&(nl(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&&(nl(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(Z.active&&($s&&(Hs[0]=Date.now()),this.updateRendering(Z.active),$s)){const e=Date.now()-Hs[0];Hs.push(e),Hs.length>=30&&(Hs[0]=0,Hs.reduce((t,i)=>t+i,0)/Hs.length,Hs.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){$s&&console.warn("XRControllerModel.onUpdateXR: controller is not connected anymore",n.side,n.hand);continue}if(i.model&&!i.handmesh)i.model.matrixAutoUpdate=!1,i.model.matrix.copy(n.gripMatrix),i.model.visible=n.isTracking,e.rig?.gameObject.add(i.model);else if(n.inputSource.hand&&i.handmesh){const s=e.referenceSpace,r=this.context.renderer.xr.getHand(n.index);if(s&&e.frame.getJointPose){for(const a of n.inputSource.hand.values()){const l=r.joints[a.jointName];if(l){const c=n.getHandJointPose(a);if(c){const h=c.transform.position,d=c.transform.orientation;l.position.copy(h),l.quaternion.copy(d),l.matrixAutoUpdate=!1}l.visible=c!=null}}i.model&&(i.model.visible=n.isTracking,i.model.visible&&i.model.parent!==e.rig?.gameObject&&e.rig?.gameObject.add(i.model)),i.model?.visible&&(i.handmesh?.updateMesh(),i.model.matrixAutoUpdate=!1,i.model.matrix.identity(),i.model.applyMatrix4(Ha))}}}}async loadModel(e,t){if(!e.connected)return console.warn("XRControllerModel.onXRControllerAdded: controller is not connected anymore",e.side),null;const i=await ne.getOrCreate("",t).instantiate();return nl(i),Z.active?.isPassThrough&&i.traverseVisible(n=>{this.makeOccluder(n)}),i}async loadHandModel(e,t){const i=this.context,n=i.renderer.xr.getHand(t.index);n||($s?B.DrawLabel(t.rayWorldPosition,"No hand found for index "+t.index,.05,5):console.warn("No hand found for index "+t.index));const s=new Eo;Af(s,i),await sp(s,i,this.sourceId??"",this.sourceId??"");const r=hy(s);let a="";const l=t.side==="left"?this.customLeftHand:this.customRightHand;l?(a=l.url.split(".").slice(0,-1).join("."),s.setPath("")):(a=t.inputSource.handedness==="left"?"left":"right",s.setPath("https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/"));const c=new M;nl(c);const h=new wP(c,n,s.path,a,s,d=>{const p=r?.gltf;p?.scene.children?.length===0&&(p.scene.children[0]=d),r?.gltf&&Cn().createBuiltinComponents(e.context,e.sourceId||a,r.gltf,null,r),d.traverse(m=>{m.layers.set(2),Z.active?.isPassThrough&&!l&&this.makeOccluder(m),m instanceof H&&Ve.assignMeshLOD(m,0)}),t.connected||($s&&B.DrawLabel(t.rayWorldPosition,"Hand is loaded but not connected anymore",.05,5),d.removeFromParent())});if($s&&c.add(new Pi(.5)),t.inputSource.hand){$s&&console.log(t.inputSource.hand);for(const d of t.inputSource.hand.values())if(n.joints[d.jointName]===void 0){const p=new Po;p.matrixAutoUpdate=!1,p.visible=!0,n.joints[d.jointName]=p,n.add(p)}}else $s&&B.DrawLabel(t.rayWorldPosition,"No inputSource.hand found for index "+t.index,.05,5);return{handObject:c,handmesh:h}}makeOccluder(e){if(e instanceof H){let t=e.material;t instanceof we&&(t=e.material=t.clone(),t.depthWrite=!0,t.depthTest=!0,t.colorWrite=!1,e.receiveShadow=!1,e.renderOrder=-100)}}}Sp([u()],Ko.prototype,"createControllerModel"),Sp([u()],Ko.prototype,"createHandModel"),Sp([u(ne)],Ko.prototype,"customLeftHand"),Sp([u(ne)],Ko.prototype,"customRightHand");class Cp extends E{}var SA=Object.defineProperty,Gs=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&SA(e,t,n),n};const $y=w("debugwebxr");class Bi extends E{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=F(i.x,0,i.y);n.multiplyScalar(this.context.time.deltaTimeUnscaled*this.movementSpeed);const s=$e(t);n.multiplyScalar(s.x),n.applyQuaternion(e.xr.poseOrientation),n.y=0,n.applyQuaternion(t.worldQuaternion),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 i=e.getStick("xr-standard-thumbstick").x;if(this._didApplyRotation)Math.abs(i)<.3&&(this._didApplyRotation=!1);else if(Math.abs(i)>.5){this._didApplyRotation=!0;const n=i>0?1:-1,s=ee(this.context.mainCamera).clone();t.rotateY(n*D.toRadians(this.rotationStep));const r=ee(this.context.mainCamera).clone().sub(s);r.y=0,t.position.sub(r)}}_teleportBuffer=new Array;onHandleTeleport(e,t){let i=0;if(e.hand&&this.usePinchToTeleport&&e.isTeleportGesture){const n=e.getPointerId("primary");if(n!=null&&this.context.input.getIsPointerIdInUse(n))return;const s=e.getGesture("pinch");s&&(i=s.value)}else i=e.getStick("xr-standard-thumbstick")?.y;if(this._didTeleport)i>=0&&i<.4?this._didTeleport=!1:i<0&&i>-.4&&(this._didTeleport=!1);else if(i>.8){this._didTeleport=!0;const n=this.context.physics.raycastFromRay(e.ray)[0];if(n&&n.object instanceof Da){const r=n.normal?.dot(F(0,1,0));if(r!==void 0&&r<.4)return}let s=n?.point;if(!s&&!this.useTeleportTarget){this._plane||(this._plane=new _r(new b(0,1,0),0));const r=t.worldPosition;this._plane.setFromNormalAndCoplanarPoint(new b(0,1,0),r);const a=e.ray;s=r.clone(),this._plane.intersectLine(new VC(a.origin,F(a.direction).multiplyScalar(1e4).add(a.origin)),s),s.distanceTo(r)>t.scale.x*10&&(s=null)}if(s){if(this.useTeleportTarget&&!S.getComponentInParent(n.object,Cp))return;const r=s.clone();if($y&&B.DrawSphere(s,.025,16711680,5),this.context.mainCamera?.position){const a=this.context.xr?.getUserOffsetInRig();a&&(a.y=0,r.sub(a),$y&&B.DrawWireSphere(a.add(r),.025,65280,5))}this._teleportBuffer.push(t.matrix.clone()),this._teleportBuffer.length>10&&this._teleportBuffer.shift(),this.useTeleportFade?e.xr.fadeTransition()?.then(()=>{t.worldPosition=r}):t.worldPosition=r}}else if(i<-.8&&(this._didTeleport=!0,this._teleportBuffer.length>0)){const n=this._teleportBuffer.pop();n&&n.decompose(t.position,t.quaternion,t.scale)}}_plane=null;_lines=[];_hitDiscs=[];_hitDistances=[];_lastHitDistances=[];renderRays(e){for(let t=0;t<this._lines.length;t++){const i=this._lines[t];i&&(i.visible=!1)}for(let t=0;t<e.controllers.length;t++){const i=e.controllers[t];let n=this._lines[t];if(!i.connected||!i.isTracking||!i.ray||i.targetRayMode==="transient-pointer"||!i.hasSelectEvent){n&&(n.visible=!1);continue}n||(n=this.createRayLineObject(),n.scale.z=.5,this._lines[t]=n),i.updateRayWorldPosition(),i.updateRayWorldQuaternion();const s=i.rayWorldPosition,r=i.rayWorldQuaternion;n.position.copy(s),n.quaternion.copy(r);const a=e.rigScale,l=this.usePinchToTeleport&&i.isTeleportGesture,c=this._lastHitDistances[t],h=this._hitDistances[t]!=null,d=c??a;n.scale.set(a,a,d),n.visible=!0,n.layers.disableAll(),n.layers.enable(2);let p=n.material.opacity;l?p=1:this.showHits&&d<e.rigScale*.5?p=0:i.getButton("primary")?.pressed?p=.5:p=h?.2:.1,n.material.opacity=D.lerp(n.material.opacity,p,this.context.time.deltaTimeUnscaled/.1),n.parent!==this.context.scene&&this.context.scene.add(n)}}renderHits(e){for(const t of this._hitDiscs){if(!t)continue;const i=t.controller;if(!i||!i.connected||!i.isTracking){t.visible=!1;continue}}for(let t=0;t<e.controllers.length;t++){const i=e.controllers[t];if(!i.connected||!i.isTracking||!i.ray||!i.hasSelectEvent)continue;let n=this._hitDiscs[t],s=!0;const r=i.getPointerId("primary");r!=null&&this.context.input.getIsPointerIdInUse(r)&&(n&&(n.visible=!1),this._hitDistances[t]=null,this._lastHitDistances[t]=0,s=!1);const a=this.context.time.smoothedFps>=59?1:10;if((this.context.time.frame+i.index)%a!==0&&(s=!1),!s){const h=this._hitDiscs[t];h&&h.visible&&h.hit&&this.updateHitPointerPosition(i,h,h.hit.distance);continue}const l=this.context.physics.raycastFromRay(i.ray,{testObject:this.hitPointRaycastFilter,precise:!1});let c=l.find(h=>this.usePinchToTeleport&&i.isTeleportGesture?!0:this.isObjectWithInteractiveComponent(h.object));if(c||(c=l[0]),n&&(n.controller=i,n.hit=c),this._hitDistances[t]=c?.distance||null,c){this._lastHitDistances[t]=c.distance;const h=e.rigScale??1;$y&&(B.DrawWireSphere(c.point,.025*h,16711680),B.DrawLabel(F(0,.2,0).add(c.point),c.object.name,.02,0)),n||(n=this.createHitPointObject(),this._hitDiscs[t]=n),n.hit=c,n.visible=c.distance>h*.05;let d=.01*(h+c.distance);const p=i.getButton("primary")?.pressed;p&&(d*=1.1),n.scale.set(d,d,d),n.layers.set(2);let m=n.material.opacity;if(p?m=1:m=c.distance<.15*h?.2:.6,n.material.opacity=D.lerp(n.material.opacity,m,this.context.time.deltaTimeUnscaled/.1),n.visible){if(c.normal){this.updateHitPointerPosition(i,n,c.distance);const g=c.normal.applyQuaternion(_e(c.object));n.quaternion.setFromUnitVectors(CA,g)}else this.updateHitPointerPosition(i,n,c.distance);n.parent!==this.context.scene&&this.context.scene.add(n)}}else this._hitDiscs[t]&&(this._hitDiscs[t].visible=!1)}}isObjectWithInteractiveComponent(e,t=0){return Fu(e)||e.isUI===!0?!0:e.isScene?!1:e.parent?this.isObjectWithInteractiveComponent(e.parent,t+1):!1}updateHitPointerPosition(e,t,i){const n=F(e.rayWorldPosition);n.add(F(0,0,i-.01).applyQuaternion(e.rayWorldQuaternion)),t.position.lerp(n,this.context.time.deltaTimeUnscaled/.05)}hitPointRaycastFilter=e=>e.type==="SkinnedMesh"?"continue in children":!0;createHitPointObject(){const e=new H(new Pd(.3,6,6),new Ce({color:15658734,opacity:.7,transparent:!0,depthTest:!1,depthWrite:!1,side:Oi}));return e.layers.disableAll(),e.layers.enable(2),e}createRayLineObject(){const e=new xP;e.layers.disableAll(),e.layers.enable(2);const t=new SP;e.geometry=t;const i=new Float32Array(9);i.set([0,0,.02,0,0,.4,0,0,1]),t.setPositions(i);const n=new Float32Array(9);n.set([1,1,1,.1,.1,.1,0,0,0]),t.setColors(n);const s=new CP({color:16777215,vertexColors:!0,worldUnits:!0,linewidth:.004,transparent:!0,depthWrite:!1,blending:Rb,dashed:!1});return e.material=s,e}}Gs([u()],Bi.prototype,"movementSpeed"),Gs([u()],Bi.prototype,"rotationStep"),Gs([u()],Bi.prototype,"useTeleport"),Gs([u()],Bi.prototype,"usePinchToTeleport"),Gs([u()],Bi.prototype,"useTeleportTarget"),Gs([u()],Bi.prototype,"useTeleportFade"),Gs([u()],Bi.prototype,"showRays"),Gs([u()],Bi.prototype,"showHits");const CA=new b(0,1,0);var PA=Object.defineProperty,xt=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&PA(e,t,n),n};const fh=w("debugwebxr"),OA=w("debugusdz"),ct=class ic extends E{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(){Z.getXRSync(this.context)}onEnable(){window.location.protocol!=="https:"&&be('<a href="https://developer.mozilla.org/en-US/docs/Web/API/WebXR_Device_API" target="_blank">WebXR</a> only works on secure connections (https).'),navigator.xr?.isSessionSupported("immersive-ar").catch(()=>!1).then(e=>{const t=I.isVisionOS()&&!e;(this.useQuicklookExport||t)&&(S.findObjectOfType(uo)||(fh&&console.log("WebXR: Adding USDZExporter"),this._usdzExporter=S.addComponent(this.gameObject,uo),this._usdzExporter.objectToExport=this.context.scene,this._usdzExporter.autoExportAnimations=!0,this._usdzExporter.autoExportAudioSources=!0))}),this.handleCreatingHTML(),this.handleOfferSession(),this.defaultAvatar===!0&&(fh&&console.warn("WebXR: No default avatar set, using static default avatar"),this.defaultAvatar=new ne("https://cdn.needle.tools/static/avatars/DefaultAvatar.glb")),this.defaultAvatar&&(this._playerSync=this.gameObject.getOrAddComponent(Ny),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 Z.isVRSupported()&&this.createVRButton?Z.offerSession("immersive-vr","default",this.context):this.createARButton&&await Z.isARSupported()&&this.createARButton?Z.offerSession("immersive-ar","default",this.context):!1}get session(){return Z.active??null}get sessionMode(){return Z.activeMode??null}get arSessionRoot(){return this._activeWebARSessionRoot}async enterVR(e){return Z.start("immersive-vr",e,this.context)}async enterAR(e){return Z.start("immersive-ar",e,this.context)}exitXR(){Z.stop()}_exitXRMenuButton;_previousXRState=0;_spatialGrabRaycaster;_activeWebARSessionRoot=null;get isActiveWebXR(){return!ic.activeWebXRComponent||ic.activeWebXRComponent===this}onBeforeXR(e,t){if(!this.isActiveWebXR){console.warn(`WebXR: another WebXR component is already active (${ic.activeWebXRComponent?.name}). This is ignored: ${this.name}`);return}if(this.activeAndEnabled===!1||this.destroyed){console.debug("[WebXR] onBeforeXR called on disabled or destroyed component");return}ic.activeWebXRComponent=this,e=="immersive-ar"&&this.useDepthSensing&&(t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.push("depth-sensing"))}async onEnterXR(e){if(!this.isActiveWebXR)return;fh&&console.log("WebXR onEnterXR"),this._previousXRState=ai.Global.Mask;const t=e.xr.isVR;if(ai.Global.Set(t?no.VR:no.AR),e.xr.isAR){let i=S.findObjectOfType(yn,this.context,!1);if(!i)if(this.usePlacementReticle){const n=new M;for(const s of this.context.scene.children)n.add(s);this.context.scene.add(n),i=S.addComponent(n,yn),this._createdComponentsInSession.push(i)}else(fh||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(Ca)??void 0,this._spatialGrabRaycaster||(this._spatialGrabRaycaster=this.gameObject.addComponent(Ca))),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){ai.Global.Set(this._previousXRState),this._playerSync?.destroyInstance();for(const t of this._createdComponentsInSession)t.destroy();this._createdComponentsInSession.length=0,this._activeWebARSessionRoot=null,this.handleOfferSession(),mc(1).then(()=>ic.activeWebXRComponent=null)}}setDefaultMovementEnabled(e){let t=this.gameObject.getComponent(Bi);return!t&&e&&(t=this.gameObject.addComponent(Bi),this._createdComponentsInSession.push(t)),t&&(t.enabled=e),t}setDefaultControllerRenderingEnabled(e){let t=this.gameObject.getComponent(Ko);return!t&&e&&(t=this.gameObject.addComponent(Ko),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=>{fh&&console.log("WebXR.onAvatarSpawned",e);let t=S.getComponentInChildren(e,Vs);t??=S.addComponent(e,Vs)};getButtonsContainer(){return this.getButtonsFactory()}getButtonsFactory(){return this._buttonFactory||(this._buttonFactory=ur.getOrCreate()),this._buttonFactory}_buttonFactory;handleCreatingHTML(){if(this.createARButton||this.createVRButton||this.useQuicklookExport){if((I.isiOS()&&I.isSafari()||OA)&&this.useQuicklookExport){const e=S.findObjectOfType(uo);if(!e||e&&e.allowCreateQuicklookButton){const t=this.getButtonsFactory().createQuicklookButton();this.addButton(t)}}if(this.createARButton){const e=this.getButtonsFactory().createARButton();this.addButton(e)}if(this.createVRButton){const e=this.getButtonsFactory().createVRButton();this.addButton(e)}}if(this.createSendToQuestButton&&!I.isQuest()&&Z.isVRSupported().then(e=>{if(!e){const t=this.getButtonsFactory().createSendToQuestButton();this.addButton(t)}}),this.createQRCode){const e=tl(co);if(e&&e.createQRCodeButton===!1)A()&&console.warn("WebXR: QRCode button is disabled in the Needle Menu component");else if(!I.isMobileDevice()){const t=mn.getOrCreate().createQRCode();this.addButton(t)}}}_buttons=[];addButton(e){this._buttons.push(e),this.context.menu.appendChild(e)}removeButtons(){for(const e of this._buttons)e.remove();this._buttons.length=0}};xt([u()],ct.prototype,"createVRButton"),xt([u()],ct.prototype,"createARButton"),xt([u()],ct.prototype,"createSendToQuestButton"),xt([u()],ct.prototype,"createQRCode"),xt([u()],ct.prototype,"useDefaultControls"),xt([u()],ct.prototype,"showControllerModels"),xt([u()],ct.prototype,"showHandModels"),xt([u()],ct.prototype,"usePlacementReticle"),xt([u(ne)],ct.prototype,"customARPlacementReticle"),xt([u()],ct.prototype,"usePlacementAdjustment"),xt([u()],ct.prototype,"arScale"),xt([u()],ct.prototype,"useXRAnchor"),xt([u()],ct.prototype,"autoPlace"),xt([u()],ct.prototype,"autoCenter"),xt([u()],ct.prototype,"useQuicklookExport"),xt([u()],ct.prototype,"useDepthSensing"),xt([u()],ct.prototype,"useSpatialGrab"),xt([u(ne)],ct.prototype,"defaultAvatar");let Pp=ct;const Op=w("debugusdzbehaviours");class Hy{get extensionName(){return"Behaviour"}behaviours=[];addBehavior(e){this.behaviours.push(e)}addAudioClip(e){if(!e||typeof e!="string")return"";const t="audio/"+Pa.getName(e);return this.audioClips.push({clipUrl:e,filesKey:t}),t}behaviourComponents=[];behaviourComponentsCopy=[];audioClips=[];audioClipsCopy=[];targetUuids=new Set;getAllTargetUuids(){return this.targetUuids}onBeforeBuildDocument(e){if(!e.root)return Promise.resolve();const t=[];return e.root.traverse(i=>{S.foreachComponent(i,n=>{const s=n;if(typeof s.createBehaviours=="function"||typeof s.beforeCreateDocument=="function"||typeof s.afterCreateDocument=="function"||typeof s.afterSerialize=="function"){this.behaviourComponents.push(s);const r=s.beforeCreateDocument?.call(s,this,e);r instanceof Promise&&t.push(r)}},!1)}),Op&&console.log("onBeforeBuildDocument: all components",this.behaviourComponents),Promise.all(t)}onExportObject(e,t,i){for(const n of this.behaviourComponents)n.createBehaviours?.call(n,this,t,i)}onAfterBuildDocument(e){for(const d of this.behaviourComponents)typeof d.afterCreateDocument=="function"&&d.afterCreateDocument(this,e);this.behaviourComponentsCopy=this.behaviourComponents.slice(),this.behaviourComponents.length=0,this.audioClipsCopy=this.audioClips.slice(),this.audioClips.length=0;const t=new Set,i=new Set,n=new Set,s=new Set,r=Op;let a=`graph LR
|
|
1289
|
+
`))}for(const q of R){const he=s.get(q);he&&$.set(q,he)}return $},m=function(R){const $=p(R),q=l($);return c($,q,R)};const g=n.skinnedMesh.skeleton,f=new Array,y=[],_=[];for(const R of g.bones){y.push(R),_.push(R.uuid);const $=g.boneInverses[g.bones.indexOf(R)];f.push({bone:R,inverse:$})}let v=1e4;for(;_.length<g.bones.length&&v-- >0;)for(const R of y){const $=R.children;for(const q of $)if(_.indexOf(q.uuid)===-1&&g.bones.indexOf(q)!==-1){y.push(q),_.push(q.uuid);const he=g.boneInverses[g.bones.indexOf(q)];f.push({bone:q,inverse:he})}}v<=0&&console.error("Failed to sort bones in skinned mesh",n.skinnedMesh,g.bones,_);for(const R of Kx(g.bones))f.push({bone:R,inverse:R.matrixWorld.clone().invert()});const P=f[0].bone.parent;P||console.error("No bone parent found for skinned mesh during USDZ export",n.skinnedMesh),f.sort((R,$)=>Cl(R.bone,P)>Cl($.bone,P)?1:-1);const k=t.quickLookCompatible,O=[],D=[],L=[],V=[];for(const{bone:R}of f){if(k){const $=R.scale;$.x==0&&($.x=1e-5),$.y==0&&($.y=1e-5),$.z==0&&($.z=1e-5),O.push(new J().compose(R.position,R.quaternion,R.scale))}else O.push(R.matrix.clone());D.push(R.position),L.push(R.quaternion),V.push(R.scale)}const W=f.map(R=>'"'+Cl(R.bone,P)+'"').join(", "),G=f.map(R=>h1(R.inverse.clone().invert())).join(", ");e.beginBlock('def Skeleton "Rig"'),e.appendLine(`uniform matrix4d[] bindTransforms = [${G}]`),e.appendLine(`uniform token[] joints = [${W}]`),e.appendLine('uniform token purpose = "guide"'),e.appendLine(`uniform matrix4d[] restTransforms = [${O.map(R=>h1(R)).join(", ")}]`);const X=m(f.map(R=>R.bone));if(lo){let R=1e7,$=0;for(const q of X.position?.keys()??[])R=Math.min(R,q),$=Math.max($,q);console.log("Time samples",R,$,X)}if(e.beginBlock('def SkelAnimation "_anim"'),e.appendLine(`uniform token[] joints = [${W}]`),e.appendLine(`quatf[] rotations = [${d(L)}]`),X&&X.quaternion){e.beginBlock("quatf[] rotations.timeSamples = {","");const R=a(X.quaternion);for(const $ of R)e.appendLine($);e.closeBlock()}if(e.appendLine(`half3[] scales = [${h(V)}]`),X&&X.scale){e.beginBlock("half3[] scales.timeSamples = {","");const R=r(X.scale);for(const $ of R)e.appendLine($);e.closeBlock()}if(e.appendLine(`float3[] translations = [${h(D)}]`),X&&X.position){e.beginBlock("float3[] translations.timeSamples = {","");const R=r(X.position);for(const $ of R)e.appendLine($);e.closeBlock()}e.closeBlock(),e.closeBlock()}}onSerialize(e,t){if(!this.model)return;const i=this.animationData.get(this.object);if(i)for(let h=0;h<i.length;h++)i[h]===void 0&&(i[h]=new Ne(null,this.object,null));const n=this.ext;this.skinnedMeshExport(e,t,n);const s=this.object,r=this.model,a=this.animationData.get(s);if(!a||s.isSkinnedMesh)return;Ty&&console.log("SERIALIZE",this.model.name,this.object.type,a);const l=Intl.NumberFormat("en-US",{maximumFractionDigits:3,minimumFractionDigits:0,useGrouping:!1});function c(h,d){if(h.some(p=>p&&{position:p.pos,rotation:p.rot,scale:p.scale}[d])){switch(d){case"position":r.needsTranslate=!0,e.beginBlock("double3 xformOp:translate.timeSamples = {","");break;case"rotation":r.needsOrient=!0,e.beginBlock("quatf xformOp:orient.timeSamples = {","");break;case"scale":r.needsScale=!0,e.beginBlock("double3 xformOp:scale.timeSamples = {","");break}for(let p=0;p<h.length;p++){const m=h[p];if(!m)continue;const g=n.getStartTimeByClip(m.clip),f=m.getSortedTimesArray(d==="position",d==="rotation",d==="scale");if(!f||f.length===0){console.error("got an animated object but no time values?",s,m);continue}const y=!m.clip,_=d==="position"&&(m.pos||y),v=d==="rotation"&&(m.rot||y),P=d==="scale"&&(m.scale||y);if(_||v||P){const k=m.clip?.name??"rest",O=m.getDuration();lo&&console.log("Write .timeSamples:",k,g,O,h),e.appendLine("# "+k+": start="+l.format(g*Ne.frameRate)+", length="+l.format(O*Ne.frameRate)+", frames="+m.getFrames())}if(_)for(const{time:k,translation:O}of m.getValues(f,!0,!1,!1)){const D=`${l.format((g+k)*Ne.frameRate)}: (${ce(O.x)}, ${ce(O.y)}, ${ce(O.z)}),`;e.appendLine(D)}if(v)for(const{time:k,rotation:O}of m.getValues(f,!1,!0,!1)){const D=`${l.format((g+k)*Ne.frameRate)}: (${ce(O.w)}, ${ce(O.x)}, ${ce(O.y)}, ${ce(O.z)}),`;e.appendLine(D)}if(P)for(const{time:k,scale:O}of m.getValues(f,!1,!1,!0)){const D=`${l.format((g+k)*Ne.frameRate)}: (${ce(O.x)}, ${ce(O.y)}, ${ce(O.z)}),`;e.appendLine(D)}}e.closeBlock()}}c(a,"position"),c(a,"rotation"),c(a,"scale")}}const oA=w("debugusdz");class Pa{static getName(e){const t=e.split(".").pop();let i=e.split(".").slice(0,-1).join(".").split("/").pop()?.replace(".","_");return i||(i="Audio_"+Math.random().toString(36).substring(2,15)),Di(i)+"."+t}get extensionName(){return"Audio"}files=new Array;onExportObject(e,t,i){const n=S.getComponents(e,ji);if(n.length)for(const s of n){if(!s.clip||typeof s.clip!="string"||!s.playOnAwake)continue;const r=s.clip.split("/").pop()||"Audio",a=Pa.getName(s.clip),l=Di(a);if(!this.files.some(c=>c.path===s.clip)){this.files.push({path:s.clip,name:a});const c=a.toLowerCase();i.quickLookCompatible&&!c.endsWith(".mp3")&&!c.endsWith(".wav")&&!c.endsWith(".m4a")&&console.error("Audio file "+s.clip+" from "+s.name+" is not an MP3 or WAV file. QuickLook may not support playing it.")}i.quickLookCompatible||t.addEventListener("serialize",(c,h)=>{c.appendLine(),c.beginBlock(`def SpatialAudio "${l}"`,"(",!1),c.appendLine(`displayName = "${r}"`),c.closeBlock(")"),c.beginBlock(),c.appendLine(`uniform asset filePath = @audio/${a}@`),c.appendLine(`uniform token auralMode = "${s.spatialBlend>0?"spatial":"nonSpatial"}"`),c.appendLine(`uniform token playbackMode = "${s.loop?"loopFromStage":"onceFromStart"}"`),c.appendLine(`uniform float gain = ${s.volume}`),c.closeBlock()})}}async onAfterSerialize(e){for(const t of this.files){const i="audio/"+t.name;if(e.files[i]){oA&&console.warn("Audio file with name "+i+" already exists in the context. Skipping.");continue}const n=await(await(await fetch(t.path)).blob()).arrayBuffer(),s=new Uint8Array(n);e.files[i]=s}}}var sA=Object.defineProperty,Be=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&sA(e,t,n),n};const y1=w("debugusdzbehaviours");class ea extends E{object;target;duration=1;relativeMotion=!1;coroutine=null;targetPos=new b;targetRot=new N;targetScale=new b;onEnable(){this.context.accessibility.updateElement(this,{role:"button",label:"Move "+(this.object?.name||"object")+" to "+(this.target?.name||"target")+" on click",hidden:!1})}onDisable(){this.context.accessibility.updateElement(this,{hidden:!0})}onDestroy(){this.context.accessibility.removeElement(this)}onPointerEnter(){this.context.input.setCursor("pointer")}onPointerExit(){this.context.input.unsetCursor("pointer")}onPointerClick(e){const t=this.object?.getComponentsInChildren(Ke);if(t)for(const i of t)i.resetVelocities(),i.resetForcesAndTorques();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=ee(this.object).clone(),t=ee(this.target).clone(),i=_e(this.object).clone(),n=_e(this.target).clone(),s=$e(this.object).clone(),r=$e(this.target).clone(),a=e.distanceTo(t),l=i.angleTo(n),c=s.distanceTo(r);if(a<.01&&l<.01&&c<.01){yt(this.object,t),Sn(this.object,n),za(this.object,r),this.coroutine=null;return}let h=0,d=0;for(;h<1;)h+=this.context.time.deltaTime/this.duration,h>1&&(h=1),d=h<.5?4*h*h*h:1-Math.pow(-2*h+2,3)/2,this.targetPos.lerpVectors(e,t,d),this.targetRot.slerpQuaternions(i,n,d),this.targetScale.lerpVectors(s,r,d),yt(this.object,this.targetPos),Sn(this.object,this.targetRot),za(this.object,this.targetScale),yield;this.coroutine=null}*moveRelative(){if(!this.target||!this.object)return;const e=this.object.position.clone(),t=this.object.quaternion.clone(),i=this.object.scale.clone(),n=this.target.position.clone(),s=this.target.quaternion.clone(),r=this.target.scale.clone();n.applyQuaternion(this.object.quaternion),this.targetPos.copy(this.object.position).add(n),this.targetRot.copy(this.object.quaternion).multiply(s),this.targetScale.copy(this.object.scale).multiply(r);let a=0,l=0;for(;a<1;)a+=this.context.time.deltaTime/this.duration,a>1&&(a=1),l=a<.5?4*a*a*a:1-Math.pow(-2*a+2,3)/2,this.object.position.lerpVectors(e,this.targetPos,l),this.object.quaternion.slerpQuaternions(t,this.targetRot,l),this.object.scale.lerpVectors(i,this.targetScale,l),yield;this.coroutine=null}beforeCreateDocument(e){if(this.target&&this.object&&this.gameObject){const t=new jt("Move to "+this.target?.name,$t.tapTrigger(this.gameObject),fe.transformAction(this.object,this.target,this.duration,this.relativeMotion?"relative":"absolute"));e.addBehavior(t)}}}Be([u(M)],ea.prototype,"object"),Be([u(M)],ea.prototype,"target"),Be([u()],ea.prototype,"duration"),Be([u()],ea.prototype,"relativeMotion");const vp=class ri extends E{materialToSwitch;variantMaterial;fadeDuration=0;start(){this._objectsWithThisMaterial=this.objectsWithThisMaterial,A()&&this._objectsWithThisMaterial.length<=0&&console.warn('ChangeMaterialOnClick: No objects found with material "'+this.materialToSwitch?.name+'"')}onEnable(){this.context.accessibility.updateElement(this,{role:"button",label:"Change material to "+(this.variantMaterial?.name||"unknown material"),hidden:!1})}onDisable(){this.context.accessibility.updateElement(this,{hidden:!0})}onDestroy(){this.context.accessibility.removeElement(this)}onPointerEnter(e){this.context.input.setCursor("pointer")}onPointerExit(e){this.context.input.unsetCursor("pointer")}onPointerClick(e){if(e.use(),!!this.variantMaterial)for(let t=0;t<this.objectsWithThisMaterial.length;t++){const i=this.objectsWithThisMaterial[t];i.material=this.variantMaterial}}_objectsWithThisMaterial=null;get objectsWithThisMaterial(){return this._objectsWithThisMaterial!=null?this._objectsWithThisMaterial:(this._objectsWithThisMaterial=[],this.variantMaterial&&this.materialToSwitch&&this.context.scene.traverse(e=>{if(e instanceof H)if(Array.isArray(e.material)){for(const t of e.material)if(t===this.materialToSwitch){this.objectsWithThisMaterial.push(e);break}}else e.material===this.materialToSwitch?this.objectsWithThisMaterial.push(e):Zv(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=[],ri._materialTriggersPerId={},ri.variantSwitchIndex=0,this.materialToSwitch&&await Ve.assignTextureLOD(this.materialToSwitch,0),this.variantMaterial&&await Ve.assignTextureLOD(this.variantMaterial,0)}createBehaviours(e,t,i){this.objectsWithThisMaterial.find(n=>n.uuid===t.uuid)&&this.targetModels.push(t),this.gameObject.uuid===t.uuid&&(this.selfModel=t,this.materialToSwitch&&(ri._materialTriggersPerId[this.materialToSwitch.uuid]||(ri._materialTriggersPerId[this.materialToSwitch.uuid]=[]),ri._materialTriggersPerId[this.materialToSwitch.uuid].push(this)))}afterCreateDocument(e,t){if(!this.materialToSwitch)return;const i=ri._materialTriggersPerId[this.materialToSwitch.uuid];if(i){const n={};for(const s of i){const r=s.createVariants();r&&r.length>0&&(n[s.selfModel.uuid]=r)}for(const s of i){const r=[];for(const a in n)a!==s.selfModel.uuid&&r.push(...n[a]);s.createAndAttachBehaviors(e,n[s.selfModel.uuid],r)}}delete ri._materialTriggersPerId[this.materialToSwitch.uuid]}createAndAttachBehaviors(e,t,i){const n=[],s=Math.max(0,this.fadeDuration);n.push(fe.fadeAction([...this.targetModels,...i],s,!1)),n.push(fe.fadeAction(t,s,!0)),e.addBehavior(new jt("Select_"+this.selfModel.name,$t.tapTrigger(this.selfModel),fe.parallel(...n))),ri._parallelStartHiddenActions.push(...t),ri._startHiddenBehaviour||(ri._startHiddenBehaviour=new jt("StartHidden_"+this.selfModel.name,$t.sceneStartTrigger(),fe.fadeAction(ri._parallelStartHiddenActions,s,!1)),e.addBehavior(ri._startHiddenBehaviour))}static getMaterialName(e){return Di(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_"+ri.variantSwitchIndex+++"_"+ri.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())&&rt.createEmptyParent(t),t.parent&&t.parent.add(i),e.push(i)}return e}};Be([u(we)],vp.prototype,"materialToSwitch"),Be([u(we)],vp.prototype,"variantMaterial"),Be([u()],vp.prototype,"fadeDuration");let Ay=vp;const ch=class ze extends E{target;toggleOnClick=!1;targetState=!0;hideSelf=!0;onPointerEnter(){this.context.input.setCursor("pointer")}onPointerExit(){this.context.input.unsetCursor("pointer")}onPointerClick(e){e.use(),!this.toggleOnClick&&this.hideSelf&&(this.gameObject.visible=!1),this.target&&(this.target.visible=this.toggleOnClick?!this.target.visible:this.targetState)}selfModel;selfModelClone;targetModel;toggleModel;createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&(this.selfModel=t,this.selfModelClone=t.clone())}stateBeforeCreatingDocument=!1;targetStateBeforeCreatingDocument=!1;static clonedToggleIndex=0;static wasVisible=Symbol("usdz_SetActiveOnClick_wasVisible");static toggleClone=Symbol("clone for toggling");static reverseToggleClone=Symbol("clone for reverse toggling");beforeCreateDocument(){this.target&&(this.gameObject[ze.wasVisible]===void 0&&(this.gameObject[ze.wasVisible]=this.gameObject.activeSelf),this.target[ze.wasVisible]===void 0&&(this.target[ze.wasVisible]=this.target.activeSelf),this.stateBeforeCreatingDocument=this.gameObject[ze.wasVisible],this.targetStateBeforeCreatingDocument=this.target[ze.wasVisible],this.gameObject.visible=!0,this.target.visible=!0)}afterCreateDocument(e,t){if(!this.target)return;this.targetModel=t.document.findById(this.target.uuid);const i=this.selfModel;if(this.selfModel&&this.targetModel){let n=this.selfModel,s=this.targetState;if(this.toggleOnClick)if(s=!this.targetStateBeforeCreatingDocument,!this.selfModelClone.geometry)(!this.selfModel.parent||this.selfModel.parent.isEmpty())&&xy.createEmptyParent(this.selfModel),this.toggleModel=this.selfModel.deepClone(),this.toggleModel.name+="_toggle",this.selfModel.parent.add(this.toggleModel);else{if(!this.gameObject[ze.toggleClone]){const l=this.selfModelClone.clone();l.setMatrix(new J),l.name+="_toggle"+ze.clonedToggleIndex++,i.add(l),this.gameObject[ze.toggleClone]=l,console.warn("USDZExport: Toggle "+this.gameObject.name+" doesn't have geometry. It will be deep cloned and nested behaviours will likely not work.")}const a=this.gameObject[ze.toggleClone];if(!this.gameObject[ze.reverseToggleClone]){const l=this.selfModelClone.clone();l.setMatrix(new J),l.name+="_toggleReverse"+ze.clonedToggleIndex++,i.add(l),this.gameObject[ze.reverseToggleClone]=l}this.toggleModel=this.gameObject[ze.reverseToggleClone],(!this.toggleModel.geometry||!a.geometry)&&console.error("triggers without childs and without geometry won't work!",this,i.geometry),n=a,i.geometry=null,i.material=null}if(this.toggleModel){if(this.toggleOnClick){const a=[];a.push(fe.fadeAction(n,0,!1)),a.push(fe.fadeAction(this.toggleModel,0,!0)),a.push(fe.fadeAction(this.targetModel,0,s)),e.addBehavior(new jt("Toggle_"+n.name+"_ToggleTo"+(s?"On":"Off"),$t.tapTrigger(n),fe.parallel(...a)));const l=[];l.push(fe.fadeAction(this.toggleModel,0,!1)),l.push(fe.fadeAction(n,0,!0)),l.push(fe.fadeAction(this.targetModel,0,!s)),e.addBehavior(new jt("Toggle_"+n.name+"_ToggleTo"+(s?"Off":"On"),$t.tapTrigger(this.toggleModel),fe.parallel(...l)))}}else{const a=[];this.hideSelf&&a.push(fe.fadeAction(n,0,!1)),a.push(fe.fadeAction(this.targetModel,0,s)),e.addBehavior(new jt("Toggle_"+n.name+"_ToggleTo"+(s?"On":"Off"),$t.tapTrigger(n),a.length>1?fe.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),fn.add(r,e)}}afterSerialize(e,t){this.gameObject[ze.wasVisible]!==void 0&&(this.gameObject.visible=this.gameObject[ze.wasVisible],delete this.gameObject[ze.wasVisible]),this.target&&this.target[ze.wasVisible]!==void 0&&(this.target.visible=this.target[ze.wasVisible],delete this.target[ze.wasVisible]),delete this.gameObject[ze.toggleClone],delete this.gameObject[ze.reverseToggleClone]}};Be([u(M)],ch.prototype,"target"),Be([u()],ch.prototype,"toggleOnClick"),Be([u()],ch.prototype,"targetState"),Be([u()],ch.prototype,"hideSelf");let Iy=ch;class fn extends E{static _fadeBehaviour;static _fadeObjects=[];static add(e,t){const i=Array.isArray(e)?e:[e];for(const n of i)fn._fadeObjects.includes(n)||(console.log("adding hide on start",n),fn._fadeObjects.push(n));fn._fadeBehaviour===void 0&&(fn._fadeBehaviour=new jt("HideOnStart",$t.sceneStartTrigger(),fe.fadeAction(fn._fadeObjects,0,!1)),t.addBehavior(fn._fadeBehaviour))}start(){S.setActive(this.gameObject,!1)}createBehaviours(e,t,i){t.uuid===this.gameObject.uuid&&(this.wasVisible||fn.add(t,e))}wasVisible=!1;beforeCreateDocument(){this.wasVisible=S.isActiveSelf(this.gameObject)}}class Ol extends E{target;duration=.5;motionType="bounce";onEnable(){this.context.accessibility.updateElement(this,{role:"button",label:"Emphasize "+this.target?.name+" on click",hidden:!1})}onDisable(){this.context.accessibility.updateElement(this,{hidden:!0})}onDestroy(){this.context.accessibility.removeElement(this)}beforeCreateDocument(){}createBehaviours(e,t,i){if(this.target&&t.uuid===this.gameObject.uuid){const n=new jt("emphasize "+this.name,$t.tapTrigger(this.gameObject),fe.emphasize(this.target,this.duration,this.motionType,void 0,"basic"));e.addBehavior(n)}}afterCreateDocument(e,t){}}Be([u()],Ol.prototype,"target"),Be([u()],Ol.prototype,"duration"),Be([u()],Ol.prototype,"motionType");class Ns extends E{target;clip="";toggleOnClick=!1;trigger="tap";ensureAudioSource(){if(!this.target){const e=this.gameObject.addComponent(ji);e&&(this.target=e,e.spatialBlend=1,e.volume=1,e.loop=!1,e.preload=!0)}}onEnable(){this.context.accessibility.updateElement(this,{role:"button",label:"Play audio: "+(this.clip||this.target?.clip||"unknown clip"),hidden:!1})}onDisable(){this.context.accessibility.updateElement(this,{hidden:!0})}onDestroy(){this.context.accessibility.removeElement(this)}onPointerEnter(){this.context.input.setCursor("pointer")}onPointerExit(){this.context.input.unsetCursor("pointer")}onPointerClick(e){e.use(),!(!this.target?.clip&&!this.clip)&&(this.ensureAudioSource(),this.target&&(this.target.isPlaying&&this.toggleOnClick?this.target.stop():(!this.toggleOnClick&&this.target.isPlaying&&this.target.stop(),this.clip?this.target.play(this.clip):this.target.play())))}createBehaviours(e,t,i){if(!(!this.target&&!this.clip)&&t.uuid===this.gameObject.uuid){const n=this.clip?this.clip:this.target?this.target.clip:void 0;if(!n||typeof n!="string")return;const s=this.target?this.target.gameObject:this.gameObject;Pa.getName(n);const r=this.target?this.target.volume:1,a=this.target&&this.target.spatialBlend==0?"nonSpatial":"spatial";let l=!1;this.gameObject.traverse(p=>{p instanceof H&&p.visible&&(l=!0)}),l=!0;const c=e.addAudioClip(n);let h=fe.playAudioAction(s,c,"play",r,a);this.target&&this.target.loop&&(h=fe.sequence(h).makeLooping());const d=this.name?"_"+this.name:"";if(l&&this.trigger==="tap"){this.toggleOnClick&&(h.multiplePerformOperation="stop");const p=new jt("playAudio"+d,$t.tapTrigger(t),h);e.addBehavior(p)}if(this.target&&this.target.playOnAwake&&this.target.enabled)if(l&&this.trigger==="tap")console.warn("USDZExport: Audio sources that are played on tap can't also auto-play at scene start due to a QuickLook bug.");else{const p=new jt("playAudioOnStart"+d,$t.sceneStartTrigger(),h);e.addBehavior(p)}}}}Be([u(ji)],Ns.prototype,"target"),Be([u(URL)],Ns.prototype,"clip"),Be([u()],Ns.prototype,"toggleOnClick");const Ly=class vo extends E{animator;stateName;trigger="tap";animation;get target(){return this.animator?.gameObject||this.animation?.gameObject}onEnable(){this.context.accessibility.updateElement(this,{role:"button",label:"Plays animation "+(this.stateName||"")+" on "+(this.target?this.target.name:""),hidden:!1})}onDisable(){this.context.accessibility.updateElement(this,{hidden:!0})}onDestroy(){this.context.accessibility.removeElement(this)}onPointerEnter(){this.context.input.setCursor("pointer"),this.context.accessibility.hover(this,"Click to play animation "+(this.stateName||"")+" on "+(this.target?this.target.name:""))}onPointerExit(){this.context.input.unsetCursor("pointer")}onPointerClick(e){e.use(),this.target&&this.stateName&&(this.context.accessibility.focus(this),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(vo.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()&&be(e),console.warn(e,...vo.rootsWithExclusivePlayback)}vo.animationActions=[],vo.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 _p);if(!n)return;const s=n.getClipCount(this.target)>1;s&&(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."),vo.rootsWithExclusivePlayback.add(this.target));const r=this.name?this.name:"";i.traverse(a=>{if(a.uuid===this.target?.uuid){const l=vo.getActionForSequences(i,a,this.animationSequence,this.animationLoopAfterSequence,this.randomOffsetNormalized),c=new jt(this.trigger+"_"+r+"_toPlayAnimation_"+this.stateName+"_on_"+this.target?.name,this.trigger=="tap"?$t.tapTrigger(this.selfModel):$t.sceneStartTrigger(),l);s&&c.makeExclusive(!0),e.addBehavior(c)}})}static getActionForSequences(e,t,i,n,s){const r=(l,c)=>{let h=vo.animationActions.find(d=>d.affectedObjects==l&&d.start==c.start&&d.duration==c.duration&&d.animationSpeed==c.speed);return h||(h=fe.startAnimationAction(l,c),vo.animationActions.push(h)),h},a=fe.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:fe.sequence();for(const c of n)l.addAction(r(t,c));l.makeLooping(),a!==l&&a.addAction(l)}return s&&s>0&&a.actions.unshift(fe.waitAction(s)),a}static getAndRegisterAnimationSequences(e,t,i){if(!t)return;const n=t.getComponent(_t),s=t.getComponent(Ut);if(!n&&!s)return;if(n&&!i)throw new Error("PlayAnimationOnClick: No stateName specified for animator "+n.name+" on "+t.name);let r=[],a=[];if(s){const g=e.registerAnimation(t,s.clip);g&&(s.loop?a.push(g):r.push(g));let f=0;if(s.minMaxOffsetNormalized){const y=s.minMaxOffsetNormalized.x,_=s.minMaxOffsetNormalized.y;f=(s.clip?.duration||1)*(y+Math.random()*(_-y))}return{animationSequence:r,animationLoopAfterSequence:a,randomTimeOffset:f}}const l=n?.runtimeAnimatorController;let c=l?.findState(i),h=[],d=[];if(l&&c){const g=new Array;g.push(c);let f=!1;for(;g.length<100;){if(!c||c===null||!c.transitions||c.transitions.length===0){c.motion?.isLooping&&(f=!0);break}const y=c.transitions.find(v=>v.conditions.length===0),_=y?l.getState(y.destinationState,0):null;if(_&&g.includes(_)){c=_,f=!0;break}else if(y){if(c=_,!c)break;g.push(c)}else{f=c.motion?.isLooping??!1;break}}if(f&&c){const y=g.indexOf(c);h=g.slice(0,y),d=g.slice(y),y1&&console.log("found loop from "+i,"states until loop",h,"states looping",d)}else h=g,d=[],y1&&console.log("found no loop from "+i,"states",h);if(!d.length){const y=h[h.length-1],_=y.motion?.clip;if(_){let v;if(e.holdClipMap.has(_))v=e.holdClipMap.get(_);else{const P=y.name+"_hold";v=_.clone(),v.duration=1,v.name=P;const k=_.duration;v.tracks=_.tracks.map(O=>{const D=O.clone();D.times=new Float32Array([0,k]);const L=O.values.length,V=O.getValueSize(),W=O.values.slice(L-V,L);return D.values=new Float32Array(2*V),D.values.set(W,0),D.values.set(W,V),D}),v.name=P,e.holdClipMap.set(_,v)}if(v){const P={name:v.name,motion:{clip:v,isLooping:!1,name:v.name},speed:1,transitions:[],behaviours:[],hash:y.hash+1};d.push(P)}}}}if(h.length===1&&(!h[0].motion?.clip||h[0].motion?.clip.tracks?.length===0)){r=new Array;const g=e.registerAnimation(t,null);g&&r.push(g);return}if(h=h.filter(g=>g.motion?.clip&&g.motion?.clip.tracks?.length>0),d=d.filter(g=>g.motion?.clip&&g.motion?.clip.tracks?.length>0),h.length===0&&d.length===0){console.warn("No clips found for state "+i+" on "+n?.name+", can't export animation data");return}const p=(g,f)=>{if(!t)return;const y=e.registerAnimation(t,g.motion.clip??null);y?(y.speed=g.speed,f.push(y)):console.warn("Couldn't register animation for state "+g.name+" on "+n?.name)};if(h.length>0){r=new Array;for(const g of h)p(g,r)}if(d.length>0){a=new Array;for(const g of d)p(g,a)}let m=0;if(n&&l&&n.minMaxOffsetNormalized){const g=n.minMaxOffsetNormalized.x,f=n.minMaxOffsetNormalized.y;m=((h.length?h[0]:d.length?d[0]:null)?.motion.clip?.duration||1)*(g+Math.random()*(f-g))}return{animationSequence:r,animationLoopAfterSequence:a,randomTimeOffset:m}}createAnimation(e,t,i){if(!this.target||!this.animator&&!this.animation)return;const n=vo.getAndRegisterAnimationSequences(e,this.target,this.stateName);n&&(this.animationSequence=n.animationSequence,this.animationLoopAfterSequence=n.animationLoopAfterSequence,this.randomOffsetNormalized=n.randomTimeOffset,this.stateAnimationModel=t)}};Be([u(_t)],Ly.prototype,"animator"),Be([u()],Ly.prototype,"stateName");let hh=Ly;class kl extends E{getType(){}target;getDuration(){}}Be([u(M)],kl.prototype,"target");class dh extends E{target}Be([u(kl)],dh.prototype,"target");class uh extends kl{type=1;duration=1;getType(){switch(this.type){case 1:return"hide";case 0:return"show"}}getDuration(){return this.duration}}Be([u()],uh.prototype,"type"),Be([u()],uh.prototype,"duration");class jy extends dh{}const rA=100,aA=200,lA=300;class ur{static _instance;static create(){return new ur}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 mn.getOrCreate().createQRCode()}createQuicklookButton(){if(this._quicklookButton)return this._quicklookButton;const e=document.createElement("button");this._quicklookButton=e,e.dataset.needle="quicklook-button";const t=I.supportsQuickLookAR();let i="View in AR";I.isVisionOS()?i="View in AR":(t||I.isiOS())&&(i="Open in Quicklook"),e.innerText=i,e.prepend(Pt("view_in_ar")),Es.setElementPriority(e,aA);let n=!1,s=null;return e.addEventListener("click",()=>{s=tl(uo),s||(n=!0,s=new uo),n&&(s.objectToExport=U.Current.scene),s?(e.classList.add("this-mode-is-requested"),s.exportAndOpen().then(()=>{e.classList.remove("this-mode-is-requested")}).catch(r=>{e.classList.remove("this-mode-is-requested"),console.error(r)})):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",()=>Z.start(t,e)),Es.setElementPriority(i,lA),this.updateSessionSupported(i,t),this.listenToXRSessionState(i,t),this.hideElementDuringXRSession(i),this.isSecureConnection||(i.disabled=!0,i.title="WebXR requires a secure connection (HTTPS)"),I.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",()=>Z.start(t,e)),Es.setElementPriority(i,rA),this.updateSessionSupported(i,t),this.listenToXRSessionState(i,t),this.hideElementDuringXRSession(i),this.isSecureConnection||(i.disabled=!0,i.title="WebXR requires a secure connection (HTTPS)"),I.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&&Oe("This page doesn't allow popups. Please paste "+n+" into your browser.")}),this.listenToXRSessionState(t),this.hideElementDuringXRSession(t),I.isMozillaXR()||navigator.xr?.addEventListener("devicechange",()=>{navigator.xr?.isSessionSupported("immersive-vr")?t.style.display="none":t.style.display=""}),t}createQRCode(){return mn.getOrCreate().createQRCode()}updateSessionSupported(e,t){if(!(t==="immersive-ar"&&I.isiOS()&&!I.isVisionOS())){if(!("xr"in navigator)){e.style.display="none";return}Z.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){Qd(t=>{e["previous-display"]=e.style.display,e.style.setProperty("display","none","important")}),Cg(t=>{e["previous-display"]!=null&&(e.style.display=e["previous-display"])})}listenToXRSessionState(e,t){t&&(Z.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"))}),Z.onSessionRequestEnd(i=>{e.classList.remove("this-mode-is-requested"),e.classList.remove("other-mode-is-requested"),e.disabled=e["was-disabled"]}))}}var cA=Object.defineProperty,hA=Object.getOwnPropertyDescriptor,wt=(o,e,t,i)=>{for(var n=i>1?void 0:i?hA(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&cA(e,t,n),n};const ph=w("debugspriterenderer"),dA=w("wireframe");class ka{static cache={};static getOrCreateGeometry(e){if(e.__cached_geometry)return e.__cached_geometry;if(e.guid&&ka.cache[e.guid])return ph&&console.log("Take cached geometry for sprite",e.guid),ka.cache[e.guid];const t=new wn;e.__cached_geometry=t;const i=new Float32Array(e.triangles.length*3),n=new Float32Array(e.triangles.length*2);for(let s=0;s<e.triangles.length;s+=1){const r=e.triangles[s];i[s*3]=-e.vertices[r].x,i[s*3+1]=e.vertices[r].y,i[s*3+2]=0;const a=e.uv[r];n[s*2]=a.x,n[s*2+1]=1-a.y}return t.setAttribute("position",new ft(i,3)),t.setAttribute("uv",new ft(n,2)),e.guid&&(this.cache[e.guid]=t),ph&&console.log("Built sprite geometry",e,t),t}}class uA{x;y}function b1(o){o&&(o.colorSpace!=Mo&&(o.colorSpace=Mo,o.needsUpdate=!0),o.minFilter==Ad&&o.magFilter==Ad&&(o.anisotropy=1,o.needsUpdate=!0))}let Zo=class{constructor(o){o&&(this.texture=o,this.triangles=[0,1,2,0,2,3],this.uv=[{x:0,y:0},{x:1,y:0},{x:1,y:1},{x:0,y:1}],this.vertices=[{x:-.5,y:-.5},{x:.5,y:-.5},{x:.5,y:.5},{x:-.5,y:.5}])}guid;texture;triangles;uv;vertices;__cached_geometry;get mesh(){return this._mesh||(this._mesh=new H(ka.getOrCreateGeometry(this),this.material)),this._mesh}_mesh;get material(){return this._material||(this.texture&&b1(this.texture),this._material=new Ce({map:this.texture,color:16777215,side:Oi,transparent:!0})),this._material}_material;getGeometry(){return ka.getOrCreateGeometry(this)}};wt([u()],Zo.prototype,"guid",2),wt([u(Se)],Zo.prototype,"texture",2),wt([Ye()],Zo.prototype,"triangles",2),wt([Ye()],Zo.prototype,"uv",2),wt([Ye()],Zo.prototype,"vertices",2);const Dy=Symbol("spriteOwner");class Ml{sprites;constructor(){this.sprites=[]}}wt([u(Zo)],Ml.prototype,"sprites",2);const By=class db{static create(){const e=new db;return e.spriteSheet=new Ml,e}constructor(){}clone(){const e=new db;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 Ml,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&&(b1(n),!i.__hasLoadedProgressive)){i.__hasLoadedProgressive=!0;const s=n;Ve.assignTextureLOD(n,0).then(r=>{r instanceof Se&&(i.texture=r,e?.map===s&&(e.map=r,e.needsUpdate=!0))})}}};wt([u(Ml)],By.prototype,"spriteSheet",2),wt([u()],By.prototype,"index",2);let El=By;class _i extends E{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=El.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);ph&&console.log("[SpriteSheet] Set index to "+t+" (was "+this.spriteIndex+")",e),this.spriteIndex=t}else e instanceof Zo?(this._spriteSheet||(this._spriteSheet=El.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=El.create(),ph&&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 ph&&console.warn("Sprite not found",this.spriteIndex,t.spriteSheet.sprites),!1;if(this._currentSprite)this._currentSprite.geometry=ka.getOrCreateGeometry(i),this._currentSprite.material.map=i.texture;else{const n=new Ce({color:16777215,side:Oi});if(dA&&(n.wireframe=!0),this.color&&(n.color||(n.color=new oe),n.color.copy(this.color),n.opacity=this.color.alpha),n.transparent=!0,n.toneMapped=this.toneMapped,n.depthWrite=!1,i.texture&&!n.wireframe){let s=i.texture;s[Dy]!==void 0&&s[Dy]!==this&&this.spriteFrames>1&&(s=i.texture=s.clone()),s[Dy]=this,n.map=s}this.sharedMaterial=n,this._currentSprite=new H(ka.getOrCreateGeometry(i),n),this._currentSprite.renderOrder=Math.round(this.renderOrder),Ve.assignTextureLOD(n,0)}return this._currentSprite.parent!==this.gameObject&&(this.drawMode===2&&this._currentSprite.scale.set(this.size.x,this.size.y,1),this.gameObject&&this.gameObject.add(this._currentSprite)),this._currentSprite&&this._currentSprite.layers.set(this.layer),this.sharedMaterial&&(this.sharedMaterial.alphaTest=this.cutoutThreshold,this.sharedMaterial.transparent=this.transparent),this._currentSprite.castShadow=this.castShadows,t?.update(this.sharedMaterial),!0}}wt([u()],_i.prototype,"drawMode",2),wt([u(uA)],_i.prototype,"size",2),wt([u(se)],_i.prototype,"color",2),wt([u(we)],_i.prototype,"sharedMaterial",2),wt([u()],_i.prototype,"transparent",2),wt([u()],_i.prototype,"cutoutThreshold",2),wt([u()],_i.prototype,"castShadows",2),wt([u()],_i.prototype,"renderOrder",2),wt([u()],_i.prototype,"toneMapped",2),wt([u(El)],_i.prototype,"sprite",1);const _1=w("debugwebxr"),pA=new J().makeRotationY(Math.PI);class yn extends E{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 J;_createdPlacementObject=null;_reparentedComponents=[];_placementScene=new Hi;_reticle=[];_hits=[];_placementStartTime=-1;_rigPlacementMatrix;_anchor=null;userInput;onEnable(){this.customReticle?.preload()}supportsXR(e){return e==="immersive-ar"}onEnterXR(e){_1&&console.log("ENTER WEBXR: SessionRoot start..."),this._anchor=null,yn._hasPlaced=!1,this.gameObject.updateMatrixWorld(),this._startOffset.copy(this.gameObject.matrixWorld);const t=new M;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=di(this._placementScene.children),n=i.getCenter(new b),s=i.getSize(new b),r=new J;r.makeTranslation(n.x,n.y-s.y*.5,n.z),this._startOffset.multiply(r)}this._reparentedComponents.length=0,this._reparentedComponents.push({comp:this,originalObject:this.gameObject}),S.addComponent(t,this);for(const i of this._reticle)Ii(i);this._reticle.length=0,this._isPlacing=!0,this.context.input.addEventListener("pointerup",this.onPlaceScene,{queue:pi.Early})}onLeaveXR(){this.context.input.removeEventListener("pointerup",this.onPlaceScene,{queue:pi.Early}),this.onRevertSceneChanges(),this._anchor=null,yn._hasPlaced=!1,this._rigPlacementMatrix=void 0}onUpdateXR(e){if(e.xr.isTrackingImages){for(const t of this._reticle)t.visible=!1;return}if(this._isPlacing){const t=e.xr.rig?.gameObject;t&&t.parent!==this.context.scene&&this.context.scene.add(t);let i=!1;if(e.xr.isPassThrough&&e.xr.controllers.length>0&&!this.autoPlace)for(const n of e.xr.controllers){const s=n.getHitTest();s&&(i=!0,this.updateReticleAndHits(e.xr,n.index,s,e.xr.rigScale))}if(!i){const n=e.xr.getHitTest();n&&this.updateReticleAndHits(e.xr,0,n,e.xr.rigScale)}}else{if(this._anchor&&e.xr.referenceSpace){const t=e.xr.frame.getPose(this._anchor.anchorSpace,e.xr.referenceSpace);if(t&&this.context.time.frame%20===0){const i=e.xr.convertSpace(t.transform),n=this._reticle[0];n&&(n.position.copy(i.position),n.quaternion.copy(i.quaternion),this.onApplyPose(n))}}if(this.arTouchTransform?(this.userInput||(this.userInput=new Pm(this.context)),this.userInput?.enable()):this.userInput?.disable(),this.arTouchTransform&&this.userInput?.hasChanged){if(e.xr.rig){const t=e.xr.rig.gameObject;this.userInput.applyMatrixTo(t.matrix,!0),t.matrix.decompose(t.position,t.quaternion,t.scale),this.userInput.factor=t.scale.x}this.userInput.reset()}}}updateReticleAndHits(e,t,i,n){this._hits[t]=i.hit;let s=this._reticle[t];if(!s){if(this.customReticle)if(this.customReticle.asset)s=Ur(this.customReticle.asset);else{this.customReticle.loadAssetAsync();return}else s=new H(new WC(.07,.09,32).rotateX(-Math.PI/2),new Ce({side:Oi,depthTest:!1,depthWrite:!1,transparent:!0,opacity:1,color:15658734})),s.name="AR Placement Reticle";if(_1){const r=new Pi(1);r.position.y+=.01,s.add(r)}this._reticle[t]=s,s.matrixAutoUpdate=!1,s.visible=!1}if(s.lastPos=s.lastPos||i.position.clone(),s.lastQuat=s.lastQuat||i.quaternion.clone(),s.position.copy(s.lastPos.lerp(i.position,this.context.time.deltaTime/.1)),s.lastPos.copy(s.position),s.quaternion.copy(s.lastQuat.slerp(i.quaternion,this.context.time.deltaTime/.05)),s.lastQuat.copy(s.quaternion),s.scale.set(n,n,n),this.customReticle&&this.applyViewBasedTransform(s),s.updateMatrix(),s.visible=!0,s.parent!==this.context.scene&&this.context.scene.add(s),this._placementStartTime<0&&(this._placementStartTime=this.context.time.realtimeSinceStartup),this.autoPlace)if(this.upVec.set(0,1,0).applyQuaternion(s.quaternion),this.upVec.dot(F(0,1,0))>.9){let r=s["autoplace:timer"]||0;r>=1?(s.visible=!1,this.onPlaceScene(null)):(r+=this.context.time.deltaTime,s["autoplace:timer"]=r)}else s["autoplace:timer"]=0}onPlaceScene=e=>{if(this._isPlacing==!1||e?.used)return;let t=this._reticle[0];if(!t){console.warn("No reticle to place...");return}if(!t.visible&&!this.autoPlace){console.warn("Reticle is not visible (can not place)");return}if(Z.active?.isTrackingImages){console.warn("Scene Placement is disabled while images are being tracked");return}let i=this._hits[0];if(e&&e.origin instanceof Pg){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),yn._hasPlaced=!0,this.useXRAnchor&&this.onCreateAnchor(Z.active,i),this.context.xr)for(const n of this.context.xr.controllers)n.cancelHitTestSource()};onSetScale(){if(!yn._hasPlaced)return;const e=Z.active?.rig?.gameObject;if(e){const t=Z.active?.rigScale||1,i=1/this._arScale*t,n=new J().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()&&be("Hit does not support creating an anchor");return}else{const i=await t.createAnchor(e.viewerPose.transform);e.running&&i&&(this._anchor=i)}}upVec=new b(0,1,0);lookPoint=new b;worldUpVec=new b(0,1,0);applyViewBasedTransform(e){const t=this.context.mainCamera,i=e,n=t.worldPosition,s=i.worldPosition;this.upVec.set(0,1,0).applyQuaternion(e.quaternion);const r=t.worldPosition;r&&e.position.clone().sub(r).angleTo(this.upVec)<Math.PI/2&&this.upVec.negate();const a=this.upVec.angleTo(this.worldUpVec)*180/Math.PI,l=30;a>l&&a<180-l||a<-l&&a>-180+l?(this.lookPoint.copy(e.position).add(this.upVec),this.lookPoint.y=e.position.y,e.lookAt(this.lookPoint)):(n.y=s.y,e.lookAt(n))}onApplyPose(e){const t=Z.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(pA),t.matrix.premultiply(this._startOffset),t.matrix.decompose(t.position,t.quaternion,t.scale),i.add(t)}}class Pm{static up=new b(0,1,0);static zero=new b(0,0,0);static one=new b(1,1,1);oneFingerDrag=!0;twoFingerRotate=!0;twoFingerScale=!0;factor=1;context;offset;plane;_scale=1;_hasChanged=!1;get scale(){return this._scale}constructor(e){this.context=e,this.offset=new J,this.plane=new _r,this.plane.setFromNormalAndCoplanarPoint(Pm.up,Pm.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:pi.Early}),this.context.input.addEventListener("pointerdown",this.onPointerDownLate,{queue:pi.Late}),this.context.input.addEventListener("pointerup",this.onPointerUpEarly,{queue:pi.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:pi.Early}),this.context.input.removeEventListener("pointerdown",this.onPointerDownLate,{queue:pi.Late}),this.context.input.removeEventListener("pointerup",this.onPointerUpEarly,{queue:pi.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=I.isAndroidDevice()&&i.clientY<window.innerHeight*.1;this.prev.has(i.identifier)||this.prev.set(i.identifier,{ignore:n,x:0,z:0,screenx:0,screeny:0});const s=this.prev.get(i.identifier);if(s){const r=this.getPositionOnPlane(i.clientX,i.clientY);s.x=r.x,s.z=r.z,s.screenx=i.clientX,s.screeny=i.clientY}}};touchEnd=e=>{e.touches.length<=0&&(this._didMultitouch=!1);for(let t=0;t<e.changedTouches.length;t++){const i=e.changedTouches[t];this.prev.delete(i.identifier)}};touchMove=e=>{if(!e.defaultPrevented&&this.isActive){if(e.touches.length===1){if(this._didMultitouch)return;const t=e.touches[0],i=this.prev.get(t.identifier);if(!i||i.ignore)return;const n=this.getPositionOnPlane(t.clientX,t.clientY),s=n.x-i.x,r=n.z-i.z;if(s===0&&r===0)return;this.oneFingerDrag&&this.addMovement(s,r),i.x=n.x,i.z=n.z,i.screenx=t.clientX,i.screeny=t.clientY;return}else if(e.touches.length===2){this._didMultitouch=!0;const t=e.touches[0],i=e.touches[1],n=this.prev.get(t.identifier),s=this.prev.get(i.identifier);if(!n||!s)return;if(this.twoFingerRotate){const r=Math.atan2(t.clientY-i.clientY,t.clientX-i.clientX),a=Math.atan2(n.screeny-s.screeny,n.screenx-s.screenx),l=r-a;Math.abs(l)>.001&&this.addRotation(l)}if(this.twoFingerScale){const r=t.clientX-i.clientX,a=t.clientY-i.clientY,l=Math.sqrt(r*r+a*a),c=n.screenx-s.screenx,h=n.screeny-s.screeny,d=Math.sqrt(c*c+h*h),p=l-d;Math.abs(p)>2&&this.addScale(p)}n.screenx=t.clientX,n.screeny=t.clientY,s.screenx=i.clientX,s.screeny=i.clientY}}};_raycaster=new Od;_intersection=new b;_screenPos=new b;getPositionOnPlane(e,t){const i=this.context.mainCamera;return this._screenPos.x=e/window.innerWidth*2-1,this._screenPos.y=-(t/window.innerHeight)*2+1,this._screenPos.z=1,this._screenPos.unproject(i),this._raycaster.set(i.position,this._screenPos.sub(i.position)),this._raycaster.ray.intersectPlane(this.plane,this._intersection),this._intersection}addMovement(e,t){e/=this._scale,t/=this._scale,e*=this.factor,t*=this.factor,this.offset.elements[12]+=e,this.offset.elements[14]+=t,(e!==0||t!==0)&&(this._hasChanged=!0)}_tempMatrix=new J;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 Ws=w("debugautosync"),Fy=Symbol("syncerId");class mA{_syncers={};getOrCreateSyncer(e){if(!e.guid)return null;if(this._syncers[e.guid])return this._syncers[e.guid];const t=new gA(e);return t[Fy]=e.guid,this._syncers[t[Fy]]=t,t}removeSyncer(e){delete this._syncers[e[Fy]]}}const Uy=new mA;class gA{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||(Ws&&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];Ws&&console.log("SEND",this.comp.guid,this.networkingKey),e.send(this.networkingKey,{guid:this.comp.guid,property:t,data:i},Pn.Queued),delete this.changedProperties[t]}};onHandleReceiving=e=>{if(Ws&&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 fA(o,e){let t=e!==o;return!t&&o&&e&&(Array.isArray(o)&&Array.isArray(e)||typeof o=="object"&&typeof e=="object")&&(t=!0),t}const mh=Symbol("AutoSyncHandler");function yA(o){if(o[mh])return o[mh];const e=Uy.getOrCreateSyncer(o);return e?.init(o),o[mh]=e,e}function bA(o){const e=o[mh];e&&(Uy.removeSyncer(e),e.destroy(),delete o[mh])}const zy=function(o=null){return function(e,t){let i="";typeof t=="string"?i=t:i=t.name;let n=null,s;typeof o=="string"?s=e[o]:typeof o=="function"&&(s=o),s==null&&(A()||Ws)&&o!=null&&console.warn('syncField: no callback function found for property "'+i+'"','"'+o+'"');const r=e,a=r.__internalAwake;if(typeof a!="function"){(Ws||A())&&console.error('@syncField can currently only used on Needle Engine Components, custom object of type "'+e?.constructor?.name+'" is not supported',e);return}Ws&&console.log(i);const l=Symbol(i);r.__internalAwake=function(){if(this[l]===void 0){if(this[l]=this[i],n=Uy.getOrCreateSyncer(this),Object.getOwnPropertyDescriptor(this,i)?.set===void 0){let h=!1;Object.defineProperty(this,i,{set:function(d){const p=this[l];if(this[l]=d,h){(A()||Ws)&&console.warn("Recursive call detected",i);return}h=!0;try{const m=fA(d,p);Ws&&console.log("SyncField assignment",i,"changed?",m,d,s),m&&s?.call(this,d,p)!==!1&&yA(this)?.notifyChanged(i,d)}finally{h=!1}},get:function(){return this[l]},configurable:!0,enumerable:!0})}n?.init(this),a.call(this)}};const c=r.__internalDestroy;r.__internalDestroy=function(){bA(this),c.call(this)}}};var _A=Object.defineProperty,wp=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&_A(e,t,n),n};const oi=w("debugplayersync"),xp=class US extends E{static async setupFrom(e,t){const i=ne.getOrCreateFromUrl(e);if(!i.asset){const r=await i.loadAssetAsync();r&&S.getOrAddComponent(r,sn)}const n=new US;n._internalInit(t),n.asset=i;const s=new M;return s.guid=e,S.addComponent(s,n),n}autoSync=!0;asset;onPlayerSpawned;_localInstance;awake(){this.watchTabVisible(),this.onPlayerSpawned||(this.onPlayerSpawned=new ae)}onEnable(){this.context.connection.beginListen(ie.RoomStateSent,this.onJoinedRoom),this.context.connection.beginListen(ie.JoinedRoom,this.onJoinedRoom),this.context.connection.beginListen(ie.LeftRoom,this.destroyInstance),this.context.connection.isInRoom&&this.onJoinedRoom()}onDisable(){this.context.connection.stopListen(ie.RoomStateSent,this.onJoinedRoom),this.context.connection.stopListen(ie.JoinedRoom,this.onJoinedRoom),this.context.connection.stopListen(ie.LeftRoom,this.destroyInstance)}onJoinedRoom=()=>{oi&&console.log("PlayerSync.joinedRoom. autoSync is set to "+this.autoSync),this.autoSync&&this.getInstance()};async getInstance(){if(this._localInstance)return this._localInstance;if(oi&&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,sn);if(oi&&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=>{oi&&console.log("PlayerSync.destroyInstance",e),Lc(e,this.context.connection,!0,{saveInRoom:!1})}),this._localInstance=void 0};watchTabVisible(){window.addEventListener("visibilitychange",e=>{if(document.visibilityState==="visible")for(let t=sn.all.length-1;t>=0;t--){const i=sn.all[t];(!i.owner||!this.context.connection.userIsInRoom(i.owner))&&i.doDestroy()}})}};wp([u()],xp.prototype,"autoSync"),wp([u(ne)],xp.prototype,"asset"),wp([u(ae)],xp.prototype,"onPlayerSpawned");let Ny=xp;var v1=(o=>(o.OwnerChanged="ownerChanged",o))(v1||{});const Wy=class It extends E{static _all=[];static get all(){return It._all}static _local=[];static get local(){return It._local}static getFor(e){if(e instanceof M)return S.getComponentInParent(e,It);if(e instanceof E)return S.getComponentInParent(e.gameObject,It)}static isLocalPlayer(e){return It.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 ae;onFirstOwnerChangeEvent=new ae;hasOwner=!1;owner;dontDestroy=!1;get isLocalPlayer(){return this.owner===this.context.connection.connectionId}onOwnerChange(e,t){oi&&console.log(`PlayerSync.onOwnerChange: ${t} \u2192 ${e} (me: ${this.context.connection.connectionId})`);const i=It._local.indexOf(this);i>=0&&It._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){It._local.push(this);const r=new CustomEvent("local-owner-changed",{detail:n});this.dispatchEvent(r)}const s=new CustomEvent("owner-changed",{detail:n});this.dispatchEvent(s),It.dispatchEvent("ownerChanged",s)}awake(){It.all.push(this),oi&&console.log("Registered new PlayerState",this.guid,It.all.length-1,It.all),this.context.connection.beginListen(ie.UserLeftRoom,this.onUserLeftRoom)}async start(){oi&&console.log("PLAYERSTATE.START, owner: "+this.owner,this.context.connection.usersInRoom([])),this.owner?(this.context.connection.isInRoom||await To(300),this.context.connection.userIsInRoom(this.owner)==!1&&(oi&&console.log(`PlayerSync.start \u2192 doDestroy "${this.name}" because user "${this.owner}" is not in room anymore...`,"Currently in room:",...this.context.connection.usersInRoom()),this.doDestroy())):this.owner||(oi&&console.warn("PlayerState.start \u2192 owner is undefined!",this.name),setTimeout(()=>{!this.destroyed&&!this.owner?this.dontDestroy?oi&&console.warn("PlayerState.start \u2192 owner is still undefined but dontDestroy is set to true",this.name):(oi&&console.warn(`PlayerState.start \u2192 owner is still undefined: destroying "${this.name}" instance now`),this.doDestroy()):oi&&console.log("PlayerState.start \u2192 owner is assigned",this.owner)},2e3))}doDestroy(){oi&&console.log("PlayerSync.doDestroy \u2192 syncDestroy",this.name),Lc(this.gameObject,this.context.connection,!0,{saveInRoom:!1})}onDestroy(){if(oi&&console.warn("PlayerState.onDestroy",this.owner),this.context.connection.stopListen(ie.UserLeftRoom,this.onUserLeftRoom),It.all.splice(It.all.indexOf(this),1),this.isLocalPlayer){const e=It._local.indexOf(this);e>=0&&It._local.splice(e,1)}}onUserLeftRoom=e=>{if(e.userId===this.owner){oi&&console.log("PLAYERSYNC LEFT",this.owner),this.doDestroy();return}}};wp([zy(Wy.prototype.onOwnerChange)],Wy.prototype,"owner");let sn=Wy;var vA=Object.defineProperty,Rl=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&vA(e,t,n),n};class co extends E{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&&(I.isMobileDevice()||this.context.menu.showQRCodeButton(!0))}}Rl([u()],co.prototype,"position"),Rl([u()],co.prototype,"showNeedleLogo"),Rl([u()],co.prototype,"showSpatialMenu"),Rl([u()],co.prototype,"createFullscreenButton"),Rl([u()],co.prototype,"createMuteButton"),Rl([u()],co.prototype,"createQRCodeButton");var wA=Object.defineProperty,Vy=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&wA(e,t,n),n};const gh=w("debugwebxr"),w1=new N().setFromAxisAngle(new b(0,1,0),Math.PI);class Vs extends E{head;leftHand;rightHand;_leftHandMeshes;_rightHandMeshes;_syncTransforms;async onEnterXR(e){if(!this.activeAndEnabled)return;gh&&console.warn("AVATAR ENTER XR",this.guid,this.sourceId,this,this.activeAndEnabled),this._syncTransforms&&(this._syncTransforms.length=0),await this.prepareAvatar();const t=sn.getFor(this);if(t?.owner){const i=this.gameObject.addComponent(Le);i.avatar=this.gameObject,i.connectionId=t.owner,this.context.players.setPlayerView(t.owner,this.head?.asset,Uo.Headset)}else this.context.connection.isConnected?console.error("No player state found for avatar",this):t&&!this.context.connection.isConnected&&(t.dontDestroy=!0)}onLeaveXR(e){const t=this.gameObject.getComponent(Le);t&&t.destroy()}onUpdateXR(e){if(!this.activeAndEnabled)return;const t=sn.isLocalPlayer(this);if(!t)return;const i=e.xr;if(i.rig&&i.rig.gameObject!==this.gameObject.parent&&(this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),this.gameObject.scale.set(1,1,1),i.rig.gameObject.add(this.gameObject)),this._syncTransforms&&t)for(const l of this._syncTransforms)l.fastMode=!0,l.isOwned()||l.requestOwnership();if(this.head&&this.context.mainCamera){const l=this.head.asset;if(l.position.copy(this.context.mainCamera.position),l.position.x*=-1,l.position.z*=-1,l.quaternion.copy(this.context.mainCamera.quaternion),l.quaternion.x*=-1,this.context.time.frameCount%10===0&&this.head.asset){const c=S.getComponentsInChildren(this.head.asset,tn);for(const h of c)h.enabled=!1,h.gameObject.visible=!1}}const n=e.xr.leftController,s=this.leftHand?.asset;n&&s?(s.position.copy(n.gripPosition),s.quaternion.copy(n.gripQuaternion),s.quaternion.multiply(w1),s.visible=n.isTracking,this.updateHandVisibility(n,s,this._leftHandMeshes)):s&&s.visible&&(s.visible=!1);const r=e.xr.rightController,a=this.rightHand?.asset;r&&a?(a.position.copy(r.gripPosition),a.quaternion.copy(r.gripQuaternion),a.quaternion.multiply(w1),a.visible=r.isTracking,this.updateHandVisibility(r,a,this._rightHandMeshes)):a&&a.visible&&(a.visible=!1)}onBeforeRender(){this.context.xr&&this.context.time.frame%10===0&&this.updateRemoteAvatarVisibility()}updateHandVisibility(e,t,i){if(i){const n=e.model&&e.model.visible&&e.model!==t;i.forEach(s=>{Fo(s,!n)})}}updateRemoteAvatarVisibility(){if(this.context.connection.isConnected){const e=sn.getFor(this);if(e&&e.isLocalPlayer==!1){const t=Z.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,tn);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};xv.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 M&&(this.head=new ne("",this.sourceId,this.head));else{const e=new M;e.name="Head";const t=Os.createPrimitive(Qa.Cube);e.add(t),this.gameObject.add(e),this.head=new ne("",this.sourceId,e),gh&&console.log("Create head",e)}if(this.rightHand)this.rightHand instanceof M&&(this.rightHand=new ne("",this.sourceId,this.rightHand));else{const e=new M;e.name="Right Hand",this.gameObject.add(e),this.rightHand=new ne("",this.sourceId,e),gh&&console.log("Create right hand",e)}if(this.leftHand)this.leftHand instanceof M&&(this.leftHand=new ne("",this.sourceId,this.leftHand));else{const e=new M;e.name="Left Hand",this.gameObject.add(e),this.leftHand=new ne("",this.sourceId,e),gh&&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)}),sn.isLocalPlayer(this.gameObject)&&(this._syncTransforms=S.getComponentsInChildren(this.gameObject,Tn))}async loadAvatarObjects(e,t,i){const n=e.loadAssetAsync(),s=t.loadAssetAsync(),r=i.loadAssetAsync(),a=new Array;n&&a.push(n),s&&a.push(s),r&&a.push(r);const l=await Jm(a);gh&&console.log("Avatar loaded results:",l)}}Vy([u(ne)],Vs.prototype,"head"),Vy([u(ne)],Vs.prototype,"leftHand"),Vy([u(ne)],Vs.prototype,"rightHand");var xA=Object.defineProperty,Sp=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&xA(e,t,n),n};const $s=w("debugwebxr"),Hs=new Array;class Ko extends E{createControllerModel=!0;createHandModel=!0;customLeftHand;customRightHand;static factory=new vP;supportsXR(e){return e==="immersive-vr"||e==="immersive-ar"}_models=new Array;async onXRControllerAdded(e){if(!(e.xr.isVR||e.xr.isPassThrough))return;console.debug("XR Controller Added",e.controller.side,e.controller.index);const{controller:t}=e;if(this.createControllerModel||this.createHandModel){if(t.hand){if(this.createHandModel){const i=await this.loadHandModel(this,t);if(!i||!t.connected||!t.isHand){i?.handObject&&nl(i.handObject,!1),i?.handObject?.destroy();return}this._models.push({controller:t,model:i.handObject,handmesh:i.handmesh}),this._models.sort((n,s)=>n.controller.index-s.controller.index),this.scene.add(i.handObject),t.model=i.handObject}}else if(this.createControllerModel){const i=await t.getModelUrl();if(i){const n=await this.loadModel(t,i);if(!n||!t.connected||t.isHand)return;this._models.push({controller:t,model:n}),this._models.sort((s,r)=>s.controller.index-r.controller.index),this.scene.add(n),n.traverse(s=>{s.layers.set(2),s.matrixAutoUpdate=!1,s.updateMatrix()}),t.model=n}else t.targetRayMode!=="transient-pointer"&&console.warn("XRControllerModel: no model found for "+t.side)}}}onXRControllerRemoved(e){console.debug("XR Controller Removed",e.controller.side,e.controller.index);const t=this._models.findIndex(n=>n.controller===e.controller),i=this._models[t];i&&(this._models.splice(t,1),i.model&&(nl(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&&(nl(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(Z.active&&($s&&(Hs[0]=Date.now()),this.updateRendering(Z.active),$s)){const e=Date.now()-Hs[0];Hs.push(e),Hs.length>=30&&(Hs[0]=0,Hs.reduce((t,i)=>t+i,0)/Hs.length,Hs.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){$s&&console.warn("XRControllerModel.onUpdateXR: controller is not connected anymore",n.side,n.hand);continue}if(i.model&&!i.handmesh)i.model.matrixAutoUpdate=!1,i.model.matrix.copy(n.gripMatrix),i.model.visible=n.isTracking,e.rig?.gameObject.add(i.model);else if(n.inputSource.hand&&i.handmesh){const s=e.referenceSpace,r=this.context.renderer.xr.getHand(n.index);if(s&&e.frame.getJointPose){for(const a of n.inputSource.hand.values()){const l=r.joints[a.jointName];if(l){const c=n.getHandJointPose(a);if(c){const h=c.transform.position,d=c.transform.orientation;l.position.copy(h),l.quaternion.copy(d),l.matrixAutoUpdate=!1}l.visible=c!=null}}i.model&&(i.model.visible=n.isTracking,i.model.visible&&i.model.parent!==e.rig?.gameObject&&e.rig?.gameObject.add(i.model)),i.model?.visible&&(i.handmesh?.updateMesh(),i.model.matrixAutoUpdate=!1,i.model.matrix.identity(),i.model.applyMatrix4(Ha))}}}}async loadModel(e,t){if(!e.connected)return console.warn("XRControllerModel.onXRControllerAdded: controller is not connected anymore",e.side),null;const i=await ne.getOrCreate("",t).instantiate();return nl(i),Z.active?.isPassThrough&&i.traverseVisible(n=>{this.makeOccluder(n)}),i}async loadHandModel(e,t){const i=this.context,n=i.renderer.xr.getHand(t.index);n||($s?B.DrawLabel(t.rayWorldPosition,"No hand found for index "+t.index,.05,5):console.warn("No hand found for index "+t.index));const s=new Eo;Af(s,i),await sp(s,i,this.sourceId??"",this.sourceId??"");const r=hy(s);let a="";const l=t.side==="left"?this.customLeftHand:this.customRightHand;l?(a=l.url.split(".").slice(0,-1).join("."),s.setPath("")):(a=t.inputSource.handedness==="left"?"left":"right",s.setPath("https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/"));const c=new M;nl(c);const h=new wP(c,n,s.path,a,s,d=>{const p=r?.gltf;p?.scene.children?.length===0&&(p.scene.children[0]=d),r?.gltf&&Cn().createBuiltinComponents(e.context,e.sourceId||a,r.gltf,null,r),d.traverse(m=>{m.layers.set(2),Z.active?.isPassThrough&&!l&&this.makeOccluder(m),m instanceof H&&Ve.assignMeshLOD(m,0)}),t.connected||($s&&B.DrawLabel(t.rayWorldPosition,"Hand is loaded but not connected anymore",.05,5),d.removeFromParent())});if($s&&c.add(new Pi(.5)),t.inputSource.hand){$s&&console.log(t.inputSource.hand);for(const d of t.inputSource.hand.values())if(n.joints[d.jointName]===void 0){const p=new Po;p.matrixAutoUpdate=!1,p.visible=!0,n.joints[d.jointName]=p,n.add(p)}}else $s&&B.DrawLabel(t.rayWorldPosition,"No inputSource.hand found for index "+t.index,.05,5);return{handObject:c,handmesh:h}}makeOccluder(e){if(e instanceof H){let t=e.material;t instanceof we&&(t=e.material=t.clone(),t.depthWrite=!0,t.depthTest=!0,t.colorWrite=!1,e.receiveShadow=!1,e.renderOrder=-100)}}}Sp([u()],Ko.prototype,"createControllerModel"),Sp([u()],Ko.prototype,"createHandModel"),Sp([u(ne)],Ko.prototype,"customLeftHand"),Sp([u(ne)],Ko.prototype,"customRightHand");class Cp extends E{}var SA=Object.defineProperty,Gs=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&SA(e,t,n),n};const $y=w("debugwebxr");class Bi extends E{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=F(i.x,0,i.y);n.multiplyScalar(this.context.time.deltaTimeUnscaled*this.movementSpeed);const s=$e(t);n.multiplyScalar(s.x),n.applyQuaternion(e.xr.poseOrientation),n.y=0,n.applyQuaternion(t.worldQuaternion),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 i=e.getStick("xr-standard-thumbstick").x;if(this._didApplyRotation)Math.abs(i)<.3&&(this._didApplyRotation=!1);else if(Math.abs(i)>.5){this._didApplyRotation=!0;const n=i>0?1:-1,s=ee(this.context.mainCamera).clone();t.rotateY(n*j.toRadians(this.rotationStep));const r=ee(this.context.mainCamera).clone().sub(s);r.y=0,t.position.sub(r)}}_teleportBuffer=new Array;onHandleTeleport(e,t){let i=0;if(e.hand&&this.usePinchToTeleport&&e.isTeleportGesture){const n=e.getPointerId("primary");if(n!=null&&this.context.input.getIsPointerIdInUse(n))return;const s=e.getGesture("pinch");s&&(i=s.value)}else i=e.getStick("xr-standard-thumbstick")?.y;if(this._didTeleport)i>=0&&i<.4?this._didTeleport=!1:i<0&&i>-.4&&(this._didTeleport=!1);else if(i>.8){this._didTeleport=!0;const n=this.context.physics.raycastFromRay(e.ray)[0];if(n&&n.object instanceof Da){const r=n.normal?.dot(F(0,1,0));if(r!==void 0&&r<.4)return}let s=n?.point;if(!s&&!this.useTeleportTarget){this._plane||(this._plane=new _r(new b(0,1,0),0));const r=t.worldPosition;this._plane.setFromNormalAndCoplanarPoint(new b(0,1,0),r);const a=e.ray;s=r.clone(),this._plane.intersectLine(new VC(a.origin,F(a.direction).multiplyScalar(1e4).add(a.origin)),s),s.distanceTo(r)>t.scale.x*10&&(s=null)}if(s){if(this.useTeleportTarget&&!S.getComponentInParent(n.object,Cp))return;const r=s.clone();if($y&&B.DrawSphere(s,.025,16711680,5),this.context.mainCamera?.position){const a=this.context.xr?.getUserOffsetInRig();a&&(a.y=0,r.sub(a),$y&&B.DrawWireSphere(a.add(r),.025,65280,5))}this._teleportBuffer.push(t.matrix.clone()),this._teleportBuffer.length>10&&this._teleportBuffer.shift(),this.useTeleportFade?e.xr.fadeTransition()?.then(()=>{t.worldPosition=r}):t.worldPosition=r}}else if(i<-.8&&(this._didTeleport=!0,this._teleportBuffer.length>0)){const n=this._teleportBuffer.pop();n&&n.decompose(t.position,t.quaternion,t.scale)}}_plane=null;_lines=[];_hitDiscs=[];_hitDistances=[];_lastHitDistances=[];renderRays(e){for(let t=0;t<this._lines.length;t++){const i=this._lines[t];i&&(i.visible=!1)}for(let t=0;t<e.controllers.length;t++){const i=e.controllers[t];let n=this._lines[t];if(!i.connected||!i.isTracking||!i.ray||i.targetRayMode==="transient-pointer"||!i.hasSelectEvent){n&&(n.visible=!1);continue}n||(n=this.createRayLineObject(),n.scale.z=.5,this._lines[t]=n),i.updateRayWorldPosition(),i.updateRayWorldQuaternion();const s=i.rayWorldPosition,r=i.rayWorldQuaternion;n.position.copy(s),n.quaternion.copy(r);const a=e.rigScale,l=this.usePinchToTeleport&&i.isTeleportGesture,c=this._lastHitDistances[t],h=this._hitDistances[t]!=null,d=c??a;n.scale.set(a,a,d),n.visible=!0,n.layers.disableAll(),n.layers.enable(2);let p=n.material.opacity;l?p=1:this.showHits&&d<e.rigScale*.5?p=0:i.getButton("primary")?.pressed?p=.5:p=h?.2:.1,n.material.opacity=j.lerp(n.material.opacity,p,this.context.time.deltaTimeUnscaled/.1),n.parent!==this.context.scene&&this.context.scene.add(n)}}renderHits(e){for(const t of this._hitDiscs){if(!t)continue;const i=t.controller;if(!i||!i.connected||!i.isTracking){t.visible=!1;continue}}for(let t=0;t<e.controllers.length;t++){const i=e.controllers[t];if(!i.connected||!i.isTracking||!i.ray||!i.hasSelectEvent)continue;let n=this._hitDiscs[t],s=!0;const r=i.getPointerId("primary");r!=null&&this.context.input.getIsPointerIdInUse(r)&&(n&&(n.visible=!1),this._hitDistances[t]=null,this._lastHitDistances[t]=0,s=!1);const a=this.context.time.smoothedFps>=59?1:10;if((this.context.time.frame+i.index)%a!==0&&(s=!1),!s){const h=this._hitDiscs[t];h&&h.visible&&h.hit&&this.updateHitPointerPosition(i,h,h.hit.distance);continue}const l=this.context.physics.raycastFromRay(i.ray,{testObject:this.hitPointRaycastFilter,precise:!1});let c=l.find(h=>this.usePinchToTeleport&&i.isTeleportGesture?!0:this.isObjectWithInteractiveComponent(h.object));if(c||(c=l[0]),n&&(n.controller=i,n.hit=c),this._hitDistances[t]=c?.distance||null,c){this._lastHitDistances[t]=c.distance;const h=e.rigScale??1;$y&&(B.DrawWireSphere(c.point,.025*h,16711680),B.DrawLabel(F(0,.2,0).add(c.point),c.object.name,.02,0)),n||(n=this.createHitPointObject(),this._hitDiscs[t]=n),n.hit=c,n.visible=c.distance>h*.05;let d=.01*(h+c.distance);const p=i.getButton("primary")?.pressed;p&&(d*=1.1),n.scale.set(d,d,d),n.layers.set(2);let m=n.material.opacity;if(p?m=1:m=c.distance<.15*h?.2:.6,n.material.opacity=j.lerp(n.material.opacity,m,this.context.time.deltaTimeUnscaled/.1),n.visible){if(c.normal){this.updateHitPointerPosition(i,n,c.distance);const g=c.normal.applyQuaternion(_e(c.object));n.quaternion.setFromUnitVectors(CA,g)}else this.updateHitPointerPosition(i,n,c.distance);n.parent!==this.context.scene&&this.context.scene.add(n)}}else this._hitDiscs[t]&&(this._hitDiscs[t].visible=!1)}}isObjectWithInteractiveComponent(e,t=0){return Fu(e)||e.isUI===!0?!0:e.isScene?!1:e.parent?this.isObjectWithInteractiveComponent(e.parent,t+1):!1}updateHitPointerPosition(e,t,i){const n=F(e.rayWorldPosition);n.add(F(0,0,i-.01).applyQuaternion(e.rayWorldQuaternion)),t.position.lerp(n,this.context.time.deltaTimeUnscaled/.05)}hitPointRaycastFilter=e=>e.type==="SkinnedMesh"?"continue in children":!0;createHitPointObject(){const e=new H(new Pd(.3,6,6),new Ce({color:15658734,opacity:.7,transparent:!0,depthTest:!1,depthWrite:!1,side:Oi}));return e.layers.disableAll(),e.layers.enable(2),e}createRayLineObject(){const e=new xP;e.layers.disableAll(),e.layers.enable(2);const t=new SP;e.geometry=t;const i=new Float32Array(9);i.set([0,0,.02,0,0,.4,0,0,1]),t.setPositions(i);const n=new Float32Array(9);n.set([1,1,1,.1,.1,.1,0,0,0]),t.setColors(n);const s=new CP({color:16777215,vertexColors:!0,worldUnits:!0,linewidth:.004,transparent:!0,depthWrite:!1,blending:Rb,dashed:!1});return e.material=s,e}}Gs([u()],Bi.prototype,"movementSpeed"),Gs([u()],Bi.prototype,"rotationStep"),Gs([u()],Bi.prototype,"useTeleport"),Gs([u()],Bi.prototype,"usePinchToTeleport"),Gs([u()],Bi.prototype,"useTeleportTarget"),Gs([u()],Bi.prototype,"useTeleportFade"),Gs([u()],Bi.prototype,"showRays"),Gs([u()],Bi.prototype,"showHits");const CA=new b(0,1,0);var PA=Object.defineProperty,xt=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&PA(e,t,n),n};const fh=w("debugwebxr"),OA=w("debugusdz"),ct=class ic extends E{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(){Z.getXRSync(this.context)}onEnable(){window.location.protocol!=="https:"&&be('<a href="https://developer.mozilla.org/en-US/docs/Web/API/WebXR_Device_API" target="_blank">WebXR</a> only works on secure connections (https).'),navigator.xr?.isSessionSupported("immersive-ar").catch(()=>!1).then(e=>{const t=I.isVisionOS()&&!e;(this.useQuicklookExport||t)&&(S.findObjectOfType(uo)||(fh&&console.log("WebXR: Adding USDZExporter"),this._usdzExporter=S.addComponent(this.gameObject,uo),this._usdzExporter.objectToExport=this.context.scene,this._usdzExporter.autoExportAnimations=!0,this._usdzExporter.autoExportAudioSources=!0))}),this.handleCreatingHTML(),this.handleOfferSession(),this.defaultAvatar===!0&&(fh&&console.warn("WebXR: No default avatar set, using static default avatar"),this.defaultAvatar=new ne("https://cdn.needle.tools/static/avatars/DefaultAvatar.glb")),this.defaultAvatar&&(this._playerSync=this.gameObject.getOrAddComponent(Ny),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 Z.isVRSupported()&&this.createVRButton?Z.offerSession("immersive-vr","default",this.context):this.createARButton&&await Z.isARSupported()&&this.createARButton?Z.offerSession("immersive-ar","default",this.context):!1}get session(){return Z.active??null}get sessionMode(){return Z.activeMode??null}get arSessionRoot(){return this._activeWebARSessionRoot}async enterVR(e){return Z.start("immersive-vr",e,this.context)}async enterAR(e){return Z.start("immersive-ar",e,this.context)}exitXR(){Z.stop()}_exitXRMenuButton;_previousXRState=0;_spatialGrabRaycaster;_activeWebARSessionRoot=null;get isActiveWebXR(){return!ic.activeWebXRComponent||ic.activeWebXRComponent===this}onBeforeXR(e,t){if(!this.isActiveWebXR){console.warn(`WebXR: another WebXR component is already active (${ic.activeWebXRComponent?.name}). This is ignored: ${this.name}`);return}if(this.activeAndEnabled===!1||this.destroyed){console.debug("[WebXR] onBeforeXR called on disabled or destroyed component");return}ic.activeWebXRComponent=this,e=="immersive-ar"&&this.useDepthSensing&&(t.optionalFeatures=t.optionalFeatures||[],t.optionalFeatures.push("depth-sensing"))}async onEnterXR(e){if(!this.isActiveWebXR)return;fh&&console.log("WebXR onEnterXR"),this._previousXRState=ai.Global.Mask;const t=e.xr.isVR;if(ai.Global.Set(t?no.VR:no.AR),e.xr.isAR){let i=S.findObjectOfType(yn,this.context,!1);if(!i)if(this.usePlacementReticle){const n=new M;for(const s of this.context.scene.children)n.add(s);this.context.scene.add(n),i=S.addComponent(n,yn),this._createdComponentsInSession.push(i)}else(fh||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(Ca)??void 0,this._spatialGrabRaycaster||(this._spatialGrabRaycaster=this.gameObject.addComponent(Ca))),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){ai.Global.Set(this._previousXRState),this._playerSync?.destroyInstance();for(const t of this._createdComponentsInSession)t.destroy();this._createdComponentsInSession.length=0,this._activeWebARSessionRoot=null,this.handleOfferSession(),mc(1).then(()=>ic.activeWebXRComponent=null)}}setDefaultMovementEnabled(e){let t=this.gameObject.getComponent(Bi);return!t&&e&&(t=this.gameObject.addComponent(Bi),this._createdComponentsInSession.push(t)),t&&(t.enabled=e),t}setDefaultControllerRenderingEnabled(e){let t=this.gameObject.getComponent(Ko);return!t&&e&&(t=this.gameObject.addComponent(Ko),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=>{fh&&console.log("WebXR.onAvatarSpawned",e);let t=S.getComponentInChildren(e,Vs);t??=S.addComponent(e,Vs)};getButtonsContainer(){return this.getButtonsFactory()}getButtonsFactory(){return this._buttonFactory||(this._buttonFactory=ur.getOrCreate()),this._buttonFactory}_buttonFactory;handleCreatingHTML(){if(this.createARButton||this.createVRButton||this.useQuicklookExport){if((I.isiOS()&&I.isSafari()||OA)&&this.useQuicklookExport){const e=S.findObjectOfType(uo);if(!e||e&&e.allowCreateQuicklookButton){const t=this.getButtonsFactory().createQuicklookButton();this.addButton(t)}}if(this.createARButton){const e=this.getButtonsFactory().createARButton();this.addButton(e)}if(this.createVRButton){const e=this.getButtonsFactory().createVRButton();this.addButton(e)}}if(this.createSendToQuestButton&&!I.isQuest()&&Z.isVRSupported().then(e=>{if(!e){const t=this.getButtonsFactory().createSendToQuestButton();this.addButton(t)}}),this.createQRCode){const e=tl(co);if(e&&e.createQRCodeButton===!1)A()&&console.warn("WebXR: QRCode button is disabled in the Needle Menu component");else if(!I.isMobileDevice()){const t=mn.getOrCreate().createQRCode();this.addButton(t)}}}_buttons=[];addButton(e){this._buttons.push(e),this.context.menu.appendChild(e)}removeButtons(){for(const e of this._buttons)e.remove();this._buttons.length=0}};xt([u()],ct.prototype,"createVRButton"),xt([u()],ct.prototype,"createARButton"),xt([u()],ct.prototype,"createSendToQuestButton"),xt([u()],ct.prototype,"createQRCode"),xt([u()],ct.prototype,"useDefaultControls"),xt([u()],ct.prototype,"showControllerModels"),xt([u()],ct.prototype,"showHandModels"),xt([u()],ct.prototype,"usePlacementReticle"),xt([u(ne)],ct.prototype,"customARPlacementReticle"),xt([u()],ct.prototype,"usePlacementAdjustment"),xt([u()],ct.prototype,"arScale"),xt([u()],ct.prototype,"useXRAnchor"),xt([u()],ct.prototype,"autoPlace"),xt([u()],ct.prototype,"autoCenter"),xt([u()],ct.prototype,"useQuicklookExport"),xt([u()],ct.prototype,"useDepthSensing"),xt([u()],ct.prototype,"useSpatialGrab"),xt([u(ne)],ct.prototype,"defaultAvatar");let Pp=ct;const Op=w("debugusdzbehaviours");class Hy{get extensionName(){return"Behaviour"}behaviours=[];addBehavior(e){this.behaviours.push(e)}addAudioClip(e){if(!e||typeof e!="string")return"";const t="audio/"+Pa.getName(e);return this.audioClips.push({clipUrl:e,filesKey:t}),t}behaviourComponents=[];behaviourComponentsCopy=[];audioClips=[];audioClipsCopy=[];targetUuids=new Set;getAllTargetUuids(){return this.targetUuids}onBeforeBuildDocument(e){if(!e.root)return Promise.resolve();const t=[];return e.root.traverse(i=>{S.foreachComponent(i,n=>{const s=n;if(typeof s.createBehaviours=="function"||typeof s.beforeCreateDocument=="function"||typeof s.afterCreateDocument=="function"||typeof s.afterSerialize=="function"){this.behaviourComponents.push(s);const r=s.beforeCreateDocument?.call(s,this,e);r instanceof Promise&&t.push(r)}},!1)}),Op&&console.log("onBeforeBuildDocument: all components",this.behaviourComponents),Promise.all(t)}onExportObject(e,t,i){for(const n of this.behaviourComponents)n.createBehaviours?.call(n,this,t,i)}onAfterBuildDocument(e){for(const d of this.behaviourComponents)typeof d.afterCreateDocument=="function"&&d.afterCreateDocument(this,e);this.behaviourComponentsCopy=this.behaviourComponents.slice(),this.behaviourComponents.length=0,this.audioClipsCopy=this.audioClips.slice(),this.audioClips.length=0;const t=new Set,i=new Set,n=new Set,s=new Set,r=Op;let a=`graph LR
|
|
1290
1290
|
`,l="";function c(d){if(d instanceof Jr){r&&(a+=`subgraph Group_${d.id}
|
|
1291
1291
|
`);for(const p of d.actions)r&&(a+=`${d.id}[${d.id}] -- ${d.type},loops:${d.loops} --> ${p.id}[${p.id}]
|
|
1292
1292
|
`),c(p);r&&(a+=`end
|
|
@@ -1308,7 +1308,7 @@ dateFormat X
|
|
|
1308
1308
|
axisFormat %s
|
|
1309
1309
|
`;const p=Array.from(s),m=new Set;for(const _ of p)if(_.affectedObjects&&typeof _.affectedObjects!="string"){if(Array.isArray(_.affectedObjects))for(const v of _.affectedObjects)m.add(v);else m.add(_.affectedObjects);r&&(d+=`section ${_.animationName} (${_.id})
|
|
1310
1310
|
`,d+=`${_.id} : ${_.start}, ${_.duration}s
|
|
1311
|
-
`)}r&&s.size&&console.log(d);const g=new Set;for(const _ of m){_.getPath||console.error("USDZExporter: Animation target object has no getPath method. This is likely a bug",_);let v=_.getPath();v.startsWith("<")&&(v=v.substring(1)),v.endsWith(">")&&(v=v.substring(0,v.length-1)),g.add({path:v,obj:_})}const f=Array.from(g).sort((_,v)=>_.path.length-v.path.length),y=new Array;for(let _=0;_<f.length;_++)for(let v=_+1;v<f.length;v++)if(f[v].path.startsWith(f[_].path)){const P=f[v],k=f[_];y.push({child:P.obj.displayName+" ("+P.path+")",parent:k.obj.displayName+" ("+k.path+")"})}y.length&&console.warn("USDZExporter: There are overlapping PlayAnimation actions. This can lead to undefined runtime behaviour when playing multiple animations. Please restructure the hierarchy so that animations don't overlap.",{overlappingTargets:y,playAnimationActions:s})}for(const d of new Set([...t,...i]))if(Array.isArray(d))for(const p of d)n.add(p.uuid);else n.add(d.uuid);Op&&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){Op&&console.log("onAfterSerialize behaviours",this.behaviourComponentsCopy);for(const t of this.behaviourComponentsCopy)typeof t.afterSerialize=="function"&&(t.afterSerialize.constructor.name==="AsyncFunction"?await t.afterSerialize(this,e):t.afterSerialize(this,e));for(const{clipUrl:t,filesKey:i}of this.audioClipsCopy){if(e.files[i])return;const n=await(await(await fetch(t)).blob()).arrayBuffer(),s=new Uint8Array(n);e.files[i]=s}this.behaviourComponentsCopy.length=0,this.audioClipsCopy.length=0}}class Gy{get extensionName(){return"Physics"}onExportObject(e,t,i){const n=S.getComponents(e,Ke).filter(l=>l.enabled),s=S.getComponents(e,nn).filter(l=>l.enabled&&!l.isTrigger);let r=n.length>0?n[0]:null;const a=s.length>0?s[0]:null;a&&!r&&(r=new Ke,r.isKinematic=!0),r&&t.addEventListener("serialize",(l,c)=>{if(r){if(l.appendLine(),l.beginBlock('def RealityKitComponent "RigidBody"',"{",!0),r.useGravity||l.appendLine("bool gravityEnabled = 0"),l.appendLine('uniform token info:id = "RealityKit.RigidBody"'),r.isKinematic&&l.appendLine('token motionType = "Kinematic"'),l.beginBlock('def RealityKitStruct "massFrame"',"{",!0),l.appendLine(`float m_mass = ${r.mass}`),l.beginBlock('def RealityKitStruct "m_pose"',"{",!0),l.appendLine(`float3 position = (${r.centerOfMass.x}, ${r.centerOfMass.y}, ${r.centerOfMass.z})`),l.closeBlock("}"),l.closeBlock("}"),s.length>0){const h=s[0];l.beginBlock('def RealityKitStruct "material"',"{",!0);const d=h.sharedMaterial;d&&d.dynamicFriction!==void 0&&l.appendLine(`double dynamicFriction = ${h.sharedMaterial?.dynamicFriction}`),d&&d.bounciness!==void 0&&l.appendLine(`double restitution = ${h.sharedMaterial?.bounciness}`),d&&d.staticFriction!==void 0&&l.appendLine(`double staticFriction = ${h.sharedMaterial?.staticFriction}`),l.closeBlock("}")}l.closeBlock("}")}}),a&&(t.addEventListener("serialize",(l,c)=>{l.beginBlock('def RealityKitComponent "Collider"',"{",!0),l.appendLine("uint group = 1"),l.appendLine('uniform token info:id = "RealityKit.Collider"'),l.appendLine("uint mask = 4294967295");const h=a.isTrigger?"Trigger":"Default";if(l.appendLine(`token type = "${h}"`),l.beginBlock('def RealityKitStruct "Shape"',"{",!0),a instanceof pl){const d=a;l.appendLine('token shapeType = "Sphere"'),l.appendLine(`float radius = ${d.radius}`)}else if(a instanceof qu){const d=a;l.appendLine('token shapeType = "Box"'),l.appendLine(`float3 extent = (${d.size.x}, ${d.size.y}, ${d.size.z})`)}else if(a instanceof Vo){const d=a;l.appendLine('token shapeType = "Capsule"'),l.appendLine(`float radius = ${d.radius}`),l.appendLine(`float height = ${d.height}`)}else if(a instanceof Bs&&a.sharedMesh?.geometry){const d=a.sharedMesh.geometry;d.boundingBox||d.computeBoundingBox();const p=a.sharedMesh.geometry.boundingBox;p&&(l.appendLine('token shapeType = "Box"'),l.appendLine(`float3 extent = (${p.max.x-p.min.x}, ${p.max.y-p.min.y}, ${p.max.z-p.min.z})`),console.log("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. MeshCollider will be exported as Box",a))}else console.warn("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. Ignoring collider:",a);l.beginBlock('def RealityKitStruct "pose"',"{",!0),l.closeBlock("}"),l.closeBlock("}"),l.closeBlock("}")}),s.length>1&&console.log("WARNING: Multiple colliders detected. visionOS / iOS can only support objects with a single collider, only exporting the first collider: ",a))}}const kA=w("debugshadowcomponents");Gb.prototype.interactable={get(){return this.interactive},set(o){this.interactable=o}};class un extends E{isRoot(){return this.Root?.gameObject===this.gameObject}get canvas(){const e=this.Root;return e?.isCanvas?e:null}get Canvas(){return this.canvas}markDirty(){li.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,yh)),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,un),!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[Ai]=this,this.setShadowComponentOwner(e);let n=!1;if(this.Root?.gameObject===this.gameObject)this.gameObject.add(e);else{const s=this._parentComponent.shadowComponent;s&&(s?.add(e),n=!0)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),jc&&e.add(new Pi(.5)),this.onAfterAddedToScene(),n&&NP(),kA&&console.warn("Added shadow component",this.shadowComponent)}setShadowComponentOwner(e){if(e&&(e[Ai]===void 0||e[Ai]===this)&&(e[Ai]=this,e.children))for(const t of e.children)this.setShadowComponentOwner(t)}traverseOwnedShadowComponents(e,t,i){if(e&&e[Ai]===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 yh extends un{awake(){super.awake()}}var MA=Object.defineProperty,EA=Object.getOwnPropertyDescriptor,bh=(o,e,t,i)=>{for(var n=i>1?void 0:i?EA(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&MA(e,t,n),n};const qy=w("debugui"),Xy=w("debuguilayout");class x1{width;height}class S1{x;y;width;height}const In=new b,_h=new J,kp=new N,Tl=class zS extends un{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 K),this._anchoredPosition}set anchoredPosition(e){this._anchoredPosition=e}sizeDelta=new K(100,100);pivot=new K(.5,.5);anchorMin=new K(0,0);anchorMax=new K(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 M,this.rectBlock.name=this.name,this.lastMatrix=new J,this._lastAnchoring=null,this._initialPosition=this.gameObject.position.clone(),this._initialPosition.z=0,this._anchoredPosition||(this._anchoredPosition=new K),hl(this,"_anchoredPosition",()=>{this.markDirty()}),hl(this,"sizeDelta",()=>{this.markDirty()}),hl(this,"pivot",()=>{this.markDirty()}),hl(this,"anchorMin",()=>{this.markDirty()}),hl(this,"anchorMax",()=>{this.markDirty()})}onEnable(){super.onEnable(),this.rectBlock||(this.rectBlock=new M),this.lastMatrix||(this.lastMatrix=new J),this._lastAnchoring||(this._lastAnchoring=new K),this._initialPosition||(this._initialPosition=new b),this._anchoredPosition||(this._anchoredPosition=new K),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(Xy?`${e.name} changed`:void 0)}get isDirty(){return this._transformNeedsUpdate||(this._transformNeedsUpdate=!this.lastMatrix.equals(this.gameObject.matrix)),this._transformNeedsUpdate}markDirty(){this._transformNeedsUpdate||(Xy&&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,zS):this._parentRectTransform=void 0,this._transformNeedsUpdate=!1,Xy&&console.warn("RectTransform \u2192 ApplyTransform",this.name+" because "+e),this.isRoot()?this.Root.screenspace||(t.rotation.y=Math.PI):(t.matrix.identity(),t.matrixAutoUpdate=!1,In.set(0,0,0),this.applyPivot(In),t.matrix.setPosition(In.x,In.y,0),(this.gameObject.quaternion.x||this.gameObject.quaternion.y||this.gameObject.quaternion.z)&&(kp.copy(this.gameObject.quaternion),kp.x*=-1,kp.z*=-1,_h.makeRotationFromQuaternion(kp),t.matrix.premultiply(_h)),In.set(0,0,0),this.applyAnchoring(In),this.canvas?.screenspace?In.z+=.1:In.z+=.01,_h.identity(),_h.setPosition(In.x,In.y,In.z),t.matrix.premultiply(_h),t.matrix.scale(this.gameObject.scale)),this.lastMatrix.copy(this.gameObject.matrix);const i=!0;for(const n of wu(this.gameObject,un,i,1)){if(n===this||!n.activeAndEnabled)continue;const s=n;s.onParentRectTransformChanged&&s.onParentRectTransformChanged(this)}}_lastAnchoring;applyAnchoring(e){this._lastAnchoring||(this._lastAnchoring=new K);const t=this._lastAnchoring.sub(this._anchoredPosition);this.gameObject.position.x+=t.x,this.gameObject.position.y+=t.y,this._lastAnchoring.copy(this._anchoredPosition),e.x+=this._initialPosition.x-this.gameObject.position.x,e.y+=this._initialPosition.y-this.gameObject.position.y,e.z+=this._initialPosition.z-this.gameObject.position.z;const i=this._parentRectTransform;if(i){let n=0;const s=1-this.anchorMax.y-this.anchorMin.y;n-=i.height*.5*s,e.y+=n;let r=0;const a=1-this.anchorMax.x-this.anchorMin.x;r-=i.width*.5*a,e.x+=r}}applyPivot(e){if(this.pivot&&!this.isRoot()){const t=this.pivot.x-.5;e.x-=t*this.sizeDelta.x*this.gameObject.scale.x;const i=this.pivot.y-.5;e.y-=i*this.sizeDelta.y*this.gameObject.scale.y}}getBasicOptions(){const e={width:this.sizeDelta.x,height:this.sizeDelta.y,offset:0,backgroundOpacity:0,borderWidth:0,borderRadius:0,borderOpacity:0,letterSpacing:-.03};return this.ensureValidSize(e),e}ensureValidSize(e,t=1e-4){return e.width<=0&&(e.width=t),e.height<=0&&(e.height=1e-4),e}_createdBlocks=[];_createdTextBlocks=[];createNewBlock(e){e={...this.getBasicOptions(),...e},qy&&console.log(this.name,e);const t=new Gb(e);return this._createdBlocks.push(t),t}createNewText(e){qy&&console.log(e),e={...this.getBasicOptions(),...e},qy&&console.log(this.name,e);const t=new Hb(e);return this._createdTextBlocks.push(t),t}};bh([u(K)],Tl.prototype,"anchoredPosition",1),bh([u(K)],Tl.prototype,"sizeDelta",2),bh([u(K)],Tl.prototype,"pivot",2),bh([u(K)],Tl.prototype,"anchorMin",2),bh([u(K)],Tl.prototype,"anchorMax",2);let Ln=Tl;var RA=Object.defineProperty,C1=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&RA(e,t,n),n};class Al extends E{effectColor;effectDistance}C1([u(se)],Al.prototype,"effectColor"),C1([u(K)],Al.prototype,"effectDistance");var TA=Object.defineProperty,AA=Object.getOwnPropertyDescriptor,P1=(o,e,t,i)=>{for(var n=i>1?void 0:i?AA(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&TA(e,t,n),n};const ta={backgroundColor:new oe(1,1,1),backgroundOpacity:1,borderColor:new oe(1,1,1),borderOpacity:1},Qy=class fd extends un{get isGraphic(){return!0}get color(){return this._color||(this._color=new se(1,1,1,1)),this._color}set color(e){(!this._color||this._color.r!==e.r||this._color.g!==e.g||this._color.b!==e.b||this._color.alpha!==e.alpha)&&(this._color||(this._color=new se(1,1,1,1)),this._color.copy(e),this.onColorChanged())}_alphaFactor=1;setAlphaFactor(e){this._alphaFactor=e,this.onColorChanged()}get alphaFactor(){return this._alphaFactor}sRGBColor=new oe(1,0,1);onColorChanged(){if(this.uiObject){this.sRGBColor.copy(this._color),this.sRGBColor.convertLinearToSRGB(),ta.backgroundColor=this.sRGBColor,ta.backgroundOpacity=this._color.alpha;const e=this.uiObject._simpleState__activeStates?.[0];if(e){const t=this.uiObject._simpleState__states?.[e];t&&("backgroundColor"in t&&(ta.backgroundColor=t.backgroundColor),"backgroundOpacity"in t&&(ta.backgroundOpacity=t.backgroundOpacity))}ta.backgroundOpacity*=this._alphaFactor,this.applyEffects(ta,this._alphaFactor),this.uiObject.set(ta),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,Ln)),!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 WP(this.uiObject)),this.uiObject.setupState(e.state,e.attributes))}setOptions(e){this.makePanel(),this.uiObject&&this.uiObject.set(e)}awake(){super.awake(),this.makePanel(),hl(this,"_color",()=>pR(this,this.onColorChanged))}onEnable(){super.onEnable(),this.uiObject&&(this.rectTransform.shadowComponent?.add(this.uiObject),this.addShadowComponent(this.uiObject,this.rectTransform))}onDisable(){super.onDisable(),this.uiObject&&this.removeShadowComponent()}_currentlyCreatingPanel=!1;makePanel(){if(this.uiObject||this._currentlyCreatingPanel)return;this._currentlyCreatingPanel=!0;const e={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:.015};this.onBeforeCreate(e),this.applyEffects(e),this.onCreate(e),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated(),this.onColorChanged()}onBeforeCreate(e){}onCreate(e){this.uiObject=this.rectTransform.createNewBlock(e),this.uiObject.name=this.name}onAfterCreated(){}applyEffects(e,t=1){const i=this.gameObject?.getComponent(Al);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(fd.textureCache.has(e))e=fd.textureCache.get(e);else if(!e.isRenderTargetTexture){const t=e.clone();t.colorSpace=Oo,fd.textureCache.set(e,t),e=t}this.setOptions({backgroundImage:e,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"}),Ve.assignTextureLOD(e,0).then(t=>{t instanceof Se&&(e&&fd.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)}};P1([u(se)],Qy.prototype,"color",1),P1([u()],Qy.prototype,"raycastTarget",2);let vh=Qy;class wh extends vh{_flippedObject=!1;onAfterCreated(){this.uiObject&&!this._flippedObject&&(this._flippedObject=!0,this.uiObject.scale.y*=-1)}}var IA=Object.defineProperty,LA=Object.getOwnPropertyDescriptor,Jo=(o,e,t,i)=>{for(var n=i>1?void 0:i?LA(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&IA(e,t,n),n};const ia=w("debugtext");var ht=(o=>(o[o.UpperLeft=0]="UpperLeft",o[o.UpperCenter=1]="UpperCenter",o[o.UpperRight=2]="UpperRight",o[o.MiddleLeft=3]="MiddleLeft",o[o.MiddleCenter=4]="MiddleCenter",o[o.MiddleRight=5]="MiddleRight",o[o.LowerLeft=6]="LowerLeft",o[o.LowerCenter=7]="LowerCenter",o[o.LowerRight=8]="LowerRight",o))(ht||{}),O1=(o=>(o[o.Normal=0]="Normal",o[o.Bold=1]="Bold",o[o.Italic=2]="Italic",o[o.BoldAndItalic=3]="BoldAndItalic",o))(O1||{});class Ht extends vh{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(),this.context.accessibility.updateElement(this,{label:this.text}))}set_text(e){this.text=e}get fontSize(){return this._fontSize}set fontSize(e){this._fontSize=e,this.uiObject?.set({fontSize:e})}sRGBTextColor=new oe(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){ia&&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,ia&&(e.backgroundColor=16750848,e.backgroundOpacity=.5);const t=this.rectTransform;e={...e,...this.getTextOpts()},this.getAlignment(e),ia&&(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.context.accessibility.updateElement(this,{role:"text",label:this.text,hidden:!1}),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),this.context.accessibility.updateElement(this,{hidden:!0})}onDestroy(){super.onDestroy(),this.context.accessibility.removeElement(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(ia&&console.log("feedText",this.uiObject,e,t),!!this.uiObject)if(this._textMeshUi||(this._textMeshUi=[]),this.uiObject.children.length=0,!t||e.length===0)this.uiObject.textContent=e;else{let i=this.getNextTag(e);if(i){if(i.startIndex>0){for(let r=this.uiObject.children.length-1;r>=0;r--){const a=this.uiObject.children[r];a.isUI&&(this.uiObject.remove(a),a.clear())}const s=new $m({textContent:e.substring(0,i.startIndex),color:"inherit"});this.uiObject.add(s)}}else{this.uiObject.textContent="",this.setOptions({textContent:e});return}const n=[];for(;i;){const s=this.getNextTag(e,i.endIndex),r={fontFamily:this.uiObject?.get("fontFamily"),color:"inherit",textContent:""};if(s){r.textContent=this.getText(e,i,s),this.handleTag(i,r,n);const a=new $m(r);this.uiObject?.add(a)}else{r.textContent=e.substring(i.endIndex),this.handleTag(i,r,n);const a=new $m(r);this.uiObject?.add(a)}i=s}}}_didHandleTextRenderOnTop=!1;handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;const e=[],t=this.canvas,i={renderOnTop:t.renderOnTop,depthWrite:t.depthWrite,doubleSided:t.doubleSided};for(;;){let n=!1;if(this._textMeshUi)for(let s=0;s<this._textMeshUi.length;s++){if(e[s]===!0)continue;n=!0;const r=this._textMeshUi[s];r.textContent&&(Vu(r,i),e[s]=!0)}if(!n)break;yield}}handleTag(e,t,i){if(!e.isEndTag){if(e.type.includes("color")){const n=new Yy(e,{color:t.color});if(i.push(n),e.type.length>6){const s=parseInt("0x"+e.type.substring(7));t.color=s}else t.color=new oe(1,1,1)}else if(e.type=="b"){this.setFont(t,1);const n=new Yy(e,{fontWeight:700});i.push(n)}else if(e.type=="i"){this.setFont(t,2);const n=new Yy(e,{fontStyle:"italic"});i.push(n)}}}getText(e,t,i){return e.substring(t.endIndex,i.startIndex)}getNextTag(e,t=0){const i=e.indexOf("<",t),n=e.indexOf(">",i);if(i>=0&&n>=0){const s=e.substring(i+1,n);return{type:s,startIndex:i,endIndex:n+1,isEndTag:s.startsWith("/")}}return null}setFont(e,t){if(!this.font)return;const i=this.font,n=this.getFamilyNameWithCorrectSuffix(i,t);ia&&console.log("Selected font family:"+n);let s=qb.getFontFamily(n);switch(s||(s=qb.addFontFamily(n)),e.fontFamily=s,t){default:case 0:e.fontWeight=400,e.fontStyle="normal";break;case 1:e.fontWeight=700,e.fontStyle="normal";break;case 2:e.fontWeight=400,e.fontStyle="italic";break;case 3:e.fontStyle="italic",e.fontWeight=400}let r=s.getVariant(e.fontWeight,e.fontStyle);if(!r){let a=n;a?.endsWith("-msdf.json")||(a+="-msdf.json");let l=n;l?.endsWith(".png")||(l+=".png"),r=s.addVariant(e.fontWeight,e.fontStyle,a,l),r?.addEventListener("ready",()=>{this.markDirty()})}}getFamilyNameWithCorrectSuffix(e,t){(e.startsWith("https:")||e.startsWith("http:"))&&(e=new URL(e).pathname);const i=e.lastIndexOf("-");if(i<0)return e;const n=e.substring(i+1)?.toLowerCase();if(jA.includes(n))return ia&&console.warn("Unsupported font style: "+n),e;const s=e.lastIndexOf("/");let r=e;s>=0&&(r=r.substring(s+1));const a=r[0]===r[0].toUpperCase(),l=e.substring(0,i>s?i:e.length);switch(ia&&console.log("Select font: ",e,O1[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}}}Jo([u()],Ht.prototype,"alignment",2),Jo([u()],Ht.prototype,"verticalOverflow",2),Jo([u()],Ht.prototype,"horizontalOverflow",2),Jo([u()],Ht.prototype,"lineSpacing",2),Jo([u()],Ht.prototype,"supportRichText",2),Jo([u(URL)],Ht.prototype,"font",2),Jo([u()],Ht.prototype,"fontStyle",2),Jo([u()],Ht.prototype,"text",1),Jo([u()],Ht.prototype,"fontSize",1);class Yy{tag;previousValues;constructor(e,t){this.tag=e,this.previousValues=t}}const jA=["medium","mediumitalic","black","blackitalic","thin","thinitalic","extrabold","light","lightitalic","semibold"];class Il{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/${fp(this.material)}>`),t.closeBlock()}}class Zy{static singleLine(e,t,i){const n=new Il("text_"+Il.getId());return n.content=e,t&&(n.pointSize=t),i&&(n.depth=i),n}static multiLine(e,t,i,n,s,r){const a=new Il("text_"+Il.getId());return a.content=e,a.width=t,a.height=i,a.horizontalAlignment=n,a.verticalAlignment=s,r!==void 0&&(a.wrapMode=r),a}}const DA=new J().makeRotationY(Math.PI),BA=new J().makeScale(-1,1,-1);class Mp{get extensionName(){return"text"}exportText(e,t,i){const n=S.getComponent(e,Ht);if(!n)return;const s=S.getComponent(e,Ln);let r=100,a=100;s&&(r=s.width,a=s.height);const l=DA.clone();s&&l.premultiply(BA),t.setMatrix(l);const c=n.color.clone();t.material=new gt({color:c,emissive:c}),t.addEventListener("serialize",(h,d)=>{let p=n.text;p=p.replace(/\r/g,""),p=p.replace(/\n/g,"\\n");const m=Zy.multiLine(p,r,a,"center","bottom","flowing");this.setTextAlignment(m,n.alignment),this.setOverflow(m,n),t.material&&(m.material=t.material),m.pointSize=this.convertToTextSize(n.fontSize),m.depth=.001,m.writeTo(void 0,h)})}convertToTextSize(e){return 1/.0502*144*e}setOverflow(e,t){t.horizontalOverflow?e.wrapMode="singleLine":e.wrapMode="flowing"}setTextAlignment(e,t){switch(t){case ht.LowerLeft:case ht.MiddleLeft:case ht.UpperLeft:e.horizontalAlignment="left";break;case ht.LowerCenter:case ht.MiddleCenter:case ht.UpperCenter:e.horizontalAlignment="center";break;case ht.LowerRight:case ht.MiddleRight:case ht.UpperRight:e.horizontalAlignment="right";break}switch(t){case ht.LowerLeft:case ht.LowerCenter:case ht.LowerRight:e.verticalAlignment="bottom";break;case ht.MiddleLeft:case ht.MiddleCenter:case ht.MiddleRight:e.verticalAlignment="middle";break;case ht.UpperLeft:case ht.UpperCenter:case ht.UpperRight:e.verticalAlignment="top";break}}}var FA=Object.defineProperty,et=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&FA(e,t,n),n};const k1=w("debuguilayout");class na{left=0;right=0;top=0;bottom=0;get vertical(){return this.top+this.bottom}get horizontal(){return this.left+this.right}}et([u()],na.prototype,"left"),et([u()],na.prototype,"right"),et([u()],na.prototype,"top"),et([u()],na.prototype,"bottom");class Fi extends E{_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&&(k1&&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(){k1&&console.log(this.name,this),this._rectTransform=this.gameObject.getComponent(Ln);const e=this.gameObject.getComponentInParent(Ll);e&&e.registerLayoutGroup(this),this._needsUpdate=!0}onDisable(){const e=this.gameObject.getComponentInParent(Ll);e&&e.unregisterLayoutGroup(this)}set m_Spacing(e){e!==this.spacing&&(this._needsUpdate=!0,this.spacing=e)}get m_Spacing(){return this.spacing}}et([u()],Fi.prototype,"childAlignment"),et([u()],Fi.prototype,"reverseArrangement"),et([u()],Fi.prototype,"spacing"),et([u(na)],Fi.prototype,"padding"),et([u()],Fi.prototype,"minWidth"),et([u()],Fi.prototype,"minHeight"),et([u()],Fi.prototype,"flexibleHeight"),et([u()],Fi.prototype,"flexibleWidth"),et([u()],Fi.prototype,"preferredHeight"),et([u()],Fi.prototype,"preferredWidth");class qs extends Fi{childControlHeight=!0;childControlWidth=!0;childForceExpandHeight=!1;childForceExpandWidth=!1;childScaleHeight=!1;childScaleWidth=!1;onCalculateLayout(e){const t=this.primaryAxis,i=e.width;let n=i;const s=e.height;let r=s;n-=this.padding.horizontal,r-=this.padding.vertical,t==="x"?this.padding.horizontal:this.padding.vertical;const a=t==="x",l=a?"y":"x",c=a?this.childControlWidth:this.childControlHeight,h=a?this.childControlHeight:this.childControlWidth,d=a?this.childForceExpandWidth:this.childForceExpandHeight,p=a?this.childForceExpandHeight:this.childForceExpandWidth,m=a?r:n,g=a?i:s,f=.5*(a?this.childAlignment%3:Math.floor(this.childAlignment/3));let y=0;a?y+=this.padding.left:y+=this.padding.top;let _=0,v=0;for(let L=0;L<this.gameObject.children.length;L++){const V=this.gameObject.children[L],W=S.getComponent(V,Ln);W?.activeAndEnabled&&(v+=1,a?_+=W.width:_+=W.height)}let P=0;const k=this.spacing*(v-1);if(d||c){let L=0;a?L=n-=k:L=r-=k,v>0&&(P=L/v)}let O=0;O+=this.padding.left,O-=this.padding.right,f!==0&&(y=g-_,y*=f,y-=k*f,a?(y-=this.padding.right*f,y+=this.padding.left*(1-f),y<this.padding.left&&(y=this.padding.left)):(y-=this.padding.bottom*f,y+=this.padding.top*(1-f),y<this.padding.top&&(y=this.padding.top)));let j=1;for(let L=0;L<this.gameObject.children.length;L++){const V=this.gameObject.children[L],W=S.getComponent(V,Ln);if(W?.activeAndEnabled){W.pivot?.set(.5,.5),W.anchorMin.set(0,1),W.anchorMax.set(0,1);const G=i*.5+O*.5;W.anchoredPosition.x!==G&&(W.anchoredPosition.x=G);const X=s*-.5;W.anchoredPosition.y!==X&&(W.anchoredPosition.y=X),p&&h&&W.sizeDelta[l]!==m&&(W.sizeDelta[l]=m),d&&c&&W.sizeDelta[t]!==P&&(W.sizeDelta[t]=P);const R=a?W.width:W.height,$=R*.5;if(y+=$,d){const he=P*j-P*.5;he>y&&(y=he-P*.5+R+this.padding.left,y-=$)}let q=y;t==="y"&&(q=-q),W.anchoredPosition[t]!==q&&(W.anchoredPosition[t]=q),y+=$,y+=this.spacing,j+=1}}}}et([u()],qs.prototype,"childControlHeight"),et([u()],qs.prototype,"childControlWidth"),et([u()],qs.prototype,"childForceExpandHeight"),et([u()],qs.prototype,"childForceExpandWidth"),et([u()],qs.prototype,"childScaleHeight"),et([u()],qs.prototype,"childScaleWidth");class Ky extends qs{get primaryAxis(){return"y"}}class Jy extends qs{get primaryAxis(){return"x"}}class e0 extends Fi{onCalculateLayout(){}}var UA=Object.defineProperty,zA=Object.getOwnPropertyDescriptor,ho=(o,e,t,i)=>{for(var n=i>1?void 0:i?zA(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&UA(e,t,n),n},M1=(o=>(o[o.ScreenSpaceOverlay=0]="ScreenSpaceOverlay",o[o.ScreenSpaceCamera=1]="ScreenSpaceCamera",o[o.WorldSpace=2]="WorldSpace",o[o.Undefined=-1]="Undefined",o))(M1||{});const t0=w("debuguilayout"),rn=class NS extends yh{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 NS||(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,t0&&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 J,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 mc(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(),li.ensureUpdateMeshUI(Xb,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(),li.ensureUpdateMeshUI(Xb,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 J);const e=!this._lastMatrixWorld.equals(this.gameObject.matrixWorld);t0&&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(Fi)),(t.isDirty||i?.isDirty)&&(t0&&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(),xe.OnBeforeRender))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.onUpdateRenderMode(),Vu(this.shadowComponent,this);for(const e of S.getComponentsInChildren(this.gameObject,un))Vu(e.shadowComponent,this)}}_activeRenderMode=-1;_lastWidth=-1;_lastHeight=-1;onUpdateRenderMode(e=!1){if(!e&&this._renderMode===this._activeRenderMode&&this._lastWidth===this.context.domWidth&&this._lastHeight===this.context.domHeight)return;this._activeRenderMode=this._renderMode;let t=this.context.mainCameraComponent,i=10;switch(t&&t.nearClipPlane>0&&t.farClipPlane>0&&(i=D.lerp(t.nearClipPlane,t.farClipPlane,.01)),this._renderMode===1&&(this.worldCamera&&(t=this.worldCamera),this.planeDistance>0&&(i=this.planeDistance)),this._renderMode){case 0:case 1:if(this._lastWidth=this.context.domWidth,this._lastHeight=this.context.domHeight,!t)return;const n=i+.01;this.gameObject.position.x=0,this.gameObject.position.y=0,this.gameObject.position.z=-n,this.gameObject.quaternion.identity();const s=this.gameObject.getComponent(Ln);let r=!1;s.sizeDelta.x!==this.context.domWidth&&(r=!0),s.sizeDelta.y!==this.context.domHeight&&(r=!0);const a=t.fieldOfView*Math.PI/180,l=2*Math.tan(a/2)*Math.abs(n);this.gameObject.scale.x=l/this.context.domHeight,this.gameObject.scale.y=l/this.context.domHeight,this.gameObject.scale.z=.01,r&&(s.sizeDelta.x=this.context.domWidth,s.sizeDelta.y=this.context.domHeight,s?.markDirty());break;case 2:this._lastWidth=-1,this._lastHeight=-1;break}}};ho([u()],rn.prototype,"renderOnTop",1),ho([u()],rn.prototype,"depthWrite",1),ho([u()],rn.prototype,"doubleSided",1),ho([u()],rn.prototype,"castShadows",1),ho([u()],rn.prototype,"receiveShadows",1),ho([u()],rn.prototype,"renderMode",1),ho([u(rn)],rn.prototype,"rootCanvas",1),ho([u()],rn.prototype,"scaleFactor",1),ho([u(yi)],rn.prototype,"worldCamera",2),ho([u()],rn.prototype,"planeDistance",2);let Ll=rn;var NA=Object.defineProperty,WA=Object.getOwnPropertyDescriptor,i0=(o,e,t,i)=>{for(var n=i>1?void 0:i?WA(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&NA(e,t,n),n};class Xs extends E{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(),xe.OnBeforeRender))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}_buffer=[];applyChangesNow(){this._buffer.length=0;for(const e of S.getComponentsInChildren(this.gameObject,un,this._buffer)){const t=e;t.setAlphaFactor&&t.setAlphaFactor(this._alpha)}}}i0([u()],Xs.prototype,"alpha",1),i0([u()],Xs.prototype,"interactable",2),i0([u()],Xs.prototype,"blocksRaycasts",2);class n0{get extensionName(){return"tmui"}onExportObject(e,t,i){const n=S.getComponent(e,Ll);if(n&&n.enabled&&n.renderMode===M1.WorldSpace){const s=new Mp,r=S.getComponent(e,Ln),a=S.getComponent(e,Xs),l=new Array;if(r){if(!S.isActiveSelf(e)){const d=S.isActiveSelf(e);S.setActive(e,!0),r.onEnable(),r.updateTransform(),l.push(()=>{r.onDisable(),S.setActive(e,d)})}e.traverse(d=>{if(!S.isActiveInHierarchy(d)){const p=S.isActiveSelf(d);S.setActive(d,!0);const m=S.getComponent(d,un);m&&(m.onEnable(),l.push(()=>{m.onDisable()}));const g=S.getComponent(d,Ln);g&&(g.onEnable(),g.updateTransform(),g.onApplyTransform(),l.push(()=>{g.onDisable()}));const f=S.getComponent(d,Ht);f&&(f.onEnable(),l.push(()=>{f.onDisable()})),l.push(()=>{S.setActive(d,p)})}}),r.width,r.height;const c=rt.createEmpty(),h=r.shadowComponent;if(t.add(c),h){const d=h.matrix;c.setMatrix(d);const p=new Map,m=new Map;p.set(h,c),m.set(h,a?a.alpha:1),h.traverse(g=>{if(g===h)return;const f=rt.createEmpty();f.setMatrix(g.matrix);const y=g.parent,_=!!y&&typeof y.textContent=="string"&&y.textContent.length>0;let v=m.get(y)||1;const P=S.getComponent(g,Xs);if(P&&(v*=P.alpha),g instanceof H&&_){const O=g[Ai];O?s.exportText(O.gameObject,f,i):console.error("Error when exporting UI: shadow component owner not found. This is likely a bug.",g)}if(g instanceof H&&!_){const O=g.geometry.clone();O.scale(1,1,-1),this.flipWindingOrder(O),f.geometry=O;const j=new oe,L=g.material.opacity;j.copy(g.material.color),f.material=new Ce({color:j,opacity:L*v,map:g.material.map,transparent:!0})}p.set(g,f),m.set(g,v);const k=p.get(y);if(!k){console.error("Error when exporting UI: shadow component parent not found!",g,g.parent);return}k.add(f)})}}for(const c of l)c()}}flipWindingOrder(e){const t=e.index.array;for(let i=0,n=t.length/3;i<n;i++){const s=t[i*3];t[i*3]=t[i*3+2],t[i*3+2]=s}e.index.needsUpdate=!0}}const xh=w("debugusdz");function VA(o,e){const t=[],i=S.getComponentsInChildren(o,_t),n=S.getComponentsInChildren(o,Ut),s=new Array,r=new Array;if(e.injectImplicitBehaviours)for(const a of i){if(!a||!a.runtimeAnimatorController||!a.enabled)continue;const l=a.runtimeAnimatorController.activeState;if(!l||!l.motion||!l.motion.clip||l.motion.clip.tracks?.length<1||s.includes(a))continue;const c=new hh;c.animator=a,c.stateName=l.name,c.trigger="start",c.name="PlayAnimationOnClick_implicitAtStart_"+c.stateName;const h=new M;S.addComponent(h,c),r.push(h),s.push(a),o.add(h)}else for(const a of i){if(!a||!a.runtimeAnimatorController||!a.enabled)continue;xh&&console.log(a);const l=[];for(const c of a.runtimeAnimatorController.enumerateActions()){xh&&console.log(c);const h=c.getClip();l.includes(h)||l.push(h)}t.push({root:a.gameObject,clips:l})}if(e.injectImplicitBehaviours)for(const a of n){if(!a||!a.clip||!a.enabled||!a.playAutomatically||s.includes(a))continue;const l=new hh;l.animation=a,l.stateName=a.clip.name,l.trigger="start",l.name="PlayAnimationOnClick_implicitAtStart_"+l.stateName;const c=new M;S.addComponent(c,l),r.push(c),s.push(a),o.add(c)}else for(const a of n){xh&&console.log(a);const l=[];for(const c of a.animations)l.includes(c)||l.push(c);t.push({root:a.gameObject,clips:l})}xh&&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 $A(o,e){const t=S.getComponentsInChildren(o,ji),i=S.getComponentsInChildren(o,Ns),n=new Array,s=new Array;xh&&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 Ns;a.target=r,a.name="PlayAudioOnClick_implicitAtStart_",a.trigger="start";const l=new M;S.addComponent(l,a),console.log("implicit PlayAudioOnStart",l,a),s.push(l),n.push(r),o.add(l)}return s}function HA(o){return new jt("DisableAtStart",$t.sceneStartTrigger(),fe.fadeAction(o,0,!1))}function E1(o,e){const t=o.domElement.shadowRoot.querySelector("link[rel='ar']");if(t)return t;const i=document.createElement("div");i.classList.add("menu"),i.classList.add("quicklook-menu"),i.style.display="none",i.style.visibility="hidden";const n=document.createElement("button");n.id="open-in-ar",e?(n.innerText="View in AR",n.title="View this scene in AR. The scene will be exported to USDZ and opened with Apple's QuickLook."):(n.innerText="View in AR",n.title="Download this scene for AR. Open the downloaded USDZ file to view it in AR using Apple's QuickLook."),i.appendChild(n);const s=document.createElement("a");s.id="needle-usdz-link",s.style.display="none",s.rel="ar",s.href="",s.target="_blank",i.appendChild(s);const r=document.createElement("img");return r.id="button",s.appendChild(r),o.domElement.shadowRoot.appendChild(i),s}var GA=Object.defineProperty,Et=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&GA(e,t,n),n};const Rt=w("debugusdz"),qA=w("debugusdzpruning");class oa{callToAction;checkoutTitle;checkoutSubtitle;callToActionURL}Et([u()],oa.prototype,"callToAction"),Et([u()],oa.prototype,"checkoutTitle"),Et([u()],oa.prototype,"checkoutSubtitle"),Et([u()],oa.prototype,"callToActionURL");const vi=class Sa extends E{static beforeExport=new ae;static afterExport=new ae;static beforeLODExport=new ae;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(){Rt&&(console.log("USDZExporter",this),console.log("Debug USDZ Mode. Press 'T' to export"),window.addEventListener("keydown",e=>{e.key==="t"&&this.exportAndOpen()})),this.objectToExport||(this.objectToExport=this.gameObject),!this.objectToExport?.children?.length&&!this.objectToExport?.isMesh&&(this.objectToExport=this.context.scene)}onEnable(){const e=I.supportsQuickLookAR(),t=I.isiOS()||I.isiPad();!this.button&&(Rt||e||t)&&(this.allowCreateQuicklookButton&&(this.button=this.createQuicklookButton()),this.lastCallback=this.quicklookCallback.bind(this),this.link=E1(this.context,e),this.link.addEventListener("message",this.lastCallback)),Rt&&Oe("USDZ Exporter enabled: "+this.name),document.getElementById("open-in-ar")?.addEventListener("click",this.onClickedOpenInARElement),kc.registerExporter(this)}onDisable(){this.button?.remove(),this.link?.removeEventListener("message",this.lastCallback),Rt&&Oe("USDZ Exporter disabled: "+this.name),document.getElementById("open-in-ar")?.removeEventListener("click",this.onClickedOpenInARElement),kc.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+="-"+Qx(),Zn()||(e!==""&&(e+="-"),e+="MadeWithNeedle"),this.link||(this.link=E1(this.context,I.supportsQuickLookAR())),this.customUsdzFile)return Rt&&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;Sa.beforeExport.invoke({exporter:this});const t=await this.export(this.objectToExport).finally(()=>{Sa.afterExport.invoke({exporter:this})});return t?(Rt&&console.log("USDZ generation done. Downloading as "+e),this.openInQuickLook(t,e),t):(console.error("USDZ generation failed. Please report a bug",this),null)}async export(e){if(!e)return console.warn("No object to export"),null;const t=this._currentExportTasks.get(e);if(t)return t;const i=this.internalExport(e);return i instanceof Promise?(this._currentExportTasks.set(e,i),i.then(n=>(this._currentExportTasks.delete(e),n)).catch(n=>(this._currentExportTasks.delete(e),console.error("Error during USDZ export \u2013 please report a bug!",n),null))):i}_currentExportTasks=new Map;_previousTimeScale=1;async internalExport(e){le.start("export-usdz",{onProgress:k=>{this.dispatchEvent(new CustomEvent("export-progress",{detail:{progress:k}}))}}),le.report("export-usdz",{message:"Starting export",totalSteps:40,currentStep:0}),le.report("export-usdz",{message:"Load progressive textures",autoStep:5}),le.start("export-usdz-textures","export-usdz");const t=S.getComponentsInChildren(e,_i);for(const k of t)k&&k.enabled&&k.updateSprite(!0);const i=S.getComponentsInChildren(e,ti),n=new Array;let s=0;for(const k of i){for(const O of k.sharedMeshes)if(O){let j=0;const L={exporter:this,type:"mesh",object:k.gameObject,mesh:O};if(Sa.beforeLODExport.invoke(L),L.overrideLevel!==void 0)if(L.overrideLevel===-1){Rt&&console.warn("Skipping LOD export for mesh due to overrideLevel -1",k.gameObject,O);continue}else L.overrideLevel>=0&&(j=L.overrideLevel,Rt&&console.log("Overriding LOD level for mesh export to level "+j+" "+O.name));const V=Ve.assignMeshLOD(O,j);V instanceof Promise&&n.push(new Promise((W,G)=>{V.then(()=>{s++,le.report("export-usdz-textures",{message:"Loaded progressive mesh",currentStep:s,totalSteps:n.length}),W()}).catch(X=>G(X))}))}for(const O of k.sharedMaterials)if(O){let j=0;const L={exporter:this,type:"texture",object:k.gameObject,material:O};if(Sa.beforeLODExport.invoke(L),L.overrideLevel!==void 0)if(L.overrideLevel===-1){Rt&&console.warn("Skipping LOD assignment due to overrideLevel -1",k.gameObject,O);continue}else L.overrideLevel>=0&&(j=L.overrideLevel,Rt&&console.log("Overriding LOD level for texture export to level "+j+" "+O.name));const V=Ve.assignTextureLOD(O,j);V instanceof Promise&&n.push(new Promise((W,G)=>{V.then(()=>{s++,le.report("export-usdz-textures",{message:"Loaded progressive texture",currentStep:s,totalSteps:n.length}),W()}).catch(X=>G(X))}))}}Rt&&Oe("Progressive Loading: "+n.length),await Promise.all(n),Rt&&Oe("Progressive Loading: done"),le.end("export-usdz-textures");const r=ai.Global.Mask;ai.Global.Set(no.AR);const a=new t1,l=new _p(this.quickLookCompatible);let c;const h=[];this.interactive&&(h.push(new Hy),h.push(new Pa),globalThis.NEEDLE_USE_RAPIER&&S.getComponentsInChildren(e,Ke).length>0&&(this.physics?(c=new Gy,h.push(c)):A()&&console.warn("USDZExporter: Physics export is disabled, but there are active Rigidbody components in the scene. They will not be exported.")),h.push(new Mp),h.push(new n0));const d=[l,...h,...this.extensions],p={self:this,exporter:a,extensions:d,object:e};le.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,le.report("export-usdz","auto export animations and audio sources");const m=new Array;this.autoExportAnimations&&m.push(...VA(e,l)),d.find(k=>k.extensionName==="Audio")&&this.autoExportAudioSources&&m.push(...$A(e)),a.debug=Rt,a.pruneUnusedNodes=!qA;const g=Oa.instance.objs.map(k=>k.batchedMesh);a.keepObject=k=>{let O=!0;const j=S.getComponent(k,ti);return j&&!j.enabled&&(O=!1),O&&g.includes(k)&&(O=!1),O&&S.getComponentInParent(k,nh)&&(O=!1),O&&S.getComponentInParent(k,Jn)&&(O=!1),Rt&&!O&&console.log("USDZExporter: Discarding object",k),O},a.beforeWritingDocument=()=>{if(A()&&l&&c){const k=l.animatedRoots;for(const O of k){const j=S.getComponentsInChildren(O,Ke).filter(V=>V.enabled),L=S.getComponents(O,nn).filter(V=>V.enabled&&!V.isTrigger);(j.length>0||L.length>0)&&console.error("An animated object has physics components in its child hierarchy. This can lead to undefined behaviour due to a bug in Apple's QuickLook (FB15925487). Remove the physics components from child objects or verify that you get the expected results.",O)}}};const f=new Array;this.objectToExport&&this.quickLookCompatible&&this.interactive&&this.objectToExport.traverse(k=>{k.visible||f.push(k)});const y=d.find(k=>k.extensionName==="Behaviour");this.interactive&&y&&f.length>0&&y.addBehavior(HA(f));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"),le.report("export-usdz","Invoking exporter.parse");const v=await a.parse(this.objectToExport,{ar:{anchoring:{type:this.anchoringType},planeAnchoring:{alignment:this.planeAnchoringAlignment}},extensions:d,quickLookCompatible:this.quickLookCompatible,maxTextureSize:this.maxTextureSize,exportInvisible:_}),P=new Blob([v],{type:"model/vnd.usdz+zip"});this.revertWebARSessionRoot(),this.context.time.timeScale=this._previousTimeScale,le.report("export-usdz","Invoking after-export"),this.dispatchEvent(new CustomEvent("after-export",{detail:p}));for(const k of m)S.destroy(k);return ai.Global.Set(r),le.end("export-usdz"),P}openInQuickLook(e,t){const i=e instanceof Blob?URL.createObjectURL(e):e,n=this.buildQuicklookOverlay();Rt&&console.log("QuickLook Overlay",n);const s=n.callToAction?encodeURIComponent(n.callToAction):"",r=n.checkoutTitle?encodeURIComponent(n.checkoutTitle):"",a=n.checkoutSubtitle?encodeURIComponent(n.checkoutSubtitle):"";this.link.href=i+`#callToAction=${s}&checkoutTitle=${r}&checkoutSubtitle=${a}&callToActionURL=${n.callToActionURL}`,this.lastCallback||(this.lastCallback=this.quicklookCallback.bind(this),this.link.addEventListener("message",this.lastCallback)),this.link.download=t+".usdz",this.link.click()}download(e,t){Sa.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"){Rt&&be("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");Rt&&Oe("Quicklook url: "+n),n&&(Zn()?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),Zn()||(console.log("Custom Quicklook banner text requires pro license: https://needle.tools/pricing"),e.callToAction="Close",e.checkoutTitle="\u{1F335} Made with Needle",e.checkoutSubtitle="_"),(e.callToAction?.length||e.checkoutTitle?.length||e.checkoutSubtitle?.length)&&(e.callToAction?.length||(e.callToAction="\0"),e.checkoutTitle?.length||(e.checkoutTitle="\0"),e.checkoutSubtitle?.length||(e.checkoutSubtitle="\0")),this.dispatchEvent(new CustomEvent("quicklook-overlay",{detail:e})),e}static invertForwardMatrix=new J().makeRotationY(Math.PI);static invertForwardQuaternion=new N().setFromEuler(new at(0,Math.PI,0));_rootSessionRootWasAppliedTo=null;_rootPositionBeforeExport=new b;_rootRotationBeforeExport=new N;_rootScaleBeforeExport=new b;getARScaleAndTarget(){if(!this.objectToExport)return{scale:1,_invertForward:!1,target:this.gameObject,sessionRoot:null};const e=S.findObjectOfType(Pp);let t=S.getComponentInParent(this.objectToExport,yn);t||(t=S.getComponentInChildren(this.objectToExport,yn));let i=1,n=!1;const s=this.objectToExport;return e?i=e.arScale:t&&(i=t.arScale,n=t.invertForward),{scale:1/i,_invertForward:n,target:s,sessionRoot:t?.gameObject??null}}applyWebARSessionRoot(){if(!this.objectToExport)return;const{scale:e,_invertForward:t,target:i,sessionRoot:n}=this.getARScaleAndTarget(),s=n?.matrixWorld.clone().invert();this._rootSessionRootWasAppliedTo=i,this._rootPositionBeforeExport.copy(i.position),this._rootRotationBeforeExport.copy(i.quaternion),this._rootScaleBeforeExport.copy(i.scale),i.scale.multiplyScalar(e),t&&i.quaternion.multiply(Sa.invertForwardQuaternion),i.updateMatrix(),i.updateMatrixWorld(!0),n&&s&&i.matrix.premultiply(s)}revertWebARSessionRoot(){if(!this.objectToExport||!this._rootSessionRootWasAppliedTo)return;const e=this._rootSessionRootWasAppliedTo;e.position.copy(this._rootPositionBeforeExport),e.quaternion.copy(this._rootRotationBeforeExport),e.scale.copy(this._rootScaleBeforeExport),e.updateMatrix(),e.updateMatrixWorld(!0),this._rootSessionRootWasAppliedTo=null}createQuicklookButton(){const e=ur.getOrCreate().createQuicklookButton();return e.parentNode||this.context.menu.appendChild(e),e}};Et([u(M)],vi.prototype,"objectToExport"),Et([u()],vi.prototype,"autoExportAnimations"),Et([u()],vi.prototype,"autoExportAudioSources"),Et([u()],vi.prototype,"exportFileName"),Et([u(URL)],vi.prototype,"customUsdzFile"),Et([u(oa)],vi.prototype,"customBranding"),Et([u()],vi.prototype,"anchoringType"),Et([u()],vi.prototype,"maxTextureSize"),Et([u()],vi.prototype,"planeAnchoringAlignment"),Et([u()],vi.prototype,"interactive"),Et([u()],vi.prototype,"physics"),Et([u()],vi.prototype,"allowCreateQuicklookButton"),Et([u()],vi.prototype,"quickLookCompatible");let uo=vi;var XA=Object.defineProperty,QA=Object.getOwnPropertyDescriptor,o0=(o,e,t,i)=>{for(var n=QA(e,t),s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&XA(e,t,n),n};class jl extends E{get fog(){return this._fog||(this._fog=new _b(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)}}o0([u()],jl.prototype,"near"),o0([u()],jl.prototype,"far"),o0([u(oe)],jl.prototype,"color");var YA=Object.defineProperty,s0=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&YA(e,t,n),n};class sa extends E{objectBounds=!1;color;isGizmo=!0;_gizmoObject=null;_boxHelper=null;onEnable(){this.isGizmo&&!jc||(this._gizmoObject||(this.objectBounds?this._gizmoObject=new $C(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=iu(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),xe.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){for(;this._boxHelper;)this._boxHelper?.update(),yield}}s0([u()],sa.prototype,"objectBounds"),s0([u(oe)],sa.prototype,"color"),s0([u()],sa.prototype,"isGizmo");var ZA=Object.defineProperty,r0=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&ZA(e,t,n),n};class Dl extends E{isGizmo=!1;color0;color1;gridHelper;size;divisions;offset;onEnable(){if(this.isGizmo&&!jc)return;const e=this.size,t=this.divisions;this.gridHelper||(this.gridHelper=new fb(e,t,this.color0??new oe(.4,.4,.4),this.color1??new oe(.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)}}r0([u()],Dl.prototype,"isGizmo"),r0([u(oe)],Dl.prototype,"color0"),r0([u(oe)],Dl.prototype,"color1");var KA=Object.defineProperty,a0=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&KA(e,t,n),n};class l0 extends E{connectedBody;get rigidBody(){return this._rigidBody}_rigidBody=null;onEnable(){this._rigidBody||(this._rigidBody=this.gameObject.getComponent(Ke)),this.rigidBody&&this.connectedBody&&this.startCoroutine(this.create())}*create(){yield,this.rigidBody&&this.connectedBody&&this.activeAndEnabled&&this.createJoint(this.rigidBody,this.connectedBody)}}a0([u(Ke)],l0.prototype,"connectedBody");class c0 extends l0{createJoint(e,t){this.context.physics.engine?.addFixedJoint(e,t)}}class Sh extends l0{anchor;axis;createJoint(e,t){this.axis&&this.anchor&&this.context.physics.engine?.addHingeJoint(e,t,this.anchor,this.axis)}}a0([u(b)],Sh.prototype,"anchor"),a0([u(b)],Sh.prototype,"axis");var JA=Object.defineProperty,e2=Object.getOwnPropertyDescriptor,Ui=(o,e,t,i)=>{for(var n=i>1?void 0:i?e2(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&JA(e,t,n),n};function Bl(o){return o*Math.PI/180}const R1=300,Qs=w("debuglights");class Tt extends E{type=0;get range(){return this._range}set range(e){this._range=e,this.light&&(this.light.type==="SpotLight"||this.light.type==="PointLight")&&"distance"in this.light&&(this.light.distance=e)}_range=1;get spotAngle(){return this._spotAngle}set spotAngle(e){this._spotAngle=e,this.light&&this.light.type==="SpotLight"&&"angle"in this.light&&(this.light.angle=Bl(e/2))}_spotAngle=30;get innerSpotAngle(){return this._innerSpotAngle}set innerSpotAngle(e){if(this._innerSpotAngle=e,this.light&&this.light.type==="SpotLight"&&"penumbra"in this.light){const t=this.spotAngle,i=1-Bl(e/2)/Bl(t/2);this.light.penumbra=i}}_innerSpotAngle=10;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 oe(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){this._intensity=e,this.light&&(this.light.intensity=e),Qs&&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 oe(this.color??16777215),Qs&&console.log(this.name,this)}onEnable(){Qs&&console.log("ENABLE LIGHT",this.name),this.createLight(),!this.isBaked&&(this.light&&(this.light.visible=!0,this.light.intensity=this._intensity,Qs&&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(),xe.LateUpdate))}onDisable(){Qs&&console.log("DISABLE LIGHT",this.name),this.light&&(this.selfIsLight?this.light.intensity=0:this.light.visible=!1)}createLight(){const e=this.selfIsLight;if(e&&!this.light)this.light=this.gameObject,this.light.name=this.name,this._intensity=this.light.intensity,this.type===1&&this.setDirectionalLight(this.light);else if(!this.light)switch(this.type){case 1:const t=new km(this.color,this.intensity*Math.PI);if(t.position.set(0,0,-R1*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(t.target),Sr(t.target,0,0,0),this.light=t,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),Qs){const r=new GC(this.light,.2,this.color);this.context.scene.add(r)}break;case 0:const i=new HC(this.color,this.intensity*Math.PI,this.range,Bl(this.spotAngle/2),1-Bl(this.innerSpotAngle/2)/Bl(this.spotAngle/2),2);i.position.set(0,0,0),i.rotation.set(0,0,0),this.light=i;const n=i.target;i.add(n),n.position.set(0,0,this.range),n.rotation.set(0,0,0);break;case 2:const s=new Mm(this.color,this.intensity*Math.PI,this.range);this.light=s;break}if(this.light){if(this._intensity>=0?this.light.intensity=this._intensity:this._intensity=this.light.intensity,this.shadows!==0?this.light.castShadow=!0:this.light.castShadow=!1,this.light.shadow){this._shadowResolution!==void 0&&this._shadowResolution>4?(this.light.shadow.mapSize.width=this._shadowResolution,this.light.shadow.mapSize.height=this._shadowResolution):(this.light.shadow.mapSize.width=2048,this.light.shadow.mapSize.height=2048),Qs&&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=R1*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,Qs&&this.context.scene.add(new qC(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)}}Ui([u()],Tt.prototype,"type",2),Ui([u()],Tt.prototype,"range",1),Ui([u()],Tt.prototype,"spotAngle",1),Ui([u()],Tt.prototype,"innerSpotAngle",1),Ui([u(oe)],Tt.prototype,"color",1),Ui([u()],Tt.prototype,"shadowNearPlane",1),Ui([u()],Tt.prototype,"shadowBias",1),Ui([u()],Tt.prototype,"shadowNormalBias",1),Ui([u()],Tt.prototype,"shadows",1),Ui([u()],Tt.prototype,"lightmapBakeType",2),Ui([u()],Tt.prototype,"intensity",1),Ui([u()],Tt.prototype,"shadowDistance",1),Ui([u()],Tt.prototype,"shadowResolution",1),new b(0,0,0);var t2=Object.defineProperty,Ep=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&t2(e,t,n),n};const h0=w("debuglods"),i2=w("nolods");class Fl{screenRelativeTransitionHeight;distance;renderers}Ep([u()],Fl.prototype,"screenRelativeTransitionHeight"),Ep([u()],Fl.prototype,"distance"),Ep([u(ti)],Fl.prototype,"renderers");class n2{model;get renderers(){return this.model.renderers}constructor(e){this.model=e}}class Rp extends E{lodModels=[];_lods=[];_settings=[];_lodsHandler;start(){if(h0&&console.log("LODGROUP",this.name,this.lodModels,this),!i2&&!this._lodsHandler&&this.gameObject&&this.lodModels&&Array.isArray(this.lodModels)){const e=[];for(const i of this.lodModels){const n=new n2(i);this._lods.push(n);for(const s of n.renderers)e.includes(s)||e.push(s)}this._lodsHandler=new Array;for(let i=0;i<e.length;i++){const n=new XC;this._lodsHandler.push(n),this.gameObject.add(n)}const t=new M;t.name="Cull "+this.name;for(let i=0;i<e.length;i++){const n=e[i],s=this._lodsHandler[i],r=n.gameObject;h0&&console.log(i,r.name);for(const a of this._lods){const l=a.model.distance;let c=null;if(a.renderers.includes(n)?c=r:c=t,c.type==="Group"){console.warn(`LODGroup ${this.name}: Group or MultiMaterial object's are not supported as LOD object: ${c.name}`);continue}h0&&console.log("LEVEL",c.name,l),s.autoUpdate=!1,this.onAddLodLevel(s,c,a.model.distance)}}}}onAfterRender(){if(!this.gameObject||!this._lodsHandler)return;const e=this.context.mainCamera;if(e)for(const t of this._lodsHandler){t.update(e);const i=t.getCurrentLevel(),n=t.levels[i];t.layers.mask=n.object.layers.mask}}onAddLodLevel(e,t,i){if(t===this.gameObject){console.warn("LODGroup component must be on parent object and not mesh directly at the moment",t.name,t);return}e.addLevel(t,i*this._distanceFactor,.01);const n={lod:e,levelIndex:e.levels.length-1,distance:i};this._settings.push(n)}_distanceFactor=1;distanceFactor(e){if(e!==this._distanceFactor){this._distanceFactor=e;for(const t of this._settings){const i=t.lod.levels[t.levelIndex];i.distance=t.distance*e}}}}Ep([u(Fl)],Rp.prototype,"lodModels");var o2=Object.defineProperty,d0=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&o2(e,t,n),n};const Tp=w("debugnestedgltf");class Ul extends E{filePath;loaded=new ae;loadAssetInParent=!0;_isLoadingOrDoneLoading=!1;listenToProgress(e){this.filePath?.beginListenDownload(e)}preload(){return this.filePath?.preload()||null}async start(){if(this._isLoadingOrDoneLoading)return;Tp&&console.log(this,this.guid);const e=this.gameObject.parent;if(e&&this.filePath){this._isLoadingOrDoneLoading=!0;const t=new Wn;t.idProvider=new Dt(this.hash(this.guid)),t.parent=this.loadAssetInParent!==!1?e:this.gameObject,this.gameObject.updateMatrix();const i=this.gameObject.matrix;Tp&&console.log("Load nested:",this.filePath?.url??this.filePath,this.gameObject.position);const n=await this.filePath?.instantiate?.call(this.filePath,t);Tp&&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})),Tp&&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}}d0([u(ne)],Ul.prototype,"filePath"),d0([u(ae)],Ul.prototype,"loaded"),d0([u()],Ul.prototype,"loadAssetInParent");var s2=Object.defineProperty,u0=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&s2(e,t,n),n};const r2=w("debugnet"),Ap=class ub extends E{url=null;urlParameterName=null;localhost=null;awake(){r2&&console.log(this),this.context.connection.registerProvider(this)}getWebsocketUrl(){let e=this.url?ub.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){const i=w(this.urlParameterName);i&&typeof i=="string"&&(e=i)}if(!e)return null;const t=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(e);return t?.groups?t?.groups.socket_prefix?e:"wss://"+t?.groups.url:null}static GetUrl(e,t){let i=e;const n=ub.IsLocalNetwork()&&t;if(n&&(i=t),e?.startsWith("/")){const s=n?i:window.location.origin;s?.endsWith("/")&&e.startsWith("/")&&(e=e.substring(1)),i=s+e}return i}static IsLocalNetwork(e=window.location.hostname){return Mi(e)}};u0([u()],Ap.prototype,"url"),u0([u()],Ap.prototype,"urlParameterName"),u0([u()],Ap.prototype,"localhost");let p0=Ap;var a2=Object.defineProperty,Ip=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&a2(e,t,n),n};class ra extends E{referenceSpace;from;affectPosition=!1;affectRotation=!1;alignLookDirection=!1;levelLookDirection=!1;levelPosition=!1;positionOffset=new b(0,0,0);rotationOffset=new b(0,0,0);offset=new b(0,0,0);update(){if(!this.from)return;var e=ee(this.from),t=_e(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 _r(this.gameObject.up,0),l=ee(this.referenceSpace);a.setFromNormalAndCoplanarPoint(this.gameObject.up,l);const c=new b(0,0,0);a.projectPoint(e,c),e.copy(c)}this.affectPosition&&yt(this.gameObject,e);const n=new at(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),s=new N().setFromEuler(n);this.affectRotation&&Sn(this.gameObject,t.multiply(s));const r=new b;this.from.getWorldDirection(r).multiplyScalar(50),this.levelLookDirection&&(r.y=0),this.alignLookDirection&&this.gameObject.lookAt(r)}}Ip([u(S)],ra.prototype,"referenceSpace"),Ip([u(S)],ra.prototype,"from"),Ip([u(b)],ra.prototype,"positionOffset"),Ip([u(b)],ra.prototype,"rotationOffset");var l2=Object.defineProperty,Ys=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&l2(e,t,n),n};class wi{time=0;value=0;inTangent=1/0;inWeight;outTangent=1/0;outWeight;weightedMode;constructor(e=0,t=0){this.time=e,this.value=t}}Ys([u()],wi.prototype,"time"),Ys([u()],wi.prototype,"value"),Ys([u()],wi.prototype,"inTangent"),Ys([u()],wi.prototype,"inWeight"),Ys([u()],wi.prototype,"outTangent"),Ys([u()],wi.prototype,"outWeight"),Ys([u()],wi.prototype,"weightedMode");const T1=class yd{static linearFromTo(e,t,i){const n=new yd,s=new wi;s.time=0,s.value=e;const r=new wi;return r.time=i,r.value=t,n.keys.push(s,r),n}static constant(e){const t=new yd,i=new wi;return i.time=0,i.value=e,t.keys.push(i),t}keys=[];clone(){const e=new yd;return e.keys=this.keys?.map(t=>{const i=new wi;return i.time=t.time,i.value=t.value,i.inTangent=t.inTangent,i.inWeight=t.inWeight,i.outTangent=t.outTangent,i.outWeight=t.outWeight,i.weightedMode=t.weightedMode,i})||[],e}get duration(){return!this.keys||this.keys.length==0?0:this.keys[this.keys.length-1].time}evaluate(e){if(!this.keys||this.keys.length==0)return 0;if(this.keys.length===1)return this.keys[0].value;if(this.keys[0].time>=e)return this.keys[0].value;for(let t=0;t<this.keys.length;t++){const i=this.keys[t];if(i.time<=e)if(t+1<this.keys.length){const n=this.keys[t+1];if(n.time<e)continue;return!isFinite(i.outTangent)||!isFinite(n.inTangent)?i.value:yd.interpolateValue(e,i,n)}else return i.value}return this.keys[this.keys.length-1].value}static interpolateValue(e,t,i){const n=t.time,s=t.value,r=t.outTangent,a=i.time,l=i.value,c=i.inTangent,h=a-n,d=h*h,p=d*h,m=((r+c)*h-2*(l-s))/p,g=(3*(l-s)-(c+2*r)*h)/d,f=r,y=s,_=e-n,v=_*_,P=v*_;return m*P+g*v+f*_+y}};Ys([u(wi)],T1.prototype,"keys");let Ch=T1;var c2=Object.defineProperty,x=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&c2(e,t,n),n};const Lp=w("debugparticles");var es=(o=>(o[o.Billboard=0]="Billboard",o[o.Stretch=1]="Stretch",o[o.HorizontalBillboard=2]="HorizontalBillboard",o[o.VerticalBillboard=3]="VerticalBillboard",o[o.Mesh=4]="Mesh",o))(es||{});class aa{alphaKeys=[];colorKeys=[];get duration(){return 1}evaluate(e,t){let i,n=0,s=null,r=0;for(let a=0;a<this.alphaKeys.length;a++){const l=this.alphaKeys[a];(l.time<e||!i)&&(i=l,n=a)}for(let a=0;a<this.colorKeys.length;a++){const l=this.colorKeys[a];(l.time<e||!s)&&(s=l,r=a)}if(s)if(r+1<this.colorKeys.length){const a=this.colorKeys[r+1],l=D.remap(e,s.time,a.time,0,1);t.r=D.lerp(s.color.r,a.color.r,l),t.g=D.lerp(s.color.g,a.color.g,l),t.b=D.lerp(s.color.b,a.color.b,l)}else t.r=s.color.r,t.g=s.color.g,t.b=s.color.b;if(i)if(n+1<this.alphaKeys.length){const a=this.alphaKeys[n+1],l=D.remap(e,i.time,a.time,0,1);t.alpha=D.lerp(i.alpha,a.alpha,l)}else t.alpha=i.alpha;return t}}x([u()],aa.prototype,"alphaKeys"),x([u()],aa.prototype,"colorKeys");var Ph=(o=>(o[o.Local=0]="Local",o[o.World=1]="World",o[o.Custom=2]="Custom",o))(Ph||{}),jp=(o=>(o[o.Sphere=0]="Sphere",o[o.SphereShell=1]="SphereShell",o[o.Hemisphere=2]="Hemisphere",o[o.HemisphereShell=3]="HemisphereShell",o[o.Cone=4]="Cone",o[o.Box=5]="Box",o[o.Mesh=6]="Mesh",o[o.ConeShell=7]="ConeShell",o[o.ConeVolume=8]="ConeVolume",o[o.ConeVolumeShell=9]="ConeVolumeShell",o[o.Circle=10]="Circle",o[o.CircleEdge=11]="CircleEdge",o[o.SingleSidedEdge=12]="SingleSidedEdge",o[o.MeshRenderer=13]="MeshRenderer",o[o.SkinnedMeshRenderer=14]="SkinnedMeshRenderer",o[o.BoxShell=15]="BoxShell",o[o.BoxEdge=16]="BoxEdge",o[o.Donut=17]="Donut",o[o.Rectangle=18]="Rectangle",o[o.Sprite=19]="Sprite",o[o.SpriteRenderer=20]="SpriteRenderer",o))(jp||{});const ts=class bd{static constant(e){const t=new bd;return t.setConstant(e),t}static betweenTwoConstants(e,t){const i=new bd;return i.setMinMaxConstant(e,t),i}static curve(e,t=1){const i=new bd;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 bd;return e.mode=this.mode,e.constant=this.constant,e.constantMin=this.constantMin,e.constantMax=this.constantMax,e.curve=this.curve?.clone(),e.curveMin=this.curveMin?.clone(),e.curveMax=this.curveMax?.clone(),e.curveMultiplier=this.curveMultiplier,e}evaluate(e,t){const i=t===void 0?Math.random():t;switch(this.mode){case 0:case"Constant":return this.constant;case 1:case"Curve":return e=D.clamp01(e),this.curve.evaluate(e)*this.curveMultiplier;case 2:case"TwoCurves":const n=e*this.curveMin.duration,s=e*this.curveMax.duration;return D.lerp(this.curveMin.evaluate(n),this.curveMax.evaluate(s),i%1)*this.curveMultiplier;case 3:case"TwoConstants":return D.lerp(this.constantMin,this.constantMax,i%1);default:this.curveMax.evaluate(e)*this.curveMultiplier;break}return 0}getMax(){switch(this.mode){case 0:case"Constant":return this.constant;case 1:case"Curve":return this.getMaxFromCurve(this.curve)*this.curveMultiplier;case 2:case"TwoCurves":return Math.max(this.getMaxFromCurve(this.curveMin),this.getMaxFromCurve(this.curveMax))*this.curveMultiplier;case 3:case"TwoConstants":return Math.max(this.constantMin,this.constantMax);default:return 0}}getMaxFromCurve(e){if(!e)return 0;let t=Number.MIN_VALUE;for(let i=0;i<e.keys.length;i++){const n=e.keys[i];n.value>t&&(t=n.value)}return t}};x([u()],ts.prototype,"mode"),x([u()],ts.prototype,"constant"),x([u()],ts.prototype,"constantMin"),x([u()],ts.prototype,"constantMax"),x([u(Ch)],ts.prototype,"curve"),x([u(Ch)],ts.prototype,"curveMin"),x([u(Ch)],ts.prototype,"curveMax"),x([u()],ts.prototype,"curveMultiplier");let Y=ts;const Zs=class Lt{static constant(e){const t=new Lt;return t.constant(e),t}static betweenTwoColors(e,t){const i=new Lt;return i.betweenTwoColors(e,t),i}constant(e){return this.mode=0,this.color=e,this}betweenTwoColors(e,t){return this.mode=2,this.colorMin=e,this.colorMax=t,this}mode=0;color;colorMin;colorMax;gradient;gradientMin;gradientMax;static _temp=new se(0,0,0,1);static _temp2=new se(0,0,0,1);evaluate(e,t){const i=t===void 0?Math.random():t;switch(this.mode){case 0:case"Color":return this.color;case 1:case"Gradient":return this.gradient.evaluate(e,Lt._temp),Lt._temp;case 2:case"TwoColors":return Lt._temp.lerpColors(this.colorMin,this.colorMax,i);case 3:case"TwoGradients":return this.gradientMin.evaluate(e,Lt._temp),this.gradientMax.evaluate(e,Lt._temp2),Lt._temp.lerp(Lt._temp2,i);case 4:case"RandomColor":const n=Math.random();return this.gradientMin.evaluate(e,Lt._temp),this.gradientMax.evaluate(e,Lt._temp2),Lt._temp.lerp(Lt._temp2,n)}return Lt._temp.set(16777215),Lt._temp.alpha=1,Lt._temp}};x([u()],Zs.prototype,"mode"),x([u(se)],Zs.prototype,"color"),x([u(se)],Zs.prototype,"colorMin"),x([u(se)],Zs.prototype,"colorMax"),x([u(aa)],Zs.prototype,"gradient"),x([u(aa)],Zs.prototype,"gradientMin"),x([u(aa)],Zs.prototype,"gradientMax");let la=Zs;var m0=(o=>(o[o.Hierarchy=0]="Hierarchy",o[o.Local=1]="Local",o[o.Shape=2]="Shape",o))(m0||{});class Gt{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}x([u(Y)],Gt.prototype,"gravityModifier"),x([u(la)],Gt.prototype,"startColor"),x([u(Y)],Gt.prototype,"startDelay"),x([u(Y)],Gt.prototype,"startLifetime"),x([u(Y)],Gt.prototype,"startRotation"),x([u(Y)],Gt.prototype,"startRotationX"),x([u(Y)],Gt.prototype,"startRotationY"),x([u(Y)],Gt.prototype,"startRotationZ"),x([u(Y)],Gt.prototype,"startSize"),x([u(Y)],Gt.prototype,"startSizeX"),x([u(Y)],Gt.prototype,"startSizeY"),x([u(Y)],Gt.prototype,"startSizeZ"),x([u(Y)],Gt.prototype,"startSpeed");class Dp{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 is{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}}x([u()],is.prototype,"enabled"),x([u()],is.prototype,"bursts"),x([u(Y)],is.prototype,"rateOverTime"),x([u()],is.prototype,"rateOverTimeMultiplier"),x([u(Y)],is.prototype,"rateOverDistance"),x([u()],is.prototype,"rateOverDistanceMultiplier");class Bp{enabled;color}x([u(la)],Bp.prototype,"color");class ca{enabled;separateAxes;size;sizeMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;_time=0;_temp=new b;evaluate(e,t,i){if(t||(t=this._temp),!this.enabled)return t.x=t.y=t.z=1,t;if(this.separateAxes)t.x=this.x.evaluate(e,i)*this.xMultiplier,t.y=this.y.evaluate(e,i)*this.yMultiplier,t.z=this.z.evaluate(e,i)*this.zMultiplier;else{const n=this.size.evaluate(e,i)*this.sizeMultiplier;t.x=n}return t}}x([u(Y)],ca.prototype,"size"),x([u(Y)],ca.prototype,"x"),x([u(Y)],ca.prototype,"y"),x([u(Y)],ca.prototype,"z");const tt=class _d{get type(){return jp[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 _d}shapeType=5;enabled=!0;alignToDirection=!1;angle=0;arc=360;arcSpread;arcSpeedMultiplier;arcMode;boxThickness;position;rotation;_rotation=new at;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 J;_worldSpaceMatrixInverse=new J;constructor(){Lp&&console.log(this)}update(e,t){}onUpdate(e,t,i,n){this.system=e,this._space=i,i===1&&(this._worldSpaceMatrix.copy(n.matrixWorld),this._worldSpaceMatrix.elements[0]=1,this._worldSpaceMatrix.elements[5]=1,this._worldSpaceMatrix.elements[10]=1,this._worldSpaceMatrixInverse.copy(this._worldSpaceMatrix).invert())}applyRotation(e){const t=this.rotation.x!==0||this.rotation.y!==0||this.rotation.z!==0;return t&&(this._rotation.x=D.toRadians(this.rotation.x),this._rotation.y=D.toRadians(this.rotation.y),this._rotation.z=D.toRadians(this.rotation.z),this._rotation.order="ZYX",e.applyEuler(this._rotation)),t}_vector=new b(0,0,0);_temp=new b(0,0,0);_triangle=new QC;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:Lp&&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 s=this.meshRenderer;s?.destroyed==!1&&this.setMesh(s);const r=e.mesh=this._meshObj,a=e.mesh_geometry=this._meshGeometry;if(r&&a)switch(this.meshShapeType){case 0:{const l=a.getAttribute("position"),c=Math.floor(Math.random()*l.count);this._vector.fromBufferAttribute(l,c),this._vector.applyMatrix4(r.matrixWorld),e.mesh_normal=c}break;case 1:break;case 2:{const l=a.index;if(l){let c=Math.random(),h=Math.random();c+h>1&&(c=1-c,h=1-h);const d=Math.floor(Math.random()*(l.count/3));let p=d*3,m=d*3+1,g=d*3+2;p=l.getX(p),m=l.getX(m),g=l.getX(g);const f=a.getAttribute("position");this._triangle.a.fromBufferAttribute(f,p),this._triangle.b.fromBufferAttribute(f,m),this._triangle.c.fromBufferAttribute(f,g),this._vector.set(0,0,0).addScaledVector(this._triangle.a,c).addScaledVector(this._triangle.b,h).addScaledVector(this._triangle.c,1-(c+h)),this._vector.applyMatrix4(r.matrixWorld),e.mesh_normal=d}}break}break;default:this._vector.set(0,0,0),A()&&!globalThis.__particlesystem_shapetype_unsupported&&(console.warn("ParticleSystem ShapeType is not supported:",jp[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)),Lp&&B.DrawSphere(this._vector,.03,16711680,.5,!0)}_dir=new b;getDirection(e,t){if(!this.enabled)return this._dir.set(0,0,1),this._dir;switch(this.shapeType){case 5:this._dir.set(0,0,1);break;case 4:this._dir.set(0,0,1);break;case 10:case 0:const i=t.x,n=t.y,s=t.z;this._dir.set(i,n,s),this.system?.worldspace?this._dir.sub(this.system.worldPos):this._dir.sub(this.position);break;case 13:const r=e.mesh,a=e.mesh_geometry;if(r&&a)switch(this.meshShapeType){case 0:{const l=a.getAttribute("normal"),c=e.mesh_normal;this._dir.fromBufferAttribute(l,c)}break;case 1:break;case 2:{const l=a.index;if(l){const c=e.mesh_normal,h=l.getX(c*3),d=l.getX(c*3+1),p=l.getX(c*3+2),m=a.getAttribute("position"),g=F(),f=F(),y=F();g.fromBufferAttribute(m,h),f.fromBufferAttribute(m,d),y.fromBufferAttribute(m,p),g.sub(f),y.sub(f),g.cross(y),this._dir.copy(g).multiplyScalar(-1);const _=_e(r);this._dir.applyQuaternion(_)}}break}break;default:this._dir.set(0,0,1);break}return this._space===1&&this._dir.applyQuaternion(this.system.worldQuaternion),this.applyRotation(this._dir),this._dir.normalize(),this.spherizeDirection(this._dir,this.sphericalDirectionAmount),this.randomizeDirection(this._dir,this.randomDirectionAmount),Lp&&(B.DrawSphere(t,.01,8925952,.5,!0),B.DrawDirection(t,this._dir,8925952,.5,!0)),this._dir}static _randomQuat=new N;static _tempVec=new b;randomizePosition(e,t){if(t<=0)return;const i=_d._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=_d._randomQuat,n=_d._tempVec;n.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).normalize(),i.setFromAxisAngle(n,t*Math.random()*Math.PI),e.applyQuaternion(i)}spherizeDirection(e,t){if(t===0)return;const i=Math.random()*Math.PI*2,n=Math.acos(1-Math.random()*2),s=Math.sin(n)*Math.cos(i),r=Math.sin(n)*Math.sin(i),a=Math.cos(n),l=new b(s,r,a);e.lerp(l,t)}randomSpherePoint(e,t,i,n,s){const r=Math.random(),a=Math.random(),l=2*Math.PI*r*(n/360),c=Math.acos(2*a-1),h=D.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,d=e.x+this.scale.x*(-h*Math.sin(c)*Math.cos(l)),p=e.y+this.scale.y*(h*Math.sin(c)*Math.sin(l)),m=e.z+this.scale.z*(h*Math.cos(c));s.x=d,s.y=p,s.z=m}randomCirclePoint(e,t,i,n,s){const r=Math.random(),a=2*Math.PI*r*(n/360),l=D.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,c=e.x+this.scale.x*l*Math.cos(a),h=e.y+this.scale.y*l*Math.sin(a),d=e.z;s.x=c,s.y=h,s.z=d}_loopTime=0;_loopDirection=1;randomConePoint(e,t,i,n,s,r,a){let l=0,c=0;switch(r){case 0:l=Math.random(),c=Math.random();break;case 2:this._loopTime>1&&(this._loopDirection=-1),this._loopTime<0&&(this._loopDirection=1);case 1:l=.5,c=Math.random(),this._loopTime+=this.system.deltaTime*this._loopDirection;break}let h=2*Math.PI*l*(s/360);switch(r){case 2:case 1:h+=Math.PI+.5,h+=this._loopTime*Math.PI*2,h%=D.toRadians(s);break}const d=Math.acos(2*c-1),p=D.lerp(1,1-Math.pow(1-Math.random(),Math.PI),n)*i,m=e.x+-p*Math.sin(d)*Math.cos(h),g=e.y+p*Math.sin(d)*Math.sin(h),f=e.z;a.x=m*this.scale.x,a.y=g*this.scale.y,a.z=f*this.scale.z}};x([u()],tt.prototype,"shapeType"),x([u()],tt.prototype,"enabled"),x([u()],tt.prototype,"alignToDirection"),x([u()],tt.prototype,"angle"),x([u()],tt.prototype,"arc"),x([u()],tt.prototype,"arcSpread"),x([u()],tt.prototype,"arcSpeedMultiplier"),x([u()],tt.prototype,"arcMode"),x([u(b)],tt.prototype,"boxThickness"),x([u(b)],tt.prototype,"position"),x([u(b)],tt.prototype,"rotation"),x([u(b)],tt.prototype,"scale"),x([u()],tt.prototype,"radius"),x([u()],tt.prototype,"radiusThickness"),x([u()],tt.prototype,"sphericalDirectionAmount"),x([u()],tt.prototype,"randomDirectionAmount"),x([u()],tt.prototype,"randomPositionAmount"),x([u()],tt.prototype,"meshShapeType"),x([u(ah)],tt.prototype,"meshRenderer");let g0=tt;class ve{damping;enabled;frequency;octaveCount;octaveMultiplier;octaveScale;positionAmount;quality;remap;remapEnabled;remapMultiplier;remapX;remapXMultiplier;remapY;remapYMultiplier;remapZ;remapZMultiplier;scrollSpeedMultiplier;separateAxes;strengthMultiplier;strengthX;strengthXMultiplier;strengthY;strengthYMultiplier;strengthZ;strengthZMultiplier;_noise;_time=0;update(e){this._time+=e.time.deltaTime*this.scrollSpeedMultiplier}_temp=new b;apply(e,t,i,n,s,r){if(!this.enabled)return;this._noise||(this._noise=IP(()=>0));const a=this._temp.set(t.x,t.y,t.z).multiplyScalar(this.frequency),l=this._noise(a.x,a.y,a.z,this._time),c=this._noise(a.x,a.y,a.z,this._time+1e3*this.frequency),h=this._noise(a.x,a.y,a.z,this._time+2e3*this.frequency);this._temp.set(l,c,h).normalize();const d=s/r;let p=this.positionAmount.evaluate(d);this.separateAxes?(this._temp.x*=p*this.strengthXMultiplier,this._temp.y*=p*this.strengthYMultiplier,this._temp.z*=p*this.strengthZMultiplier):(this.strengthX&&(p*=this.strengthX.evaluate(d)*1.5),this._temp.multiplyScalar(p)),i.x+=this._temp.x,i.y+=this._temp.y,i.z+=this._temp.z}}x([u()],ve.prototype,"damping"),x([u()],ve.prototype,"enabled"),x([u()],ve.prototype,"frequency"),x([u()],ve.prototype,"octaveCount"),x([u()],ve.prototype,"octaveMultiplier"),x([u()],ve.prototype,"octaveScale"),x([u(Y)],ve.prototype,"positionAmount"),x([u()],ve.prototype,"quality"),x([u(Y)],ve.prototype,"remap"),x([u()],ve.prototype,"remapEnabled"),x([u()],ve.prototype,"remapMultiplier"),x([u(Y)],ve.prototype,"remapX"),x([u()],ve.prototype,"remapXMultiplier"),x([u(Y)],ve.prototype,"remapY"),x([u()],ve.prototype,"remapYMultiplier"),x([u(Y)],ve.prototype,"remapZ"),x([u()],ve.prototype,"remapZMultiplier"),x([u()],ve.prototype,"scrollSpeedMultiplier"),x([u()],ve.prototype,"separateAxes"),x([u()],ve.prototype,"strengthMultiplier"),x([u(Y)],ve.prototype,"strengthX"),x([u()],ve.prototype,"strengthXMultiplier"),x([u(Y)],ve.prototype,"strengthY"),x([u()],ve.prototype,"strengthYMultiplier"),x([u(Y)],ve.prototype,"strengthZ"),x([u()],ve.prototype,"strengthZMultiplier");class Fe{enabled;attachRibbonToTransform=!1;colorOverLifetime;colorOverTrail;dieWithParticles=!0;inheritParticleColor=!0;lifetime;lifetimeMultiplier;minVertexDistance=.2;mode=0;ratio=1;ribbonCount=1;shadowBias=0;sizeAffectsLifetime=!1;sizeAffectsWidth=!1;splitSubEmitterRibbons=!1;textureMode=0;widthOverTrail;widthOverTrailMultiplier;worldSpace=!1;getWidth(e,t,i,n){const s=this.widthOverTrail.evaluate(i,n);return e*=s,e}getColor(e,t,i){const n=this.colorOverTrail.evaluate(i),s=this.colorOverLifetime.evaluate(t);e.x*=n.r*s.r,e.y*=n.g*s.g,e.z*=n.b*s.b,"alpha"in n&&"alpha"in s&&(e.w*=n.alpha*s.alpha)}}x([u()],Fe.prototype,"enabled"),x([u()],Fe.prototype,"attachRibbonToTransform"),x([u(la)],Fe.prototype,"colorOverLifetime"),x([u(la)],Fe.prototype,"colorOverTrail"),x([u()],Fe.prototype,"dieWithParticles"),x([u()],Fe.prototype,"inheritParticleColor"),x([u(Y)],Fe.prototype,"lifetime"),x([u()],Fe.prototype,"lifetimeMultiplier"),x([u()],Fe.prototype,"minVertexDistance"),x([u()],Fe.prototype,"mode"),x([u()],Fe.prototype,"ratio"),x([u()],Fe.prototype,"ribbonCount"),x([u()],Fe.prototype,"shadowBias"),x([u()],Fe.prototype,"sizeAffectsLifetime"),x([u()],Fe.prototype,"sizeAffectsWidth"),x([u()],Fe.prototype,"splitSubEmitterRibbons"),x([u()],Fe.prototype,"textureMode"),x([u(Y)],Fe.prototype,"widthOverTrail"),x([u()],Fe.prototype,"widthOverTrailMultiplier"),x([u()],Fe.prototype,"worldSpace");class He{enabled;space=0;orbitalX;orbitalY;orbitalZ;orbitalXMultiplier;orbitalYMultiplier;orbitalZMultiplier;orbitalOffsetX;orbitalOffsetY;orbitalOffsetZ;speedModifier;speedModifierMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;_system;update(e){this._system=e}_temp=new b;_temp2=new b;_temp3=new b;_hasOrbital=!1;_index=0;_orbitalMatrix=new J;init(e){this._index==0&&(e.debug=!0),this._index+=1,e.orbitx=this.orbitalX.evaluate(Math.random()),e.orbity=this.orbitalY.evaluate(Math.random()),e.orbitz=this.orbitalZ.evaluate(Math.random()),this._hasOrbital=e.orbitx!=0||e.orbity!=0||e.orbitz!=0}apply(e,t,i,n,s,r,a){if(!this.enabled)return;const l=r/a,c=this.speedModifier.evaluate(l)*this.speedModifierMultiplier,h=this.x.evaluate(l),d=this.y.evaluate(l),p=this.z.evaluate(l);if(this._temp.set(-h,d,p),this._system&&this._system.main.simulationSpace===1&&this._temp.applyQuaternion(this._system.worldQuaternion),this._hasOrbital&&this._system?.worldPos){const m=this._temp2.set(i.x,i.y,i.z),g=this.orbitalXMultiplier,f=this.orbitalYMultiplier,y=this.orbitalZMultiplier,_=c*Math.PI*2*10,v=Math.cos(_*g),P=Math.sin(_*g),k=Math.cos(_*f),O=Math.sin(_*f),j=Math.cos(_*y),L=Math.sin(_*y),V=m.x*(k*j)+m.y*(k*L)+m.z*-O,W=m.x*(P*O*j-v*L)+m.y*(P*O*L+v*j)+m.z*(P*k),G=m.x*(v*O*j+P*L)+m.y*(v*O*L-P*j)+m.z*(v*k),X=this._temp3.set(m.x-V,m.y-W,m.z-G);X.normalize(),X.multiplyScalar(.2/s*Math.max(this.orbitalXMultiplier,this.orbitalYMultiplier,this.orbitalZMultiplier)),n.x+=X.x,n.y+=X.y,n.z+=X.z}n.x+=this._temp.x,n.y+=this._temp.y,n.z+=this._temp.z,n.x*=c,n.y*=c,n.z*=c}}x([u()],He.prototype,"enabled"),x([u()],He.prototype,"space"),x([u(Y)],He.prototype,"orbitalX"),x([u(Y)],He.prototype,"orbitalY"),x([u(Y)],He.prototype,"orbitalZ"),x([u()],He.prototype,"orbitalXMultiplier"),x([u()],He.prototype,"orbitalYMultiplier"),x([u()],He.prototype,"orbitalZMultiplier"),x([u()],He.prototype,"orbitalOffsetX"),x([u()],He.prototype,"orbitalOffsetY"),x([u()],He.prototype,"orbitalOffsetZ"),x([u(Y)],He.prototype,"speedModifier"),x([u()],He.prototype,"speedModifierMultiplier"),x([u(Y)],He.prototype,"x"),x([u()],He.prototype,"xMultiplier"),x([u(Y)],He.prototype,"y"),x([u()],He.prototype,"yMultiplier"),x([u(Y)],He.prototype,"z"),x([u()],He.prototype,"zMultiplier");class qt{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}}x([u()],qt.prototype,"animation"),x([u()],qt.prototype,"enabled"),x([u()],qt.prototype,"cycleCount"),x([u(Y)],qt.prototype,"frameOverTime"),x([u()],qt.prototype,"frameOverTimeMultiplier"),x([u()],qt.prototype,"numTilesX"),x([u()],qt.prototype,"numTilesY"),x([u(Y)],qt.prototype,"startFrame"),x([u()],qt.prototype,"startFrameMultiplier"),x([u()],qt.prototype,"rowMode"),x([u()],qt.prototype,"rowIndex"),x([u()],qt.prototype,"spriteCount"),x([u()],qt.prototype,"timeMode");class jn{enabled;separateAxes;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t){return this.enabled?this.separateAxes?0:this.z.evaluate(e,t)*-1:0}}x([u()],jn.prototype,"enabled"),x([u()],jn.prototype,"separateAxes"),x([u(Y)],jn.prototype,"x"),x([u()],jn.prototype,"xMultiplier"),x([u(Y)],jn.prototype,"y"),x([u()],jn.prototype,"yMultiplier"),x([u(Y)],jn.prototype,"z"),x([u()],jn.prototype,"zMultiplier");class an{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}}x([u()],an.prototype,"enabled"),x([u()],an.prototype,"range"),x([u()],an.prototype,"separateAxes"),x([u(Y)],an.prototype,"x"),x([u()],an.prototype,"xMultiplier"),x([u(Y)],an.prototype,"y"),x([u()],an.prototype,"yMultiplier"),x([u(Y)],an.prototype,"z"),x([u()],an.prototype,"zMultiplier");class dt{enabled;dampen;drag;dragMultiplier;limit;limitMultiplier;separateAxes;limitX;limitXMultiplier;limitY;limitYMultiplier;limitZ;limitZMultiplier;multiplyDragByParticleSize=!1;multiplyDragByParticleVelocity=!1;space;_temp=new b;_temp2=new b;apply(e,t,i,n,s,r,a){if(this.enabled){const l=this.limit.evaluate(s)*this.limitMultiplier;if(t.length()>l){this._temp.copy(t).normalize().multiplyScalar(l);const c=this.dampen*.5;t.x=D.lerp(t.x,this._temp.x,c),t.y=D.lerp(t.y,this._temp.y,c),t.z=D.lerp(t.z,this._temp.z,c),i.x=D.lerp(i.x,this._temp.x,c),i.y=D.lerp(i.y,this._temp.y,c),i.z=D.lerp(i.z,this._temp.z,c)}}}}x([u()],dt.prototype,"enabled"),x([u()],dt.prototype,"dampen"),x([u(Y)],dt.prototype,"drag"),x([u()],dt.prototype,"dragMultiplier"),x([u(Y)],dt.prototype,"limit"),x([u()],dt.prototype,"limitMultiplier"),x([u()],dt.prototype,"separateAxes"),x([u(Y)],dt.prototype,"limitX"),x([u()],dt.prototype,"limitXMultiplier"),x([u(Y)],dt.prototype,"limitY"),x([u()],dt.prototype,"limitYMultiplier"),x([u(Y)],dt.prototype,"limitZ"),x([u()],dt.prototype,"limitZMultiplier"),x([u()],dt.prototype,"multiplyDragByParticleSize"),x([u()],dt.prototype,"multiplyDragByParticleVelocity"),x([u()],dt.prototype,"space");const Oh=class WS{enabled;curve;curveMultiplier;mode;clone(){const e=new WS;return e.enabled=this.enabled,e.curve=this.curve?.clone(),e.curveMultiplier=this.curveMultiplier,e.mode=this.mode,e}system;get _lastWorldPosition(){return this.system._iv_lastWorldPosition||(this.system._iv_lastWorldPosition=new b),this.system._iv_lastWorldPosition}get _velocity(){return this.system._iv_velocity||(this.system._iv_velocity=new b),this.system._iv_velocity}_temp=new b;_firstUpdate=!0;awake(e){this.system=e,this.reset()}reset(){this._firstUpdate=!0}update(e){this.enabled&&this.system.worldspace!==!1&&(this._firstUpdate?(this._firstUpdate=!1,this._velocity.set(0,0,0),this._lastWorldPosition.copy(this.system.worldPos)):this._lastWorldPosition&&(this._velocity.copy(this.system.worldPos).sub(this._lastWorldPosition).multiplyScalar(1/this.system.deltaTime),this._lastWorldPosition.copy(this.system.worldPos)))}applyInitial(e){if(this.enabled&&this.system.worldspace!==!1&&this.mode===0){const t=this.curve.evaluate(Math.random(),Math.random());this._temp.copy(this._velocity).multiplyScalar(t),e.x+=this._temp.x,e.y+=this._temp.y,e.z+=this._temp.z}}_frames=0;applyCurrent(e,t,i){if(this.enabled&&this.system&&this.system.worldspace!==!1&&this.mode===1){const n=this.curve.evaluate(t,i);this._temp.copy(this._velocity).multiplyScalar(n),e.x+=this._temp.x,e.y+=this._temp.y,e.z+=this._temp.z}}};x([u()],Oh.prototype,"enabled"),x([u(Y)],Oh.prototype,"curve"),x([u()],Oh.prototype,"curveMultiplier"),x([u()],Oh.prototype,"mode");let f0=Oh;class xi{enabled;range;separateAxes;size;sizeMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t,i,n){const s=e.length(),r=D.remap(s,this.range.x,this.range.y,0,1),a=this.size.evaluate(r,i);return n.x*=a,n.y*=a,n.z*=a,n}}x([u()],xi.prototype,"enabled"),x([u(K)],xi.prototype,"range"),x([u()],xi.prototype,"separateAxes"),x([u(Y)],xi.prototype,"size"),x([u()],xi.prototype,"sizeMultiplier"),x([u(Y)],xi.prototype,"x"),x([u()],xi.prototype,"xMultiplier"),x([u(Y)],xi.prototype,"y"),x([u()],xi.prototype,"yMultiplier"),x([u(Y)],xi.prototype,"z"),x([u()],xi.prototype,"zMultiplier");class zl{enabled;range;color;evaluate(e,t,i){const n=e.length(),s=D.remap(n,this.range.x,this.range.y,0,1),r=this.color.evaluate(s,t);i.x*=r.r,i.y*=r.g,i.z*=r.b,"alpha"in r&&(i.w*=r.alpha)}}x([u()],zl.prototype,"enabled"),x([u(K)],zl.prototype,"range"),x([u(la)],zl.prototype,"color"),new b(1,1,1),new b(0,0,1);class y0{constructor(e,t,i,n){this.system=e,this.particleSystem=t,this.subSystem=i,this.subParticleSystem=n,this.subParticleSystem&&this.subParticleSystem&&(this.subParticleSystem.onlyUsedByOther=!0);const s=1e3;this._circularBuffer=new Ei(()=>new Vm,s)}type="NeedleParticleSubEmitter";emitterType;emitterProbability;q_=new N;v_=new b;v2_=new b;_emitterMatrix=new Vm;_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===b0.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===b0.Death){let n=e.life;if(e[Nl]!==void 0&&(n=e[Nl]),!(e.age+t*1.2>=n))return;const s=this.subSystem.main.maxParticles-this.subSystem.currentParticles;e.emissionState.waitEmiting=s}const i=new Vm;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 h2=Object.defineProperty,Ue=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&h2(e,t,n),n};const Ks=w("debugparticles"),d2=w("noprogressive"),u2=w("debugprogressive");var b0=(o=>(o[o.Birth=0]="Birth",o[o.Collision=1]="Collision",o[o.Death=2]="Death",o[o.Trigger=3]="Trigger",o[o.Manual=4]="Manual",o))(b0||{});class ln extends E{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"){Ks&&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=Oo,t.map.premultiplyAlpha=!1);const i=new Ce;i.copy(t),e?this.trailMaterial=i:this.particleMaterial=i}t.map&&(t.map.colorSpace=Oo,t.map.premultiplyAlpha=!1),e&&t.side===ws&&(t=t.clone(),t.side=Id,e?this.trailMaterial=t:this.particleMaterial=t)}return t&&!d2&&t._didRequestTextureLOD===void 0&&(t._didRequestTextureLOD=0,u2&&console.log("Load material LOD",t.name),Ve.assignTextureLOD(t,0)),t}getMesh(e){let t=null;if(!t&&(this.particleMesh instanceof H&&(t=this.particleMesh.geometry),t===null)){t=new vn(1,1);const i=t.attributes.uv;for(let n=0;n<i.count;n++)i.setX(n,1-i.getX(n))}return new H(t,this.getMaterial())}}Ue([u()],ln.prototype,"renderMode"),Ue([u(we)],ln.prototype,"particleMaterial"),Ue([u(we)],ln.prototype,"trailMaterial"),Ue([u()],ln.prototype,"maxParticleSize"),Ue([u()],ln.prototype,"minParticleSize"),Ue([u()],ln.prototype,"velocityScale"),Ue([u()],ln.prototype,"cameraVelocityScale"),Ue([u()],ln.prototype,"lengthScale");class Fp{_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 _0{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 p2 extends _0{genValue(){return this.system.textureSheetAnimation.getStartIndex()}}class m2 extends _0{_lastPosition=new b;_lastDistance=0;update(){const e=ee(this.system.gameObject);this._lastDistance=this._lastPosition.distanceTo(e),this._lastPosition.copy(e)}genValue(){if(!this.system.isPlaying||!this.system.emission.enabled||this.system.currentParticles>=this.system.maxParticles)return 0;let e=this.system.emission.rateOverTime.evaluate(this.system.time/this.system.duration,Math.random());if(this.system.deltaTime>0){const n=this.system.emission.rateOverDistance.evaluate(this.system.time/this.system.duration,Math.random());let s=this._lastDistance/this.system.deltaTime*n;Number.isFinite(s)||(s=0),e+=s}const t=this.system.emission.getBurst();t>0&&(e+=t/this.system.deltaTime);const i=this.system.maxParticles-this.system.currentParticles;return D.clamp(e,0,i/this.system.deltaTime)}}class g2 extends _0{genValue(){return this.system.isPlaying,0}}class Js{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 f2 extends Js{type="NeedleTextureSheet";update(e,t){const i=this.system.textureSheetAnimation;if(i.enabled){const n=e.age/e.life,s=i.evaluate(n);s!==void 0&&(e.uvTile=s)}}}const A1=Symbol("particleRotation");class y2 extends Js{type="NeedleRotation";initialize(e){e[A1]=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[A1])*t:this.system.renderer.renderMode===es.Billboard&&(e.rotation=Math.PI),this.system.rotationBySpeed.enabled)){const n=e.velocity.length();e.rotation+=this.system.rotationBySpeed.evaluate(i,n)*t}}}const I1=Symbol("sizeLerpFactor"),b2=new b;class _2 extends Js{type="NeedleSize";_minSize=0;_maxSize=1;initialize(e){e[I1]=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[I1]).x);let s=1;this.system.renderer.renderMode!==es.Mesh&&(s=this.system.worldScale.x/this.system.cameraScale);const r=F(e.startSize).multiplyScalar(n*s);if(e.size.set(r.x,r.y,r.z),this.system.localspace){const a=F1(this.system,b2);e.size.x*=a.x,e.size.y*=a.y,e.size.z*=a.z}}}const Nl=Symbol("particleLife"),v0=Symbol("trailLifetime"),L1=Symbol("trailStartLength"),w0=Symbol("trailWidthRandom");class v2 extends Js{type="NeedleTrail";initialize(e){e instanceof $b&&(e[Nl]=e.life,this.system.trails.enabled&&this.system.trails.dieWithParticles===!1&&(e[v0]=this.system.trails.lifetime.evaluate(Math.random(),Math.random()),e.life+=e[v0]),e[L1]=e.length,e[w0]=Math.random())}update(e){if(this.system.trails?.enabled&&e instanceof $b){const t=e,i=e.age/e[Nl],n=e.previous.values(),s=e.previous.length;for(let r=0;r<s;r++){const a=n.next().value,l=1-r/(s-1),c=e.size;if(c.x<=0&&!this.system.trails.sizeAffectsWidth){const h=20*this.system.trails.widthOverTrail.evaluate(.5,t[w0]);c.x=h,c.y=h,c.z=h}a.size=this.system.trails.getWidth(c.x,i,l,t[w0]),a.color.copy(e.color),this.system.trails.getColor(a.color,i,l)}if(e.age>e[Nl]){e.velocity.set(0,0,0);const r=(e.age-e[Nl])/e[v0];t.length=D.lerp(e[L1],0,r)}}}}const Up=Symbol("startVelocity"),j1=Symbol("gravityModifier"),x0=Symbol("gravitySpeed"),zp=Symbol("velocity lerp factor"),S0=new b;class w2 extends Js{type="NeedleVelocity";_gravityDirection=new b;initialize(e){const t=this.system.main.simulationSpeed;e.startSpeed=this.system.main.startSpeed.evaluate(Math.random(),Math.random());const i=this.system.shape.getDirection(e,e.position);e.velocity.x=i.x*e.startSpeed,e.velocity.y=i.y*e.startSpeed,e.velocity.z=i.z*e.startSpeed,this.system.inheritVelocity?.enabled&&this.system.inheritVelocity.applyInitial(e.velocity),e[Up]?e[Up].copy(e.velocity):e[Up]=e.velocity.clone();const n=this.system.main.gravityModifier.evaluate(Math.random(),Math.random());e[j1]=n*t,e[x0]=n*t*.5,e[zp]=Math.random(),this.system.velocityOverLifetime?.init(e),this._gravityDirection.set(0,-1,0),this.system.main.simulationSpace===Ph.Local&&this._gravityDirection.applyQuaternion(this.system.worldQuaternionInverted).normalize()}update(e,t){const i=e[Up],n=e[j1];if(n!==0){const d=n*e[x0];S0.copy(this._gravityDirection).multiplyScalar(d),e[x0]+=t*.05,i.add(S0)}e.velocity.copy(i);const s=e.age/e.life;this.system.inheritVelocity?.enabled&&this.system.inheritVelocity.applyCurrent(e.velocity,s,e[zp]);const r=this.system.noise;r.enabled&&r.apply(0,e.position,e.velocity,t,e.age,e.life);const a=this.system.sizeBySpeed;a?.enabled&&(e.size=a.evaluate(e.velocity,s,e[zp],e.size));const l=this.system.colorBySpeed;l?.enabled&&l.evaluate(e.velocity,e[zp],e.color);const c=this.system.velocityOverLifetime;c.enabled&&c.apply(e,0,e.position,e.velocity,t,e.age,e.life);const h=this.system.limitVelocityOverLifetime;if(h.enabled&&h.apply(e.position,i,e.velocity,e.size,s,t,1),this.system.worldspace){const d=this.system.worldScale;e.velocity.x*=d.x,e.velocity.y*=d.y,e.velocity.z*=d.z}}}const D1=Symbol("colorLerpFactor"),B1=new se(1,1,1,1),ha=new se(1,1,1,1);class x2 extends Js{type="NeedleColor";initialize(e){}_init(e){const t=this.system.renderer.particleMaterial;ha.copy(this.system.main.startColor.evaluate(Math.random())),t?.color&&(B1.copy(t.color),ha.multiply(B1)),ha.convertLinearToSRGB(),e.startColor.set(ha.r,ha.g,ha.b,ha.alpha),e.color.copy(e.startColor),e[D1]=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[D1]);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 S2{system;emission;get anim(){return this.system.textureSheetAnimation}constructor(e){this.system=e,this.emission=new m2(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 Fp(this.system.main.startLifetime)}get startSpeed(){return new Fp(this.system.main.startSpeed)}get startRotation(){return new Fp(this.system.main.startRotation)}get startSize(){return new Fp(this.system.main.startSize)}startLength;get startColor(){return new DP(new BP(1,1,1,1))}get emissionOverTime(){return this.emission}get emissionOverDistance(){return new g2(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 Ro.Trail;switch(this.system.renderer.renderMode){case es.Billboard:return Ro.BillBoard;case es.Stretch:return Ro.StretchedBillBoard;case es.HorizontalBillboard:return Ro.HorizontalBillBoard;case es.VerticalBillboard:return Ro.VerticalBillBoard;case es.Mesh:return Ro.Mesh}return Ro.BillBoard}rendererEmitterSettings={startLength:new FP(220),followLocalOrigin:!1};get speedFactor(){let e=this.system.main.simulationSpeed;return this.system.renderer?.renderMode===es.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=Oo,this.clonedTexture.original=t,this.clonedTexture.clone=i}return this.clonedTexture.clone}return this.flatWhiteTexture||(this.flatWhiteTexture=ff(new se(1,1,1,1),1)),this.flatWhiteTexture}get startTileIndex(){return new p2(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??YC}get transparent(){return this.system.renderer.transparent}get worldSpace(){return this.system.main.simulationSpace===Ph.World}}class C2{burstParticleIndex=0;burstParticleCount=0;isBursting=!1;travelDistance=0;previousWorldPos;burstIndex=0;burstWaveIndex=0;time=0;waitEmiting=0}const Xt=class vm extends E{play(e=!1){e&&S.foreachComponent(this.gameObject,t=>{t instanceof vm&&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 vm&&t!==this&&t.pause(!1)},!0),this._isPlaying=!1}stop(e=!0,t=!1){e&&S.foreachComponent(this.gameObject,i=>{i instanceof vm&&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 C2),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===Ph.World}get localspace(){return this.main.simulationSpace===Ph.Local}__worldQuaternion=new N;get worldQuaternion(){return this.__worldQuaternion}_worldQuaternionInverted=new N;get worldQuaternionInverted(){return this._worldQuaternionInverted}_worldScale=new b;get worldScale(){return this._worldScale}_worldPositionFrame=-1;_worldPos=new b;get worldPos(){return this._worldPositionFrame!==this.context.time.frame&&(this._worldPositionFrame=this.context.time.frame,ee(this.gameObject,this._worldPos)),this._worldPos}get matrixWorld(){return this._container.matrixWorld}get isSubsystem(){return this._isUsedAsSubsystem}addBehaviour(e){return this._particleSystem?(e instanceof Js&&(e.system=this),Ks&&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()||Ks)&&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 Dp)){const n=new Dp;Ja(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 Np)){const n=new Np;Ja(n,i),e[t]=n}}Ks&&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(ln),!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 M,this._container.matrixAutoUpdate=!1,this.context.scene.add(this._container),this._batchSystem=new LP,this._batchSystem.name=this.gameObject.name,this._container.add(this._batchSystem),this._interface=new S2(this),this._particleSystem=new jP(this._interface),this._particleSystem.addBehavior(new _2(this)),this._particleSystem.addBehavior(new x2(this)),this._particleSystem.addBehavior(new f2(this)),this._particleSystem.addBehavior(new y2(this)),this._particleSystem.addBehavior(new w2(this)),this._particleSystem.addBehavior(new v2(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),Ks&&(console.log(this),this.gameObject.add(new Pi(1)))}start(){this.addSubParticleSystems(),this.updateLayers(),this.renderer.particleMesh instanceof H&&this._interface.renderMode==Ro.Mesh&&Ve.assignMeshLOD(this.renderer.particleMesh,0).then(e=>{e&&this.particleSystem&&this._interface.renderMode==Ro.Mesh&&(this.particleSystem.instancingGeometry=e)})}onDestroy(){this._container?.removeFromParent(),this._batchSystem?.removeFromParent(),this._particleSystem?.emitter.removeFromParent(),this._particleSystem?.dispose()}onEnable(){this.main&&(this.inheritVelocity&&(this.inheritVelocity.system=this),this._batchSystem&&(this._batchSystem.visible=!0),this.playOnAwake&&this.play(),this._isPlaying=this.playOnAwake)}onDisable(){this._batchSystem&&(this._batchSystem.visible=!1)}onBeforeRender(){this.main&&(this._didPreWarm===!1&&this.main?.prewarm===!0&&(this._didPreWarm=!0,this.preWarm()),this.onUpdate(),this.onSimulate(this.deltaTime))}preWarm(){if(!this.emission?.enabled||this.emission.rateOverTime.getMax()<=0)return;const e=1/60,t=this.main.duration,i=this.main.startLifetime.getMax(),n=Math.min(Math.max(t,i)/Math.max(.01,this.main.simulationSpeed),1e3),s=Math.ceil(n/e),r=Date.now();Ks&&console.log(`Particles ${this.name} - Prewarm for ${s} frames (${n} sec). Duration: ${t}, Lifetime: ${i}`);for(let a=0;a<s&&!(this.currentParticles>=this.maxParticles);a++){const l=Date.now()-r;if(l>2e3){console.warn(`Particles ${this.name} - Prewarm took too long. Aborting: ${l}`);break}this.onUpdate(),this.onSimulate(e)}}_lastBatchesCount=-1;onSimulate(e){if(this._batchSystem){let t=this.context.time.frameCount%60===0;this._lastBatchesCount!==this._batchSystem.batches.length&&(this._lastBatchesCount=this._batchSystem.batches.length,t=!0),t&&this.updateLayers(),this._batchSystem.update(e)}this._time+=e,this._time>this.duration&&(this._time=0)}updateLayers(){if(this._batchSystem)for(let e=0;e<this._batchSystem.batches.length;e++){const t=this._batchSystem.batches[e];t.layers.disableAll();const i=this.layer;t.layers.mask=1<<i}}onUpdate(){if(this._bursts&&(this.emission.bursts=this._bursts,delete this._bursts),!this._isPlaying)return;const e=this.context.mainCamera;if(e){const n=$e(e);this._cameraScale=n.x}const t=!this.worldspace,i=this.gameObject;if(_e(i,this.__worldQuaternion),this._worldQuaternionInverted.copy(this.__worldQuaternion).invert(),$e(this.gameObject,this._worldScale),t&&this._container&&this.gameObject?.parent){const n=F1(this,S0);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 y0(this,this._particleSystem,e.particleSystem,t);i.emitterType=e.type,i.emitterProbability=e.emitProbability,this._particleSystem.addBehavior(i)}else Ks&&console.warn("Could not add SubParticleSystem",e,this)}}};Ue([u(Bp)],Xt.prototype,"colorOverLifetime"),Ue([u(Gt)],Xt.prototype,"main"),Ue([u(is)],Xt.prototype,"emission"),Ue([u(ca)],Xt.prototype,"sizeOverLifetime"),Ue([u(g0)],Xt.prototype,"shape"),Ue([u(ve)],Xt.prototype,"noise"),Ue([u(Fe)],Xt.prototype,"trails"),Ue([u(He)],Xt.prototype,"velocityOverLifetime"),Ue([u(dt)],Xt.prototype,"limitVelocityOverLifetime"),Ue([u(f0)],Xt.prototype,"inheritVelocity"),Ue([u(zl)],Xt.prototype,"colorBySpeed"),Ue([u(qt)],Xt.prototype,"textureSheetAnimation"),Ue([u(jn)],Xt.prototype,"rotationOverLifetime"),Ue([u(an)],Xt.prototype,"rotationBySpeed"),Ue([u(xi)],Xt.prototype,"sizeBySpeed");let kh=Xt;class Np{particleSystem;emitProbability=1;properties;type;_deserialize(e,t){const i=this.particleSystem;if(i instanceof kh)return;let n="";i&&typeof i.guid=="string"&&(n=i.guid,this.particleSystem=S.findByGuid(n,t)),Ks&&!(this.particleSystem instanceof kh)&&console.warn("Could not find particle system for sub emitter",n,t,this)}}function F1(o,e){if(e.set(1,1,1),o.gameObject.parent&&o.localspace)switch(o.main.scalingMode){case m0.Local:e=$e(o.gameObject.parent,e),e.x=1/e.x,e.y=1/e.y,e.z=1/e.z;break;default:if(!o.unsupported_scaling_mode){o.unsupported_scaling_mode=!0;const t="ParticleSystem scale mode "+m0[o.main.scalingMode]+" is not supported";A()&&be(t),console.warn(t,o.name,o)}e=$e(o.gameObject,e);break}return e}var P2=Object.defineProperty,C0=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&P2(e,t,n),n};class Wl extends E{strength=1;radius=2;targets=[];update(){const e=this.gameObject.worldPosition,t=-this.strength*this.context.time.deltaTime;this.targets?.forEach(i=>{if(!i)return;const n=i.gameObject.worldPosition.sub(e),s=n.length();if(s>this.radius)return;let r=t;s>1?r/=s*s:r/=Math.max(.05,s),i.applyImpulse(n.multiplyScalar(r))})}}C0([u()],Wl.prototype,"strength"),C0([u()],Wl.prototype,"radius"),C0([u(Ke)],Wl.prototype,"targets");class rc extends E{_didAssignPlayerColor=!1;onEnable(){this.context.connection.beginListen(ie.JoinedRoom,this.tryAssignColor),this._didAssignPlayerColor||this.startCoroutine(this.waitForConnection())}onDisable(){this.context.connection.stopListen(ie.JoinedRoom,this.tryAssignColor)}*waitForConnection(){for(;!this.destroyed&&this.activeAndEnabled&&(yield mf(.2),!this.tryAssignColor()););}tryAssignColor=()=>{const e=S.getComponentInParent(this.gameObject,sn);if(e&&e.owner)return this._didAssignPlayerColor=!0,this.assignUserColor(e.owner),!0;const t=S.getComponentInParent(this.gameObject,Le);return t?.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(t.connectionId),!0):!1};assignUserColor(e){const t=rc.hashCode(e),i=rc.colorFromHashCode(t);if(this.gameObject.type==="Mesh"){const n=this.gameObject;this.assignColor(i,e,n)}else if(this.gameObject.children)for(const n of this.gameObject.children){const s=n;s.material&&s.material.color&&this.assignColor(i,e,s)}}assignColor(e,t,i){let n=i.material;n&&(n._playerMaterial!==t&&(n=n.clone(),n._playerMaterial=t,i.material=n),n.color=e)}static hashCode(e){var t=0,i,n;if(e.length===0)return t;for(i=0;i<e.length;i++)n=e.charCodeAt(i),t=(t<<5)-t+n,t|=0;return t}static colorFromHashCode(e){const t=(e&16711680)>>16,i=(e&65280)>>8,n=e&255;return new oe(t/255,i/255,n/255)}}const Mh=w("debugpost");let P0=null;function O2(o){P0=o}function U1(o){let e=o.gameObject;for(;e;){for(const t of wu(e))if(t.isPostProcessingManager===!0)return t;e=e.parent}return null}function k2(o){let e=U1(o);if(!e)if(P0){Mh&&console.warn("Adding postprocessing manager to the scene.");const t=o.scene;e=Mn(t,P0)}else A()&&console.warn("No post processing manager found");return e}const ut={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 it=null;function M2(o){Mh==="verbose"&&console.debug("Before ordering effects",[...o]),it||(it=new Map,it.set(T.POSTPROCESSING.MODULE.NormalPass,ut.NormalPass),it.set(T.POSTPROCESSING.MODULE.DepthDownsamplingPass,ut.DepthDownsamplingPass),it.set(T.POSTPROCESSING.MODULE.SMAAEffect,ut.SMAA),it.set(T.POSTPROCESSING.MODULE.SSAOEffect,ut.SSAO),it.set(T.POSTPROCESSING_AO.MODULE.N8AOPostPass,ut.SSAO),it.set(T.POSTPROCESSING_AO.MODULE.N8AOPass,ut.SSAO),it.set(T.POSTPROCESSING.MODULE.TiltShiftEffect,ut.TiltShift),it.set(T.POSTPROCESSING.MODULE.DepthOfFieldEffect,ut.DepthOfField),it.set(T.POSTPROCESSING.MODULE.ChromaticAberrationEffect,ut.ChromaticAberration),it.set(T.POSTPROCESSING.MODULE.BloomEffect,ut.Bloom),it.set(T.POSTPROCESSING.MODULE.SelectiveBloomEffect,ut.Bloom),it.set(T.POSTPROCESSING.MODULE.VignetteEffect,ut.Vignette),it.set(T.POSTPROCESSING.MODULE.PixelationEffect,ut.Pixelation),it.set(T.POSTPROCESSING.MODULE.ToneMappingEffect,ut.ToneMapping),it.set(T.POSTPROCESSING.MODULE.HueSaturationEffect,ut.HueSaturation),it.set(T.POSTPROCESSING.MODULE.BrightnessContrastEffect,ut.BrightnessContrast)),o.sort((e,t)=>{const i=typeof e.priority=="number"?e.priority:it.get(e.effect.constructor)??Number.NEGATIVE_INFINITY,n=typeof t.priority=="number"?t.priority:it.get(t.effect.constructor)??Number.NEGATIVE_INFINITY;return i===Number.NEGATIVE_INFINITY?(Mh&&console.warn("Unknown effect found: ",e.constructor.name,e),1):n===Number.NEGATIVE_INFINITY?(Mh&&console.warn("Unknown effect found: ",t.constructor.name,t),-1):i-n}),Mh==="verbose"&&console.debug("After ordering effects",[...o])}var E2=Object.defineProperty,R2=Object.getOwnPropertyDescriptor,z1=(o,e,t,i)=>{for(var n=R2(e,t),s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&E2(e,t,n),n};const T2=w("debugpost");class z{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;T2&&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}}z1([u()],z.prototype,"overrideState"),z1([u()],z.prototype,"value");class A2 extends Zi{constructor(){super([z])}onSerialize(e,t){}onDeserialize(e,t){const i=t.target,n=t.path;let s;if(i&&n&&(s=i[n]),(typeof s!="object"||typeof s=="object"&&s.isVolumeParameter!==!0)&&(s=new z),typeof e=="object"&&"value"in e){const r=e.value;s.initialize(r),s.overrideState=e.overrideState}else s.value=e;return s}}new A2;var I2=Object.defineProperty,L2=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&I2(e,t,n),n};const O0=w("debugpost");class nt extends E{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 z?n.initialize(i):n!==void 0&&(this[t]=i)}}active=!0;_manager=null;onEnable(){super.onEnable(),O0&&console.warn("Enable",this.constructor.name+(this.__internalDidAwakeAndStart?"":" (awake)")),this.__internalDidAwakeAndStart&&(this.active=!0),this.onEffectEnabled()}onDisable(){super.onDisable(),O0&&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=k2(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(){O0&&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 z&&i.__init()}}onEditorModification(e){const t=e.propertyName;if(this[t]instanceof z){const i=e.value;return this[t].value=i,!0}}}L2([u()],nt.prototype,"active");var j2=Object.defineProperty,D2=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&j2(e,t,n),n};const B2=w("debugpost"),k0={};function cn(o,e){k0[o]=e}function F2(o){return o.__type in k0?k0[o.__type]:(B2&&o.__type&&console.warn("Unknown postprocessing type",o.__type,o),nt)}class Wp{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)}}D2([Ye([o=>F2(o),nt])],Wp.prototype,"components");var U2=Object.defineProperty,z2=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&U2(e,t,n),n};const N2=w("debugpost");class Eh extends nt{get typeName(){return"Antialiasing"}preset=new z(2);onCreateEffect(){const e=new T.POSTPROCESSING.MODULE.SMAAEffect({preset:this.preset?.value??T.POSTPROCESSING.MODULE.SMAAPreset.HIGH,edgeDetectionMode:T.POSTPROCESSING.MODULE.EdgeDetectionMode.LUMA});return this.preset.onValueChanged=t=>{N2&&console.log("Antialiasing preset changed to",t),e.applyPreset(t)},e}}z2([u(z)],Eh.prototype,"preset"),cn("Antialiasing",Eh);var W2=Object.defineProperty,M0=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&W2(e,t,n),n};const Vp=class VS extends nt{static useSelectiveBloom=!1;get typeName(){return"Bloom"}threshold=new z(.9);intensity=new z(1);scatter=new z(.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=VS.useSelectiveBloom),this.selectiveBloom){const t=e=new T.POSTPROCESSING.MODULE.SelectiveBloomEffect(this.context.scene,this.context.mainCamera,{blendFunction:T.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});t.inverted=!0}else e=new T.POSTPROCESSING.MODULE.BloomEffect({blendFunction:T.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});return this.intensity.onValueChanged=t=>{e.intensity=t},this.threshold.onValueChanged=t=>{e.luminanceMaterial.threshold=Math.pow(t,2.2)},this.scatter.onValueChanged=t=>{e.luminancePass.enabled=!0,e.luminanceMaterial.smoothing=t,e.mipmapBlurPass&&(e.mipmapBlurPass.radius=Co.lerp(.1,.9,t))},e}};M0([u(z)],Vp.prototype,"threshold"),M0([u(z)],Vp.prototype,"intensity"),M0([u(z)],Vp.prototype,"scatter");let $p=Vp;cn("Bloom",$p);var V2=Object.defineProperty,$2=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&V2(e,t,n),n};class Rh extends nt{get typeName(){return"ChromaticAberration"}intensity=new z(0);onCreateEffect(){const e=new T.POSTPROCESSING.MODULE.ChromaticAberrationEffect;return e.offset=new K(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}}$2([u(z)],Rh.prototype,"intensity"),cn("ChromaticAberration",Rh);var Th=(o=>(o[o.None=0]="None",o[o.Neutral=1]="Neutral",o[o.ACES=2]="ACES",o[o.AgX=3]="AgX",o[o.KhronosNeutral=4]="KhronosNeutral",o))(Th||{});const N1=new Map;function E0(o){switch(o){case 0:return Bm;case 1:return Dm;case 2:return Rd;case 3:return Ed;case 4:return ja;default:return N1.has(o)||(N1.set(o,!0),console.warn("[Postprocessing] Unknown tone mapping mode",o)),ja}}function H2(o){switch(o){case Bm:return 0;case Rd:return 2;case Ed:return 3;case ja:return 1;case Dm:return 1;default:return 0}}function Hp(o){switch(o){case Bm:return T.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR;case Rd:return T.POSTPROCESSING.MODULE.ToneMappingMode.ACES_FILMIC;case Ed:return T.POSTPROCESSING.MODULE.ToneMappingMode.AGX;case ja:return T.POSTPROCESSING.MODULE.ToneMappingMode.NEUTRAL;case Dm:return T.POSTPROCESSING.MODULE.ToneMappingMode.REINHARD;default:return T.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR}}var G2=Object.defineProperty,W1=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&G2(e,t,n),n};const R0=w("debugpost");class er extends nt{get typeName(){return"ToneMapping"}mode=new z(void 0);exposure=new z(1);setMode(e){const t=Th[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=U1(this);e&&super.onEffectEnabled(e)}_tonemappingEffect=null;onCreateEffect(){if(this.mode.isInitialized==!1){const i=H2(this.context.renderer.toneMapping);R0&&console.log("[PostProcessing] Initializing ToneMapping mode to renderer.toneMapping",this.context.renderer.toneMapping+" \u2192 "+i),this.mode.initialize(i)}this._tonemappingEffect?.dispose();const e=E0(this.mode.value),t=this._tonemappingEffect=new T.POSTPROCESSING.MODULE.ToneMappingEffect({mode:Hp(e)});return this.mode.onValueChanged=i=>{if(typeof i=="string")i=Bw(i),t.mode=Hp(i);else{const n=E0(i);t.mode=Hp(n)}t.name="ToneMapping ("+Th[i]+")",R0&&console.log("[PostProcessing] ToneMapping mode changed to",Th[i],e,t.mode)},R0&&console.log("[PostProcessing] Use ToneMapping",Th[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=E0(this.mode.value)),this.exposure.overrideState&&this.exposure.value!==void 0)){const e=Math.max(0,this.exposure.value);this.context.renderer.toneMappingExposure=e}}}W1([u(z)],er.prototype,"mode"),W1([u(z)],er.prototype,"exposure"),cn("Tonemapping",er);var q2=Object.defineProperty,Gp=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&q2(e,t,n),n};class tr extends nt{get typeName(){return"ColorAdjustments"}remap=!0;postExposure=new z(1);contrast=new z(0);hueShift=new z(0);saturation=new z(0);init(){this.postExposure.valueProcessor=e=>(this.remap&&(e=Math.pow(2,e)),e),this.contrast.valueProcessor=e=>{if(!this.remap)return e;let t=1;return e>0?t=200:e<0&&(t=100),e/t},this.contrast.defaultValue=0,this.hueShift.valueProcessor=e=>this.remap?Math.PI*e/180:e,this.hueShift.defaultValue=0,this.saturation.valueProcessor=e=>this.remap?e<0?e/100:e/(100*Math.PI):e,this.saturation.defaultValue=0}onCreateEffect(){const e=[];let t=this.postprocessingContext?.components.find(s=>s instanceof er);t||(t=new er,this.postprocessingContext?.components.push(t)),this.postExposure.onValueChanged=s=>{this.postExposure.overrideState&&t?t.exposure.value=s:console.warn("[PostProcessing] PostExposure is set to override but no ToneMappingEffect found in the postprocessing stack. Please add a ToneMappingEffect to your postprocessing stack to use PostExposure.")};const i=new T.POSTPROCESSING.MODULE.BrightnessContrastEffect;this.contrast.onValueChanged=s=>i.contrast=s;const n=new T.POSTPROCESSING.MODULE.HueSaturationEffect;return this.hueShift.onValueChanged=s=>n.hue=s,this.saturation.onValueChanged=s=>n.saturation=s,e.push(i),e.push(n),e}}Gp([u(z)],tr.prototype,"postExposure"),Gp([u(z)],tr.prototype,"contrast"),Gp([u(z)],tr.prototype,"hueShift"),Gp([u(z)],tr.prototype,"saturation"),cn("ColorAdjustments",tr);var X2=Object.defineProperty,da=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&X2(e,t,n),n};const Q2=w("debugpost");class Dn extends nt{get typeName(){return"DepthOfField"}mode;focusDistance=new z(1);focalLength=new z(.2);aperture=new z(20);gaussianMaxRadius=new z;resolutionScale=new z(1/window.devicePixelRatio);bokehScale=new z;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){Q2&&console.warn("DepthOfField: Mode is set to Off");return}const e=new T.POSTPROCESSING.MODULE.DepthOfFieldEffect(this.context.mainCamera,{worldFocusRange:.2,focalLength:1,bokehScale:20,resolutionScale:this.resolutionScale.value});return this.focusDistance.onValueChanged=t=>{e.cocMaterial.worldFocusDistance=t},this.focalLength.onValueChanged=t=>e.cocMaterial.worldFocusRange=t,this.aperture.onValueChanged=t=>e.bokehScale=t,this.resolutionScale&&(this.resolutionScale.onValueChanged=t=>e.resolution.scale=t),[e]}unapply(){}}da([u()],Dn.prototype,"mode"),da([u(z)],Dn.prototype,"focusDistance"),da([u(z)],Dn.prototype,"focalLength"),da([u(z)],Dn.prototype,"aperture"),da([u(z)],Dn.prototype,"gaussianMaxRadius"),da([u(z)],Dn.prototype,"resolutionScale"),da([u(z)],Dn.prototype,"bokehScale"),cn("DepthOfField",Dn);class Ah extends nt{effect;constructor(e){super(),this.effect=e}get typeName(){return this.effect.constructor.name}onCreateEffect(){return this.effect}}var Y2=Object.defineProperty,Z2=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&Y2(e,t,n),n};class Ih extends nt{get typeName(){return"PixelationEffect"}granularity=new z(10);onCreateEffect(){const e=new T.POSTPROCESSING.MODULE.PixelationEffect;return this.granularity.onValueChanged=t=>{e.granularity=t},e}}Z2([u(z)],Ih.prototype,"granularity"),cn("PixelationEffect",Ih);var K2=Object.defineProperty,Lh=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&K2(e,t,n),n};class ns extends nt{get typeName(){return"ScreenSpaceAmbientOcclusion"}intensity=new z(2);falloff=new z(1);samples=new z(9);color=new z(new oe(0,0,0));luminanceInfluence=new z(.7);onBeforeRender(){if(this._ssao&&this.context.mainCamera instanceof de){const e=this.context.mainCamera.far-this.context.mainCamera.near;this._ssao.ssaoMaterial.worldDistanceFalloff=e*.01,this._ssao.ssaoMaterial.worldDistanceThreshold=this.context.mainCamera.far}}_ssao;onCreateEffect(){const e=this.context.mainCamera,t=new T.POSTPROCESSING.MODULE.NormalPass(this.context.scene,e),i=new T.POSTPROCESSING.MODULE.DepthDownsamplingPass({normalBuffer:t.texture,resolutionScale:.5}),n=this._ssao=new T.POSTPROCESSING.MODULE.SSAOEffect(e,t.texture,{normalDepthBuffer:i.texture,worldDistanceThreshold:1,worldDistanceFalloff:1,worldProximityThreshold:.1,worldProximityFalloff:2,intensity:1,blendFunction:T.POSTPROCESSING.MODULE.BlendFunction.MULTIPLY,luminanceInfluence:.5});this.intensity.onValueChanged=r=>{n.intensity=r},this.falloff.onValueChanged=r=>{n.ssaoMaterial.radius=r*.1},this.samples.onValueChanged=r=>{n.ssaoMaterial.samples=r},this.color.onValueChanged=r=>{n.color||(n.color=new oe),n.color.copy(r)},this.luminanceInfluence.onValueChanged=r=>{n.luminanceInfluence=r};const s=new Array;return s.push(t),s.push(i),s.push(n),s}}Lh([u(z)],ns.prototype,"intensity"),Lh([u(z)],ns.prototype,"falloff"),Lh([u(z)],ns.prototype,"samples"),Lh([u(z)],ns.prototype,"color"),Lh([u(z)],ns.prototype,"luminanceInfluence"),cn("ScreenSpaceAmbientOcclusion",ns);var J2=Object.defineProperty,ua=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&J2(e,t,n),n};const eI=w("debugN8AO");var T0=(o=>(o[o.Performance=0]="Performance",o[o.Low=1]="Low",o[o.Medium=2]="Medium",o[o.High=3]="High",o[o.Ultra=4]="Ultra",o))(T0||{});class Bn extends nt{get typeName(){return"ScreenSpaceAmbientOcclusionN8"}get pass(){return this._ssao}gammaCorrection=!0;aoRadius=new z(1);falloff=new z(1);intensity=new z(1);color=new z(new oe(0,0,0));screenspaceRadius=!1;quality=2;_ssao;onValidate(){this._ssao&&(this._ssao.setQualityMode(T0[this.quality]),this._ssao.configuration.gammaCorrection=this.gammaCorrection,this._ssao.configuration.screenSpaceRadius=this.screenspaceRadius)}onCreateEffect(){const e=this.context.mainCamera,t=this.context.domWidth,i=this.context.domHeight,n=this._ssao=new T.POSTPROCESSING_AO.MODULE.N8AOPostPass(this.context.scene,e,t,i);n.name="SSAO_N8";const s=T0[this.quality];n.setQualityMode(s),n.configuration.transparencyAware=!1;const r=new $n(t,i);return n.configuration.beautyRenderTarget=r,n.configuration.autoRenderBeauty=!1,n.configuration.gammaCorrection=this.gammaCorrection,n.configuration.screenSpaceRadius=this.screenspaceRadius,eI&&(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 oe),n.configuration.color.copy(a)},n}}ua([kt(),u()],Bn.prototype,"gammaCorrection"),ua([u(z)],Bn.prototype,"aoRadius"),ua([u(z)],Bn.prototype,"falloff"),ua([u(z)],Bn.prototype,"intensity"),ua([u(z)],Bn.prototype,"color"),ua([kt(),u()],Bn.prototype,"screenspaceRadius"),ua([kt(),u()],Bn.prototype,"quality"),cn("ScreenSpaceAmbientOcclusionN8",Bn);var tI=Object.defineProperty,iI=Object.getOwnPropertyDescriptor,V1=(o,e,t,i)=>{for(var n=iI(e,t),s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&tI(e,t,n),n};class jh extends nt{get typeName(){return"Sharpening"}order=ut.Sharpening;_effect;onCreateEffect(){return this._effect??=new(nI()),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}V1([u()],jh.prototype,"amount"),V1([u()],jh.prototype,"radius");function nI(){const o=`
|
|
1311
|
+
`)}r&&s.size&&console.log(d);const g=new Set;for(const _ of m){_.getPath||console.error("USDZExporter: Animation target object has no getPath method. This is likely a bug",_);let v=_.getPath();v.startsWith("<")&&(v=v.substring(1)),v.endsWith(">")&&(v=v.substring(0,v.length-1)),g.add({path:v,obj:_})}const f=Array.from(g).sort((_,v)=>_.path.length-v.path.length),y=new Array;for(let _=0;_<f.length;_++)for(let v=_+1;v<f.length;v++)if(f[v].path.startsWith(f[_].path)){const P=f[v],k=f[_];y.push({child:P.obj.displayName+" ("+P.path+")",parent:k.obj.displayName+" ("+k.path+")"})}y.length&&console.warn("USDZExporter: There are overlapping PlayAnimation actions. This can lead to undefined runtime behaviour when playing multiple animations. Please restructure the hierarchy so that animations don't overlap.",{overlappingTargets:y,playAnimationActions:s})}for(const d of new Set([...t,...i]))if(Array.isArray(d))for(const p of d)n.add(p.uuid);else n.add(d.uuid);Op&&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){Op&&console.log("onAfterSerialize behaviours",this.behaviourComponentsCopy);for(const t of this.behaviourComponentsCopy)typeof t.afterSerialize=="function"&&(t.afterSerialize.constructor.name==="AsyncFunction"?await t.afterSerialize(this,e):t.afterSerialize(this,e));for(const{clipUrl:t,filesKey:i}of this.audioClipsCopy){if(e.files[i])return;const n=await(await(await fetch(t)).blob()).arrayBuffer(),s=new Uint8Array(n);e.files[i]=s}this.behaviourComponentsCopy.length=0,this.audioClipsCopy.length=0}}class Gy{get extensionName(){return"Physics"}onExportObject(e,t,i){const n=S.getComponents(e,Ke).filter(l=>l.enabled),s=S.getComponents(e,nn).filter(l=>l.enabled&&!l.isTrigger);let r=n.length>0?n[0]:null;const a=s.length>0?s[0]:null;a&&!r&&(r=new Ke,r.isKinematic=!0),r&&t.addEventListener("serialize",(l,c)=>{if(r){if(l.appendLine(),l.beginBlock('def RealityKitComponent "RigidBody"',"{",!0),r.useGravity||l.appendLine("bool gravityEnabled = 0"),l.appendLine('uniform token info:id = "RealityKit.RigidBody"'),r.isKinematic&&l.appendLine('token motionType = "Kinematic"'),l.beginBlock('def RealityKitStruct "massFrame"',"{",!0),l.appendLine(`float m_mass = ${r.mass}`),l.beginBlock('def RealityKitStruct "m_pose"',"{",!0),l.appendLine(`float3 position = (${r.centerOfMass.x}, ${r.centerOfMass.y}, ${r.centerOfMass.z})`),l.closeBlock("}"),l.closeBlock("}"),s.length>0){const h=s[0];l.beginBlock('def RealityKitStruct "material"',"{",!0);const d=h.sharedMaterial;d&&d.dynamicFriction!==void 0&&l.appendLine(`double dynamicFriction = ${h.sharedMaterial?.dynamicFriction}`),d&&d.bounciness!==void 0&&l.appendLine(`double restitution = ${h.sharedMaterial?.bounciness}`),d&&d.staticFriction!==void 0&&l.appendLine(`double staticFriction = ${h.sharedMaterial?.staticFriction}`),l.closeBlock("}")}l.closeBlock("}")}}),a&&(t.addEventListener("serialize",(l,c)=>{l.beginBlock('def RealityKitComponent "Collider"',"{",!0),l.appendLine("uint group = 1"),l.appendLine('uniform token info:id = "RealityKit.Collider"'),l.appendLine("uint mask = 4294967295");const h=a.isTrigger?"Trigger":"Default";if(l.appendLine(`token type = "${h}"`),l.beginBlock('def RealityKitStruct "Shape"',"{",!0),a instanceof pl){const d=a;l.appendLine('token shapeType = "Sphere"'),l.appendLine(`float radius = ${d.radius}`)}else if(a instanceof qu){const d=a;l.appendLine('token shapeType = "Box"'),l.appendLine(`float3 extent = (${d.size.x}, ${d.size.y}, ${d.size.z})`)}else if(a instanceof Vo){const d=a;l.appendLine('token shapeType = "Capsule"'),l.appendLine(`float radius = ${d.radius}`),l.appendLine(`float height = ${d.height}`)}else if(a instanceof Bs&&a.sharedMesh?.geometry){const d=a.sharedMesh.geometry;d.boundingBox||d.computeBoundingBox();const p=a.sharedMesh.geometry.boundingBox;p&&(l.appendLine('token shapeType = "Box"'),l.appendLine(`float3 extent = (${p.max.x-p.min.x}, ${p.max.y-p.min.y}, ${p.max.z-p.min.z})`),console.log("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. MeshCollider will be exported as Box",a))}else console.warn("[USDZ] Only Box, Sphere, and Capsule colliders are supported in visionOS/iOS. Ignoring collider:",a);l.beginBlock('def RealityKitStruct "pose"',"{",!0),l.closeBlock("}"),l.closeBlock("}"),l.closeBlock("}")}),s.length>1&&console.log("WARNING: Multiple colliders detected. visionOS / iOS can only support objects with a single collider, only exporting the first collider: ",a))}}const kA=w("debugshadowcomponents");Gb.prototype.interactable={get(){return this.interactive},set(o){this.interactable=o}};class un extends E{isRoot(){return this.Root?.gameObject===this.gameObject}get canvas(){const e=this.Root;return e?.isCanvas?e:null}get Canvas(){return this.canvas}markDirty(){li.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,yh)),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,un),!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[Ai]=this,this.setShadowComponentOwner(e);let n=!1;if(this.Root?.gameObject===this.gameObject)this.gameObject.add(e);else{const s=this._parentComponent.shadowComponent;s&&(s?.add(e),n=!0)}this.shadowComponent=e,t&&t.shadowComponent&&this.shadowComponent&&t.shadowComponent.add(this.shadowComponent),jc&&e.add(new Pi(.5)),this.onAfterAddedToScene(),n&&NP(),kA&&console.warn("Added shadow component",this.shadowComponent)}setShadowComponentOwner(e){if(e&&(e[Ai]===void 0||e[Ai]===this)&&(e[Ai]=this,e.children))for(const t of e.children)this.setShadowComponentOwner(t)}traverseOwnedShadowComponents(e,t,i){if(e&&e[Ai]===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 yh extends un{awake(){super.awake()}}var MA=Object.defineProperty,EA=Object.getOwnPropertyDescriptor,bh=(o,e,t,i)=>{for(var n=i>1?void 0:i?EA(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&MA(e,t,n),n};const qy=w("debugui"),Xy=w("debuguilayout");class x1{width;height}class S1{x;y;width;height}const In=new b,_h=new J,kp=new N,Tl=class zS extends un{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 K),this._anchoredPosition}set anchoredPosition(e){this._anchoredPosition=e}sizeDelta=new K(100,100);pivot=new K(.5,.5);anchorMin=new K(0,0);anchorMax=new K(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 M,this.rectBlock.name=this.name,this.lastMatrix=new J,this._lastAnchoring=null,this._initialPosition=this.gameObject.position.clone(),this._initialPosition.z=0,this._anchoredPosition||(this._anchoredPosition=new K),hl(this,"_anchoredPosition",()=>{this.markDirty()}),hl(this,"sizeDelta",()=>{this.markDirty()}),hl(this,"pivot",()=>{this.markDirty()}),hl(this,"anchorMin",()=>{this.markDirty()}),hl(this,"anchorMax",()=>{this.markDirty()})}onEnable(){super.onEnable(),this.rectBlock||(this.rectBlock=new M),this.lastMatrix||(this.lastMatrix=new J),this._lastAnchoring||(this._lastAnchoring=new K),this._initialPosition||(this._initialPosition=new b),this._anchoredPosition||(this._anchoredPosition=new K),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(Xy?`${e.name} changed`:void 0)}get isDirty(){return this._transformNeedsUpdate||(this._transformNeedsUpdate=!this.lastMatrix.equals(this.gameObject.matrix)),this._transformNeedsUpdate}markDirty(){this._transformNeedsUpdate||(Xy&&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,zS):this._parentRectTransform=void 0,this._transformNeedsUpdate=!1,Xy&&console.warn("RectTransform \u2192 ApplyTransform",this.name+" because "+e),this.isRoot()?this.Root.screenspace||(t.rotation.y=Math.PI):(t.matrix.identity(),t.matrixAutoUpdate=!1,In.set(0,0,0),this.applyPivot(In),t.matrix.setPosition(In.x,In.y,0),(this.gameObject.quaternion.x||this.gameObject.quaternion.y||this.gameObject.quaternion.z)&&(kp.copy(this.gameObject.quaternion),kp.x*=-1,kp.z*=-1,_h.makeRotationFromQuaternion(kp),t.matrix.premultiply(_h)),In.set(0,0,0),this.applyAnchoring(In),this.canvas?.screenspace?In.z+=.1:In.z+=.01,_h.identity(),_h.setPosition(In.x,In.y,In.z),t.matrix.premultiply(_h),t.matrix.scale(this.gameObject.scale)),this.lastMatrix.copy(this.gameObject.matrix);const i=!0;for(const n of wu(this.gameObject,un,i,1)){if(n===this||!n.activeAndEnabled)continue;const s=n;s.onParentRectTransformChanged&&s.onParentRectTransformChanged(this)}}_lastAnchoring;applyAnchoring(e){this._lastAnchoring||(this._lastAnchoring=new K);const t=this._lastAnchoring.sub(this._anchoredPosition);this.gameObject.position.x+=t.x,this.gameObject.position.y+=t.y,this._lastAnchoring.copy(this._anchoredPosition),e.x+=this._initialPosition.x-this.gameObject.position.x,e.y+=this._initialPosition.y-this.gameObject.position.y,e.z+=this._initialPosition.z-this.gameObject.position.z;const i=this._parentRectTransform;if(i){let n=0;const s=1-this.anchorMax.y-this.anchorMin.y;n-=i.height*.5*s,e.y+=n;let r=0;const a=1-this.anchorMax.x-this.anchorMin.x;r-=i.width*.5*a,e.x+=r}}applyPivot(e){if(this.pivot&&!this.isRoot()){const t=this.pivot.x-.5;e.x-=t*this.sizeDelta.x*this.gameObject.scale.x;const i=this.pivot.y-.5;e.y-=i*this.sizeDelta.y*this.gameObject.scale.y}}getBasicOptions(){const e={width:this.sizeDelta.x,height:this.sizeDelta.y,offset:0,backgroundOpacity:0,borderWidth:0,borderRadius:0,borderOpacity:0,letterSpacing:-.03};return this.ensureValidSize(e),e}ensureValidSize(e,t=1e-4){return e.width<=0&&(e.width=t),e.height<=0&&(e.height=1e-4),e}_createdBlocks=[];_createdTextBlocks=[];createNewBlock(e){e={...this.getBasicOptions(),...e},qy&&console.log(this.name,e);const t=new Gb(e);return this._createdBlocks.push(t),t}createNewText(e){qy&&console.log(e),e={...this.getBasicOptions(),...e},qy&&console.log(this.name,e);const t=new Hb(e);return this._createdTextBlocks.push(t),t}};bh([u(K)],Tl.prototype,"anchoredPosition",1),bh([u(K)],Tl.prototype,"sizeDelta",2),bh([u(K)],Tl.prototype,"pivot",2),bh([u(K)],Tl.prototype,"anchorMin",2),bh([u(K)],Tl.prototype,"anchorMax",2);let Ln=Tl;var RA=Object.defineProperty,C1=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&RA(e,t,n),n};class Al extends E{effectColor;effectDistance}C1([u(se)],Al.prototype,"effectColor"),C1([u(K)],Al.prototype,"effectDistance");var TA=Object.defineProperty,AA=Object.getOwnPropertyDescriptor,P1=(o,e,t,i)=>{for(var n=i>1?void 0:i?AA(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&TA(e,t,n),n};const ta={backgroundColor:new oe(1,1,1),backgroundOpacity:1,borderColor:new oe(1,1,1),borderOpacity:1},Qy=class fd extends un{get isGraphic(){return!0}get color(){return this._color||(this._color=new se(1,1,1,1)),this._color}set color(e){(!this._color||this._color.r!==e.r||this._color.g!==e.g||this._color.b!==e.b||this._color.alpha!==e.alpha)&&(this._color||(this._color=new se(1,1,1,1)),this._color.copy(e),this.onColorChanged())}_alphaFactor=1;setAlphaFactor(e){this._alphaFactor=e,this.onColorChanged()}get alphaFactor(){return this._alphaFactor}sRGBColor=new oe(1,0,1);onColorChanged(){if(this.uiObject){this.sRGBColor.copy(this._color),this.sRGBColor.convertLinearToSRGB(),ta.backgroundColor=this.sRGBColor,ta.backgroundOpacity=this._color.alpha;const e=this.uiObject._simpleState__activeStates?.[0];if(e){const t=this.uiObject._simpleState__states?.[e];t&&("backgroundColor"in t&&(ta.backgroundColor=t.backgroundColor),"backgroundOpacity"in t&&(ta.backgroundOpacity=t.backgroundOpacity))}ta.backgroundOpacity*=this._alphaFactor,this.applyEffects(ta,this._alphaFactor),this.uiObject.set(ta),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,Ln)),!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 WP(this.uiObject)),this.uiObject.setupState(e.state,e.attributes))}setOptions(e){this.makePanel(),this.uiObject&&this.uiObject.set(e)}awake(){super.awake(),this.makePanel(),hl(this,"_color",()=>pR(this,this.onColorChanged))}onEnable(){super.onEnable(),this.uiObject&&(this.rectTransform.shadowComponent?.add(this.uiObject),this.addShadowComponent(this.uiObject,this.rectTransform))}onDisable(){super.onDisable(),this.uiObject&&this.removeShadowComponent()}_currentlyCreatingPanel=!1;makePanel(){if(this.uiObject||this._currentlyCreatingPanel)return;this._currentlyCreatingPanel=!0;const e={backgroundColor:this.color,backgroundOpacity:this.color.alpha,offset:.015};this.onBeforeCreate(e),this.applyEffects(e),this.onCreate(e),this.controlsChildLayout=!1,this._currentlyCreatingPanel=!1,this.onAfterCreated(),this.onColorChanged()}onBeforeCreate(e){}onCreate(e){this.uiObject=this.rectTransform.createNewBlock(e),this.uiObject.name=this.name}onAfterCreated(){}applyEffects(e,t=1){const i=this.gameObject?.getComponent(Al);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(fd.textureCache.has(e))e=fd.textureCache.get(e);else if(!e.isRenderTargetTexture){const t=e.clone();t.colorSpace=Oo,fd.textureCache.set(e,t),e=t}this.setOptions({backgroundImage:e,borderRadius:0,backgroundOpacity:this.color.alpha,backgroundSize:"stretch"}),Ve.assignTextureLOD(e,0).then(t=>{t instanceof Se&&(e&&fd.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)}};P1([u(se)],Qy.prototype,"color",1),P1([u()],Qy.prototype,"raycastTarget",2);let vh=Qy;class wh extends vh{_flippedObject=!1;onAfterCreated(){this.uiObject&&!this._flippedObject&&(this._flippedObject=!0,this.uiObject.scale.y*=-1)}}var IA=Object.defineProperty,LA=Object.getOwnPropertyDescriptor,Jo=(o,e,t,i)=>{for(var n=i>1?void 0:i?LA(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&IA(e,t,n),n};const ia=w("debugtext");var ht=(o=>(o[o.UpperLeft=0]="UpperLeft",o[o.UpperCenter=1]="UpperCenter",o[o.UpperRight=2]="UpperRight",o[o.MiddleLeft=3]="MiddleLeft",o[o.MiddleCenter=4]="MiddleCenter",o[o.MiddleRight=5]="MiddleRight",o[o.LowerLeft=6]="LowerLeft",o[o.LowerCenter=7]="LowerCenter",o[o.LowerRight=8]="LowerRight",o))(ht||{}),O1=(o=>(o[o.Normal=0]="Normal",o[o.Bold=1]="Bold",o[o.Italic=2]="Italic",o[o.BoldAndItalic=3]="BoldAndItalic",o))(O1||{});class Ht extends vh{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(),this.context.accessibility.updateElement(this,{label:this.text}))}set_text(e){this.text=e}get fontSize(){return this._fontSize}set fontSize(e){this._fontSize=e,this.uiObject?.set({fontSize:e})}sRGBTextColor=new oe(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){ia&&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,ia&&(e.backgroundColor=16750848,e.backgroundOpacity=.5);const t=this.rectTransform;e={...e,...this.getTextOpts()},this.getAlignment(e),ia&&(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.context.accessibility.updateElement(this,{role:"text",label:this.text,hidden:!1}),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),this.context.accessibility.updateElement(this,{hidden:!0})}onDestroy(){super.onDestroy(),this.context.accessibility.removeElement(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(ia&&console.log("feedText",this.uiObject,e,t),!!this.uiObject)if(this._textMeshUi||(this._textMeshUi=[]),this.uiObject.children.length=0,!t||e.length===0)this.uiObject.textContent=e;else{let i=this.getNextTag(e);if(i){if(i.startIndex>0){for(let r=this.uiObject.children.length-1;r>=0;r--){const a=this.uiObject.children[r];a.isUI&&(this.uiObject.remove(a),a.clear())}const s=new $m({textContent:e.substring(0,i.startIndex),color:"inherit"});this.uiObject.add(s)}}else{this.uiObject.textContent="",this.setOptions({textContent:e});return}const n=[];for(;i;){const s=this.getNextTag(e,i.endIndex),r={fontFamily:this.uiObject?.get("fontFamily"),color:"inherit",textContent:""};if(s){r.textContent=this.getText(e,i,s),this.handleTag(i,r,n);const a=new $m(r);this.uiObject?.add(a)}else{r.textContent=e.substring(i.endIndex),this.handleTag(i,r,n);const a=new $m(r);this.uiObject?.add(a)}i=s}}}_didHandleTextRenderOnTop=!1;handleTextRenderOnTop(){this._didHandleTextRenderOnTop||(this._didHandleTextRenderOnTop=!0,this.startCoroutine(this.renderOnTopCoroutine()))}*renderOnTopCoroutine(){if(!this.canvas)return;const e=[],t=this.canvas,i={renderOnTop:t.renderOnTop,depthWrite:t.depthWrite,doubleSided:t.doubleSided};for(;;){let n=!1;if(this._textMeshUi)for(let s=0;s<this._textMeshUi.length;s++){if(e[s]===!0)continue;n=!0;const r=this._textMeshUi[s];r.textContent&&(Vu(r,i),e[s]=!0)}if(!n)break;yield}}handleTag(e,t,i){if(!e.isEndTag){if(e.type.includes("color")){const n=new Yy(e,{color:t.color});if(i.push(n),e.type.length>6){const s=parseInt("0x"+e.type.substring(7));t.color=s}else t.color=new oe(1,1,1)}else if(e.type=="b"){this.setFont(t,1);const n=new Yy(e,{fontWeight:700});i.push(n)}else if(e.type=="i"){this.setFont(t,2);const n=new Yy(e,{fontStyle:"italic"});i.push(n)}}}getText(e,t,i){return e.substring(t.endIndex,i.startIndex)}getNextTag(e,t=0){const i=e.indexOf("<",t),n=e.indexOf(">",i);if(i>=0&&n>=0){const s=e.substring(i+1,n);return{type:s,startIndex:i,endIndex:n+1,isEndTag:s.startsWith("/")}}return null}setFont(e,t){if(!this.font)return;const i=this.font,n=this.getFamilyNameWithCorrectSuffix(i,t);ia&&console.log("Selected font family:"+n);let s=qb.getFontFamily(n);switch(s||(s=qb.addFontFamily(n)),e.fontFamily=s,t){default:case 0:e.fontWeight=400,e.fontStyle="normal";break;case 1:e.fontWeight=700,e.fontStyle="normal";break;case 2:e.fontWeight=400,e.fontStyle="italic";break;case 3:e.fontStyle="italic",e.fontWeight=400}let r=s.getVariant(e.fontWeight,e.fontStyle);if(!r){let a=n;a?.endsWith("-msdf.json")||(a+="-msdf.json");let l=n;l?.endsWith(".png")||(l+=".png"),r=s.addVariant(e.fontWeight,e.fontStyle,a,l),r?.addEventListener("ready",()=>{this.markDirty()})}}getFamilyNameWithCorrectSuffix(e,t){(e.startsWith("https:")||e.startsWith("http:"))&&(e=new URL(e).pathname);const i=e.lastIndexOf("-");if(i<0)return e;const n=e.substring(i+1)?.toLowerCase();if(jA.includes(n))return ia&&console.warn("Unsupported font style: "+n),e;const s=e.lastIndexOf("/");let r=e;s>=0&&(r=r.substring(s+1));const a=r[0]===r[0].toUpperCase(),l=e.substring(0,i>s?i:e.length);switch(ia&&console.log("Select font: ",e,O1[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}}}Jo([u()],Ht.prototype,"alignment",2),Jo([u()],Ht.prototype,"verticalOverflow",2),Jo([u()],Ht.prototype,"horizontalOverflow",2),Jo([u()],Ht.prototype,"lineSpacing",2),Jo([u()],Ht.prototype,"supportRichText",2),Jo([u(URL)],Ht.prototype,"font",2),Jo([u()],Ht.prototype,"fontStyle",2),Jo([u()],Ht.prototype,"text",1),Jo([u()],Ht.prototype,"fontSize",1);class Yy{tag;previousValues;constructor(e,t){this.tag=e,this.previousValues=t}}const jA=["medium","mediumitalic","black","blackitalic","thin","thinitalic","extrabold","light","lightitalic","semibold"];class Il{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/${fp(this.material)}>`),t.closeBlock()}}class Zy{static singleLine(e,t,i){const n=new Il("text_"+Il.getId());return n.content=e,t&&(n.pointSize=t),i&&(n.depth=i),n}static multiLine(e,t,i,n,s,r){const a=new Il("text_"+Il.getId());return a.content=e,a.width=t,a.height=i,a.horizontalAlignment=n,a.verticalAlignment=s,r!==void 0&&(a.wrapMode=r),a}}const DA=new J().makeRotationY(Math.PI),BA=new J().makeScale(-1,1,-1);class Mp{get extensionName(){return"text"}exportText(e,t,i){const n=S.getComponent(e,Ht);if(!n)return;const s=S.getComponent(e,Ln);let r=100,a=100;s&&(r=s.width,a=s.height);const l=DA.clone();s&&l.premultiply(BA),t.setMatrix(l);const c=n.color.clone();t.material=new gt({color:c,emissive:c}),t.addEventListener("serialize",(h,d)=>{let p=n.text;p=p.replace(/\r/g,""),p=p.replace(/\n/g,"\\n");const m=Zy.multiLine(p,r,a,"center","bottom","flowing");this.setTextAlignment(m,n.alignment),this.setOverflow(m,n),t.material&&(m.material=t.material),m.pointSize=this.convertToTextSize(n.fontSize),m.depth=.001,m.writeTo(void 0,h)})}convertToTextSize(e){return 1/.0502*144*e}setOverflow(e,t){t.horizontalOverflow?e.wrapMode="singleLine":e.wrapMode="flowing"}setTextAlignment(e,t){switch(t){case ht.LowerLeft:case ht.MiddleLeft:case ht.UpperLeft:e.horizontalAlignment="left";break;case ht.LowerCenter:case ht.MiddleCenter:case ht.UpperCenter:e.horizontalAlignment="center";break;case ht.LowerRight:case ht.MiddleRight:case ht.UpperRight:e.horizontalAlignment="right";break}switch(t){case ht.LowerLeft:case ht.LowerCenter:case ht.LowerRight:e.verticalAlignment="bottom";break;case ht.MiddleLeft:case ht.MiddleCenter:case ht.MiddleRight:e.verticalAlignment="middle";break;case ht.UpperLeft:case ht.UpperCenter:case ht.UpperRight:e.verticalAlignment="top";break}}}var FA=Object.defineProperty,et=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&FA(e,t,n),n};const k1=w("debuguilayout");class na{left=0;right=0;top=0;bottom=0;get vertical(){return this.top+this.bottom}get horizontal(){return this.left+this.right}}et([u()],na.prototype,"left"),et([u()],na.prototype,"right"),et([u()],na.prototype,"top"),et([u()],na.prototype,"bottom");class Fi extends E{_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&&(k1&&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(){k1&&console.log(this.name,this),this._rectTransform=this.gameObject.getComponent(Ln);const e=this.gameObject.getComponentInParent(Ll);e&&e.registerLayoutGroup(this),this._needsUpdate=!0}onDisable(){const e=this.gameObject.getComponentInParent(Ll);e&&e.unregisterLayoutGroup(this)}set m_Spacing(e){e!==this.spacing&&(this._needsUpdate=!0,this.spacing=e)}get m_Spacing(){return this.spacing}}et([u()],Fi.prototype,"childAlignment"),et([u()],Fi.prototype,"reverseArrangement"),et([u()],Fi.prototype,"spacing"),et([u(na)],Fi.prototype,"padding"),et([u()],Fi.prototype,"minWidth"),et([u()],Fi.prototype,"minHeight"),et([u()],Fi.prototype,"flexibleHeight"),et([u()],Fi.prototype,"flexibleWidth"),et([u()],Fi.prototype,"preferredHeight"),et([u()],Fi.prototype,"preferredWidth");class qs extends Fi{childControlHeight=!0;childControlWidth=!0;childForceExpandHeight=!1;childForceExpandWidth=!1;childScaleHeight=!1;childScaleWidth=!1;onCalculateLayout(e){const t=this.primaryAxis,i=e.width;let n=i;const s=e.height;let r=s;n-=this.padding.horizontal,r-=this.padding.vertical,t==="x"?this.padding.horizontal:this.padding.vertical;const a=t==="x",l=a?"y":"x",c=a?this.childControlWidth:this.childControlHeight,h=a?this.childControlHeight:this.childControlWidth,d=a?this.childForceExpandWidth:this.childForceExpandHeight,p=a?this.childForceExpandHeight:this.childForceExpandWidth,m=a?r:n,g=a?i:s,f=.5*(a?this.childAlignment%3:Math.floor(this.childAlignment/3));let y=0;a?y+=this.padding.left:y+=this.padding.top;let _=0,v=0;for(let L=0;L<this.gameObject.children.length;L++){const V=this.gameObject.children[L],W=S.getComponent(V,Ln);W?.activeAndEnabled&&(v+=1,a?_+=W.width:_+=W.height)}let P=0;const k=this.spacing*(v-1);if(d||c){let L=0;a?L=n-=k:L=r-=k,v>0&&(P=L/v)}let O=0;O+=this.padding.left,O-=this.padding.right,f!==0&&(y=g-_,y*=f,y-=k*f,a?(y-=this.padding.right*f,y+=this.padding.left*(1-f),y<this.padding.left&&(y=this.padding.left)):(y-=this.padding.bottom*f,y+=this.padding.top*(1-f),y<this.padding.top&&(y=this.padding.top)));let D=1;for(let L=0;L<this.gameObject.children.length;L++){const V=this.gameObject.children[L],W=S.getComponent(V,Ln);if(W?.activeAndEnabled){W.pivot?.set(.5,.5),W.anchorMin.set(0,1),W.anchorMax.set(0,1);const G=i*.5+O*.5;W.anchoredPosition.x!==G&&(W.anchoredPosition.x=G);const X=s*-.5;W.anchoredPosition.y!==X&&(W.anchoredPosition.y=X),p&&h&&W.sizeDelta[l]!==m&&(W.sizeDelta[l]=m),d&&c&&W.sizeDelta[t]!==P&&(W.sizeDelta[t]=P);const R=a?W.width:W.height,$=R*.5;if(y+=$,d){const he=P*D-P*.5;he>y&&(y=he-P*.5+R+this.padding.left,y-=$)}let q=y;t==="y"&&(q=-q),W.anchoredPosition[t]!==q&&(W.anchoredPosition[t]=q),y+=$,y+=this.spacing,D+=1}}}}et([u()],qs.prototype,"childControlHeight"),et([u()],qs.prototype,"childControlWidth"),et([u()],qs.prototype,"childForceExpandHeight"),et([u()],qs.prototype,"childForceExpandWidth"),et([u()],qs.prototype,"childScaleHeight"),et([u()],qs.prototype,"childScaleWidth");class Ky extends qs{get primaryAxis(){return"y"}}class Jy extends qs{get primaryAxis(){return"x"}}class e0 extends Fi{onCalculateLayout(){}}var UA=Object.defineProperty,zA=Object.getOwnPropertyDescriptor,ho=(o,e,t,i)=>{for(var n=i>1?void 0:i?zA(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&UA(e,t,n),n},M1=(o=>(o[o.ScreenSpaceOverlay=0]="ScreenSpaceOverlay",o[o.ScreenSpaceCamera=1]="ScreenSpaceCamera",o[o.WorldSpace=2]="WorldSpace",o[o.Undefined=-1]="Undefined",o))(M1||{});const t0=w("debuguilayout"),rn=class NS extends yh{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 NS||(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,t0&&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 J,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 mc(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(),li.ensureUpdateMeshUI(Xb,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(),li.ensureUpdateMeshUI(Xb,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 J);const e=!this._lastMatrixWorld.equals(this.gameObject.matrixWorld);t0&&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(Fi)),(t.isDirty||i?.isDirty)&&(t0&&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(),xe.OnBeforeRender))}*_updateRenderSettingsDelayed(){if(yield,this._updateRenderSettingsRoutine=void 0,this.shadowComponent){this.onUpdateRenderMode(),Vu(this.shadowComponent,this);for(const e of S.getComponentsInChildren(this.gameObject,un))Vu(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=j.lerp(t.nearClipPlane,t.farClipPlane,.01)),this._renderMode===1&&(this.worldCamera&&(t=this.worldCamera),this.planeDistance>0&&(i=this.planeDistance)),this._renderMode){case 0:case 1:if(this._lastWidth=this.context.domWidth,this._lastHeight=this.context.domHeight,!t)return;const n=i+.01;this.gameObject.position.x=0,this.gameObject.position.y=0,this.gameObject.position.z=-n,this.gameObject.quaternion.identity();const s=this.gameObject.getComponent(Ln);let r=!1;s.sizeDelta.x!==this.context.domWidth&&(r=!0),s.sizeDelta.y!==this.context.domHeight&&(r=!0);const a=t.fieldOfView*Math.PI/180,l=2*Math.tan(a/2)*Math.abs(n);this.gameObject.scale.x=l/this.context.domHeight,this.gameObject.scale.y=l/this.context.domHeight,this.gameObject.scale.z=.01,r&&(s.sizeDelta.x=this.context.domWidth,s.sizeDelta.y=this.context.domHeight,s?.markDirty());break;case 2:this._lastWidth=-1,this._lastHeight=-1;break}}};ho([u()],rn.prototype,"renderOnTop",1),ho([u()],rn.prototype,"depthWrite",1),ho([u()],rn.prototype,"doubleSided",1),ho([u()],rn.prototype,"castShadows",1),ho([u()],rn.prototype,"receiveShadows",1),ho([u()],rn.prototype,"renderMode",1),ho([u(rn)],rn.prototype,"rootCanvas",1),ho([u()],rn.prototype,"scaleFactor",1),ho([u(yi)],rn.prototype,"worldCamera",2),ho([u()],rn.prototype,"planeDistance",2);let Ll=rn;var NA=Object.defineProperty,WA=Object.getOwnPropertyDescriptor,i0=(o,e,t,i)=>{for(var n=i>1?void 0:i?WA(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&NA(e,t,n),n};class Xs extends E{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(),xe.OnBeforeRender))}*applyChangesDelayed(){this._isDirty=!1,this.applyChangesNow()}_buffer=[];applyChangesNow(){this._buffer.length=0;for(const e of S.getComponentsInChildren(this.gameObject,un,this._buffer)){const t=e;t.setAlphaFactor&&t.setAlphaFactor(this._alpha)}}}i0([u()],Xs.prototype,"alpha",1),i0([u()],Xs.prototype,"interactable",2),i0([u()],Xs.prototype,"blocksRaycasts",2);class n0{get extensionName(){return"tmui"}onExportObject(e,t,i){const n=S.getComponent(e,Ll);if(n&&n.enabled&&n.renderMode===M1.WorldSpace){const s=new Mp,r=S.getComponent(e,Ln),a=S.getComponent(e,Xs),l=new Array;if(r){if(!S.isActiveSelf(e)){const d=S.isActiveSelf(e);S.setActive(e,!0),r.onEnable(),r.updateTransform(),l.push(()=>{r.onDisable(),S.setActive(e,d)})}e.traverse(d=>{if(!S.isActiveInHierarchy(d)){const p=S.isActiveSelf(d);S.setActive(d,!0);const m=S.getComponent(d,un);m&&(m.onEnable(),l.push(()=>{m.onDisable()}));const g=S.getComponent(d,Ln);g&&(g.onEnable(),g.updateTransform(),g.onApplyTransform(),l.push(()=>{g.onDisable()}));const f=S.getComponent(d,Ht);f&&(f.onEnable(),l.push(()=>{f.onDisable()})),l.push(()=>{S.setActive(d,p)})}}),r.width,r.height;const c=rt.createEmpty(),h=r.shadowComponent;if(t.add(c),h){const d=h.matrix;c.setMatrix(d);const p=new Map,m=new Map;p.set(h,c),m.set(h,a?a.alpha:1),h.traverse(g=>{if(g===h)return;const f=rt.createEmpty();f.setMatrix(g.matrix);const y=g.parent,_=!!y&&typeof y.textContent=="string"&&y.textContent.length>0;let v=m.get(y)||1;const P=S.getComponent(g,Xs);if(P&&(v*=P.alpha),g instanceof H&&_){const O=g[Ai];O?s.exportText(O.gameObject,f,i):console.error("Error when exporting UI: shadow component owner not found. This is likely a bug.",g)}if(g instanceof H&&!_){const O=g.geometry.clone();O.scale(1,1,-1),this.flipWindingOrder(O),f.geometry=O;const D=new oe,L=g.material.opacity;D.copy(g.material.color),f.material=new Ce({color:D,opacity:L*v,map:g.material.map,transparent:!0})}p.set(g,f),m.set(g,v);const k=p.get(y);if(!k){console.error("Error when exporting UI: shadow component parent not found!",g,g.parent);return}k.add(f)})}}for(const c of l)c()}}flipWindingOrder(e){const t=e.index.array;for(let i=0,n=t.length/3;i<n;i++){const s=t[i*3];t[i*3]=t[i*3+2],t[i*3+2]=s}e.index.needsUpdate=!0}}const xh=w("debugusdz");function VA(o,e){const t=[],i=S.getComponentsInChildren(o,_t),n=S.getComponentsInChildren(o,Ut),s=new Array,r=new Array;if(e.injectImplicitBehaviours)for(const a of i){if(!a||!a.runtimeAnimatorController||!a.enabled)continue;const l=a.runtimeAnimatorController.activeState;if(!l||!l.motion||!l.motion.clip||l.motion.clip.tracks?.length<1||s.includes(a))continue;const c=new hh;c.animator=a,c.stateName=l.name,c.trigger="start",c.name="PlayAnimationOnClick_implicitAtStart_"+c.stateName;const h=new M;S.addComponent(h,c),r.push(h),s.push(a),o.add(h)}else for(const a of i){if(!a||!a.runtimeAnimatorController||!a.enabled)continue;xh&&console.log(a);const l=[];for(const c of a.runtimeAnimatorController.enumerateActions()){xh&&console.log(c);const h=c.getClip();l.includes(h)||l.push(h)}t.push({root:a.gameObject,clips:l})}if(e.injectImplicitBehaviours)for(const a of n){if(!a||!a.clip||!a.enabled||!a.playAutomatically||s.includes(a))continue;const l=new hh;l.animation=a,l.stateName=a.clip.name,l.trigger="start",l.name="PlayAnimationOnClick_implicitAtStart_"+l.stateName;const c=new M;S.addComponent(c,l),r.push(c),s.push(a),o.add(c)}else for(const a of n){xh&&console.log(a);const l=[];for(const c of a.animations)l.includes(c)||l.push(c);t.push({root:a.gameObject,clips:l})}xh&&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 $A(o,e){const t=S.getComponentsInChildren(o,ji),i=S.getComponentsInChildren(o,Ns),n=new Array,s=new Array;xh&&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 Ns;a.target=r,a.name="PlayAudioOnClick_implicitAtStart_",a.trigger="start";const l=new M;S.addComponent(l,a),console.log("implicit PlayAudioOnStart",l,a),s.push(l),n.push(r),o.add(l)}return s}function HA(o){return new jt("DisableAtStart",$t.sceneStartTrigger(),fe.fadeAction(o,0,!1))}function E1(o,e){const t=o.domElement.shadowRoot.querySelector("link[rel='ar']");if(t)return t;const i=document.createElement("div");i.classList.add("menu"),i.classList.add("quicklook-menu"),i.style.display="none",i.style.visibility="hidden";const n=document.createElement("button");n.id="open-in-ar",e?(n.innerText="View in AR",n.title="View this scene in AR. The scene will be exported to USDZ and opened with Apple's QuickLook."):(n.innerText="View in AR",n.title="Download this scene for AR. Open the downloaded USDZ file to view it in AR using Apple's QuickLook."),i.appendChild(n);const s=document.createElement("a");s.id="needle-usdz-link",s.style.display="none",s.rel="ar",s.href="",s.target="_blank",i.appendChild(s);const r=document.createElement("img");return r.id="button",s.appendChild(r),o.domElement.shadowRoot.appendChild(i),s}var GA=Object.defineProperty,Et=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&GA(e,t,n),n};const Rt=w("debugusdz"),qA=w("debugusdzpruning");class oa{callToAction;checkoutTitle;checkoutSubtitle;callToActionURL}Et([u()],oa.prototype,"callToAction"),Et([u()],oa.prototype,"checkoutTitle"),Et([u()],oa.prototype,"checkoutSubtitle"),Et([u()],oa.prototype,"callToActionURL");const vi=class Sa extends E{static beforeExport=new ae;static afterExport=new ae;static beforeLODExport=new ae;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(){Rt&&(console.log("USDZExporter",this),console.log("Debug USDZ Mode. Press 'T' to export"),window.addEventListener("keydown",e=>{e.key==="t"&&this.exportAndOpen()})),this.objectToExport||(this.objectToExport=this.gameObject),!this.objectToExport?.children?.length&&!this.objectToExport?.isMesh&&(this.objectToExport=this.context.scene)}onEnable(){const e=I.supportsQuickLookAR(),t=I.isiOS()||I.isiPad();!this.button&&(Rt||e||t)&&(this.allowCreateQuicklookButton&&(this.button=this.createQuicklookButton()),this.lastCallback=this.quicklookCallback.bind(this),this.link=E1(this.context,e),this.link.addEventListener("message",this.lastCallback)),Rt&&Oe("USDZ Exporter enabled: "+this.name),document.getElementById("open-in-ar")?.addEventListener("click",this.onClickedOpenInARElement),kc.registerExporter(this)}onDisable(){this.button?.remove(),this.link?.removeEventListener("message",this.lastCallback),Rt&&Oe("USDZ Exporter disabled: "+this.name),document.getElementById("open-in-ar")?.removeEventListener("click",this.onClickedOpenInARElement),kc.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+="-"+Qx(),Zn()||(e!==""&&(e+="-"),e+="MadeWithNeedle"),this.link||(this.link=E1(this.context,I.supportsQuickLookAR())),this.customUsdzFile)return Rt&&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;Sa.beforeExport.invoke({exporter:this});const t=await this.export(this.objectToExport).finally(()=>{Sa.afterExport.invoke({exporter:this})});return t?(Rt&&console.log("USDZ generation done. Downloading as "+e),this.openInQuickLook(t,e),t):(console.error("USDZ generation failed. Please report a bug",this),null)}async export(e){if(!e)return console.warn("No object to export"),null;const t=this._currentExportTasks.get(e);if(t)return t;const i=this.internalExport(e);return i instanceof Promise?(this._currentExportTasks.set(e,i),i.then(n=>(this._currentExportTasks.delete(e),n)).catch(n=>(this._currentExportTasks.delete(e),console.error("Error during USDZ export \u2013 please report a bug!",n),null))):i}_currentExportTasks=new Map;_previousTimeScale=1;async internalExport(e){le.start("export-usdz",{onProgress:k=>{this.dispatchEvent(new CustomEvent("export-progress",{detail:{progress:k}}))}}),le.report("export-usdz",{message:"Starting export",totalSteps:40,currentStep:0}),le.report("export-usdz",{message:"Load progressive textures",autoStep:5}),le.start("export-usdz-textures","export-usdz");const t=S.getComponentsInChildren(e,_i);for(const k of t)k&&k.enabled&&k.updateSprite(!0);const i=S.getComponentsInChildren(e,ti),n=new Array;let s=0;for(const k of i){for(const O of k.sharedMeshes)if(O){let D=0;const L={exporter:this,type:"mesh",object:k.gameObject,mesh:O};if(Sa.beforeLODExport.invoke(L),L.overrideLevel!==void 0)if(L.overrideLevel===-1){Rt&&console.warn("Skipping LOD export for mesh due to overrideLevel -1",k.gameObject,O);continue}else L.overrideLevel>=0&&(D=L.overrideLevel,Rt&&console.log("Overriding LOD level for mesh export to level "+D+" "+O.name));const V=Ve.assignMeshLOD(O,D);V instanceof Promise&&n.push(new Promise((W,G)=>{V.then(()=>{s++,le.report("export-usdz-textures",{message:"Loaded progressive mesh",currentStep:s,totalSteps:n.length}),W()}).catch(X=>G(X))}))}for(const O of k.sharedMaterials)if(O){let D=0;const L={exporter:this,type:"texture",object:k.gameObject,material:O};if(Sa.beforeLODExport.invoke(L),L.overrideLevel!==void 0)if(L.overrideLevel===-1){Rt&&console.warn("Skipping LOD assignment due to overrideLevel -1",k.gameObject,O);continue}else L.overrideLevel>=0&&(D=L.overrideLevel,Rt&&console.log("Overriding LOD level for texture export to level "+D+" "+O.name));const V=Ve.assignTextureLOD(O,D);V instanceof Promise&&n.push(new Promise((W,G)=>{V.then(()=>{s++,le.report("export-usdz-textures",{message:"Loaded progressive texture",currentStep:s,totalSteps:n.length}),W()}).catch(X=>G(X))}))}}Rt&&Oe("Progressive Loading: "+n.length),await Promise.all(n),Rt&&Oe("Progressive Loading: done"),le.end("export-usdz-textures");const r=ai.Global.Mask;ai.Global.Set(no.AR);const a=new t1,l=new _p(this.quickLookCompatible);let c;const h=[];this.interactive&&(h.push(new Hy),h.push(new Pa),globalThis.NEEDLE_USE_RAPIER&&S.getComponentsInChildren(e,Ke).length>0&&(this.physics?(c=new Gy,h.push(c)):A()&&console.warn("USDZExporter: Physics export is disabled, but there are active Rigidbody components in the scene. They will not be exported.")),h.push(new Mp),h.push(new n0));const d=[l,...h,...this.extensions],p={self:this,exporter:a,extensions:d,object:e};le.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,le.report("export-usdz","auto export animations and audio sources");const m=new Array;this.autoExportAnimations&&m.push(...VA(e,l)),d.find(k=>k.extensionName==="Audio")&&this.autoExportAudioSources&&m.push(...$A(e)),a.debug=Rt,a.pruneUnusedNodes=!qA;const g=Oa.instance.objs.map(k=>k.batchedMesh);a.keepObject=k=>{let O=!0;const D=S.getComponent(k,ti);return D&&!D.enabled&&(O=!1),O&&g.includes(k)&&(O=!1),O&&S.getComponentInParent(k,nh)&&(O=!1),O&&S.getComponentInParent(k,Jn)&&(O=!1),Rt&&!O&&console.log("USDZExporter: Discarding object",k),O},a.beforeWritingDocument=()=>{if(A()&&l&&c){const k=l.animatedRoots;for(const O of k){const D=S.getComponentsInChildren(O,Ke).filter(V=>V.enabled),L=S.getComponents(O,nn).filter(V=>V.enabled&&!V.isTrigger);(D.length>0||L.length>0)&&console.error("An animated object has physics components in its child hierarchy. This can lead to undefined behaviour due to a bug in Apple's QuickLook (FB15925487). Remove the physics components from child objects or verify that you get the expected results.",O)}}};const f=new Array;this.objectToExport&&this.quickLookCompatible&&this.interactive&&this.objectToExport.traverse(k=>{k.visible||f.push(k)});const y=d.find(k=>k.extensionName==="Behaviour");this.interactive&&y&&f.length>0&&y.addBehavior(HA(f));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"),le.report("export-usdz","Invoking exporter.parse");const v=await a.parse(this.objectToExport,{ar:{anchoring:{type:this.anchoringType},planeAnchoring:{alignment:this.planeAnchoringAlignment}},extensions:d,quickLookCompatible:this.quickLookCompatible,maxTextureSize:this.maxTextureSize,exportInvisible:_}),P=new Blob([v],{type:"model/vnd.usdz+zip"});this.revertWebARSessionRoot(),this.context.time.timeScale=this._previousTimeScale,le.report("export-usdz","Invoking after-export"),this.dispatchEvent(new CustomEvent("after-export",{detail:p}));for(const k of m)S.destroy(k);return ai.Global.Set(r),le.end("export-usdz"),P}openInQuickLook(e,t){const i=e instanceof Blob?URL.createObjectURL(e):e,n=this.buildQuicklookOverlay();Rt&&console.log("QuickLook Overlay",n);const s=n.callToAction?encodeURIComponent(n.callToAction):"",r=n.checkoutTitle?encodeURIComponent(n.checkoutTitle):"",a=n.checkoutSubtitle?encodeURIComponent(n.checkoutSubtitle):"";this.link.href=i+`#callToAction=${s}&checkoutTitle=${r}&checkoutSubtitle=${a}&callToActionURL=${n.callToActionURL}`,this.lastCallback||(this.lastCallback=this.quicklookCallback.bind(this),this.link.addEventListener("message",this.lastCallback)),this.link.download=t+".usdz",this.link.click()}download(e,t){Sa.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"){Rt&&be("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");Rt&&Oe("Quicklook url: "+n),n&&(Zn()?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),Zn()||(console.log("Custom Quicklook banner text requires pro license: https://needle.tools/pricing"),e.callToAction="Close",e.checkoutTitle="\u{1F335} Made with Needle",e.checkoutSubtitle="_"),(e.callToAction?.length||e.checkoutTitle?.length||e.checkoutSubtitle?.length)&&(e.callToAction?.length||(e.callToAction="\0"),e.checkoutTitle?.length||(e.checkoutTitle="\0"),e.checkoutSubtitle?.length||(e.checkoutSubtitle="\0")),this.dispatchEvent(new CustomEvent("quicklook-overlay",{detail:e})),e}static invertForwardMatrix=new J().makeRotationY(Math.PI);static invertForwardQuaternion=new N().setFromEuler(new at(0,Math.PI,0));_rootSessionRootWasAppliedTo=null;_rootPositionBeforeExport=new b;_rootRotationBeforeExport=new N;_rootScaleBeforeExport=new b;getARScaleAndTarget(){if(!this.objectToExport)return{scale:1,_invertForward:!1,target:this.gameObject,sessionRoot:null};const e=S.findObjectOfType(Pp);let t=S.getComponentInParent(this.objectToExport,yn);t||(t=S.getComponentInChildren(this.objectToExport,yn));let i=1,n=!1;const s=this.objectToExport;return e?i=e.arScale:t&&(i=t.arScale,n=t.invertForward),{scale:1/i,_invertForward:n,target:s,sessionRoot:t?.gameObject??null}}applyWebARSessionRoot(){if(!this.objectToExport)return;const{scale:e,_invertForward:t,target:i,sessionRoot:n}=this.getARScaleAndTarget(),s=n?.matrixWorld.clone().invert();this._rootSessionRootWasAppliedTo=i,this._rootPositionBeforeExport.copy(i.position),this._rootRotationBeforeExport.copy(i.quaternion),this._rootScaleBeforeExport.copy(i.scale),i.scale.multiplyScalar(e),t&&i.quaternion.multiply(Sa.invertForwardQuaternion),i.updateMatrix(),i.updateMatrixWorld(!0),n&&s&&i.matrix.premultiply(s)}revertWebARSessionRoot(){if(!this.objectToExport||!this._rootSessionRootWasAppliedTo)return;const e=this._rootSessionRootWasAppliedTo;e.position.copy(this._rootPositionBeforeExport),e.quaternion.copy(this._rootRotationBeforeExport),e.scale.copy(this._rootScaleBeforeExport),e.updateMatrix(),e.updateMatrixWorld(!0),this._rootSessionRootWasAppliedTo=null}createQuicklookButton(){const e=ur.getOrCreate().createQuicklookButton();return e.parentNode||this.context.menu.appendChild(e),e}};Et([u(M)],vi.prototype,"objectToExport"),Et([u()],vi.prototype,"autoExportAnimations"),Et([u()],vi.prototype,"autoExportAudioSources"),Et([u()],vi.prototype,"exportFileName"),Et([u(URL)],vi.prototype,"customUsdzFile"),Et([u(oa)],vi.prototype,"customBranding"),Et([u()],vi.prototype,"anchoringType"),Et([u()],vi.prototype,"maxTextureSize"),Et([u()],vi.prototype,"planeAnchoringAlignment"),Et([u()],vi.prototype,"interactive"),Et([u()],vi.prototype,"physics"),Et([u()],vi.prototype,"allowCreateQuicklookButton"),Et([u()],vi.prototype,"quickLookCompatible");let uo=vi;var XA=Object.defineProperty,QA=Object.getOwnPropertyDescriptor,o0=(o,e,t,i)=>{for(var n=QA(e,t),s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&XA(e,t,n),n};class jl extends E{get fog(){return this._fog||(this._fog=new _b(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)}}o0([u()],jl.prototype,"near"),o0([u()],jl.prototype,"far"),o0([u(oe)],jl.prototype,"color");var YA=Object.defineProperty,s0=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&YA(e,t,n),n};class sa extends E{objectBounds=!1;color;isGizmo=!0;_gizmoObject=null;_boxHelper=null;onEnable(){this.isGizmo&&!jc||(this._gizmoObject||(this.objectBounds?this._gizmoObject=new $C(this.gameObject,this.color??16776960):(this.objectBounds=!1,this._gizmoObject=iu(this.color??16776960))),this.objectBounds?(this.scene.add(this._gizmoObject),this._boxHelper=this._gizmoObject,this.startCoroutine(this.syncObjectBounds(),xe.OnBeforeRender)):this.gameObject.add(this._gizmoObject))}onDisable(){this._gizmoObject&&this.gameObject.remove(this._gizmoObject)}*syncObjectBounds(){for(;this._boxHelper;)this._boxHelper?.update(),yield}}s0([u()],sa.prototype,"objectBounds"),s0([u(oe)],sa.prototype,"color"),s0([u()],sa.prototype,"isGizmo");var ZA=Object.defineProperty,r0=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&ZA(e,t,n),n};class Dl extends E{isGizmo=!1;color0;color1;gridHelper;size;divisions;offset;onEnable(){if(this.isGizmo&&!jc)return;const e=this.size,t=this.divisions;this.gridHelper||(this.gridHelper=new fb(e,t,this.color0??new oe(.4,.4,.4),this.color1??new oe(.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)}}r0([u()],Dl.prototype,"isGizmo"),r0([u(oe)],Dl.prototype,"color0"),r0([u(oe)],Dl.prototype,"color1");var KA=Object.defineProperty,a0=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&KA(e,t,n),n};class l0 extends E{connectedBody;get rigidBody(){return this._rigidBody}_rigidBody=null;onEnable(){this._rigidBody||(this._rigidBody=this.gameObject.getComponent(Ke)),this.rigidBody&&this.connectedBody&&this.startCoroutine(this.create())}*create(){yield,this.rigidBody&&this.connectedBody&&this.activeAndEnabled&&this.createJoint(this.rigidBody,this.connectedBody)}}a0([u(Ke)],l0.prototype,"connectedBody");class c0 extends l0{createJoint(e,t){this.context.physics.engine?.addFixedJoint(e,t)}}class Sh extends l0{anchor;axis;createJoint(e,t){this.axis&&this.anchor&&this.context.physics.engine?.addHingeJoint(e,t,this.anchor,this.axis)}}a0([u(b)],Sh.prototype,"anchor"),a0([u(b)],Sh.prototype,"axis");var JA=Object.defineProperty,e2=Object.getOwnPropertyDescriptor,Ui=(o,e,t,i)=>{for(var n=i>1?void 0:i?e2(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&JA(e,t,n),n};function Bl(o){return o*Math.PI/180}const R1=300,Qs=w("debuglights");class Tt extends E{type=0;get range(){return this._range}set range(e){this._range=e,this.light&&(this.light.type==="SpotLight"||this.light.type==="PointLight")&&"distance"in this.light&&(this.light.distance=e)}_range=1;get spotAngle(){return this._spotAngle}set spotAngle(e){this._spotAngle=e,this.light&&this.light.type==="SpotLight"&&"angle"in this.light&&(this.light.angle=Bl(e/2))}_spotAngle=30;get innerSpotAngle(){return this._innerSpotAngle}set innerSpotAngle(e){if(this._innerSpotAngle=e,this.light&&this.light.type==="SpotLight"&&"penumbra"in this.light){const t=this.spotAngle,i=1-Bl(e/2)/Bl(t/2);this.light.penumbra=i}}_innerSpotAngle=10;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 oe(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){this._intensity=e,this.light&&(this.light.intensity=e),Qs&&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 oe(this.color??16777215),Qs&&console.log(this.name,this)}onEnable(){Qs&&console.log("ENABLE LIGHT",this.name),this.createLight(),!this.isBaked&&(this.light&&(this.light.visible=!0,this.light.intensity=this._intensity,Qs&&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(),xe.LateUpdate))}onDisable(){Qs&&console.log("DISABLE LIGHT",this.name),this.light&&(this.selfIsLight?this.light.intensity=0:this.light.visible=!1)}createLight(){const e=this.selfIsLight;if(e&&!this.light)this.light=this.gameObject,this.light.name=this.name,this._intensity=this.light.intensity,this.type===1&&this.setDirectionalLight(this.light);else if(!this.light)switch(this.type){case 1:const t=new km(this.color,this.intensity*Math.PI);if(t.position.set(0,0,-R1*.5).applyQuaternion(this.gameObject.quaternion),this.gameObject.add(t.target),Sr(t.target,0,0,0),this.light=t,this.gameObject.position.set(0,0,0),this.gameObject.rotation.set(0,0,0),Qs){const r=new GC(this.light,.2,this.color);this.context.scene.add(r)}break;case 0:const i=new HC(this.color,this.intensity*Math.PI,this.range,Bl(this.spotAngle/2),1-Bl(this.innerSpotAngle/2)/Bl(this.spotAngle/2),2);i.position.set(0,0,0),i.rotation.set(0,0,0),this.light=i;const n=i.target;i.add(n),n.position.set(0,0,this.range),n.rotation.set(0,0,0);break;case 2:const s=new Mm(this.color,this.intensity*Math.PI,this.range);this.light=s;break}if(this.light){if(this._intensity>=0?this.light.intensity=this._intensity:this._intensity=this.light.intensity,this.shadows!==0?this.light.castShadow=!0:this.light.castShadow=!1,this.light.shadow){this._shadowResolution!==void 0&&this._shadowResolution>4?(this.light.shadow.mapSize.width=this._shadowResolution,this.light.shadow.mapSize.height=this._shadowResolution):(this.light.shadow.mapSize.width=2048,this.light.shadow.mapSize.height=2048),Qs&&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=R1*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,Qs&&this.context.scene.add(new qC(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)}}Ui([u()],Tt.prototype,"type",2),Ui([u()],Tt.prototype,"range",1),Ui([u()],Tt.prototype,"spotAngle",1),Ui([u()],Tt.prototype,"innerSpotAngle",1),Ui([u(oe)],Tt.prototype,"color",1),Ui([u()],Tt.prototype,"shadowNearPlane",1),Ui([u()],Tt.prototype,"shadowBias",1),Ui([u()],Tt.prototype,"shadowNormalBias",1),Ui([u()],Tt.prototype,"shadows",1),Ui([u()],Tt.prototype,"lightmapBakeType",2),Ui([u()],Tt.prototype,"intensity",1),Ui([u()],Tt.prototype,"shadowDistance",1),Ui([u()],Tt.prototype,"shadowResolution",1),new b(0,0,0);var t2=Object.defineProperty,Ep=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&t2(e,t,n),n};const h0=w("debuglods"),i2=w("nolods");class Fl{screenRelativeTransitionHeight;distance;renderers}Ep([u()],Fl.prototype,"screenRelativeTransitionHeight"),Ep([u()],Fl.prototype,"distance"),Ep([u(ti)],Fl.prototype,"renderers");class n2{model;get renderers(){return this.model.renderers}constructor(e){this.model=e}}class Rp extends E{lodModels=[];_lods=[];_settings=[];_lodsHandler;start(){if(h0&&console.log("LODGROUP",this.name,this.lodModels,this),!i2&&!this._lodsHandler&&this.gameObject&&this.lodModels&&Array.isArray(this.lodModels)){const e=[];for(const i of this.lodModels){const n=new n2(i);this._lods.push(n);for(const s of n.renderers)e.includes(s)||e.push(s)}this._lodsHandler=new Array;for(let i=0;i<e.length;i++){const n=new XC;this._lodsHandler.push(n),this.gameObject.add(n)}const t=new M;t.name="Cull "+this.name;for(let i=0;i<e.length;i++){const n=e[i],s=this._lodsHandler[i],r=n.gameObject;h0&&console.log(i,r.name);for(const a of this._lods){const l=a.model.distance;let c=null;if(a.renderers.includes(n)?c=r:c=t,c.type==="Group"){console.warn(`LODGroup ${this.name}: Group or MultiMaterial object's are not supported as LOD object: ${c.name}`);continue}h0&&console.log("LEVEL",c.name,l),s.autoUpdate=!1,this.onAddLodLevel(s,c,a.model.distance)}}}}onAfterRender(){if(!this.gameObject||!this._lodsHandler)return;const e=this.context.mainCamera;if(e)for(const t of this._lodsHandler){t.update(e);const i=t.getCurrentLevel(),n=t.levels[i];t.layers.mask=n.object.layers.mask}}onAddLodLevel(e,t,i){if(t===this.gameObject){console.warn("LODGroup component must be on parent object and not mesh directly at the moment",t.name,t);return}e.addLevel(t,i*this._distanceFactor,.01);const n={lod:e,levelIndex:e.levels.length-1,distance:i};this._settings.push(n)}_distanceFactor=1;distanceFactor(e){if(e!==this._distanceFactor){this._distanceFactor=e;for(const t of this._settings){const i=t.lod.levels[t.levelIndex];i.distance=t.distance*e}}}}Ep([u(Fl)],Rp.prototype,"lodModels");var o2=Object.defineProperty,d0=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&o2(e,t,n),n};const Tp=w("debugnestedgltf");class Ul extends E{filePath;loaded=new ae;loadAssetInParent=!0;_isLoadingOrDoneLoading=!1;listenToProgress(e){this.filePath?.beginListenDownload(e)}preload(){return this.filePath?.preload()||null}async start(){if(this._isLoadingOrDoneLoading)return;Tp&&console.log(this,this.guid);const e=this.gameObject.parent;if(e&&this.filePath){this._isLoadingOrDoneLoading=!0;const t=new Wn;t.idProvider=new Dt(this.hash(this.guid)),t.parent=this.loadAssetInParent!==!1?e:this.gameObject,this.gameObject.updateMatrix();const i=this.gameObject.matrix;Tp&&console.log("Load nested:",this.filePath?.url??this.filePath,this.gameObject.position);const n=await this.filePath?.instantiate?.call(this.filePath,t);Tp&&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})),Tp&&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}}d0([u(ne)],Ul.prototype,"filePath"),d0([u(ae)],Ul.prototype,"loaded"),d0([u()],Ul.prototype,"loadAssetInParent");var s2=Object.defineProperty,u0=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&s2(e,t,n),n};const r2=w("debugnet"),Ap=class ub extends E{url=null;urlParameterName=null;localhost=null;awake(){r2&&console.log(this),this.context.connection.registerProvider(this)}getWebsocketUrl(){let e=this.url?ub.GetUrl(this.url,this.localhost):null;if(this.urlParameterName){const i=w(this.urlParameterName);i&&typeof i=="string"&&(e=i)}if(!e)return null;const t=new RegExp("(((https?)|(?<socket_prefix>wss?))://)?(www.)?(?<url>.+)","gm").exec(e);return t?.groups?t?.groups.socket_prefix?e:"wss://"+t?.groups.url:null}static GetUrl(e,t){let i=e;const n=ub.IsLocalNetwork()&&t;if(n&&(i=t),e?.startsWith("/")){const s=n?i:window.location.origin;s?.endsWith("/")&&e.startsWith("/")&&(e=e.substring(1)),i=s+e}return i}static IsLocalNetwork(e=window.location.hostname){return Mi(e)}};u0([u()],Ap.prototype,"url"),u0([u()],Ap.prototype,"urlParameterName"),u0([u()],Ap.prototype,"localhost");let p0=Ap;var a2=Object.defineProperty,Ip=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&a2(e,t,n),n};class ra extends E{referenceSpace;from;affectPosition=!1;affectRotation=!1;alignLookDirection=!1;levelLookDirection=!1;levelPosition=!1;positionOffset=new b(0,0,0);rotationOffset=new b(0,0,0);offset=new b(0,0,0);update(){if(!this.from)return;var e=ee(this.from),t=_e(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 _r(this.gameObject.up,0),l=ee(this.referenceSpace);a.setFromNormalAndCoplanarPoint(this.gameObject.up,l);const c=new b(0,0,0);a.projectPoint(e,c),e.copy(c)}this.affectPosition&&yt(this.gameObject,e);const n=new at(this.rotationOffset.x,this.rotationOffset.y,this.rotationOffset.z),s=new N().setFromEuler(n);this.affectRotation&&Sn(this.gameObject,t.multiply(s));const r=new b;this.from.getWorldDirection(r).multiplyScalar(50),this.levelLookDirection&&(r.y=0),this.alignLookDirection&&this.gameObject.lookAt(r)}}Ip([u(S)],ra.prototype,"referenceSpace"),Ip([u(S)],ra.prototype,"from"),Ip([u(b)],ra.prototype,"positionOffset"),Ip([u(b)],ra.prototype,"rotationOffset");var l2=Object.defineProperty,Ys=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&l2(e,t,n),n};class wi{time=0;value=0;inTangent=1/0;inWeight;outTangent=1/0;outWeight;weightedMode;constructor(e=0,t=0){this.time=e,this.value=t}}Ys([u()],wi.prototype,"time"),Ys([u()],wi.prototype,"value"),Ys([u()],wi.prototype,"inTangent"),Ys([u()],wi.prototype,"inWeight"),Ys([u()],wi.prototype,"outTangent"),Ys([u()],wi.prototype,"outWeight"),Ys([u()],wi.prototype,"weightedMode");const T1=class yd{static linearFromTo(e,t,i){const n=new yd,s=new wi;s.time=0,s.value=e;const r=new wi;return r.time=i,r.value=t,n.keys.push(s,r),n}static constant(e){const t=new yd,i=new wi;return i.time=0,i.value=e,t.keys.push(i),t}keys=[];clone(){const e=new yd;return e.keys=this.keys?.map(t=>{const i=new wi;return i.time=t.time,i.value=t.value,i.inTangent=t.inTangent,i.inWeight=t.inWeight,i.outTangent=t.outTangent,i.outWeight=t.outWeight,i.weightedMode=t.weightedMode,i})||[],e}get duration(){return!this.keys||this.keys.length==0?0:this.keys[this.keys.length-1].time}evaluate(e){if(!this.keys||this.keys.length==0)return 0;if(this.keys.length===1)return this.keys[0].value;if(this.keys[0].time>=e)return this.keys[0].value;for(let t=0;t<this.keys.length;t++){const i=this.keys[t];if(i.time<=e)if(t+1<this.keys.length){const n=this.keys[t+1];if(n.time<e)continue;return!isFinite(i.outTangent)||!isFinite(n.inTangent)?i.value:yd.interpolateValue(e,i,n)}else return i.value}return this.keys[this.keys.length-1].value}static interpolateValue(e,t,i){const n=t.time,s=t.value,r=t.outTangent,a=i.time,l=i.value,c=i.inTangent,h=a-n,d=h*h,p=d*h,m=((r+c)*h-2*(l-s))/p,g=(3*(l-s)-(c+2*r)*h)/d,f=r,y=s,_=e-n,v=_*_,P=v*_;return m*P+g*v+f*_+y}};Ys([u(wi)],T1.prototype,"keys");let Ch=T1;var c2=Object.defineProperty,x=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&c2(e,t,n),n};const Lp=w("debugparticles");var es=(o=>(o[o.Billboard=0]="Billboard",o[o.Stretch=1]="Stretch",o[o.HorizontalBillboard=2]="HorizontalBillboard",o[o.VerticalBillboard=3]="VerticalBillboard",o[o.Mesh=4]="Mesh",o))(es||{});class aa{alphaKeys=[];colorKeys=[];get duration(){return 1}evaluate(e,t){let i,n=0,s=null,r=0;for(let a=0;a<this.alphaKeys.length;a++){const l=this.alphaKeys[a];(l.time<e||!i)&&(i=l,n=a)}for(let a=0;a<this.colorKeys.length;a++){const l=this.colorKeys[a];(l.time<e||!s)&&(s=l,r=a)}if(s)if(r+1<this.colorKeys.length){const a=this.colorKeys[r+1],l=j.remap(e,s.time,a.time,0,1);t.r=j.lerp(s.color.r,a.color.r,l),t.g=j.lerp(s.color.g,a.color.g,l),t.b=j.lerp(s.color.b,a.color.b,l)}else t.r=s.color.r,t.g=s.color.g,t.b=s.color.b;if(i)if(n+1<this.alphaKeys.length){const a=this.alphaKeys[n+1],l=j.remap(e,i.time,a.time,0,1);t.alpha=j.lerp(i.alpha,a.alpha,l)}else t.alpha=i.alpha;return t}}x([u()],aa.prototype,"alphaKeys"),x([u()],aa.prototype,"colorKeys");var Ph=(o=>(o[o.Local=0]="Local",o[o.World=1]="World",o[o.Custom=2]="Custom",o))(Ph||{}),jp=(o=>(o[o.Sphere=0]="Sphere",o[o.SphereShell=1]="SphereShell",o[o.Hemisphere=2]="Hemisphere",o[o.HemisphereShell=3]="HemisphereShell",o[o.Cone=4]="Cone",o[o.Box=5]="Box",o[o.Mesh=6]="Mesh",o[o.ConeShell=7]="ConeShell",o[o.ConeVolume=8]="ConeVolume",o[o.ConeVolumeShell=9]="ConeVolumeShell",o[o.Circle=10]="Circle",o[o.CircleEdge=11]="CircleEdge",o[o.SingleSidedEdge=12]="SingleSidedEdge",o[o.MeshRenderer=13]="MeshRenderer",o[o.SkinnedMeshRenderer=14]="SkinnedMeshRenderer",o[o.BoxShell=15]="BoxShell",o[o.BoxEdge=16]="BoxEdge",o[o.Donut=17]="Donut",o[o.Rectangle=18]="Rectangle",o[o.Sprite=19]="Sprite",o[o.SpriteRenderer=20]="SpriteRenderer",o))(jp||{});const ts=class bd{static constant(e){const t=new bd;return t.setConstant(e),t}static betweenTwoConstants(e,t){const i=new bd;return i.setMinMaxConstant(e,t),i}static curve(e,t=1){const i=new bd;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 bd;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=j.clamp01(e),this.curve.evaluate(e)*this.curveMultiplier;case 2:case"TwoCurves":const n=e*this.curveMin.duration,s=e*this.curveMax.duration;return j.lerp(this.curveMin.evaluate(n),this.curveMax.evaluate(s),i%1)*this.curveMultiplier;case 3:case"TwoConstants":return j.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}};x([u()],ts.prototype,"mode"),x([u()],ts.prototype,"constant"),x([u()],ts.prototype,"constantMin"),x([u()],ts.prototype,"constantMax"),x([u(Ch)],ts.prototype,"curve"),x([u(Ch)],ts.prototype,"curveMin"),x([u(Ch)],ts.prototype,"curveMax"),x([u()],ts.prototype,"curveMultiplier");let Y=ts;const Zs=class Lt{static constant(e){const t=new Lt;return t.constant(e),t}static betweenTwoColors(e,t){const i=new Lt;return i.betweenTwoColors(e,t),i}constant(e){return this.mode=0,this.color=e,this}betweenTwoColors(e,t){return this.mode=2,this.colorMin=e,this.colorMax=t,this}mode=0;color;colorMin;colorMax;gradient;gradientMin;gradientMax;static _temp=new se(0,0,0,1);static _temp2=new se(0,0,0,1);evaluate(e,t){const i=t===void 0?Math.random():t;switch(this.mode){case 0:case"Color":return this.color;case 1:case"Gradient":return this.gradient.evaluate(e,Lt._temp),Lt._temp;case 2:case"TwoColors":return Lt._temp.lerpColors(this.colorMin,this.colorMax,i);case 3:case"TwoGradients":return this.gradientMin.evaluate(e,Lt._temp),this.gradientMax.evaluate(e,Lt._temp2),Lt._temp.lerp(Lt._temp2,i);case 4:case"RandomColor":const n=Math.random();return this.gradientMin.evaluate(e,Lt._temp),this.gradientMax.evaluate(e,Lt._temp2),Lt._temp.lerp(Lt._temp2,n)}return Lt._temp.set(16777215),Lt._temp.alpha=1,Lt._temp}};x([u()],Zs.prototype,"mode"),x([u(se)],Zs.prototype,"color"),x([u(se)],Zs.prototype,"colorMin"),x([u(se)],Zs.prototype,"colorMax"),x([u(aa)],Zs.prototype,"gradient"),x([u(aa)],Zs.prototype,"gradientMin"),x([u(aa)],Zs.prototype,"gradientMax");let la=Zs;var m0=(o=>(o[o.Hierarchy=0]="Hierarchy",o[o.Local=1]="Local",o[o.Shape=2]="Shape",o))(m0||{});class Gt{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}x([u(Y)],Gt.prototype,"gravityModifier"),x([u(la)],Gt.prototype,"startColor"),x([u(Y)],Gt.prototype,"startDelay"),x([u(Y)],Gt.prototype,"startLifetime"),x([u(Y)],Gt.prototype,"startRotation"),x([u(Y)],Gt.prototype,"startRotationX"),x([u(Y)],Gt.prototype,"startRotationY"),x([u(Y)],Gt.prototype,"startRotationZ"),x([u(Y)],Gt.prototype,"startSize"),x([u(Y)],Gt.prototype,"startSizeX"),x([u(Y)],Gt.prototype,"startSizeY"),x([u(Y)],Gt.prototype,"startSizeZ"),x([u(Y)],Gt.prototype,"startSpeed");class Dp{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=j.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=j.lerp(this.count.curveMin.evaluate(n),this.count.curveMax.evaluate(n),Math.random());break}}return t}}class is{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}}x([u()],is.prototype,"enabled"),x([u()],is.prototype,"bursts"),x([u(Y)],is.prototype,"rateOverTime"),x([u()],is.prototype,"rateOverTimeMultiplier"),x([u(Y)],is.prototype,"rateOverDistance"),x([u()],is.prototype,"rateOverDistanceMultiplier");class Bp{enabled;color}x([u(la)],Bp.prototype,"color");class ca{enabled;separateAxes;size;sizeMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;_time=0;_temp=new b;evaluate(e,t,i){if(t||(t=this._temp),!this.enabled)return t.x=t.y=t.z=1,t;if(this.separateAxes)t.x=this.x.evaluate(e,i)*this.xMultiplier,t.y=this.y.evaluate(e,i)*this.yMultiplier,t.z=this.z.evaluate(e,i)*this.zMultiplier;else{const n=this.size.evaluate(e,i)*this.sizeMultiplier;t.x=n}return t}}x([u(Y)],ca.prototype,"size"),x([u(Y)],ca.prototype,"x"),x([u(Y)],ca.prototype,"y"),x([u(Y)],ca.prototype,"z");const tt=class _d{get type(){return jp[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 _d}shapeType=5;enabled=!0;alignToDirection=!1;angle=0;arc=360;arcSpread;arcSpeedMultiplier;arcMode;boxThickness;position;rotation;_rotation=new at;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 J;_worldSpaceMatrixInverse=new J;constructor(){Lp&&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=j.toRadians(this.rotation.x),this._rotation.y=j.toRadians(this.rotation.y),this._rotation.z=j.toRadians(this.rotation.z),this._rotation.order="ZYX",e.applyEuler(this._rotation)),t}_vector=new b(0,0,0);_temp=new b(0,0,0);_triangle=new QC;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:Lp&&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 s=this.meshRenderer;s?.destroyed==!1&&this.setMesh(s);const r=e.mesh=this._meshObj,a=e.mesh_geometry=this._meshGeometry;if(r&&a)switch(this.meshShapeType){case 0:{const l=a.getAttribute("position"),c=Math.floor(Math.random()*l.count);this._vector.fromBufferAttribute(l,c),this._vector.applyMatrix4(r.matrixWorld),e.mesh_normal=c}break;case 1:break;case 2:{const l=a.index;if(l){let c=Math.random(),h=Math.random();c+h>1&&(c=1-c,h=1-h);const d=Math.floor(Math.random()*(l.count/3));let p=d*3,m=d*3+1,g=d*3+2;p=l.getX(p),m=l.getX(m),g=l.getX(g);const f=a.getAttribute("position");this._triangle.a.fromBufferAttribute(f,p),this._triangle.b.fromBufferAttribute(f,m),this._triangle.c.fromBufferAttribute(f,g),this._vector.set(0,0,0).addScaledVector(this._triangle.a,c).addScaledVector(this._triangle.b,h).addScaledVector(this._triangle.c,1-(c+h)),this._vector.applyMatrix4(r.matrixWorld),e.mesh_normal=d}}break}break;default:this._vector.set(0,0,0),A()&&!globalThis.__particlesystem_shapetype_unsupported&&(console.warn("ParticleSystem ShapeType is not supported:",jp[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)),Lp&&B.DrawSphere(this._vector,.03,16711680,.5,!0)}_dir=new b;getDirection(e,t){if(!this.enabled)return this._dir.set(0,0,1),this._dir;switch(this.shapeType){case 5:this._dir.set(0,0,1);break;case 4:this._dir.set(0,0,1);break;case 10:case 0:const i=t.x,n=t.y,s=t.z;this._dir.set(i,n,s),this.system?.worldspace?this._dir.sub(this.system.worldPos):this._dir.sub(this.position);break;case 13:const r=e.mesh,a=e.mesh_geometry;if(r&&a)switch(this.meshShapeType){case 0:{const l=a.getAttribute("normal"),c=e.mesh_normal;this._dir.fromBufferAttribute(l,c)}break;case 1:break;case 2:{const l=a.index;if(l){const c=e.mesh_normal,h=l.getX(c*3),d=l.getX(c*3+1),p=l.getX(c*3+2),m=a.getAttribute("position"),g=F(),f=F(),y=F();g.fromBufferAttribute(m,h),f.fromBufferAttribute(m,d),y.fromBufferAttribute(m,p),g.sub(f),y.sub(f),g.cross(y),this._dir.copy(g).multiplyScalar(-1);const _=_e(r);this._dir.applyQuaternion(_)}}break}break;default:this._dir.set(0,0,1);break}return this._space===1&&this._dir.applyQuaternion(this.system.worldQuaternion),this.applyRotation(this._dir),this._dir.normalize(),this.spherizeDirection(this._dir,this.sphericalDirectionAmount),this.randomizeDirection(this._dir,this.randomDirectionAmount),Lp&&(B.DrawSphere(t,.01,8925952,.5,!0),B.DrawDirection(t,this._dir,8925952,.5,!0)),this._dir}static _randomQuat=new N;static _tempVec=new b;randomizePosition(e,t){if(t<=0)return;const i=_d._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=_d._randomQuat,n=_d._tempVec;n.set(Math.random()-.5,Math.random()-.5,Math.random()-.5).normalize(),i.setFromAxisAngle(n,t*Math.random()*Math.PI),e.applyQuaternion(i)}spherizeDirection(e,t){if(t===0)return;const i=Math.random()*Math.PI*2,n=Math.acos(1-Math.random()*2),s=Math.sin(n)*Math.cos(i),r=Math.sin(n)*Math.sin(i),a=Math.cos(n),l=new b(s,r,a);e.lerp(l,t)}randomSpherePoint(e,t,i,n,s){const r=Math.random(),a=Math.random(),l=2*Math.PI*r*(n/360),c=Math.acos(2*a-1),h=j.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,d=e.x+this.scale.x*(-h*Math.sin(c)*Math.cos(l)),p=e.y+this.scale.y*(h*Math.sin(c)*Math.sin(l)),m=e.z+this.scale.z*(h*Math.cos(c));s.x=d,s.y=p,s.z=m}randomCirclePoint(e,t,i,n,s){const r=Math.random(),a=2*Math.PI*r*(n/360),l=j.lerp(1,1-Math.pow(1-Math.random(),Math.PI),i)*t,c=e.x+this.scale.x*l*Math.cos(a),h=e.y+this.scale.y*l*Math.sin(a),d=e.z;s.x=c,s.y=h,s.z=d}_loopTime=0;_loopDirection=1;randomConePoint(e,t,i,n,s,r,a){let l=0,c=0;switch(r){case 0:l=Math.random(),c=Math.random();break;case 2:this._loopTime>1&&(this._loopDirection=-1),this._loopTime<0&&(this._loopDirection=1);case 1:l=.5,c=Math.random(),this._loopTime+=this.system.deltaTime*this._loopDirection;break}let h=2*Math.PI*l*(s/360);switch(r){case 2:case 1:h+=Math.PI+.5,h+=this._loopTime*Math.PI*2,h%=j.toRadians(s);break}const d=Math.acos(2*c-1),p=j.lerp(1,1-Math.pow(1-Math.random(),Math.PI),n)*i,m=e.x+-p*Math.sin(d)*Math.cos(h),g=e.y+p*Math.sin(d)*Math.sin(h),f=e.z;a.x=m*this.scale.x,a.y=g*this.scale.y,a.z=f*this.scale.z}};x([u()],tt.prototype,"shapeType"),x([u()],tt.prototype,"enabled"),x([u()],tt.prototype,"alignToDirection"),x([u()],tt.prototype,"angle"),x([u()],tt.prototype,"arc"),x([u()],tt.prototype,"arcSpread"),x([u()],tt.prototype,"arcSpeedMultiplier"),x([u()],tt.prototype,"arcMode"),x([u(b)],tt.prototype,"boxThickness"),x([u(b)],tt.prototype,"position"),x([u(b)],tt.prototype,"rotation"),x([u(b)],tt.prototype,"scale"),x([u()],tt.prototype,"radius"),x([u()],tt.prototype,"radiusThickness"),x([u()],tt.prototype,"sphericalDirectionAmount"),x([u()],tt.prototype,"randomDirectionAmount"),x([u()],tt.prototype,"randomPositionAmount"),x([u()],tt.prototype,"meshShapeType"),x([u(ah)],tt.prototype,"meshRenderer");let g0=tt;class ve{damping;enabled;frequency;octaveCount;octaveMultiplier;octaveScale;positionAmount;quality;remap;remapEnabled;remapMultiplier;remapX;remapXMultiplier;remapY;remapYMultiplier;remapZ;remapZMultiplier;scrollSpeedMultiplier;separateAxes;strengthMultiplier;strengthX;strengthXMultiplier;strengthY;strengthYMultiplier;strengthZ;strengthZMultiplier;_noise;_time=0;update(e){this._time+=e.time.deltaTime*this.scrollSpeedMultiplier}_temp=new b;apply(e,t,i,n,s,r){if(!this.enabled)return;this._noise||(this._noise=IP(()=>0));const a=this._temp.set(t.x,t.y,t.z).multiplyScalar(this.frequency),l=this._noise(a.x,a.y,a.z,this._time),c=this._noise(a.x,a.y,a.z,this._time+1e3*this.frequency),h=this._noise(a.x,a.y,a.z,this._time+2e3*this.frequency);this._temp.set(l,c,h).normalize();const d=s/r;let p=this.positionAmount.evaluate(d);this.separateAxes?(this._temp.x*=p*this.strengthXMultiplier,this._temp.y*=p*this.strengthYMultiplier,this._temp.z*=p*this.strengthZMultiplier):(this.strengthX&&(p*=this.strengthX.evaluate(d)*1.5),this._temp.multiplyScalar(p)),i.x+=this._temp.x,i.y+=this._temp.y,i.z+=this._temp.z}}x([u()],ve.prototype,"damping"),x([u()],ve.prototype,"enabled"),x([u()],ve.prototype,"frequency"),x([u()],ve.prototype,"octaveCount"),x([u()],ve.prototype,"octaveMultiplier"),x([u()],ve.prototype,"octaveScale"),x([u(Y)],ve.prototype,"positionAmount"),x([u()],ve.prototype,"quality"),x([u(Y)],ve.prototype,"remap"),x([u()],ve.prototype,"remapEnabled"),x([u()],ve.prototype,"remapMultiplier"),x([u(Y)],ve.prototype,"remapX"),x([u()],ve.prototype,"remapXMultiplier"),x([u(Y)],ve.prototype,"remapY"),x([u()],ve.prototype,"remapYMultiplier"),x([u(Y)],ve.prototype,"remapZ"),x([u()],ve.prototype,"remapZMultiplier"),x([u()],ve.prototype,"scrollSpeedMultiplier"),x([u()],ve.prototype,"separateAxes"),x([u()],ve.prototype,"strengthMultiplier"),x([u(Y)],ve.prototype,"strengthX"),x([u()],ve.prototype,"strengthXMultiplier"),x([u(Y)],ve.prototype,"strengthY"),x([u()],ve.prototype,"strengthYMultiplier"),x([u(Y)],ve.prototype,"strengthZ"),x([u()],ve.prototype,"strengthZMultiplier");class Fe{enabled;attachRibbonToTransform=!1;colorOverLifetime;colorOverTrail;dieWithParticles=!0;inheritParticleColor=!0;lifetime;lifetimeMultiplier;minVertexDistance=.2;mode=0;ratio=1;ribbonCount=1;shadowBias=0;sizeAffectsLifetime=!1;sizeAffectsWidth=!1;splitSubEmitterRibbons=!1;textureMode=0;widthOverTrail;widthOverTrailMultiplier;worldSpace=!1;getWidth(e,t,i,n){const s=this.widthOverTrail.evaluate(i,n);return e*=s,e}getColor(e,t,i){const n=this.colorOverTrail.evaluate(i),s=this.colorOverLifetime.evaluate(t);e.x*=n.r*s.r,e.y*=n.g*s.g,e.z*=n.b*s.b,"alpha"in n&&"alpha"in s&&(e.w*=n.alpha*s.alpha)}}x([u()],Fe.prototype,"enabled"),x([u()],Fe.prototype,"attachRibbonToTransform"),x([u(la)],Fe.prototype,"colorOverLifetime"),x([u(la)],Fe.prototype,"colorOverTrail"),x([u()],Fe.prototype,"dieWithParticles"),x([u()],Fe.prototype,"inheritParticleColor"),x([u(Y)],Fe.prototype,"lifetime"),x([u()],Fe.prototype,"lifetimeMultiplier"),x([u()],Fe.prototype,"minVertexDistance"),x([u()],Fe.prototype,"mode"),x([u()],Fe.prototype,"ratio"),x([u()],Fe.prototype,"ribbonCount"),x([u()],Fe.prototype,"shadowBias"),x([u()],Fe.prototype,"sizeAffectsLifetime"),x([u()],Fe.prototype,"sizeAffectsWidth"),x([u()],Fe.prototype,"splitSubEmitterRibbons"),x([u()],Fe.prototype,"textureMode"),x([u(Y)],Fe.prototype,"widthOverTrail"),x([u()],Fe.prototype,"widthOverTrailMultiplier"),x([u()],Fe.prototype,"worldSpace");class He{enabled;space=0;orbitalX;orbitalY;orbitalZ;orbitalXMultiplier;orbitalYMultiplier;orbitalZMultiplier;orbitalOffsetX;orbitalOffsetY;orbitalOffsetZ;speedModifier;speedModifierMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;_system;update(e){this._system=e}_temp=new b;_temp2=new b;_temp3=new b;_hasOrbital=!1;_index=0;_orbitalMatrix=new J;init(e){this._index==0&&(e.debug=!0),this._index+=1,e.orbitx=this.orbitalX.evaluate(Math.random()),e.orbity=this.orbitalY.evaluate(Math.random()),e.orbitz=this.orbitalZ.evaluate(Math.random()),this._hasOrbital=e.orbitx!=0||e.orbity!=0||e.orbitz!=0}apply(e,t,i,n,s,r,a){if(!this.enabled)return;const l=r/a,c=this.speedModifier.evaluate(l)*this.speedModifierMultiplier,h=this.x.evaluate(l),d=this.y.evaluate(l),p=this.z.evaluate(l);if(this._temp.set(-h,d,p),this._system&&this._system.main.simulationSpace===1&&this._temp.applyQuaternion(this._system.worldQuaternion),this._hasOrbital&&this._system?.worldPos){const m=this._temp2.set(i.x,i.y,i.z),g=this.orbitalXMultiplier,f=this.orbitalYMultiplier,y=this.orbitalZMultiplier,_=c*Math.PI*2*10,v=Math.cos(_*g),P=Math.sin(_*g),k=Math.cos(_*f),O=Math.sin(_*f),D=Math.cos(_*y),L=Math.sin(_*y),V=m.x*(k*D)+m.y*(k*L)+m.z*-O,W=m.x*(P*O*D-v*L)+m.y*(P*O*L+v*D)+m.z*(P*k),G=m.x*(v*O*D+P*L)+m.y*(v*O*L-P*D)+m.z*(v*k),X=this._temp3.set(m.x-V,m.y-W,m.z-G);X.normalize(),X.multiplyScalar(.2/s*Math.max(this.orbitalXMultiplier,this.orbitalYMultiplier,this.orbitalZMultiplier)),n.x+=X.x,n.y+=X.y,n.z+=X.z}n.x+=this._temp.x,n.y+=this._temp.y,n.z+=this._temp.z,n.x*=c,n.y*=c,n.z*=c}}x([u()],He.prototype,"enabled"),x([u()],He.prototype,"space"),x([u(Y)],He.prototype,"orbitalX"),x([u(Y)],He.prototype,"orbitalY"),x([u(Y)],He.prototype,"orbitalZ"),x([u()],He.prototype,"orbitalXMultiplier"),x([u()],He.prototype,"orbitalYMultiplier"),x([u()],He.prototype,"orbitalZMultiplier"),x([u()],He.prototype,"orbitalOffsetX"),x([u()],He.prototype,"orbitalOffsetY"),x([u()],He.prototype,"orbitalOffsetZ"),x([u(Y)],He.prototype,"speedModifier"),x([u()],He.prototype,"speedModifierMultiplier"),x([u(Y)],He.prototype,"x"),x([u()],He.prototype,"xMultiplier"),x([u(Y)],He.prototype,"y"),x([u()],He.prototype,"yMultiplier"),x([u(Y)],He.prototype,"z"),x([u()],He.prototype,"zMultiplier");class qt{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}}x([u()],qt.prototype,"animation"),x([u()],qt.prototype,"enabled"),x([u()],qt.prototype,"cycleCount"),x([u(Y)],qt.prototype,"frameOverTime"),x([u()],qt.prototype,"frameOverTimeMultiplier"),x([u()],qt.prototype,"numTilesX"),x([u()],qt.prototype,"numTilesY"),x([u(Y)],qt.prototype,"startFrame"),x([u()],qt.prototype,"startFrameMultiplier"),x([u()],qt.prototype,"rowMode"),x([u()],qt.prototype,"rowIndex"),x([u()],qt.prototype,"spriteCount"),x([u()],qt.prototype,"timeMode");class jn{enabled;separateAxes;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t){return this.enabled?this.separateAxes?0:this.z.evaluate(e,t)*-1:0}}x([u()],jn.prototype,"enabled"),x([u()],jn.prototype,"separateAxes"),x([u(Y)],jn.prototype,"x"),x([u()],jn.prototype,"xMultiplier"),x([u(Y)],jn.prototype,"y"),x([u()],jn.prototype,"yMultiplier"),x([u(Y)],jn.prototype,"z"),x([u()],jn.prototype,"zMultiplier");class an{enabled;range;separateAxes;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t){if(!this.enabled)return 0;if(!this.separateAxes){const i=j.lerp(this.range.x,this.range.y,t);return this.z.evaluate(i)*-1}return 0}}x([u()],an.prototype,"enabled"),x([u()],an.prototype,"range"),x([u()],an.prototype,"separateAxes"),x([u(Y)],an.prototype,"x"),x([u()],an.prototype,"xMultiplier"),x([u(Y)],an.prototype,"y"),x([u()],an.prototype,"yMultiplier"),x([u(Y)],an.prototype,"z"),x([u()],an.prototype,"zMultiplier");class dt{enabled;dampen;drag;dragMultiplier;limit;limitMultiplier;separateAxes;limitX;limitXMultiplier;limitY;limitYMultiplier;limitZ;limitZMultiplier;multiplyDragByParticleSize=!1;multiplyDragByParticleVelocity=!1;space;_temp=new b;_temp2=new b;apply(e,t,i,n,s,r,a){if(this.enabled){const l=this.limit.evaluate(s)*this.limitMultiplier;if(t.length()>l){this._temp.copy(t).normalize().multiplyScalar(l);const c=this.dampen*.5;t.x=j.lerp(t.x,this._temp.x,c),t.y=j.lerp(t.y,this._temp.y,c),t.z=j.lerp(t.z,this._temp.z,c),i.x=j.lerp(i.x,this._temp.x,c),i.y=j.lerp(i.y,this._temp.y,c),i.z=j.lerp(i.z,this._temp.z,c)}}}}x([u()],dt.prototype,"enabled"),x([u()],dt.prototype,"dampen"),x([u(Y)],dt.prototype,"drag"),x([u()],dt.prototype,"dragMultiplier"),x([u(Y)],dt.prototype,"limit"),x([u()],dt.prototype,"limitMultiplier"),x([u()],dt.prototype,"separateAxes"),x([u(Y)],dt.prototype,"limitX"),x([u()],dt.prototype,"limitXMultiplier"),x([u(Y)],dt.prototype,"limitY"),x([u()],dt.prototype,"limitYMultiplier"),x([u(Y)],dt.prototype,"limitZ"),x([u()],dt.prototype,"limitZMultiplier"),x([u()],dt.prototype,"multiplyDragByParticleSize"),x([u()],dt.prototype,"multiplyDragByParticleVelocity"),x([u()],dt.prototype,"space");const Oh=class WS{enabled;curve;curveMultiplier;mode;clone(){const e=new WS;return e.enabled=this.enabled,e.curve=this.curve?.clone(),e.curveMultiplier=this.curveMultiplier,e.mode=this.mode,e}system;get _lastWorldPosition(){return this.system._iv_lastWorldPosition||(this.system._iv_lastWorldPosition=new b),this.system._iv_lastWorldPosition}get _velocity(){return this.system._iv_velocity||(this.system._iv_velocity=new b),this.system._iv_velocity}_temp=new b;_firstUpdate=!0;awake(e){this.system=e,this.reset()}reset(){this._firstUpdate=!0}update(e){this.enabled&&this.system.worldspace!==!1&&(this._firstUpdate?(this._firstUpdate=!1,this._velocity.set(0,0,0),this._lastWorldPosition.copy(this.system.worldPos)):this._lastWorldPosition&&(this._velocity.copy(this.system.worldPos).sub(this._lastWorldPosition).multiplyScalar(1/this.system.deltaTime),this._lastWorldPosition.copy(this.system.worldPos)))}applyInitial(e){if(this.enabled&&this.system.worldspace!==!1&&this.mode===0){const t=this.curve.evaluate(Math.random(),Math.random());this._temp.copy(this._velocity).multiplyScalar(t),e.x+=this._temp.x,e.y+=this._temp.y,e.z+=this._temp.z}}_frames=0;applyCurrent(e,t,i){if(this.enabled&&this.system&&this.system.worldspace!==!1&&this.mode===1){const n=this.curve.evaluate(t,i);this._temp.copy(this._velocity).multiplyScalar(n),e.x+=this._temp.x,e.y+=this._temp.y,e.z+=this._temp.z}}};x([u()],Oh.prototype,"enabled"),x([u(Y)],Oh.prototype,"curve"),x([u()],Oh.prototype,"curveMultiplier"),x([u()],Oh.prototype,"mode");let f0=Oh;class xi{enabled;range;separateAxes;size;sizeMultiplier;x;xMultiplier;y;yMultiplier;z;zMultiplier;evaluate(e,t,i,n){const s=e.length(),r=j.remap(s,this.range.x,this.range.y,0,1),a=this.size.evaluate(r,i);return n.x*=a,n.y*=a,n.z*=a,n}}x([u()],xi.prototype,"enabled"),x([u(K)],xi.prototype,"range"),x([u()],xi.prototype,"separateAxes"),x([u(Y)],xi.prototype,"size"),x([u()],xi.prototype,"sizeMultiplier"),x([u(Y)],xi.prototype,"x"),x([u()],xi.prototype,"xMultiplier"),x([u(Y)],xi.prototype,"y"),x([u()],xi.prototype,"yMultiplier"),x([u(Y)],xi.prototype,"z"),x([u()],xi.prototype,"zMultiplier");class zl{enabled;range;color;evaluate(e,t,i){const n=e.length(),s=j.remap(n,this.range.x,this.range.y,0,1),r=this.color.evaluate(s,t);i.x*=r.r,i.y*=r.g,i.z*=r.b,"alpha"in r&&(i.w*=r.alpha)}}x([u()],zl.prototype,"enabled"),x([u(K)],zl.prototype,"range"),x([u(la)],zl.prototype,"color"),new b(1,1,1),new b(0,0,1);class y0{constructor(e,t,i,n){this.system=e,this.particleSystem=t,this.subSystem=i,this.subParticleSystem=n,this.subParticleSystem&&this.subParticleSystem&&(this.subParticleSystem.onlyUsedByOther=!0);const s=1e3;this._circularBuffer=new Ei(()=>new Vm,s)}type="NeedleParticleSubEmitter";emitterType;emitterProbability;q_=new N;v_=new b;v2_=new b;_emitterMatrix=new Vm;_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===b0.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===b0.Death){let n=e.life;if(e[Nl]!==void 0&&(n=e[Nl]),!(e.age+t*1.2>=n))return;const s=this.subSystem.main.maxParticles-this.subSystem.currentParticles;e.emissionState.waitEmiting=s}const i=new Vm;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 h2=Object.defineProperty,Ue=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&h2(e,t,n),n};const Ks=w("debugparticles"),d2=w("noprogressive"),u2=w("debugprogressive");var b0=(o=>(o[o.Birth=0]="Birth",o[o.Collision=1]="Collision",o[o.Death=2]="Death",o[o.Trigger=3]="Trigger",o[o.Manual=4]="Manual",o))(b0||{});class ln extends E{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"){Ks&&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=Oo,t.map.premultiplyAlpha=!1);const i=new Ce;i.copy(t),e?this.trailMaterial=i:this.particleMaterial=i}t.map&&(t.map.colorSpace=Oo,t.map.premultiplyAlpha=!1),e&&t.side===ws&&(t=t.clone(),t.side=Id,e?this.trailMaterial=t:this.particleMaterial=t)}return t&&!d2&&t._didRequestTextureLOD===void 0&&(t._didRequestTextureLOD=0,u2&&console.log("Load material LOD",t.name),Ve.assignTextureLOD(t,0)),t}getMesh(e){let t=null;if(!t&&(this.particleMesh instanceof H&&(t=this.particleMesh.geometry),t===null)){t=new vn(1,1);const i=t.attributes.uv;for(let n=0;n<i.count;n++)i.setX(n,1-i.getX(n))}return new H(t,this.getMaterial())}}Ue([u()],ln.prototype,"renderMode"),Ue([u(we)],ln.prototype,"particleMaterial"),Ue([u(we)],ln.prototype,"trailMaterial"),Ue([u()],ln.prototype,"maxParticleSize"),Ue([u()],ln.prototype,"minParticleSize"),Ue([u()],ln.prototype,"velocityScale"),Ue([u()],ln.prototype,"cameraVelocityScale"),Ue([u()],ln.prototype,"lengthScale");class Fp{_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 _0{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 p2 extends _0{genValue(){return this.system.textureSheetAnimation.getStartIndex()}}class m2 extends _0{_lastPosition=new b;_lastDistance=0;update(){const e=ee(this.system.gameObject);this._lastDistance=this._lastPosition.distanceTo(e),this._lastPosition.copy(e)}genValue(){if(!this.system.isPlaying||!this.system.emission.enabled||this.system.currentParticles>=this.system.maxParticles)return 0;let e=this.system.emission.rateOverTime.evaluate(this.system.time/this.system.duration,Math.random());if(this.system.deltaTime>0){const n=this.system.emission.rateOverDistance.evaluate(this.system.time/this.system.duration,Math.random());let s=this._lastDistance/this.system.deltaTime*n;Number.isFinite(s)||(s=0),e+=s}const t=this.system.emission.getBurst();t>0&&(e+=t/this.system.deltaTime);const i=this.system.maxParticles-this.system.currentParticles;return j.clamp(e,0,i/this.system.deltaTime)}}class g2 extends _0{genValue(){return this.system.isPlaying,0}}class Js{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 f2 extends Js{type="NeedleTextureSheet";update(e,t){const i=this.system.textureSheetAnimation;if(i.enabled){const n=e.age/e.life,s=i.evaluate(n);s!==void 0&&(e.uvTile=s)}}}const A1=Symbol("particleRotation");class y2 extends Js{type="NeedleRotation";initialize(e){e[A1]=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[A1])*t:this.system.renderer.renderMode===es.Billboard&&(e.rotation=Math.PI),this.system.rotationBySpeed.enabled)){const n=e.velocity.length();e.rotation+=this.system.rotationBySpeed.evaluate(i,n)*t}}}const I1=Symbol("sizeLerpFactor"),b2=new b;class _2 extends Js{type="NeedleSize";_minSize=0;_maxSize=1;initialize(e){e[I1]=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[I1]).x);let s=1;this.system.renderer.renderMode!==es.Mesh&&(s=this.system.worldScale.x/this.system.cameraScale);const r=F(e.startSize).multiplyScalar(n*s);if(e.size.set(r.x,r.y,r.z),this.system.localspace){const a=F1(this.system,b2);e.size.x*=a.x,e.size.y*=a.y,e.size.z*=a.z}}}const Nl=Symbol("particleLife"),v0=Symbol("trailLifetime"),L1=Symbol("trailStartLength"),w0=Symbol("trailWidthRandom");class v2 extends Js{type="NeedleTrail";initialize(e){e instanceof $b&&(e[Nl]=e.life,this.system.trails.enabled&&this.system.trails.dieWithParticles===!1&&(e[v0]=this.system.trails.lifetime.evaluate(Math.random(),Math.random()),e.life+=e[v0]),e[L1]=e.length,e[w0]=Math.random())}update(e){if(this.system.trails?.enabled&&e instanceof $b){const t=e,i=e.age/e[Nl],n=e.previous.values(),s=e.previous.length;for(let r=0;r<s;r++){const a=n.next().value,l=1-r/(s-1),c=e.size;if(c.x<=0&&!this.system.trails.sizeAffectsWidth){const h=20*this.system.trails.widthOverTrail.evaluate(.5,t[w0]);c.x=h,c.y=h,c.z=h}a.size=this.system.trails.getWidth(c.x,i,l,t[w0]),a.color.copy(e.color),this.system.trails.getColor(a.color,i,l)}if(e.age>e[Nl]){e.velocity.set(0,0,0);const r=(e.age-e[Nl])/e[v0];t.length=j.lerp(e[L1],0,r)}}}}const Up=Symbol("startVelocity"),j1=Symbol("gravityModifier"),x0=Symbol("gravitySpeed"),zp=Symbol("velocity lerp factor"),S0=new b;class w2 extends Js{type="NeedleVelocity";_gravityDirection=new b;initialize(e){const t=this.system.main.simulationSpeed;e.startSpeed=this.system.main.startSpeed.evaluate(Math.random(),Math.random());const i=this.system.shape.getDirection(e,e.position);e.velocity.x=i.x*e.startSpeed,e.velocity.y=i.y*e.startSpeed,e.velocity.z=i.z*e.startSpeed,this.system.inheritVelocity?.enabled&&this.system.inheritVelocity.applyInitial(e.velocity),e[Up]?e[Up].copy(e.velocity):e[Up]=e.velocity.clone();const n=this.system.main.gravityModifier.evaluate(Math.random(),Math.random());e[j1]=n*t,e[x0]=n*t*.5,e[zp]=Math.random(),this.system.velocityOverLifetime?.init(e),this._gravityDirection.set(0,-1,0),this.system.main.simulationSpace===Ph.Local&&this._gravityDirection.applyQuaternion(this.system.worldQuaternionInverted).normalize()}update(e,t){const i=e[Up],n=e[j1];if(n!==0){const d=n*e[x0];S0.copy(this._gravityDirection).multiplyScalar(d),e[x0]+=t*.05,i.add(S0)}e.velocity.copy(i);const s=e.age/e.life;this.system.inheritVelocity?.enabled&&this.system.inheritVelocity.applyCurrent(e.velocity,s,e[zp]);const r=this.system.noise;r.enabled&&r.apply(0,e.position,e.velocity,t,e.age,e.life);const a=this.system.sizeBySpeed;a?.enabled&&(e.size=a.evaluate(e.velocity,s,e[zp],e.size));const l=this.system.colorBySpeed;l?.enabled&&l.evaluate(e.velocity,e[zp],e.color);const c=this.system.velocityOverLifetime;c.enabled&&c.apply(e,0,e.position,e.velocity,t,e.age,e.life);const h=this.system.limitVelocityOverLifetime;if(h.enabled&&h.apply(e.position,i,e.velocity,e.size,s,t,1),this.system.worldspace){const d=this.system.worldScale;e.velocity.x*=d.x,e.velocity.y*=d.y,e.velocity.z*=d.z}}}const D1=Symbol("colorLerpFactor"),B1=new se(1,1,1,1),ha=new se(1,1,1,1);class x2 extends Js{type="NeedleColor";initialize(e){}_init(e){const t=this.system.renderer.particleMaterial;ha.copy(this.system.main.startColor.evaluate(Math.random())),t?.color&&(B1.copy(t.color),ha.multiply(B1)),ha.convertLinearToSRGB(),e.startColor.set(ha.r,ha.g,ha.b,ha.alpha),e.color.copy(e.startColor),e[D1]=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[D1]);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 S2{system;emission;get anim(){return this.system.textureSheetAnimation}constructor(e){this.system=e,this.emission=new m2(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 Fp(this.system.main.startLifetime)}get startSpeed(){return new Fp(this.system.main.startSpeed)}get startRotation(){return new Fp(this.system.main.startRotation)}get startSize(){return new Fp(this.system.main.startSize)}startLength;get startColor(){return new DP(new BP(1,1,1,1))}get emissionOverTime(){return this.emission}get emissionOverDistance(){return new g2(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 Ro.Trail;switch(this.system.renderer.renderMode){case es.Billboard:return Ro.BillBoard;case es.Stretch:return Ro.StretchedBillBoard;case es.HorizontalBillboard:return Ro.HorizontalBillBoard;case es.VerticalBillboard:return Ro.VerticalBillBoard;case es.Mesh:return Ro.Mesh}return Ro.BillBoard}rendererEmitterSettings={startLength:new FP(220),followLocalOrigin:!1};get speedFactor(){let e=this.system.main.simulationSpeed;return this.system.renderer?.renderMode===es.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=Oo,this.clonedTexture.original=t,this.clonedTexture.clone=i}return this.clonedTexture.clone}return this.flatWhiteTexture||(this.flatWhiteTexture=ff(new se(1,1,1,1),1)),this.flatWhiteTexture}get startTileIndex(){return new p2(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??YC}get transparent(){return this.system.renderer.transparent}get worldSpace(){return this.system.main.simulationSpace===Ph.World}}class C2{burstParticleIndex=0;burstParticleCount=0;isBursting=!1;travelDistance=0;previousWorldPos;burstIndex=0;burstWaveIndex=0;time=0;waitEmiting=0}const Xt=class vm extends E{play(e=!1){e&&S.foreachComponent(this.gameObject,t=>{t instanceof vm&&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 vm&&t!==this&&t.pause(!1)},!0),this._isPlaying=!1}stop(e=!0,t=!1){e&&S.foreachComponent(this.gameObject,i=>{i instanceof vm&&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 C2),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===Ph.World}get localspace(){return this.main.simulationSpace===Ph.Local}__worldQuaternion=new N;get worldQuaternion(){return this.__worldQuaternion}_worldQuaternionInverted=new N;get worldQuaternionInverted(){return this._worldQuaternionInverted}_worldScale=new b;get worldScale(){return this._worldScale}_worldPositionFrame=-1;_worldPos=new b;get worldPos(){return this._worldPositionFrame!==this.context.time.frame&&(this._worldPositionFrame=this.context.time.frame,ee(this.gameObject,this._worldPos)),this._worldPos}get matrixWorld(){return this._container.matrixWorld}get isSubsystem(){return this._isUsedAsSubsystem}addBehaviour(e){return this._particleSystem?(e instanceof Js&&(e.system=this),Ks&&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()||Ks)&&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 Dp)){const n=new Dp;Ja(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 Np)){const n=new Np;Ja(n,i),e[t]=n}}Ks&&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(ln),!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 M,this._container.matrixAutoUpdate=!1,this.context.scene.add(this._container),this._batchSystem=new LP,this._batchSystem.name=this.gameObject.name,this._container.add(this._batchSystem),this._interface=new S2(this),this._particleSystem=new jP(this._interface),this._particleSystem.addBehavior(new _2(this)),this._particleSystem.addBehavior(new x2(this)),this._particleSystem.addBehavior(new f2(this)),this._particleSystem.addBehavior(new y2(this)),this._particleSystem.addBehavior(new w2(this)),this._particleSystem.addBehavior(new v2(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),Ks&&(console.log(this),this.gameObject.add(new Pi(1)))}start(){this.addSubParticleSystems(),this.updateLayers(),this.renderer.particleMesh instanceof H&&this._interface.renderMode==Ro.Mesh&&Ve.assignMeshLOD(this.renderer.particleMesh,0).then(e=>{e&&this.particleSystem&&this._interface.renderMode==Ro.Mesh&&(this.particleSystem.instancingGeometry=e)})}onDestroy(){this._container?.removeFromParent(),this._batchSystem?.removeFromParent(),this._particleSystem?.emitter.removeFromParent(),this._particleSystem?.dispose()}onEnable(){this.main&&(this.inheritVelocity&&(this.inheritVelocity.system=this),this._batchSystem&&(this._batchSystem.visible=!0),this.playOnAwake&&this.play(),this._isPlaying=this.playOnAwake)}onDisable(){this._batchSystem&&(this._batchSystem.visible=!1)}onBeforeRender(){this.main&&(this._didPreWarm===!1&&this.main?.prewarm===!0&&(this._didPreWarm=!0,this.preWarm()),this.onUpdate(),this.onSimulate(this.deltaTime))}preWarm(){if(!this.emission?.enabled||this.emission.rateOverTime.getMax()<=0)return;const e=1/60,t=this.main.duration,i=this.main.startLifetime.getMax(),n=Math.min(Math.max(t,i)/Math.max(.01,this.main.simulationSpeed),1e3),s=Math.ceil(n/e),r=Date.now();Ks&&console.log(`Particles ${this.name} - Prewarm for ${s} frames (${n} sec). Duration: ${t}, Lifetime: ${i}`);for(let a=0;a<s&&!(this.currentParticles>=this.maxParticles);a++){const l=Date.now()-r;if(l>2e3){console.warn(`Particles ${this.name} - Prewarm took too long. Aborting: ${l}`);break}this.onUpdate(),this.onSimulate(e)}}_lastBatchesCount=-1;onSimulate(e){if(this._batchSystem){let t=this.context.time.frameCount%60===0;this._lastBatchesCount!==this._batchSystem.batches.length&&(this._lastBatchesCount=this._batchSystem.batches.length,t=!0),t&&this.updateLayers(),this._batchSystem.update(e)}this._time+=e,this._time>this.duration&&(this._time=0)}updateLayers(){if(this._batchSystem)for(let e=0;e<this._batchSystem.batches.length;e++){const t=this._batchSystem.batches[e];t.layers.disableAll();const i=this.layer;t.layers.mask=1<<i}}onUpdate(){if(this._bursts&&(this.emission.bursts=this._bursts,delete this._bursts),!this._isPlaying)return;const e=this.context.mainCamera;if(e){const n=$e(e);this._cameraScale=n.x}const t=!this.worldspace,i=this.gameObject;if(_e(i,this.__worldQuaternion),this._worldQuaternionInverted.copy(this.__worldQuaternion).invert(),$e(this.gameObject,this._worldScale),t&&this._container&&this.gameObject?.parent){const n=F1(this,S0);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 y0(this,this._particleSystem,e.particleSystem,t);i.emitterType=e.type,i.emitterProbability=e.emitProbability,this._particleSystem.addBehavior(i)}else Ks&&console.warn("Could not add SubParticleSystem",e,this)}}};Ue([u(Bp)],Xt.prototype,"colorOverLifetime"),Ue([u(Gt)],Xt.prototype,"main"),Ue([u(is)],Xt.prototype,"emission"),Ue([u(ca)],Xt.prototype,"sizeOverLifetime"),Ue([u(g0)],Xt.prototype,"shape"),Ue([u(ve)],Xt.prototype,"noise"),Ue([u(Fe)],Xt.prototype,"trails"),Ue([u(He)],Xt.prototype,"velocityOverLifetime"),Ue([u(dt)],Xt.prototype,"limitVelocityOverLifetime"),Ue([u(f0)],Xt.prototype,"inheritVelocity"),Ue([u(zl)],Xt.prototype,"colorBySpeed"),Ue([u(qt)],Xt.prototype,"textureSheetAnimation"),Ue([u(jn)],Xt.prototype,"rotationOverLifetime"),Ue([u(an)],Xt.prototype,"rotationBySpeed"),Ue([u(xi)],Xt.prototype,"sizeBySpeed");let kh=Xt;class Np{particleSystem;emitProbability=1;properties;type;_deserialize(e,t){const i=this.particleSystem;if(i instanceof kh)return;let n="";i&&typeof i.guid=="string"&&(n=i.guid,this.particleSystem=S.findByGuid(n,t)),Ks&&!(this.particleSystem instanceof kh)&&console.warn("Could not find particle system for sub emitter",n,t,this)}}function F1(o,e){if(e.set(1,1,1),o.gameObject.parent&&o.localspace)switch(o.main.scalingMode){case m0.Local:e=$e(o.gameObject.parent,e),e.x=1/e.x,e.y=1/e.y,e.z=1/e.z;break;default:if(!o.unsupported_scaling_mode){o.unsupported_scaling_mode=!0;const t="ParticleSystem scale mode "+m0[o.main.scalingMode]+" is not supported";A()&&be(t),console.warn(t,o.name,o)}e=$e(o.gameObject,e);break}return e}var P2=Object.defineProperty,C0=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&P2(e,t,n),n};class Wl extends E{strength=1;radius=2;targets=[];update(){const e=this.gameObject.worldPosition,t=-this.strength*this.context.time.deltaTime;this.targets?.forEach(i=>{if(!i)return;const n=i.gameObject.worldPosition.sub(e),s=n.length();if(s>this.radius)return;let r=t;s>1?r/=s*s:r/=Math.max(.05,s),i.applyImpulse(n.multiplyScalar(r))})}}C0([u()],Wl.prototype,"strength"),C0([u()],Wl.prototype,"radius"),C0([u(Ke)],Wl.prototype,"targets");class rc extends E{_didAssignPlayerColor=!1;onEnable(){this.context.connection.beginListen(ie.JoinedRoom,this.tryAssignColor),this._didAssignPlayerColor||this.startCoroutine(this.waitForConnection())}onDisable(){this.context.connection.stopListen(ie.JoinedRoom,this.tryAssignColor)}*waitForConnection(){for(;!this.destroyed&&this.activeAndEnabled&&(yield mf(.2),!this.tryAssignColor()););}tryAssignColor=()=>{const e=S.getComponentInParent(this.gameObject,sn);if(e&&e.owner)return this._didAssignPlayerColor=!0,this.assignUserColor(e.owner),!0;const t=S.getComponentInParent(this.gameObject,Le);return t?.connectionId?(this._didAssignPlayerColor=!0,this.assignUserColor(t.connectionId),!0):!1};assignUserColor(e){const t=rc.hashCode(e),i=rc.colorFromHashCode(t);if(this.gameObject.type==="Mesh"){const n=this.gameObject;this.assignColor(i,e,n)}else if(this.gameObject.children)for(const n of this.gameObject.children){const s=n;s.material&&s.material.color&&this.assignColor(i,e,s)}}assignColor(e,t,i){let n=i.material;n&&(n._playerMaterial!==t&&(n=n.clone(),n._playerMaterial=t,i.material=n),n.color=e)}static hashCode(e){var t=0,i,n;if(e.length===0)return t;for(i=0;i<e.length;i++)n=e.charCodeAt(i),t=(t<<5)-t+n,t|=0;return t}static colorFromHashCode(e){const t=(e&16711680)>>16,i=(e&65280)>>8,n=e&255;return new oe(t/255,i/255,n/255)}}const Mh=w("debugpost");let P0=null;function O2(o){P0=o}function U1(o){let e=o.gameObject;for(;e;){for(const t of wu(e))if(t.isPostProcessingManager===!0)return t;e=e.parent}return null}function k2(o){let e=U1(o);if(!e)if(P0){Mh&&console.warn("Adding postprocessing manager to the scene.");const t=o.scene;e=Mn(t,P0)}else A()&&console.warn("No post processing manager found");return e}const ut={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 it=null;function M2(o){Mh==="verbose"&&console.debug("Before ordering effects",[...o]),it||(it=new Map,it.set(T.POSTPROCESSING.MODULE.NormalPass,ut.NormalPass),it.set(T.POSTPROCESSING.MODULE.DepthDownsamplingPass,ut.DepthDownsamplingPass),it.set(T.POSTPROCESSING.MODULE.SMAAEffect,ut.SMAA),it.set(T.POSTPROCESSING.MODULE.SSAOEffect,ut.SSAO),it.set(T.POSTPROCESSING_AO.MODULE.N8AOPostPass,ut.SSAO),it.set(T.POSTPROCESSING_AO.MODULE.N8AOPass,ut.SSAO),it.set(T.POSTPROCESSING.MODULE.TiltShiftEffect,ut.TiltShift),it.set(T.POSTPROCESSING.MODULE.DepthOfFieldEffect,ut.DepthOfField),it.set(T.POSTPROCESSING.MODULE.ChromaticAberrationEffect,ut.ChromaticAberration),it.set(T.POSTPROCESSING.MODULE.BloomEffect,ut.Bloom),it.set(T.POSTPROCESSING.MODULE.SelectiveBloomEffect,ut.Bloom),it.set(T.POSTPROCESSING.MODULE.VignetteEffect,ut.Vignette),it.set(T.POSTPROCESSING.MODULE.PixelationEffect,ut.Pixelation),it.set(T.POSTPROCESSING.MODULE.ToneMappingEffect,ut.ToneMapping),it.set(T.POSTPROCESSING.MODULE.HueSaturationEffect,ut.HueSaturation),it.set(T.POSTPROCESSING.MODULE.BrightnessContrastEffect,ut.BrightnessContrast)),o.sort((e,t)=>{const i=typeof e.priority=="number"?e.priority:it.get(e.effect.constructor)??Number.NEGATIVE_INFINITY,n=typeof t.priority=="number"?t.priority:it.get(t.effect.constructor)??Number.NEGATIVE_INFINITY;return i===Number.NEGATIVE_INFINITY?(Mh&&console.warn("Unknown effect found: ",e.constructor.name,e),1):n===Number.NEGATIVE_INFINITY?(Mh&&console.warn("Unknown effect found: ",t.constructor.name,t),-1):i-n}),Mh==="verbose"&&console.debug("After ordering effects",[...o])}var E2=Object.defineProperty,R2=Object.getOwnPropertyDescriptor,z1=(o,e,t,i)=>{for(var n=R2(e,t),s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&E2(e,t,n),n};const T2=w("debugpost");class z{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;T2&&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}}z1([u()],z.prototype,"overrideState"),z1([u()],z.prototype,"value");class A2 extends Zi{constructor(){super([z])}onSerialize(e,t){}onDeserialize(e,t){const i=t.target,n=t.path;let s;if(i&&n&&(s=i[n]),(typeof s!="object"||typeof s=="object"&&s.isVolumeParameter!==!0)&&(s=new z),typeof e=="object"&&"value"in e){const r=e.value;s.initialize(r),s.overrideState=e.overrideState}else s.value=e;return s}}new A2;var I2=Object.defineProperty,L2=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&I2(e,t,n),n};const O0=w("debugpost");class nt extends E{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 z?n.initialize(i):n!==void 0&&(this[t]=i)}}active=!0;_manager=null;onEnable(){super.onEnable(),O0&&console.warn("Enable",this.constructor.name+(this.__internalDidAwakeAndStart?"":" (awake)")),this.__internalDidAwakeAndStart&&(this.active=!0),this.onEffectEnabled()}onDisable(){super.onDisable(),O0&&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=k2(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(){O0&&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 z&&i.__init()}}onEditorModification(e){const t=e.propertyName;if(this[t]instanceof z){const i=e.value;return this[t].value=i,!0}}}L2([u()],nt.prototype,"active");var j2=Object.defineProperty,D2=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&j2(e,t,n),n};const B2=w("debugpost"),k0={};function cn(o,e){k0[o]=e}function F2(o){return o.__type in k0?k0[o.__type]:(B2&&o.__type&&console.warn("Unknown postprocessing type",o.__type,o),nt)}class Wp{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)}}D2([Ye([o=>F2(o),nt])],Wp.prototype,"components");var U2=Object.defineProperty,z2=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&U2(e,t,n),n};const N2=w("debugpost");class Eh extends nt{get typeName(){return"Antialiasing"}preset=new z(2);onCreateEffect(){const e=new T.POSTPROCESSING.MODULE.SMAAEffect({preset:this.preset?.value??T.POSTPROCESSING.MODULE.SMAAPreset.HIGH,edgeDetectionMode:T.POSTPROCESSING.MODULE.EdgeDetectionMode.LUMA});return this.preset.onValueChanged=t=>{N2&&console.log("Antialiasing preset changed to",t),e.applyPreset(t)},e}}z2([u(z)],Eh.prototype,"preset"),cn("Antialiasing",Eh);var W2=Object.defineProperty,M0=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&W2(e,t,n),n};const Vp=class VS extends nt{static useSelectiveBloom=!1;get typeName(){return"Bloom"}threshold=new z(.9);intensity=new z(1);scatter=new z(.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=VS.useSelectiveBloom),this.selectiveBloom){const t=e=new T.POSTPROCESSING.MODULE.SelectiveBloomEffect(this.context.scene,this.context.mainCamera,{blendFunction:T.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});t.inverted=!0}else e=new T.POSTPROCESSING.MODULE.BloomEffect({blendFunction:T.POSTPROCESSING.MODULE.BlendFunction.ADD,mipmapBlur:!0,luminanceThreshold:this.threshold.value,luminanceSmoothing:this.scatter.value,radius:.85,intensity:this.intensity.value});return this.intensity.onValueChanged=t=>{e.intensity=t},this.threshold.onValueChanged=t=>{e.luminanceMaterial.threshold=Math.pow(t,2.2)},this.scatter.onValueChanged=t=>{e.luminancePass.enabled=!0,e.luminanceMaterial.smoothing=t,e.mipmapBlurPass&&(e.mipmapBlurPass.radius=Co.lerp(.1,.9,t))},e}};M0([u(z)],Vp.prototype,"threshold"),M0([u(z)],Vp.prototype,"intensity"),M0([u(z)],Vp.prototype,"scatter");let $p=Vp;cn("Bloom",$p);var V2=Object.defineProperty,$2=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&V2(e,t,n),n};class Rh extends nt{get typeName(){return"ChromaticAberration"}intensity=new z(0);onCreateEffect(){const e=new T.POSTPROCESSING.MODULE.ChromaticAberrationEffect;return e.offset=new K(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}}$2([u(z)],Rh.prototype,"intensity"),cn("ChromaticAberration",Rh);var Th=(o=>(o[o.None=0]="None",o[o.Neutral=1]="Neutral",o[o.ACES=2]="ACES",o[o.AgX=3]="AgX",o[o.KhronosNeutral=4]="KhronosNeutral",o))(Th||{});const N1=new Map;function E0(o){switch(o){case 0:return Bm;case 1:return Dm;case 2:return Rd;case 3:return Ed;case 4:return ja;default:return N1.has(o)||(N1.set(o,!0),console.warn("[Postprocessing] Unknown tone mapping mode",o)),ja}}function H2(o){switch(o){case Bm:return 0;case Rd:return 2;case Ed:return 3;case ja:return 1;case Dm:return 1;default:return 0}}function Hp(o){switch(o){case Bm:return T.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR;case Rd:return T.POSTPROCESSING.MODULE.ToneMappingMode.ACES_FILMIC;case Ed:return T.POSTPROCESSING.MODULE.ToneMappingMode.AGX;case ja:return T.POSTPROCESSING.MODULE.ToneMappingMode.NEUTRAL;case Dm:return T.POSTPROCESSING.MODULE.ToneMappingMode.REINHARD;default:return T.POSTPROCESSING.MODULE.ToneMappingMode.LINEAR}}var G2=Object.defineProperty,W1=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&G2(e,t,n),n};const R0=w("debugpost");class er extends nt{get typeName(){return"ToneMapping"}mode=new z(void 0);exposure=new z(1);setMode(e){const t=Th[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=U1(this);e&&super.onEffectEnabled(e)}_tonemappingEffect=null;onCreateEffect(){if(this.mode.isInitialized==!1){const i=H2(this.context.renderer.toneMapping);R0&&console.log("[PostProcessing] Initializing ToneMapping mode to renderer.toneMapping",this.context.renderer.toneMapping+" \u2192 "+i),this.mode.initialize(i)}this._tonemappingEffect?.dispose();const e=E0(this.mode.value),t=this._tonemappingEffect=new T.POSTPROCESSING.MODULE.ToneMappingEffect({mode:Hp(e)});return this.mode.onValueChanged=i=>{if(typeof i=="string")i=Bw(i),t.mode=Hp(i);else{const n=E0(i);t.mode=Hp(n)}t.name="ToneMapping ("+Th[i]+")",R0&&console.log("[PostProcessing] ToneMapping mode changed to",Th[i],e,t.mode)},R0&&console.log("[PostProcessing] Use ToneMapping",Th[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=E0(this.mode.value)),this.exposure.overrideState&&this.exposure.value!==void 0)){const e=Math.max(0,this.exposure.value);this.context.renderer.toneMappingExposure=e}}}W1([u(z)],er.prototype,"mode"),W1([u(z)],er.prototype,"exposure"),cn("Tonemapping",er);var q2=Object.defineProperty,Gp=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&q2(e,t,n),n};class tr extends nt{get typeName(){return"ColorAdjustments"}remap=!0;postExposure=new z(1);contrast=new z(0);hueShift=new z(0);saturation=new z(0);init(){this.postExposure.valueProcessor=e=>(this.remap&&(e=Math.pow(2,e)),e),this.contrast.valueProcessor=e=>{if(!this.remap)return e;let t=1;return e>0?t=200:e<0&&(t=100),e/t},this.contrast.defaultValue=0,this.hueShift.valueProcessor=e=>this.remap?Math.PI*e/180:e,this.hueShift.defaultValue=0,this.saturation.valueProcessor=e=>this.remap?e<0?e/100:e/(100*Math.PI):e,this.saturation.defaultValue=0}onCreateEffect(){const e=[];let t=this.postprocessingContext?.components.find(s=>s instanceof er);t||(t=new er,this.postprocessingContext?.components.push(t)),this.postExposure.onValueChanged=s=>{this.postExposure.overrideState&&t?t.exposure.value=s:console.warn("[PostProcessing] PostExposure is set to override but no ToneMappingEffect found in the postprocessing stack. Please add a ToneMappingEffect to your postprocessing stack to use PostExposure.")};const i=new T.POSTPROCESSING.MODULE.BrightnessContrastEffect;this.contrast.onValueChanged=s=>i.contrast=s;const n=new T.POSTPROCESSING.MODULE.HueSaturationEffect;return this.hueShift.onValueChanged=s=>n.hue=s,this.saturation.onValueChanged=s=>n.saturation=s,e.push(i),e.push(n),e}}Gp([u(z)],tr.prototype,"postExposure"),Gp([u(z)],tr.prototype,"contrast"),Gp([u(z)],tr.prototype,"hueShift"),Gp([u(z)],tr.prototype,"saturation"),cn("ColorAdjustments",tr);var X2=Object.defineProperty,da=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&X2(e,t,n),n};const Q2=w("debugpost");class Dn extends nt{get typeName(){return"DepthOfField"}mode;focusDistance=new z(1);focalLength=new z(.2);aperture=new z(20);gaussianMaxRadius=new z;resolutionScale=new z(1/window.devicePixelRatio);bokehScale=new z;init(){this.focalLength.valueProcessor=t=>{const i=t/300;return j.lerp(2,.01,i)};const e=20;this.aperture.valueProcessor=t=>{const i=1-t/32;return j.lerp(1,e,i)}}onCreateEffect(){if(this.mode===0){Q2&&console.warn("DepthOfField: Mode is set to Off");return}const e=new T.POSTPROCESSING.MODULE.DepthOfFieldEffect(this.context.mainCamera,{worldFocusRange:.2,focalLength:1,bokehScale:20,resolutionScale:this.resolutionScale.value});return this.focusDistance.onValueChanged=t=>{e.cocMaterial.worldFocusDistance=t},this.focalLength.onValueChanged=t=>e.cocMaterial.worldFocusRange=t,this.aperture.onValueChanged=t=>e.bokehScale=t,this.resolutionScale&&(this.resolutionScale.onValueChanged=t=>e.resolution.scale=t),[e]}unapply(){}}da([u()],Dn.prototype,"mode"),da([u(z)],Dn.prototype,"focusDistance"),da([u(z)],Dn.prototype,"focalLength"),da([u(z)],Dn.prototype,"aperture"),da([u(z)],Dn.prototype,"gaussianMaxRadius"),da([u(z)],Dn.prototype,"resolutionScale"),da([u(z)],Dn.prototype,"bokehScale"),cn("DepthOfField",Dn);class Ah extends nt{effect;constructor(e){super(),this.effect=e}get typeName(){return this.effect.constructor.name}onCreateEffect(){return this.effect}}var Y2=Object.defineProperty,Z2=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&Y2(e,t,n),n};class Ih extends nt{get typeName(){return"PixelationEffect"}granularity=new z(10);onCreateEffect(){const e=new T.POSTPROCESSING.MODULE.PixelationEffect;return this.granularity.onValueChanged=t=>{e.granularity=t},e}}Z2([u(z)],Ih.prototype,"granularity"),cn("PixelationEffect",Ih);var K2=Object.defineProperty,Lh=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&K2(e,t,n),n};class ns extends nt{get typeName(){return"ScreenSpaceAmbientOcclusion"}intensity=new z(2);falloff=new z(1);samples=new z(9);color=new z(new oe(0,0,0));luminanceInfluence=new z(.7);onBeforeRender(){if(this._ssao&&this.context.mainCamera instanceof de){const e=this.context.mainCamera.far-this.context.mainCamera.near;this._ssao.ssaoMaterial.worldDistanceFalloff=e*.01,this._ssao.ssaoMaterial.worldDistanceThreshold=this.context.mainCamera.far}}_ssao;onCreateEffect(){const e=this.context.mainCamera,t=new T.POSTPROCESSING.MODULE.NormalPass(this.context.scene,e),i=new T.POSTPROCESSING.MODULE.DepthDownsamplingPass({normalBuffer:t.texture,resolutionScale:.5}),n=this._ssao=new T.POSTPROCESSING.MODULE.SSAOEffect(e,t.texture,{normalDepthBuffer:i.texture,worldDistanceThreshold:1,worldDistanceFalloff:1,worldProximityThreshold:.1,worldProximityFalloff:2,intensity:1,blendFunction:T.POSTPROCESSING.MODULE.BlendFunction.MULTIPLY,luminanceInfluence:.5});this.intensity.onValueChanged=r=>{n.intensity=r},this.falloff.onValueChanged=r=>{n.ssaoMaterial.radius=r*.1},this.samples.onValueChanged=r=>{n.ssaoMaterial.samples=r},this.color.onValueChanged=r=>{n.color||(n.color=new oe),n.color.copy(r)},this.luminanceInfluence.onValueChanged=r=>{n.luminanceInfluence=r};const s=new Array;return s.push(t),s.push(i),s.push(n),s}}Lh([u(z)],ns.prototype,"intensity"),Lh([u(z)],ns.prototype,"falloff"),Lh([u(z)],ns.prototype,"samples"),Lh([u(z)],ns.prototype,"color"),Lh([u(z)],ns.prototype,"luminanceInfluence"),cn("ScreenSpaceAmbientOcclusion",ns);var J2=Object.defineProperty,ua=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&J2(e,t,n),n};const eI=w("debugN8AO");var T0=(o=>(o[o.Performance=0]="Performance",o[o.Low=1]="Low",o[o.Medium=2]="Medium",o[o.High=3]="High",o[o.Ultra=4]="Ultra",o))(T0||{});class Bn extends nt{get typeName(){return"ScreenSpaceAmbientOcclusionN8"}get pass(){return this._ssao}gammaCorrection=!0;aoRadius=new z(1);falloff=new z(1);intensity=new z(1);color=new z(new oe(0,0,0));screenspaceRadius=!1;quality=2;_ssao;onValidate(){this._ssao&&(this._ssao.setQualityMode(T0[this.quality]),this._ssao.configuration.gammaCorrection=this.gammaCorrection,this._ssao.configuration.screenSpaceRadius=this.screenspaceRadius)}onCreateEffect(){const e=this.context.mainCamera,t=this.context.domWidth,i=this.context.domHeight,n=this._ssao=new T.POSTPROCESSING_AO.MODULE.N8AOPostPass(this.context.scene,e,t,i);n.name="SSAO_N8";const s=T0[this.quality];n.setQualityMode(s),n.configuration.transparencyAware=!1;const r=new $n(t,i);return n.configuration.beautyRenderTarget=r,n.configuration.autoRenderBeauty=!1,n.configuration.gammaCorrection=this.gammaCorrection,n.configuration.screenSpaceRadius=this.screenspaceRadius,eI&&(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 oe),n.configuration.color.copy(a)},n}}ua([kt(),u()],Bn.prototype,"gammaCorrection"),ua([u(z)],Bn.prototype,"aoRadius"),ua([u(z)],Bn.prototype,"falloff"),ua([u(z)],Bn.prototype,"intensity"),ua([u(z)],Bn.prototype,"color"),ua([kt(),u()],Bn.prototype,"screenspaceRadius"),ua([kt(),u()],Bn.prototype,"quality"),cn("ScreenSpaceAmbientOcclusionN8",Bn);var tI=Object.defineProperty,iI=Object.getOwnPropertyDescriptor,V1=(o,e,t,i)=>{for(var n=iI(e,t),s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&tI(e,t,n),n};class jh extends nt{get typeName(){return"Sharpening"}order=ut.Sharpening;_effect;onCreateEffect(){return this._effect??=new(nI()),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}V1([u()],jh.prototype,"amount"),V1([u()],jh.prototype,"radius");function nI(){const o=`
|
|
1312
1312
|
void mainSupport() {
|
|
1313
1313
|
vUv = uv;
|
|
1314
1314
|
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
|
|
@@ -1413,7 +1413,7 @@ If you need multisampling consider changing 'auto' to a fixed value (e.g. 4).`))
|
|
|
1413
1413
|
}
|
|
1414
1414
|
}
|
|
1415
1415
|
`}}var bI=Object.defineProperty,_I=Object.getOwnPropertyDescriptor,Fh=(o,e,t,i)=>{for(var n=i>1?void 0:i?_I(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&bI(e,t,n),n};const At=w("debugscreensharing");var Q1=(o=>(o[o.Screen=0]="Screen",o[o.Camera=1]="Camera",o[o.Canvas=2]="Canvas",o[o.Microphone=3]="Microphone",o))(Q1||{});class nr extends E{allowStartOnClick=!0;onPointerEnter(){this.context.connection.allowEditing!=!1&&this.allowStartOnClick&&this.context.input.setCursor("pointer")}onPointerExit(){this.context.connection.allowEditing!=!1&&this.allowStartOnClick&&this.context.input.unsetCursor("pointer")}onPointerClick(e){if(this.context.connection.allowEditing!=!1&&this.allowStartOnClick&&!(e&&e.pointerId!==0)){if(this.isReceiving&&this.videoPlayer?.isPlaying){this.videoPlayer&&(this.videoPlayer.screenspace=!this.videoPlayer.screenspace);return}if(this.isSending){this.close();return}this.share()}}autoConnect=!1;set videoPlayer(e){this._videoPlayer&&(this.isSending||this.isReceiving)&&this._videoPlayer.stop(),this._videoPlayer=e,this._videoPlayer&&this._currentStream&&(this.isSending||this.isReceiving)&&this._videoPlayer.setVideo(this._currentStream)}get videoPlayer(){return this._videoPlayer}_videoPlayer;_audioSource;get screenspace(){return this.videoPlayer?.screenspace??!1}set screenspace(e){this.videoPlayer&&(this.videoPlayer.screenspace=e)}device="Screen";deviceName;deviceFilter;get currentScream(){return this._currentStream}get currentMode(){return this._currentMode}get isSending(){return this._currentStream?.active&&this._currentMode===1}get isReceiving(){if(this._currentMode===2){if(!this._currentStream||this._currentStream.active===!1)return!1;const e=this._currentStream.getTracks();for(const t of e)if(t.readyState==="live")return!0}return!1}get requiresVideoPlayer(){return this.device!=="Microphone"}_net;_requestOpen=!1;_currentStream=null;_currentMode=0;awake(){typeof this.device=="number"&&(this.device=Q1[this.device]),At&&console.log("Screensharing",this.name,this),ji.registerWaitForAllowAudio(()=>{this._videoPlayer&&this._currentStream&&this._currentMode===2&&(this._videoPlayer.playInBackground=!0,this._videoPlayer.setVideo(this._currentStream))}),this._net=new wd(this)}onEnable(){this._net?.enable(),this._net?.addEventListener(to.StreamReceived,this.onReceiveStream),this._net?.addEventListener(to.StreamEnded,this.onCallEnded),this.context.connection.beginListen(ie.JoinedRoom,this.onJoinedRoom),this.autoConnect&&To(1e3).then(()=>(this.enabled&&this.autoConnect&&!this.isReceiving&&!this.isSending&&this.context.connection.isInRoom&&this.share(),0))}onDisable(){this._net?.removeEventListener(to.StreamReceived,this.onReceiveStream),this._net?.removeEventListener(to.StreamEnded,this.onCallEnded),this.context.connection.stopListen(ie.JoinedRoom,this.onJoinedRoom),this._net?.disable(),this.close()}onJoinedRoom=async()=>{await To(1e3),this.autoConnect&&!this.isSending&&!this.isReceiving&&this.context.connection.isInRoom&&this.share()};_ensureVideoPlayer(){const e=new pt;e.aspectMode=G1.AdjustWidth,S.addComponent(this.gameObject,e),this._videoPlayer=e}_activeShareRequest=null;async share(e){return this._activeShareRequest?this._activeShareRequest:(this._activeShareRequest=this.internalShare(e),this._activeShareRequest.then(()=>this._activeShareRequest=null))}async internalShare(e){if(this.context.connection.isInRoom===!1){console.warn("Can not start screensharing: requires network connection"),A()&&be("Can not start screensharing: requires network connection. Add a SyncedRoom component or join a room first.");return}if(e?.device&&(this.device=e.device),!this.videoPlayer&&this.requiresVideoPlayer&&(this._videoPlayer||(this._videoPlayer=S.getComponent(this.gameObject,pt)??void 0),this.videoPlayer||this._ensureVideoPlayer(),!this.videoPlayer)){console.warn("Can not share video without a videoPlayer assigned");return}this._requestOpen=!0;try{const t=e?.constraints??{echoCancellation:!0,autoGainControl:!1},i={video:t,audio:t},n=i.video;switch(n!==void 0&&typeof n!="boolean"&&(n.width||(n.width={max:1920}),n.height||(n.height={max:1920}),n.aspectRatio||(n.aspectRatio={ideal:1.7777777778}),n.frameRate||(n.frameRate={ideal:24}),n.facingMode||(n.facingMode={ideal:"user"})),this.device){case"Camera":this.tryShareUserCamera(i,e);break;case"Screen":{if(!navigator.mediaDevices.getDisplayMedia){console.error("No getDisplayMedia support");return}const r=await navigator.mediaDevices.getDisplayMedia(i);this._requestOpen?this.setStream(r,1):io(r)}break;case"Canvas":const s=this.context.renderer.domElement.captureStream(0);this.setStream(s,1);break;case"Microphone":{if(!navigator.mediaDevices.getUserMedia){console.error("No getDisplayMedia support");return}i.video=!1;const r=await navigator.mediaDevices.getUserMedia(i);this._requestOpen?this.setStream(r,1):io(r)}break;default:console.error("Can not start screen sharing: Unknown device type",this.device)}}catch(t){if(t.name==="NotAllowedError"){console.log("Selection cancelled"),this._requestOpen=!1;return}console.error("Error opening video",t)}}close(){this._requestOpen=!1,this._currentStream&&(At&&console.warn("Close current stream / disposing resources, stream was active?",this._currentStream.active),this._net?.stopSendingStream(this._currentStream),io(this._currentStream),this._currentMode=0,this._currentStream=null)}setStream(e,t){if(e===this._currentStream||(this.close(),!e))return;this._currentStream=e,this._requestOpen=!0,this._currentMode=t;const i=this.device!=="Microphone",n=t===1;i?(this._videoPlayer||this._ensureVideoPlayer(),this._videoPlayer?this._videoPlayer.setVideo(e):console.error("No video player assigned for video stream")):(this._audioSource||(this._audioSource=new ji,this._audioSource.spatialBlend=0,this._audioSource.volume=1,this.gameObject.addComponent(this._audioSource)),n||(At&&console.log("PLAY",e.getAudioTracks()),this._audioSource.volume=1,this._audioSource?.play(e))),n&&this._net?.startSendingStream(e),n&&(this._videoPlayer&&(this._videoPlayer.muted=!0),this._audioSource?.stop());for(const s of e.getTracks())s.addEventListener("ended",()=>{At&&console.log("Track ended",s),this.close()}),At&&s.kind==="video"&&console.log(n?"Video \u2192":"Video \u2190",s.getSettings())}onReceiveStream=e=>{e.stream?.active===!0&&this.setStream(e.stream,2)};onCallEnded=e=>{At&&console.log("CALL ENDED",this.isReceiving,this?.screenspace),this.isReceiving&&(this.screenspace=!1)};async tryShareUserCamera(e,t){const i=(await navigator.mediaDevices.enumerateDevices()).filter(s=>s.kind==="videoinput");At&&console.log(`Request camera. These are your kind:videoinput devices:
|
|
1416
|
-
`,i);let n=!1;for(const s of i)try{if(!this._requestOpen){At&&console.log("Camera selection cancelled");break}if(s.kind!=="videoinput"){At&&console.log("Skipping non-video device",s);continue}const r=s.deviceId;if(t?.deviceId!=null||t?.deviceFilter!=null){if(t?.deviceId!==void 0&&r!==t.deviceId){At&&console.log("Skipping device due to options.deviceId: "+s.label+"; "+s.deviceId);continue}if(t?.deviceFilter&&t.deviceFilter(s)===!1){At&&console.log("Skipping device due to options.deviceFilter: "+s.label+"; "+s.deviceId);continue}}else if(this.deviceFilter)if(this.deviceFilter(s)===!1){At&&console.log("Skipping device due to ScreenShare.deviceFilter: "+s.label+"; "+s.deviceId);continue}else At&&console.log("Selected device by filter",s);else if(this.deviceName){const l=s.label.toLowerCase(),c=this.deviceName.toLowerCase(),h=l.includes(c),d=s.deviceId===this.deviceName;if(!h&&!d){At&&console.log("Skipping device due to ScreenShare.deviceName: "+s.label+"; "+s.deviceId);continue}else At&&console.log("Selected device by name",s)}e.video!==!1&&((typeof e.video>"u"||typeof e.video=="boolean")&&(e.video={}),e.video.deviceId=r),n=!0;const a=await navigator.mediaDevices.getUserMedia(e).catch(l=>(console.error("Failed to get user media",l),null));if(a===null)continue;this._requestOpen?(this.setStream(a,1),At&&console.log("Selected camera",s)):(io(a),At&&console.log("Camera selection cancelled"));break}catch(r){if(r.message==="Failed to allocate videosource"||r.message==="Could not start video source"){be("Failed to start video: Try another camera (Code "+r.code+")"),console.warn(r);continue}else console.error("Failed to get user media",r.message,r.code,r)}!n&&A()&&(be("No camera found for sharing. Please connect a camera (see console for more information)"),console.warn("No camera found for sharing. Please connect a camera",i,this.deviceName,"Using deviceFilter? "+this.deviceFilter!=null,"Using options? "+t!=null,"Using deviceName? "+this.deviceName!=null,"Using options.deviceId? "+t?.deviceId!=null,"Using options.deviceFilter? "+t?.deviceFilter!=null))}}Fh([u()],nr.prototype,"allowStartOnClick",2),Fh([u()],nr.prototype,"autoConnect",2),Fh([u(pt)],nr.prototype,"videoPlayer",1),Fh([u()],nr.prototype,"device",2),Fh([u()],nr.prototype,"deviceName",2);var vI=Object.defineProperty,Hl=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&vI(e,t,n),n};const wI=w("debugseethrough");let xI=0;class ss extends E{referencePoint=null;fadeDuration=.05;minAlpha=0;useAlphaHash=!0;set needsUpdate(e){this._needsUpdate=e}get needsUpdate(){return this._needsUpdate}overrideAlpha=-1;autoUpdate=!0;_referencePointVector=new b;_referencePointDir=new b;_distance=0;_renderer=null;_needsUpdate=!0;_id=xI++;onEnable(){this._needsUpdate=!0,this._renderer=null}onDisable(){}update(){if(this._needsUpdate?(this._needsUpdate=!1,this._renderer=this.gameObject.getComponentsInChildren(ti),this.updateDirection()):this.autoUpdate&&(this.context.time.frame+this._id)%20===0&&this.updateDirection(),!this.autoUpdate||!this.referencePoint)return;const e=this._referencePointDir.dot(this.context.mainCamera.worldForward)>.2;if(wI&&this.referencePoint){const t=this.gameObject.worldPosition;B.DrawArrow(F(t),t.sub(this._referencePointDir),e?16711680:65280),B.DrawWireSphere(this.referencePoint.worldPosition,.05,255)}e?this.updateAlpha(this.minAlpha,this.fadeDuration):this.updateAlpha(1,this.fadeDuration)}updateDirection(){this.referencePoint??=this.context.scene,this._referencePointVector.copy(this.gameObject.worldPosition.sub(this.referencePoint.worldPosition)),this._distance=this._referencePointVector.length(),this._referencePointDir.copy(this._referencePointVector).multiply(F(1,.5,1)).normalize()}updateAlpha(e,t=this.fadeDuration){this.overrideAlpha!==void 0&&this.overrideAlpha!==-1&&(e=this.overrideAlpha),this._renderer?.forEach(i=>{e<.9?i.gameObject.raycastAllowed=!1:i.gameObject.raycastAllowed=!0;const n=i.sharedMaterials;if(!n)return;const s=ms.get(i.gameObject),r=s.getOverride("opacity")?.value??n[0].opacity??1;let a=
|
|
1416
|
+
`,i);let n=!1;for(const s of i)try{if(!this._requestOpen){At&&console.log("Camera selection cancelled");break}if(s.kind!=="videoinput"){At&&console.log("Skipping non-video device",s);continue}const r=s.deviceId;if(t?.deviceId!=null||t?.deviceFilter!=null){if(t?.deviceId!==void 0&&r!==t.deviceId){At&&console.log("Skipping device due to options.deviceId: "+s.label+"; "+s.deviceId);continue}if(t?.deviceFilter&&t.deviceFilter(s)===!1){At&&console.log("Skipping device due to options.deviceFilter: "+s.label+"; "+s.deviceId);continue}}else if(this.deviceFilter)if(this.deviceFilter(s)===!1){At&&console.log("Skipping device due to ScreenShare.deviceFilter: "+s.label+"; "+s.deviceId);continue}else At&&console.log("Selected device by filter",s);else if(this.deviceName){const l=s.label.toLowerCase(),c=this.deviceName.toLowerCase(),h=l.includes(c),d=s.deviceId===this.deviceName;if(!h&&!d){At&&console.log("Skipping device due to ScreenShare.deviceName: "+s.label+"; "+s.deviceId);continue}else At&&console.log("Selected device by name",s)}e.video!==!1&&((typeof e.video>"u"||typeof e.video=="boolean")&&(e.video={}),e.video.deviceId=r),n=!0;const a=await navigator.mediaDevices.getUserMedia(e).catch(l=>(console.error("Failed to get user media",l),null));if(a===null)continue;this._requestOpen?(this.setStream(a,1),At&&console.log("Selected camera",s)):(io(a),At&&console.log("Camera selection cancelled"));break}catch(r){if(r.message==="Failed to allocate videosource"||r.message==="Could not start video source"){be("Failed to start video: Try another camera (Code "+r.code+")"),console.warn(r);continue}else console.error("Failed to get user media",r.message,r.code,r)}!n&&A()&&(be("No camera found for sharing. Please connect a camera (see console for more information)"),console.warn("No camera found for sharing. Please connect a camera",i,this.deviceName,"Using deviceFilter? "+this.deviceFilter!=null,"Using options? "+t!=null,"Using deviceName? "+this.deviceName!=null,"Using options.deviceId? "+t?.deviceId!=null,"Using options.deviceFilter? "+t?.deviceFilter!=null))}}Fh([u()],nr.prototype,"allowStartOnClick",2),Fh([u()],nr.prototype,"autoConnect",2),Fh([u(pt)],nr.prototype,"videoPlayer",1),Fh([u()],nr.prototype,"device",2),Fh([u()],nr.prototype,"deviceName",2);var vI=Object.defineProperty,Hl=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&vI(e,t,n),n};const wI=w("debugseethrough");let xI=0;class ss extends E{referencePoint=null;fadeDuration=.05;minAlpha=0;useAlphaHash=!0;set needsUpdate(e){this._needsUpdate=e}get needsUpdate(){return this._needsUpdate}overrideAlpha=-1;autoUpdate=!0;_referencePointVector=new b;_referencePointDir=new b;_distance=0;_renderer=null;_needsUpdate=!0;_id=xI++;onEnable(){this._needsUpdate=!0,this._renderer=null}onDisable(){}update(){if(this._needsUpdate?(this._needsUpdate=!1,this._renderer=this.gameObject.getComponentsInChildren(ti),this.updateDirection()):this.autoUpdate&&(this.context.time.frame+this._id)%20===0&&this.updateDirection(),!this.autoUpdate||!this.referencePoint)return;const e=this._referencePointDir.dot(this.context.mainCamera.worldForward)>.2;if(wI&&this.referencePoint){const t=this.gameObject.worldPosition;B.DrawArrow(F(t),t.sub(this._referencePointDir),e?16711680:65280),B.DrawWireSphere(this.referencePoint.worldPosition,.05,255)}e?this.updateAlpha(this.minAlpha,this.fadeDuration):this.updateAlpha(1,this.fadeDuration)}updateDirection(){this.referencePoint??=this.context.scene,this._referencePointVector.copy(this.gameObject.worldPosition.sub(this.referencePoint.worldPosition)),this._distance=this._referencePointVector.length(),this._referencePointDir.copy(this._referencePointVector).multiply(F(1,.5,1)).normalize()}updateAlpha(e,t=this.fadeDuration){this.overrideAlpha!==void 0&&this.overrideAlpha!==-1&&(e=this.overrideAlpha),this._renderer?.forEach(i=>{e<.9?i.gameObject.raycastAllowed=!1:i.gameObject.raycastAllowed=!0;const n=i.sharedMaterials;if(!n)return;const s=ms.get(i.gameObject),r=s.getOverride("opacity")?.value??n[0].opacity??1;let a=j.lerp(r,e,t<=0?1:this.context.time.deltaTime/t);a>=.99?a=1:a<=.01&&(a=0),s.setOverride("alphaHash",this.useAlphaHash),s.setOverride("opacity",a),s.setOverride("transparent",a>=.99999?!1:!this.useAlphaHash)})}}Hl([u(M)],ss.prototype,"referencePoint"),Hl([u()],ss.prototype,"fadeDuration"),Hl([u()],ss.prototype,"minAlpha"),Hl([u()],ss.prototype,"useAlphaHash"),Hl([u()],ss.prototype,"overrideAlpha"),Hl([u()],ss.prototype,"autoUpdate");var SI=Object.defineProperty,Y1=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&SI(e,t,n),n};class Uh extends E{mode=0;shadowColor=new se(0,0,0,1);targetMesh;start(){if(this.gameObject instanceof H)this.gameObject instanceof H&&this.gameObject.material&&(this.gameObject.material=this.gameObject.material.clone(),this.targetMesh=this.gameObject,this.targetMesh.receiveShadow=!0);else{const e=Os.createPrimitive(Qa.Quad,{name:"ShadowCatcher",material:new gt({color:10066329,roughness:1,metalness:0,transparent:!0})});e.receiveShadow=!0,e.geometry.rotateX(-Math.PI/2),this.gameObject.add(e),this.targetMesh=e}if(!this.targetMesh){console.warn("ShadowCatcher: no mesh to apply shadow catching to. Groups are currently not supported.");return}switch(this.targetMesh.layers.set(2),this.mode){case 0:this.applyShadowMaterial();break;case 1:this.applyLightBlendMaterial();break;case 2:this.applyOccluderMaterial();break}}applyLightBlendMaterial(){if(!this.targetMesh)return;const e=this.targetMesh.material;e.blending=Rb,this.applyMaterialOptions(e),e.onBeforeCompile=t=>{t.fragmentShader=t.fragmentShader.replace("vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;",`vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;
|
|
1417
1417
|
// diffuse-only lighting with overdrive to somewhat compensate
|
|
1418
1418
|
// for the loss of indirect lighting and to make it more visible.
|
|
1419
1419
|
vec3 direct = (reflectedLight.directDiffuse + reflectedLight.directSpecular) * 6.6;
|
|
@@ -1423,20 +1423,20 @@ If you need multisampling consider changing 'auto' to a fixed value (e.g. 4).`))
|
|
|
1423
1423
|
// be blended onto the scene.
|
|
1424
1424
|
gl_FragColor = vec4(direct, max);
|
|
1425
1425
|
return;
|
|
1426
|
-
`)},e.userData.isLightBlendMaterial=!0}applyShadowMaterial(){if(this.targetMesh)if(this.targetMesh.material.type!=="ShadowMaterial"){const e=new gb;e.color=this.shadowColor,e.opacity=this.shadowColor.alpha,this.applyMaterialOptions(e),this.targetMesh.material=e,e.userData.isShadowCatcherMaterial=!0}else{const e=this.targetMesh.material;e.color=this.shadowColor,e.opacity=this.shadowColor.alpha,this.applyMaterialOptions(e),e.userData.isShadowCatcherMaterial=!0}}applyOccluderMaterial(){if(this.targetMesh){let e=this.targetMesh.material;if(!e){const t=new Ce;this.targetMesh.material=t,e=t}e.depthWrite=!0,e.stencilWrite=!0,e.colorWrite=!1,this.gameObject.renderOrder=-100}}applyMaterialOptions(e){e&&(e.depthWrite=!1,e.stencilWrite=!1)}}Y1([u()],Uh.prototype,"mode"),Y1([u(se)],Uh.prototype,"shadowColor");var CI=Object.defineProperty,zh=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&CI(e,t,n),n};const si=w("debugskybox");j0("background-image"),j0("environment-image");const Z1={studio:{url:"https://cdn.needle.tools/static/skybox/modelviewer-Neutral.pmrem4x4.ktx2?pmrem",url_low:"https://cdn.needle.tools/static/skybox/modelviewer-Neutral-small.pmrem4x4.ktx2?pmrem"},"blurred-skybox":{url:"https://cdn.needle.tools/static/skybox/blurred-skybox.pmrem4x4.ktx2?pmrem",url_low:"https://cdn.needle.tools/static/skybox/blurred-skybox-small.pmrem4x4.ktx2?pmrem"},"quicklook-ar":{url:"https://cdn.needle.tools/static/skybox/QuickLook-ARMode.pmrem4x4.ktx2?pmrem",url_low:"https://cdn.needle.tools/static/skybox/QuickLook-ARMode-small.pmrem4x4.ktx2?pmrem"},quicklook:{url:"https://cdn.needle.tools/static/skybox/QuickLook-ObjectMode.pmrem4x4.ktx2?pmrem",url_low:"https://cdn.needle.tools/static/skybox/QuickLook-ObjectMode-small.pmrem4x4.ktx2?pmrem"}};function K1(o,e,t,i,n){if(e==="transparent"||e?.startsWith("rgb")||e?.startsWith("#"))return console.warn(`Needle Engine: Invalid ${n} value (${e}). Did you mean to set background-color instead?`),null;const s=new Yp;s.sourceId=o_(e),s.allowDrop=!1,s.allowNetworking=!1,s.background=t,s.environment=i,S.addComponent(o.scene,s);const r=a=>{if(si&&console.log(n,"CHANGED TO",a),a){if(typeof a!="string"){console.warn("Invalid attribute value for "+n);return}s.setSkybox(a)}else if(s.sourceId&&(i&&(o.sceneLighting.internalEnableReflection(s.sourceId)||(o.scene.environment=null)),t)){const l=o.lightmaps.tryGetSkybox(s.sourceId);o.scene.background=l}};return Ym(o.domElement,n,r),s.addEventListener("destroy",()=>{si&&console.log("Destroyed attribute remote skybox",n),Zm(o.domElement,n,r)}),s.setSkybox(e)}const Qp=new Array;pe.registerCallback(ue.ContextCreationStart,o=>{const e=o.context,t=e.domElement.getAttribute("background-image"),i=e.domElement.getAttribute("environment-image");if(t){si&&console.log("Creating RemoteSkybox to load background "+t);const n=K1(e,t,!0,!1,"background-image");n&&Qp.push(n)}if(i){si&&console.log("Creating RemoteSkybox to load environment "+i);const n=K1(e,i,!1,!0,"environment-image");n&&Qp.push(n)}}),pe.registerCallback(ue.ContextCreationStart,()=>Promise.all(Qp).finally(()=>{Qp.length=0}));const ga=class extends E{url="studio";allowDrop=!0;background=!0;environment=!0;allowNetworking=!0;_prevUrl;_prevLoadedEnvironment;_prevEnvironment=null;_prevBackground=null;onEnable(){this.setSkybox(this.url),this.registerDropEvents()}onDisable(){this.context.scene.environment===this._prevLoadedEnvironment&&(this.context.scene.environment=this._prevEnvironment,yi.backgroundShouldBeTransparent(this.context)||(this.context.scene.background=this._prevBackground),this._prevLoadedEnvironment=void 0),this.unregisterDropEvents(),this.context.mainCameraComponent?.applyClearFlags()}urlChangedSyncField(){this.allowNetworking&&this.url&&(this.isRemoteTexture(this.url)?this.setSkybox(this.url):si&&console.warn(`RemoteSkybox: Not setting skybox: ${this.url} is not a remote texture. If you want to set a local texture, set allowNetworking to false.`))}async setSkybox(o,e){if(!this.activeAndEnabled||(o=PI(o,this.environment,this.background),!o))return!1;if(e??=o,this.isValidTextureType(e)||console.warn('Potentially invalid skybox URL: "'+e+'" on '+(this.name||this.gameObject?.name||"context")),si&&console.log("Set RemoteSkybox url: "+o),this._prevUrl===o&&this._prevLoadedEnvironment)return this.apply(),!0;this._prevLoadedEnvironment?.dispose(),this._prevLoadedEnvironment=void 0,this._prevUrl=o;const t=await ly(o,this.context.renderer);return t?!this.enabled||this.destroyed?(si&&console.warn("RemoteSkybox: Component is disabled or destroyed"),!1):this._prevUrl!==o?(si&&console.warn("RemoteSkybox: URL changed while loading texture, aborting setSkybox"),!1):(this.url=o,this._prevLoadedEnvironment=t,this.apply(),!0):(si&&console.warn("RemoteSkybox: Failed to load texture from url",o),!1)}apply(){const o=this._prevLoadedEnvironment;if(o&&(o instanceof Ob||o instanceof KC||o.mapping==Pb||(o.mapping=JC,o.needsUpdate=!0),!this.destroyed)){if(!this.context){console.warn("RemoteSkybox: Context is not available - can not apply skybox.");return}this.context.scene.background!==o&&(this._prevBackground=this.context.scene.background),this.context.scene.environment!==o&&(this._prevEnvironment=this.context.scene.environment),si&&console.log("Set RemoteSkybox ("+(this.environment&&this.background?"environment and background":this.environment?"environment":this.background?"background":"none")+")",this.url,!yi.backgroundShouldBeTransparent(this.context)),this.environment&&(this.context.scene.environment=o),this.background&&!yi.backgroundShouldBeTransparent(this.context)&&(this.context.scene.background=o),this.context.mainCameraComponent?.backgroundBlurriness!==void 0&&(this.context.scene.backgroundBlurriness=this.context.mainCameraComponent.backgroundBlurriness)}}validProtocols=["file:","blob:","data:"];validTextureTypes=[".ktx2",".hdr",".exr",".jpg",".jpeg",".png"];isRemoteTexture(o){return o.startsWith("http://")||o.startsWith("https://")}isValidTextureType(o){for(const e of this.validTextureTypes)if(o.includes(e))return!0;for(const e of this.validProtocols)if(o.startsWith(e))return!0;return!1}registerDropEvents(){this.unregisterDropEvents(),this.context.domElement.addEventListener("dragover",this.onDragOverEvent),this.context.domElement.addEventListener("drop",this.onDrop)}unregisterDropEvents(){this.context.domElement.removeEventListener("dragover",this.onDragOverEvent),this.context.domElement.removeEventListener("drop",this.onDrop)}onDragOverEvent=o=>{if(this.allowDrop&&o.dataTransfer)for(const e of o.dataTransfer.types)(e==="text/uri-list"||e==="Files")&&o.preventDefault()};onDrop=o=>{if(this.allowDrop&&o.dataTransfer){for(const e of o.dataTransfer.types)if(si&&console.log(e),e==="text/uri-list"){const t=o.dataTransfer.getData(e);si&&console.log(e,t);let i=new RegExp(/polyhaven.com\/asset_img\/.+?\/(?<name>.+)\.png/).exec(t)?.groups?.name;if(i||(i=new RegExp(/polyhaven\.com\/a\/(?<name>.+)/).exec(t)?.groups?.name),si&&console.log(i),i){const n="https://dl.polyhaven.org/file/ph-assets/HDRIs/exr/1k/"+i+"_1k.exr";console.log(`[Remote Skybox] Setting skybox from url: ${n}`),o.preventDefault(),this.setSkybox(n);break}else if(this.isValidTextureType(t)){console.log("[Remote Skybox] Setting skybox from url: "+t),o.preventDefault(),this.setSkybox(t);break}else{console.warn(`[RemoteSkybox] Unknown url ${t}. If you want to load a skybox from a url, make sure it is a valid image url. Url must end with${this.validTextureTypes.join(", ")}.`);const n=new CustomEvent("dropped-unknown-url",{detail:{sender:this,event:o,url:t,apply:s=>{o.preventDefault(),this.setSkybox(s)}}});this.dispatchEvent(n)}}else if(e=="Files"){const t=o.dataTransfer.files.item(0);if(si&&console.log(e,t),!t)continue;if(!this.isValidTextureType(t.name)){console.warn(`[RemoteSkybox]: File "${t.name}" is not supported. Supported files are ${this.validTextureTypes.join(", ")}`);return}o.preventDefault(),this.setSkybox(t.name);break}}}};zh([zy(ga.prototype.urlChangedSyncField),u(URL)],ga.prototype,"url"),zh([u()],ga.prototype,"allowDrop"),zh([u()],ga.prototype,"background"),zh([u()],ga.prototype,"environment"),zh([u()],ga.prototype,"allowNetworking");let Yp=ga;function PI(o,e,t){if(o==null)return null;const i=e&&!t,n=Z1[o.toLowerCase()];return n?i?n.url_low:n.url:(typeof o=="string"&&o?.length&&(A()||si)&&(o.includes("/")||o.includes(".")||console.warn(`RemoteSkybox: Unknown magic skybox name "${o}". Valid names are: ${Object.keys(Z1).map(s=>`"${s}"`).join(", ")}`)),o)}var OI=Object.defineProperty,Zp=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&OI(e,t,n),n};const Nh=class $S extends E{target=null;followFactor=.1;rotateFactor=.1;positionAxes=cl.All;flipForward=!1;static _invertForward=new N().setFromAxisAngle(new b(0,1,0),Math.PI);_firstUpdate=!0;onBeforeRender(){this.updateNow(!1)}updateNow(e){if(!(!this.target||this.target===this.gameObject)){if(this.followFactor>0){const t=ee(this.target),i=this._firstUpdate||e?1:D.clamp01(this.context.time.deltaTime*this.followFactor),n=this.worldPosition;this.positionAxes&cl.X&&(n.x=D.lerp(n.x,t.x,i)),this.positionAxes&cl.Y&&(n.y=D.lerp(n.y,t.y,i)),this.positionAxes&cl.Z&&(n.z=D.lerp(n.z,t.z,i)),this.worldPosition=n}if(this.rotateFactor>0){const t=_e(this.target);this.flipForward&&t.premultiply($S._invertForward);const i=this._firstUpdate||e?1:D.clamp01(this.context.time.deltaTime*this.rotateFactor);this.worldQuaternion=this.worldQuaternion.slerp(t,i)}this._firstUpdate=!1}}};Zp([u(M)],Nh.prototype,"target"),Zp([u()],Nh.prototype,"followFactor"),Zp([u()],Nh.prototype,"rotateFactor"),Zp([u()],Nh.prototype,"positionAxes");let Kp=Nh;var kI=Object.defineProperty,Wh=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&kI(e,t,n),n};const Vh=w("debugspatialtrigger"),J1=new _s,eS=new _s;function MI(o,e){return J1.mask=o,eS.mask=e,J1.test(eS)}class mo extends E{triggerMask=0;onEnter;onStay;onExit;start(){Vh&&console.log(this.name,this.triggerMask,this)}update(){this.currentIntersected.length=0;for(const e of Jp.triggers)MI(e.triggerMask,this.triggerMask)&&e.test(this.gameObject)&&this.currentIntersected.push(e);for(let e=this.lastIntersected.length-1;e>=0;e--){const t=this.lastIntersected[e];this.currentIntersected.indexOf(t)<0&&(this.onExitTrigger(t),this.lastIntersected.splice(e,1))}for(const e of this.currentIntersected)this.lastIntersected.indexOf(e)<0&&this.onEnterTrigger(e),this.onStayTrigger(e);this.lastIntersected.length=0,this.lastIntersected.push(...this.currentIntersected)}currentIntersected=[];lastIntersected=[];onEnterTrigger(e){Vh&&console.log("ENTER TRIGGER",this.name,e.name,this,e),e.raiseOnEnterEvent(this),this.onEnter?.invoke()}onExitTrigger(e){Vh&&console.log("EXIT TRIGGER",this.name,e.name),e.raiseOnExitEvent(this),this.onExit?.invoke()}onStayTrigger(e){e.raiseOnStayEvent(this),this.onStay?.invoke()}}Wh([u()],mo.prototype,"triggerMask"),Wh([u(ae)],mo.prototype,"onEnter"),Wh([u(ae)],mo.prototype,"onStay"),Wh([u(ae)],mo.prototype,"onExit");const tS=class wm extends E{static triggers=[];triggerMask;boxHelper;start(){Vh&&console.log(this.name,this.triggerMask,this)}onEnable(){wm.triggers.push(this),this.boxHelper||(this.boxHelper=S.addComponent(this.gameObject,Bt),this.boxHelper?.showHelper(null,Vh))}onDisable(){wm.triggers.splice(wm.triggers.indexOf(this),1)}test(e){return this.boxHelper?this.boxHelper.isInBox(e)??!1:!1}raiseOnEnterEvent(e){S.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof mo&&t.onEnterTrigger(this)},!1)}raiseOnStayEvent(e){S.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof mo&&t.onStayTrigger(this)},!1)}raiseOnExitEvent(e){S.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof mo&&t.onExitTrigger(this)},!1)}};Wh([u()],tS.prototype,"triggerMask");let Jp=tS;var EI=Object.defineProperty,RI=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&EI(e,t,n),n};const Ni=w("debugspectator");class em extends E{cam=null;useKeys=!0;_mode=0;get mode(){return this._mode}set mode(e){this._mode=e}get isSpectating(){return this._handler?.currentTarget!==void 0}isSpectatingUser(e){return this.target?.userId===e}isFollowedBy(e){return this.followers?.includes(e)}get followers(){return this._networking.followers}stopSpectating(){if(this.context.isInXR){this.followSelf();return}this.target=void 0}get localId(){return this.context.connection.connectionId??"local"}set target(e){if(this._handler){const t=this._handler.currentTarget?.userId,i=this.context.players.getPlayerView(this.localId);e===void 0||this.context.isInXR===!1&&i?.currentObject===e.currentObject?this._handler.currentTarget!==void 0&&(this._handler.disable(),S.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),this._networking.onSpectatedObjectChanged(e,t)):this._handler.currentTarget!==e&&(this._handler.set(e),S.setActive(this.gameObject,!0),this.orbit&&(this.orbit.enabled=!1),this._networking.onSpectatedObjectChanged(e,t))}}get target(){return this._handler?.currentTarget}requestAllFollowMe(){this._networking.onRequestFollowMe()}get isSpectatingSelf(){return this.isSpectating&&this.target?.currentObject===this.context.players.getPlayerView(this.localId)?.currentObject}orbit=null;_handler;eventSub_WebXRRequestStartEvent=null;eventSub_WebXRStartEvent=null;eventSub_WebXREndEvent=null;_debug;_networking;awake(){if(this._debug=new II(this.context,this),this._networking=new DI(this.context,this),this._networking.awake(),S.setActive(this.gameObject,!1),this.cam=S.getComponent(this.gameObject,yi),!this.cam){console.warn("SpectatorCamera: Spectator camera needs camera component on the same object.",this);return}!this._handler&&this.cam&&(this._handler=new TI(this.context,this.cam,this)),this.orbit=S.getComponent(this.context.mainCamera,ge)}onDestroy(){this.stopSpectating(),this._handler?.destroy(),this._networking?.destroy()}isSupportedPlatform(){const e=window.navigator.userAgent,t=/Windows NT/.test(e)&&/Edg/.test(e)&&!/Win64/.test(e);return I.isDesktop()&&!I.isMobileDevice()&&!t}onBeforeXR(e){this.isSupportedPlatform()&&S.setActive(this.gameObject,!0)}onEnterXR(e){this.isSupportedPlatform()&&(Ni&&console.log(this.context.mainCamera),this.context.mainCamera&&this.followSelf())}onLeaveXR(e){this.context.removeCamera(this.cam),S.setActive(this.gameObject,!1),this._handler?.set(void 0),this._handler?.disable(),this.isSpectatingSelf&&this.stopSpectating(),this.orbit&&(this.orbit.enabled=!0)}followSelf(){this.target=this.context.players.getPlayerView(this.context.connection.connectionId),this.target||(this.context.players.setPlayerView(this.localId,this.context.mainCamera,Uo.Headset),this.target=this.context.players.getPlayerView(this.localId)),Ni&&console.log("Follow self",this.target)}onAfterRender(){if(!this.cam)return;const e=this.context.renderer,t=e.xr.enabled;if(!e.xr.isPresenting&&!this._handler?.currentTarget)return;this._handler?.update(this._mode);const i=e.getRenderTarget();let n=null;const s=e.state;if(!i||i.isXRRenderTarget===!0){if(!e.state.bindFramebuffer||!s.bindXRFramebuffer)return;n=e._framebuffer,s.bindXRFramebuffer(null)}this.setAvatarFlagsBeforeRender();const r=this.context.mainCameraComponent;if(r){const c=r.backgroundColor;c&&e.setClearColor(c,c.alpha),this.cam.backgroundColor=c,this.cam.clearFlags=r.clearFlags,this.cam.nearClipPlane=r.nearClipPlane,this.cam.farClipPlane=r.farClipPlane}else e.setClearColor(new oe(1,1,1));e.setRenderTarget(null),e.xr.enabled=!1;const a=this.cam?.threeCamera;this.context.updateAspect(a);const l=e.xr.isPresenting;e.xr.isPresenting=!1,e.setSize(this.context.domWidth,this.context.domHeight),e.render(this.context.scene,a),e.xr.isPresenting=l,e.xr.enabled=t,i?e.setRenderTarget(i):s.bindXRFramebuffer&&s.bindXRFramebuffer(n),this.resetAvatarFlags()}setAvatarFlagsBeforeRender(){const e=this._mode===0;for(const t of Le.instances)if(t.avatar&&"isLocalAvatar"in t.avatar&&"flags"in t.avatar){let i=no.All;this.isSpectatingSelf&&(i=e&&t.avatar.isLocalAvatar?no.FirstPerson:no.ThirdPerson);const n=t.avatar.flags;if(!n)continue;for(const s of n)s.UpdateVisible(i)}}resetAvatarFlags(){for(const e of Le.instances)if(e.avatar&&"flags"in e.avatar){const t=e.avatar.flags;if(!t)continue;for(const i of t)"isLocalAvatar"in e.avatar&&e.avatar?.isLocalAvatar?i.UpdateVisible(no.FirstPerson):i.UpdateVisible(no.ThirdPerson)}}}RI([u()],em.prototype,"useKeys");class TI{context;cam;spectator;follow;target;view;currentObject;get currentTarget(){return this.view}constructor(e,t,i){this.context=e,this.cam=t,this.spectator=i}set(e){const t=e?.currentObject;if(!t){this.spectator.stopSpectating();return}t!==this.currentObject&&(this.currentObject=t,this.view=e,this.follow||(this.follow=S.addComponent(this.cam.gameObject,Kp)),this.target||(this.target=new M),t.add(this.target),this.follow.enabled=!0,this.follow.target=this.target,Ni&&console.log("FOLLOW",t),this.context.isInXR?this.context.removeCamera(this.cam):this.context.setCurrentCamera(this.cam))}disable(){Ni&&console.log("STOP FOLLOW",this.currentObject),this.view=void 0,this.currentObject=void 0,this.context.removeCamera(this.cam),this.follow&&(this.follow.enabled=!1)}destroy(){this.target?.removeFromParent(),this.follow&&S.destroy(this.follow)}update(e){if(this.currentTarget?.isConnected===!1||this.currentTarget?.removed===!0){Ni&&console.log("Target disconnected or timeout",this.currentTarget),this.spectator.stopSpectating();return}this.currentTarget&&this.currentTarget?.currentObject!==this.currentObject&&(Ni&&console.log("Target changed",this.currentObject,"to",this.currentTarget.currentObject),this.set(this.currentTarget));const t=this.context.mainCamera;if(t){const n=this.cam.threeCamera;(n.near!==t.near||n.far!==t.far)&&(n.near=t.near,n.far=t.far,n.updateProjectionMatrix())}const i=this.follow?.target;if(!(!i||!this.follow)){switch(e){case 0:this.view?.viewDevice!==Uo.Browser?(this.follow.followFactor=5,this.follow.rotateFactor=5):(this.follow.followFactor=50,this.follow.rotateFactor=50),i.position.set(0,0,0);break;case 1:this.follow.followFactor=3,this.follow.rotateFactor=2,i.position.set(0,.5,1.5);break}this.follow.flipForward=!1,this.view?.viewDevice!==Uo.Browser?i.quaternion.copy(AI):i.quaternion.identity()}}}const AI=new N().setFromAxisAngle(new b(0,1,0),Math.PI);class II{context;spectator;constructor(e,t){this.context=e,this.spectator=t,console.log("[Spectator Camera] Click other avatars or cameras to follow them. Press ESC to exit spectator mode."),this.context.domElement.addEventListener("keydown",n=>{!this.spectator.useKeys||n.key==="Escape"&&this.spectator.stopSpectating()});let i=0;this.context.input.addEventListener(Ae.PointerDown,n=>{i=this.context.time.time}),this.context.input.addEventListener(Ae.PointerUp,n=>{const s=this.context.time.time-i;s>1?this.spectator.stopSpectating():this.context.input.getPointerClicked(0)&&s<.3&&this.trySelectObject()})}trySelectObject(){const e=new ks;e.setMask(16777215);const t=this.context.physics.raycast(e);if(Ni&&console.log(...t),t?.length)for(const i of t){if(i.distance<.2)continue;const n=i.object,s=sn.getFor(n);let r=s?.owner;if(r||(r=S.getComponentInParent(n,Le)?.connectionId),r){const a=this.context.players.getPlayerView(r);this.spectator.target=a,Ni&&console.log("spectate",r,s);break}}}}class LI{guid;dontSave=!0;targetUserId;stoppedFollowing;constructor(e,t,i){this.guid=e,this.targetUserId=t,this.stoppedFollowing=i}}class jI{guid;userId;constructor(e,t){this.guid=e.guid,this.userId=t}}class DI{followers=[];context;spectator;_followerEventMethod;_requestFollowMethod;_joinedRoomMethod;constructor(e,t){this.context=e,this.spectator=t,this._followerEventMethod=this.onFollowerEvent.bind(this),this._requestFollowMethod=this.onRequestFollowEvent.bind(this),this._joinedRoomMethod=this.onUserJoinedRoom.bind(this)}awake(){this.context.connection.beginListen("spectator-follower-changed",this._followerEventMethod),this.context.connection.beginListen("spectator-request-follow",this._requestFollowMethod),this.context.connection.beginListen(ie.JoinedRoom,this._joinedRoomMethod),this.context.domElement.addEventListener("keydown",e=>{this.spectator.useKeys&&(e.key==="f"?this.onRequestFollowMe():e.key==="Escape"&&this.onRequestFollowMe(!0))})}destroy(){this.context.connection.stopListen("spectator-follower-changed",this._followerEventMethod),this.context.connection.stopListen("spectator-request-follow",this._requestFollowMethod),this.context.connection.stopListen(ie.JoinedRoom,this._joinedRoomMethod)}onSpectatedObjectChanged(e,t){if(Ni&&console.log(this.context.connection.connectionId,"onSpectatedObjectChanged",e,t),this.context.connection.connectionId){const i=e?.userId===void 0,n=i?t:e?.userId,s=new LI(this.context.connection.connectionId,n,i);this.context.connection.send("spectator-follower-changed",s)}}onRequestFollowMe(e=!1){if(Ni&&console.log("Request follow",this.context.connection.connectionId),this.context.connection.connectionId){this.spectator.stopSpectating();const t=e?void 0:this.context.connection.connectionId,i=new jI(this.spectator,t);this.context.connection.send("spectator-request-follow",i)}}onUserJoinedRoom(){w("followme")&&this.onRequestFollowMe()}onFollowerEvent(e){const t=e.targetUserId,i=e.guid;if(Ni&&console.log(e),t===this.context.connection.connectionId)if(e.stoppedFollowing){const n=this.followers.indexOf(i);n!==-1&&(this.followers.splice(n,1),this.removeDisconnectedFollowers(),console.log(i,"unfollows you",this.followers.length))}else this.followers.includes(i)||(this.followers.push(i),this.removeDisconnectedFollowers(),console.log(i,"follows you",this.followers.length))}removeDisconnectedFollowers(){for(let e=this.followers.length-1;e>=0;e--){const t=this.followers[e];this.context.connection.userIsInRoom(t)===!1&&this.followers.splice(e,1)}}_lastRequestFollowUser;onRequestFollowEvent(e){if(this._lastRequestFollowUser=e,e.userId===this.context.connection.connectionId)this.spectator.stopSpectating();else if(e.userId===void 0)this.spectator.stopSpectating();else{const t=this.context.players.getPlayerView(e.userId);if(t)this.spectator.target=t;else return Ni&&console.warn("Could not find view",e.userId),this.enforceFollow(),!1}return!0}_enforceFollowInterval;enforceFollow(){this._enforceFollowInterval||(this._enforceFollowInterval=setInterval(()=>{this._lastRequestFollowUser===void 0||this._lastRequestFollowUser.userId&&this.spectator.isFollowedBy(this._lastRequestFollowUser.userId)?(clearInterval(this._enforceFollowInterval),this._enforceFollowInterval=void 0):(Ni&&console.log("REQUEST FOLLOW AGAIN",this._lastRequestFollowUser.userId),this.onRequestFollowEvent(this._lastRequestFollowUser))},1e3))}}var BI=Object.defineProperty,FI=Object.getOwnPropertyDescriptor,Gl=(o,e,t,i)=>{for(var n=i>1?void 0:i?FI(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&BI(e,t,n),n};const iS=w("debugsplines");class go{position=new b;rotation=new N;tangentIn=new b;tangentOut=new b}Gl([Ye(b)],go.prototype,"position",2),Gl([Ye(N)],go.prototype,"rotation",2),Gl([Ye(b)],go.prototype,"tangentIn",2),Gl([Ye(b)],go.prototype,"tangentOut",2);class fa extends E{addKnot(e){if(e instanceof go)this.spline.push(e),this._isDirty=!0;else{const t=new go;t.position.copy(e.position),this.spline.push(t),this._isDirty=!0}return this}removeKnot(e){if(typeof e=="number")this.spline.splice(e,1),this._isDirty=!0;else{const t=this.spline.indexOf(e);t!==-1&&(this.spline.splice(t,1),this._isDirty=!0)}return this}getPointAt(e,t){if(!this.curve)return new b;const i=this.curve.getPointAt(D.clamp01(e),t),n=this.gameObject.matrixWorld??void 0;return n&&i.applyMatrix4(n),i}markDirty(){this._isDirty=!0}getTangentAt(e,t){if(!this.curve)return t??new b;const i=this.gameObject.worldQuaternion;return this.curve.getTangentAt(D.clamp01(e),t).applyQuaternion(i)}set closed(e){this._closed=e,this._isDirty=!0}get closed(){return this._closed}_closed=!1;spline=[];set debug(e){e&&!this._builtCurve&&this.buildCurve(),this._debugLine&&(this._debugLine.visible=e)}get curve(){return this._curve}get isDirty(){return this._isDirty}_isDirty=!1;_curve=null;_builtCurve=!1;_debugLine=null;awake(){iS&&(console.log(`[Spline] ${this.name}`,this),this.buildCurve())}update(){this._isDirty&&this.buildCurve(!0),this._debugLine&&this._debugLine.parent!==this.gameObject&&this.gameObject.add(this._debugLine)}buildCurve(e=!1){if(!(this._builtCurve&&!e)){if(this._builtCurve=!0,!this.spline){console.error("[Spline] Can not build curve, no spline data",this.name);return}this._isDirty=!1,this._curve=UI(this.spline,this.closed),this.buildDebugCurve()}}buildDebugCurve(){if(iS&&this.spline&&this._curve){this._debugLine?.removeFromParent(),this._debugLine=null;const e=new Em({color:6684927}),t=this.spline.length*10,i=this._curve.getPoints(t),n=new wn().setFromPoints(i);this._debugLine=new Ia(n,e),this.gameObject?.add(this._debugLine)}}}Gl([Ye()],fa.prototype,"closed",1),Gl([Ye(go)],fa.prototype,"spline",2);function UI(o,e){const t=o.map(s=>new b(-s.position.x,s.position.y,s.position.z));t.length===1&&t.push(t[0]);const i=o.reduce((s,r)=>s+Math.abs(r.tangentOut.x)+Math.abs(r.tangentOut.y)+Math.abs(r.tangentOut.z),0)/o.length,n=D.remap(i,0,.3,0,.5);return new eP(t,e,"catmullrom",n)}var zI=Object.defineProperty,NI=Object.getOwnPropertyDescriptor,or=(o,e,t,i)=>{for(var n=i>1?void 0:i?NI(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&zI(e,t,n),n};class hn extends E{spline=null;object=void 0;useLookAt=!0;lookAt=null;clamp=!1;get position01(){return this._position01}set position01(e){this._position01=e,this._needsUpdate=!0}reset(){this._position01=0}autoRun=!0;duration=10;pullStrength=1;_position01=0;_needsUpdate=!1;start(){this.object===void 0&&(this.object=this.gameObject),this.updateFromPosition()}onEnable(){window.addEventListener("pointerdown",this.onUserInput,{passive:!0}),this.context.domElement.addEventListener("wheel",this.onUserInput,{passive:!0})}onDisable(){window.removeEventListener("pointerdown",this.onUserInput),this.context.domElement.removeEventListener("wheel",this.onUserInput)}onUserInput=()=>{this.object?.contains(this.context.mainCamera)&&(this._needsUpdate=!1,this._performedUpdates+=999)};update(){this.autoRun&&(this._needsUpdate=!0,this._position01+=this.context.time.deltaTime/this.duration),this._needsUpdate&&(this._needsUpdate=!1,this.updateFromPosition())}updateFromPosition(){if(!this.spline||!this.spline.curve||!this.object)return;this.clamp?this._position01=D.clamp01(this._position01):this._position01=this._position01%1;const e=this._position01>=1?1:this._position01%1,t=this.spline.getPointAt(e);if(this.pullStrength>=1)this.object.worldPosition=t;else if(this._position01!==this._lastPosition01&&(this._performedUpdates=0),this._requiredUpdates=Math.round(100/this.pullStrength),this._performedUpdates<this._requiredUpdates){const i=this.object.worldPosition;this._performedUpdates++;const n=D.clamp01(this.pullStrength),s=this.object.worldPosition=i.lerp(t,n*(this.context.time.deltaTime/.3));this._lastPositionVector.copy(s),this._needsUpdate=!0}if(this.useLookAt)if(this.lookAt)this.object.lookAt(this.lookAt.worldPosition);else{const i=this.spline.getTangentAt(e);this.object.lookAt(t.add(i))}this._lastPosition01=this._position01}_lastPosition01=0;_requiredUpdates=0;_performedUpdates=0;_lastPositionVector=new b}or([Ye(fa)],hn.prototype,"spline",2),or([Ye(M)],hn.prototype,"object",2),or([Ye()],hn.prototype,"useLookAt",2),or([Ye(M)],hn.prototype,"lookAt",2),or([Ye()],hn.prototype,"clamp",2),or([Ye()],hn.prototype,"position01",1),or([Ye()],hn.prototype,"autoRun",2),or([Ye()],hn.prototype,"duration",2);class wo{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedCameraModel(e,t){return(t||new wo).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedCameraModel(e,t){return e.setPosition(e.position()+Vb),(t||new wo).__init(e.readInt32(e.position())+e.position(),e)}userId(e){const t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}guid(e){const t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__string(this.bb_pos+t,e):null}dontSave(){const e=this.bb.__offset(this.bb_pos,8);return e?!!this.bb.readInt8(this.bb_pos+e):!1}pos(e){const t=this.bb.__offset(this.bb_pos,10);return t?(e||new Vr).__init(this.bb_pos+t,this.bb):null}rot(e){const t=this.bb.__offset(this.bb_pos,12);return t?(e||new Vr).__init(this.bb_pos+t,this.bb):null}static startSyncedCameraModel(e){e.startObject(5)}static addUserId(e,t){e.addFieldOffset(0,t,0)}static addGuid(e,t){e.addFieldOffset(1,t,0)}static addDontSave(e,t){e.addFieldInt8(2,+t,0)}static addPos(e,t){e.addFieldStruct(3,t,0)}static addRot(e,t){e.addFieldStruct(4,t,0)}static endSyncedCameraModel(e){return e.endObject()}static finishSyncedCameraModelBuffer(e,t){e.finish(t)}static finishSizePrefixedSyncedCameraModelBuffer(e,t){e.finish(t,void 0,!0)}}var WI=Object.defineProperty,VI=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&WI(e,t,n),n};const tm="SCAM";Eg(tm,wo.getRootAsSyncedCameraModel);const Wi=new Wm;class $I{userId;guid;constructor(e,t){this.guid=t,this.userId=e}send(e,t){if(e){Wi.clear();const i=Wi.createString(this.guid),n=Wi.createString(this.userId);wo.startSyncedCameraModel(Wi),wo.addGuid(Wi,i),wo.addUserId(Wi,n);const s=ee(e),r=Vd(e);wo.addPos(Wi,Vr.createVec3(Wi,s.x,s.y,s.z)),wo.addRot(Wi,Vr.createVec3(Wi,r.x,r.y,r.z));const a=wo.endSyncedCameraModel(Wi);Wi.finish(a,tm),t.sendBinary(Wi.asUint8Array())}}}const nS=class pb extends E{static instances=[];getCameraObject(e){const t=this.userToCamMap[e];return t?this.remoteCams[t].obj:null}cameraPrefab=null;_lastWorldPosition;_lastWorldQuaternion;_model=null;_needsUpdate=!0;_lastUpdateTime=0;remoteCams={};userToCamMap={};_camTimeoutInSeconds=10;_receiveCallback=null;async awake(){this._lastWorldPosition=this.worldPosition.clone(),this._lastWorldQuaternion=this.worldQuaternion.clone(),this.cameraPrefab&&("uri"in this.cameraPrefab&&(this.cameraPrefab=await this.cameraPrefab.instantiate(this.gameObject)),this.cameraPrefab&&"isObject3D"in this.cameraPrefab&&(this.cameraPrefab.visible=!1))}onEnable(){this._receiveCallback=this.context.connection.beginListenBinary(tm,this.onReceivedRemoteCameraInfoBin.bind(this))}onDisable(){this.context.connection.stopListenBinary(tm,this._receiveCallback)}update(){for(const n in this.remoteCams){const s=this.remoteCams[n],r=this.context.time.realtimeSinceStartup-s.lastUpdate;if(!s||r>this._camTimeoutInSeconds){A()&&console.log("Remote cam timeout",n),s?.obj&&S.destroy(s.obj),delete this.remoteCams[n],s&&delete this.userToCamMap[s.userId],pb.instances.push(s),this.context.players.removePlayerView(s.userId,Uo.Browser);continue}}if(this.context.isInXR)return;const e=this.context.mainCamera;if(e===null){this.enabled=!1;return}if(!this.context.connection.isConnected||this.context.connection.connectionId===null)return;this._model===null&&(this._model=new $I(this.context.connection.connectionId,this.context.connection.connectionId+"_camera"));const t=ee(e),i=_e(e);(t.distanceTo(this._lastWorldPosition)>.001||i.angleTo(this._lastWorldQuaternion)>.01)&&(this._needsUpdate=!0),this._lastWorldPosition.copy(t),this._lastWorldQuaternion.copy(i),!((!this._needsUpdate||this.context.time.frameCount%2!==0)&&!(this.context.time.realtimeSinceStartup-this._lastUpdateTime>this._camTimeoutInSeconds*.5))&&(this._lastUpdateTime=this.context.time.realtimeSinceStartup,this._needsUpdate=!1,this._model.send(e,this.context.connection),this.context.isInXR||this.context.players.setPlayerView(this.context.connection.connectionId,e,Uo.Browser))}onReceivedRemoteCameraInfoBin(e){const t=e.guid();if(!t)return;const i=e.userId();if(!i||!this.context.connection.userIsInRoom(i)||!this.cameraPrefab)return;let n=this.remoteCams[t];if(!n)if("isObject3D"in this.cameraPrefab){const l=new Wn;l.context=this.context;const c=S.instantiate(this.cameraPrefab,l);n=this.remoteCams[t]={obj:c,lastUpdate:this.context.time.realtimeSinceStartup,userId:i},n.obj.visible=!0,this.gameObject.add(c),this.userToCamMap[i]=t,pb.instances.push(n);const h=S.getOrAddComponent(c,Le);h.connectionId=i,h.avatar=c}else return;const s=n.obj;this.context.players.setPlayerView(i,s,Uo.Browser),n.lastUpdate=this.context.time.realtimeSinceStartup,pn.markDirty(s);const r=e.pos();r&&Sr(s,r.x(),r.y(),r.z());const a=e.rot();a&&fc(s,a.x(),a.y(),a.z())}};VI([u([M,ne])],nS.prototype,"cameraPrefab");let D0=nS;var HI=Object.defineProperty,GI=Object.getOwnPropertyDescriptor,sr=(o,e,t,i)=>{for(var n=i>1?void 0:i?GI(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&HI(e,t,n),n};const B0="view",F0=w("debugsyncedroom");class Fn extends E{roomName="";urlParameterName="room";joinRandomRoom;requireRoomParameter=!1;autoRejoin=!0;createJoinButton=!0;createViewOnlyButton=!1;get currentRoomName(){return w(B0)||w(this.urlParameterName)}_lastJoinedRoom;set roomPrefix(e){this._roomPrefix=e}get roomPrefix(){return this._roomPrefix}_roomPrefix="";awake(){this.joinRandomRoom===void 0&&this.roomName?.length<=0&&(this.joinRandomRoom=!0),F0&&console.log(`SyncedRoom roomName:${this.roomName}, urlParamName:${this.urlParameterName}, joinRandomRoom:${this.joinRandomRoom}`)}onEnable(){const e=w(B0);if(e&&typeof e=="string"&&e.length>0){console.log("Join as viewer"),this.context.connection.joinRoom(e,!0);return}if(this.tryJoinRoom(),this.createJoinButton){const t=this.createRoomButton();this.context.menu.appendChild(t)}this.createViewOnlyButton&&this.onEnableViewOnlyButton()}onDisable(){this._roomButton?.remove(),this.onDisableViewOnlyButton(),this.roomName&&this.roomName.length>0&&this.context.connection.leaveRoom(this.roomName)}onDestroy(){this.destroyRoomButton()}tryJoinRandomRoom(){this.setRandomRoomUrlParameter(),this.tryJoinRoom()}tryJoinRoom(e=0){e===void 0&&(e=0);let t=!1;if(this.urlParameterName?.length>0){const i=w(this.urlParameterName);if(i&&(typeof i=="string"||typeof i=="number")){t=!0;const n=i_(i.toString());this.roomName=n}else if(this.joinRandomRoom&&(console.debug("No room name found in url, generating random one"),this.setRandomRoomUrlParameter(),e<1))return this.tryJoinRoom(e+1)}else this.joinRandomRoom&&(this.roomName===null||this.roomName===void 0||this.roomName.length<=0)&&(this.roomName=this.generateRoomName());return this.requireRoomParameter&&!t?((F0||A())&&console.warn('[SyncedRoom] Missing required room parameter "'+this.urlParameterName+`" in url - will not connect.
|
|
1426
|
+
`)},e.userData.isLightBlendMaterial=!0}applyShadowMaterial(){if(this.targetMesh)if(this.targetMesh.material.type!=="ShadowMaterial"){const e=new gb;e.color=this.shadowColor,e.opacity=this.shadowColor.alpha,this.applyMaterialOptions(e),this.targetMesh.material=e,e.userData.isShadowCatcherMaterial=!0}else{const e=this.targetMesh.material;e.color=this.shadowColor,e.opacity=this.shadowColor.alpha,this.applyMaterialOptions(e),e.userData.isShadowCatcherMaterial=!0}}applyOccluderMaterial(){if(this.targetMesh){let e=this.targetMesh.material;if(!e){const t=new Ce;this.targetMesh.material=t,e=t}e.depthWrite=!0,e.stencilWrite=!0,e.colorWrite=!1,this.gameObject.renderOrder=-100}}applyMaterialOptions(e){e&&(e.depthWrite=!1,e.stencilWrite=!1)}}Y1([u()],Uh.prototype,"mode"),Y1([u(se)],Uh.prototype,"shadowColor");var CI=Object.defineProperty,zh=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&CI(e,t,n),n};const si=w("debugskybox");j0("background-image"),j0("environment-image");const Z1={studio:{url:"https://cdn.needle.tools/static/skybox/modelviewer-Neutral.pmrem4x4.ktx2?pmrem",url_low:"https://cdn.needle.tools/static/skybox/modelviewer-Neutral-small.pmrem4x4.ktx2?pmrem"},"blurred-skybox":{url:"https://cdn.needle.tools/static/skybox/blurred-skybox.pmrem4x4.ktx2?pmrem",url_low:"https://cdn.needle.tools/static/skybox/blurred-skybox-small.pmrem4x4.ktx2?pmrem"},"quicklook-ar":{url:"https://cdn.needle.tools/static/skybox/QuickLook-ARMode.pmrem4x4.ktx2?pmrem",url_low:"https://cdn.needle.tools/static/skybox/QuickLook-ARMode-small.pmrem4x4.ktx2?pmrem"},quicklook:{url:"https://cdn.needle.tools/static/skybox/QuickLook-ObjectMode.pmrem4x4.ktx2?pmrem",url_low:"https://cdn.needle.tools/static/skybox/QuickLook-ObjectMode-small.pmrem4x4.ktx2?pmrem"}};function K1(o,e,t,i,n){if(e==="transparent"||e?.startsWith("rgb")||e?.startsWith("#"))return console.warn(`Needle Engine: Invalid ${n} value (${e}). Did you mean to set background-color instead?`),null;const s=new Yp;s.sourceId=o_(e),s.allowDrop=!1,s.allowNetworking=!1,s.background=t,s.environment=i,S.addComponent(o.scene,s);const r=a=>{if(si&&console.log(n,"CHANGED TO",a),a){if(typeof a!="string"){console.warn("Invalid attribute value for "+n);return}s.setSkybox(a)}else if(s.sourceId&&(i&&(o.sceneLighting.internalEnableReflection(s.sourceId)||(o.scene.environment=null)),t)){const l=o.lightmaps.tryGetSkybox(s.sourceId);o.scene.background=l}};return Ym(o.domElement,n,r),s.addEventListener("destroy",()=>{si&&console.log("Destroyed attribute remote skybox",n),Zm(o.domElement,n,r)}),s.setSkybox(e)}const Qp=new Array;pe.registerCallback(ue.ContextCreationStart,o=>{const e=o.context,t=e.domElement.getAttribute("background-image"),i=e.domElement.getAttribute("environment-image");if(t){si&&console.log("Creating RemoteSkybox to load background "+t);const n=K1(e,t,!0,!1,"background-image");n&&Qp.push(n)}if(i){si&&console.log("Creating RemoteSkybox to load environment "+i);const n=K1(e,i,!1,!0,"environment-image");n&&Qp.push(n)}}),pe.registerCallback(ue.ContextCreationStart,()=>Promise.all(Qp).finally(()=>{Qp.length=0}));const ga=class extends E{url="studio";allowDrop=!0;background=!0;environment=!0;allowNetworking=!0;_prevUrl;_prevLoadedEnvironment;_prevEnvironment=null;_prevBackground=null;onEnable(){this.setSkybox(this.url),this.registerDropEvents()}onDisable(){this.context.scene.environment===this._prevLoadedEnvironment&&(this.context.scene.environment=this._prevEnvironment,yi.backgroundShouldBeTransparent(this.context)||(this.context.scene.background=this._prevBackground),this._prevLoadedEnvironment=void 0),this.unregisterDropEvents(),this.context.mainCameraComponent?.applyClearFlags()}urlChangedSyncField(){this.allowNetworking&&this.url&&(this.isRemoteTexture(this.url)?this.setSkybox(this.url):si&&console.warn(`RemoteSkybox: Not setting skybox: ${this.url} is not a remote texture. If you want to set a local texture, set allowNetworking to false.`))}async setSkybox(o,e){if(!this.activeAndEnabled||(o=PI(o,this.environment,this.background),!o))return!1;if(e??=o,this.isValidTextureType(e)||console.warn('Potentially invalid skybox URL: "'+e+'" on '+(this.name||this.gameObject?.name||"context")),si&&console.log("Set RemoteSkybox url: "+o),this._prevUrl===o&&this._prevLoadedEnvironment)return this.apply(),!0;this._prevLoadedEnvironment?.dispose(),this._prevLoadedEnvironment=void 0,this._prevUrl=o;const t=await ly(o,this.context.renderer);return t?!this.enabled||this.destroyed?(si&&console.warn("RemoteSkybox: Component is disabled or destroyed"),!1):this._prevUrl!==o?(si&&console.warn("RemoteSkybox: URL changed while loading texture, aborting setSkybox"),!1):(this.url=o,this._prevLoadedEnvironment=t,this.apply(),!0):(si&&console.warn("RemoteSkybox: Failed to load texture from url",o),!1)}apply(){const o=this._prevLoadedEnvironment;if(o&&(o instanceof Ob||o instanceof KC||o.mapping==Pb||(o.mapping=JC,o.needsUpdate=!0),!this.destroyed)){if(!this.context){console.warn("RemoteSkybox: Context is not available - can not apply skybox.");return}this.context.scene.background!==o&&(this._prevBackground=this.context.scene.background),this.context.scene.environment!==o&&(this._prevEnvironment=this.context.scene.environment),si&&console.log("Set RemoteSkybox ("+(this.environment&&this.background?"environment and background":this.environment?"environment":this.background?"background":"none")+")",this.url,!yi.backgroundShouldBeTransparent(this.context)),this.environment&&(this.context.scene.environment=o),this.background&&!yi.backgroundShouldBeTransparent(this.context)&&(this.context.scene.background=o),this.context.mainCameraComponent?.backgroundBlurriness!==void 0&&(this.context.scene.backgroundBlurriness=this.context.mainCameraComponent.backgroundBlurriness)}}validProtocols=["file:","blob:","data:"];validTextureTypes=[".ktx2",".hdr",".exr",".jpg",".jpeg",".png"];isRemoteTexture(o){return o.startsWith("http://")||o.startsWith("https://")}isValidTextureType(o){for(const e of this.validTextureTypes)if(o.includes(e))return!0;for(const e of this.validProtocols)if(o.startsWith(e))return!0;return!1}registerDropEvents(){this.unregisterDropEvents(),this.context.domElement.addEventListener("dragover",this.onDragOverEvent),this.context.domElement.addEventListener("drop",this.onDrop)}unregisterDropEvents(){this.context.domElement.removeEventListener("dragover",this.onDragOverEvent),this.context.domElement.removeEventListener("drop",this.onDrop)}onDragOverEvent=o=>{if(this.allowDrop&&o.dataTransfer)for(const e of o.dataTransfer.types)(e==="text/uri-list"||e==="Files")&&o.preventDefault()};onDrop=o=>{if(this.allowDrop&&o.dataTransfer){for(const e of o.dataTransfer.types)if(si&&console.log(e),e==="text/uri-list"){const t=o.dataTransfer.getData(e);si&&console.log(e,t);let i=new RegExp(/polyhaven.com\/asset_img\/.+?\/(?<name>.+)\.png/).exec(t)?.groups?.name;if(i||(i=new RegExp(/polyhaven\.com\/a\/(?<name>.+)/).exec(t)?.groups?.name),si&&console.log(i),i){const n="https://dl.polyhaven.org/file/ph-assets/HDRIs/exr/1k/"+i+"_1k.exr";console.log(`[Remote Skybox] Setting skybox from url: ${n}`),o.preventDefault(),this.setSkybox(n);break}else if(this.isValidTextureType(t)){console.log("[Remote Skybox] Setting skybox from url: "+t),o.preventDefault(),this.setSkybox(t);break}else{console.warn(`[RemoteSkybox] Unknown url ${t}. If you want to load a skybox from a url, make sure it is a valid image url. Url must end with${this.validTextureTypes.join(", ")}.`);const n=new CustomEvent("dropped-unknown-url",{detail:{sender:this,event:o,url:t,apply:s=>{o.preventDefault(),this.setSkybox(s)}}});this.dispatchEvent(n)}}else if(e=="Files"){const t=o.dataTransfer.files.item(0);if(si&&console.log(e,t),!t)continue;if(!this.isValidTextureType(t.name)){console.warn(`[RemoteSkybox]: File "${t.name}" is not supported. Supported files are ${this.validTextureTypes.join(", ")}`);return}o.preventDefault(),this.setSkybox(t.name);break}}}};zh([zy(ga.prototype.urlChangedSyncField),u(URL)],ga.prototype,"url"),zh([u()],ga.prototype,"allowDrop"),zh([u()],ga.prototype,"background"),zh([u()],ga.prototype,"environment"),zh([u()],ga.prototype,"allowNetworking");let Yp=ga;function PI(o,e,t){if(o==null)return null;const i=e&&!t,n=Z1[o.toLowerCase()];return n?i?n.url_low:n.url:(typeof o=="string"&&o?.length&&(A()||si)&&(o.includes("/")||o.includes(".")||console.warn(`RemoteSkybox: Unknown magic skybox name "${o}". Valid names are: ${Object.keys(Z1).map(s=>`"${s}"`).join(", ")}`)),o)}var OI=Object.defineProperty,Zp=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&OI(e,t,n),n};const Nh=class $S extends E{target=null;followFactor=.1;rotateFactor=.1;positionAxes=cl.All;flipForward=!1;static _invertForward=new N().setFromAxisAngle(new b(0,1,0),Math.PI);_firstUpdate=!0;onBeforeRender(){this.updateNow(!1)}updateNow(e){if(!(!this.target||this.target===this.gameObject)){if(this.followFactor>0){const t=ee(this.target),i=this._firstUpdate||e?1:j.clamp01(this.context.time.deltaTime*this.followFactor),n=this.worldPosition;this.positionAxes&cl.X&&(n.x=j.lerp(n.x,t.x,i)),this.positionAxes&cl.Y&&(n.y=j.lerp(n.y,t.y,i)),this.positionAxes&cl.Z&&(n.z=j.lerp(n.z,t.z,i)),this.worldPosition=n}if(this.rotateFactor>0){const t=_e(this.target);this.flipForward&&t.premultiply($S._invertForward);const i=this._firstUpdate||e?1:j.clamp01(this.context.time.deltaTime*this.rotateFactor);this.worldQuaternion=this.worldQuaternion.slerp(t,i)}this._firstUpdate=!1}}};Zp([u(M)],Nh.prototype,"target"),Zp([u()],Nh.prototype,"followFactor"),Zp([u()],Nh.prototype,"rotateFactor"),Zp([u()],Nh.prototype,"positionAxes");let Kp=Nh;var kI=Object.defineProperty,Wh=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&kI(e,t,n),n};const Vh=w("debugspatialtrigger"),J1=new _s,eS=new _s;function MI(o,e){return J1.mask=o,eS.mask=e,J1.test(eS)}class mo extends E{triggerMask=0;onEnter;onStay;onExit;start(){Vh&&console.log(this.name,this.triggerMask,this)}update(){this.currentIntersected.length=0;for(const e of Jp.triggers)MI(e.triggerMask,this.triggerMask)&&e.test(this.gameObject)&&this.currentIntersected.push(e);for(let e=this.lastIntersected.length-1;e>=0;e--){const t=this.lastIntersected[e];this.currentIntersected.indexOf(t)<0&&(this.onExitTrigger(t),this.lastIntersected.splice(e,1))}for(const e of this.currentIntersected)this.lastIntersected.indexOf(e)<0&&this.onEnterTrigger(e),this.onStayTrigger(e);this.lastIntersected.length=0,this.lastIntersected.push(...this.currentIntersected)}currentIntersected=[];lastIntersected=[];onEnterTrigger(e){Vh&&console.log("ENTER TRIGGER",this.name,e.name,this,e),e.raiseOnEnterEvent(this),this.onEnter?.invoke()}onExitTrigger(e){Vh&&console.log("EXIT TRIGGER",this.name,e.name),e.raiseOnExitEvent(this),this.onExit?.invoke()}onStayTrigger(e){e.raiseOnStayEvent(this),this.onStay?.invoke()}}Wh([u()],mo.prototype,"triggerMask"),Wh([u(ae)],mo.prototype,"onEnter"),Wh([u(ae)],mo.prototype,"onStay"),Wh([u(ae)],mo.prototype,"onExit");const tS=class wm extends E{static triggers=[];triggerMask;boxHelper;start(){Vh&&console.log(this.name,this.triggerMask,this)}onEnable(){wm.triggers.push(this),this.boxHelper||(this.boxHelper=S.addComponent(this.gameObject,Bt),this.boxHelper?.showHelper(null,Vh))}onDisable(){wm.triggers.splice(wm.triggers.indexOf(this),1)}test(e){return this.boxHelper?this.boxHelper.isInBox(e)??!1:!1}raiseOnEnterEvent(e){S.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof mo&&t.onEnterTrigger(this)},!1)}raiseOnStayEvent(e){S.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof mo&&t.onStayTrigger(this)},!1)}raiseOnExitEvent(e){S.foreachComponent(this.gameObject,t=>{t!==e&&t instanceof mo&&t.onExitTrigger(this)},!1)}};Wh([u()],tS.prototype,"triggerMask");let Jp=tS;var EI=Object.defineProperty,RI=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&EI(e,t,n),n};const Ni=w("debugspectator");class em extends E{cam=null;useKeys=!0;_mode=0;get mode(){return this._mode}set mode(e){this._mode=e}get isSpectating(){return this._handler?.currentTarget!==void 0}isSpectatingUser(e){return this.target?.userId===e}isFollowedBy(e){return this.followers?.includes(e)}get followers(){return this._networking.followers}stopSpectating(){if(this.context.isInXR){this.followSelf();return}this.target=void 0}get localId(){return this.context.connection.connectionId??"local"}set target(e){if(this._handler){const t=this._handler.currentTarget?.userId,i=this.context.players.getPlayerView(this.localId);e===void 0||this.context.isInXR===!1&&i?.currentObject===e.currentObject?this._handler.currentTarget!==void 0&&(this._handler.disable(),S.setActive(this.gameObject,!1),this.orbit&&(this.orbit.enabled=!0),this._networking.onSpectatedObjectChanged(e,t)):this._handler.currentTarget!==e&&(this._handler.set(e),S.setActive(this.gameObject,!0),this.orbit&&(this.orbit.enabled=!1),this._networking.onSpectatedObjectChanged(e,t))}}get target(){return this._handler?.currentTarget}requestAllFollowMe(){this._networking.onRequestFollowMe()}get isSpectatingSelf(){return this.isSpectating&&this.target?.currentObject===this.context.players.getPlayerView(this.localId)?.currentObject}orbit=null;_handler;eventSub_WebXRRequestStartEvent=null;eventSub_WebXRStartEvent=null;eventSub_WebXREndEvent=null;_debug;_networking;awake(){if(this._debug=new II(this.context,this),this._networking=new DI(this.context,this),this._networking.awake(),S.setActive(this.gameObject,!1),this.cam=S.getComponent(this.gameObject,yi),!this.cam){console.warn("SpectatorCamera: Spectator camera needs camera component on the same object.",this);return}!this._handler&&this.cam&&(this._handler=new TI(this.context,this.cam,this)),this.orbit=S.getComponent(this.context.mainCamera,ge)}onDestroy(){this.stopSpectating(),this._handler?.destroy(),this._networking?.destroy()}isSupportedPlatform(){const e=window.navigator.userAgent,t=/Windows NT/.test(e)&&/Edg/.test(e)&&!/Win64/.test(e);return I.isDesktop()&&!I.isMobileDevice()&&!t}onBeforeXR(e){this.isSupportedPlatform()&&S.setActive(this.gameObject,!0)}onEnterXR(e){this.isSupportedPlatform()&&(Ni&&console.log(this.context.mainCamera),this.context.mainCamera&&this.followSelf())}onLeaveXR(e){this.context.removeCamera(this.cam),S.setActive(this.gameObject,!1),this._handler?.set(void 0),this._handler?.disable(),this.isSpectatingSelf&&this.stopSpectating(),this.orbit&&(this.orbit.enabled=!0)}followSelf(){this.target=this.context.players.getPlayerView(this.context.connection.connectionId),this.target||(this.context.players.setPlayerView(this.localId,this.context.mainCamera,Uo.Headset),this.target=this.context.players.getPlayerView(this.localId)),Ni&&console.log("Follow self",this.target)}onAfterRender(){if(!this.cam)return;const e=this.context.renderer,t=e.xr.enabled;if(!e.xr.isPresenting&&!this._handler?.currentTarget)return;this._handler?.update(this._mode);const i=e.getRenderTarget();let n=null;const s=e.state;if(!i||i.isXRRenderTarget===!0){if(!e.state.bindFramebuffer||!s.bindXRFramebuffer)return;n=e._framebuffer,s.bindXRFramebuffer(null)}this.setAvatarFlagsBeforeRender();const r=this.context.mainCameraComponent;if(r){const c=r.backgroundColor;c&&e.setClearColor(c,c.alpha),this.cam.backgroundColor=c,this.cam.clearFlags=r.clearFlags,this.cam.nearClipPlane=r.nearClipPlane,this.cam.farClipPlane=r.farClipPlane}else e.setClearColor(new oe(1,1,1));e.setRenderTarget(null),e.xr.enabled=!1;const a=this.cam?.threeCamera;this.context.updateAspect(a);const l=e.xr.isPresenting;e.xr.isPresenting=!1,e.setSize(this.context.domWidth,this.context.domHeight),e.render(this.context.scene,a),e.xr.isPresenting=l,e.xr.enabled=t,i?e.setRenderTarget(i):s.bindXRFramebuffer&&s.bindXRFramebuffer(n),this.resetAvatarFlags()}setAvatarFlagsBeforeRender(){const e=this._mode===0;for(const t of Le.instances)if(t.avatar&&"isLocalAvatar"in t.avatar&&"flags"in t.avatar){let i=no.All;this.isSpectatingSelf&&(i=e&&t.avatar.isLocalAvatar?no.FirstPerson:no.ThirdPerson);const n=t.avatar.flags;if(!n)continue;for(const s of n)s.UpdateVisible(i)}}resetAvatarFlags(){for(const e of Le.instances)if(e.avatar&&"flags"in e.avatar){const t=e.avatar.flags;if(!t)continue;for(const i of t)"isLocalAvatar"in e.avatar&&e.avatar?.isLocalAvatar?i.UpdateVisible(no.FirstPerson):i.UpdateVisible(no.ThirdPerson)}}}RI([u()],em.prototype,"useKeys");class TI{context;cam;spectator;follow;target;view;currentObject;get currentTarget(){return this.view}constructor(e,t,i){this.context=e,this.cam=t,this.spectator=i}set(e){const t=e?.currentObject;if(!t){this.spectator.stopSpectating();return}t!==this.currentObject&&(this.currentObject=t,this.view=e,this.follow||(this.follow=S.addComponent(this.cam.gameObject,Kp)),this.target||(this.target=new M),t.add(this.target),this.follow.enabled=!0,this.follow.target=this.target,Ni&&console.log("FOLLOW",t),this.context.isInXR?this.context.removeCamera(this.cam):this.context.setCurrentCamera(this.cam))}disable(){Ni&&console.log("STOP FOLLOW",this.currentObject),this.view=void 0,this.currentObject=void 0,this.context.removeCamera(this.cam),this.follow&&(this.follow.enabled=!1)}destroy(){this.target?.removeFromParent(),this.follow&&S.destroy(this.follow)}update(e){if(this.currentTarget?.isConnected===!1||this.currentTarget?.removed===!0){Ni&&console.log("Target disconnected or timeout",this.currentTarget),this.spectator.stopSpectating();return}this.currentTarget&&this.currentTarget?.currentObject!==this.currentObject&&(Ni&&console.log("Target changed",this.currentObject,"to",this.currentTarget.currentObject),this.set(this.currentTarget));const t=this.context.mainCamera;if(t){const n=this.cam.threeCamera;(n.near!==t.near||n.far!==t.far)&&(n.near=t.near,n.far=t.far,n.updateProjectionMatrix())}const i=this.follow?.target;if(!(!i||!this.follow)){switch(e){case 0:this.view?.viewDevice!==Uo.Browser?(this.follow.followFactor=5,this.follow.rotateFactor=5):(this.follow.followFactor=50,this.follow.rotateFactor=50),i.position.set(0,0,0);break;case 1:this.follow.followFactor=3,this.follow.rotateFactor=2,i.position.set(0,.5,1.5);break}this.follow.flipForward=!1,this.view?.viewDevice!==Uo.Browser?i.quaternion.copy(AI):i.quaternion.identity()}}}const AI=new N().setFromAxisAngle(new b(0,1,0),Math.PI);class II{context;spectator;constructor(e,t){this.context=e,this.spectator=t,console.log("[Spectator Camera] Click other avatars or cameras to follow them. Press ESC to exit spectator mode."),this.context.domElement.addEventListener("keydown",n=>{!this.spectator.useKeys||n.key==="Escape"&&this.spectator.stopSpectating()});let i=0;this.context.input.addEventListener(Ae.PointerDown,n=>{i=this.context.time.time}),this.context.input.addEventListener(Ae.PointerUp,n=>{const s=this.context.time.time-i;s>1?this.spectator.stopSpectating():this.context.input.getPointerClicked(0)&&s<.3&&this.trySelectObject()})}trySelectObject(){const e=new ks;e.setMask(16777215);const t=this.context.physics.raycast(e);if(Ni&&console.log(...t),t?.length)for(const i of t){if(i.distance<.2)continue;const n=i.object,s=sn.getFor(n);let r=s?.owner;if(r||(r=S.getComponentInParent(n,Le)?.connectionId),r){const a=this.context.players.getPlayerView(r);this.spectator.target=a,Ni&&console.log("spectate",r,s);break}}}}class LI{guid;dontSave=!0;targetUserId;stoppedFollowing;constructor(e,t,i){this.guid=e,this.targetUserId=t,this.stoppedFollowing=i}}class jI{guid;userId;constructor(e,t){this.guid=e.guid,this.userId=t}}class DI{followers=[];context;spectator;_followerEventMethod;_requestFollowMethod;_joinedRoomMethod;constructor(e,t){this.context=e,this.spectator=t,this._followerEventMethod=this.onFollowerEvent.bind(this),this._requestFollowMethod=this.onRequestFollowEvent.bind(this),this._joinedRoomMethod=this.onUserJoinedRoom.bind(this)}awake(){this.context.connection.beginListen("spectator-follower-changed",this._followerEventMethod),this.context.connection.beginListen("spectator-request-follow",this._requestFollowMethod),this.context.connection.beginListen(ie.JoinedRoom,this._joinedRoomMethod),this.context.domElement.addEventListener("keydown",e=>{this.spectator.useKeys&&(e.key==="f"?this.onRequestFollowMe():e.key==="Escape"&&this.onRequestFollowMe(!0))})}destroy(){this.context.connection.stopListen("spectator-follower-changed",this._followerEventMethod),this.context.connection.stopListen("spectator-request-follow",this._requestFollowMethod),this.context.connection.stopListen(ie.JoinedRoom,this._joinedRoomMethod)}onSpectatedObjectChanged(e,t){if(Ni&&console.log(this.context.connection.connectionId,"onSpectatedObjectChanged",e,t),this.context.connection.connectionId){const i=e?.userId===void 0,n=i?t:e?.userId,s=new LI(this.context.connection.connectionId,n,i);this.context.connection.send("spectator-follower-changed",s)}}onRequestFollowMe(e=!1){if(Ni&&console.log("Request follow",this.context.connection.connectionId),this.context.connection.connectionId){this.spectator.stopSpectating();const t=e?void 0:this.context.connection.connectionId,i=new jI(this.spectator,t);this.context.connection.send("spectator-request-follow",i)}}onUserJoinedRoom(){w("followme")&&this.onRequestFollowMe()}onFollowerEvent(e){const t=e.targetUserId,i=e.guid;if(Ni&&console.log(e),t===this.context.connection.connectionId)if(e.stoppedFollowing){const n=this.followers.indexOf(i);n!==-1&&(this.followers.splice(n,1),this.removeDisconnectedFollowers(),console.log(i,"unfollows you",this.followers.length))}else this.followers.includes(i)||(this.followers.push(i),this.removeDisconnectedFollowers(),console.log(i,"follows you",this.followers.length))}removeDisconnectedFollowers(){for(let e=this.followers.length-1;e>=0;e--){const t=this.followers[e];this.context.connection.userIsInRoom(t)===!1&&this.followers.splice(e,1)}}_lastRequestFollowUser;onRequestFollowEvent(e){if(this._lastRequestFollowUser=e,e.userId===this.context.connection.connectionId)this.spectator.stopSpectating();else if(e.userId===void 0)this.spectator.stopSpectating();else{const t=this.context.players.getPlayerView(e.userId);if(t)this.spectator.target=t;else return Ni&&console.warn("Could not find view",e.userId),this.enforceFollow(),!1}return!0}_enforceFollowInterval;enforceFollow(){this._enforceFollowInterval||(this._enforceFollowInterval=setInterval(()=>{this._lastRequestFollowUser===void 0||this._lastRequestFollowUser.userId&&this.spectator.isFollowedBy(this._lastRequestFollowUser.userId)?(clearInterval(this._enforceFollowInterval),this._enforceFollowInterval=void 0):(Ni&&console.log("REQUEST FOLLOW AGAIN",this._lastRequestFollowUser.userId),this.onRequestFollowEvent(this._lastRequestFollowUser))},1e3))}}var BI=Object.defineProperty,FI=Object.getOwnPropertyDescriptor,Gl=(o,e,t,i)=>{for(var n=i>1?void 0:i?FI(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&BI(e,t,n),n};const iS=w("debugsplines");class go{position=new b;rotation=new N;tangentIn=new b;tangentOut=new b}Gl([Ye(b)],go.prototype,"position",2),Gl([Ye(N)],go.prototype,"rotation",2),Gl([Ye(b)],go.prototype,"tangentIn",2),Gl([Ye(b)],go.prototype,"tangentOut",2);class fa extends E{addKnot(e){if(e instanceof go)this.spline.push(e),this._isDirty=!0;else{const t=new go;t.position.copy(e.position),this.spline.push(t),this._isDirty=!0}return this}removeKnot(e){if(typeof e=="number")this.spline.splice(e,1),this._isDirty=!0;else{const t=this.spline.indexOf(e);t!==-1&&(this.spline.splice(t,1),this._isDirty=!0)}return this}getPointAt(e,t){if(!this.curve)return new b;const i=this.curve.getPointAt(j.clamp01(e),t),n=this.gameObject.matrixWorld??void 0;return n&&i.applyMatrix4(n),i}markDirty(){this._isDirty=!0}getTangentAt(e,t){if(!this.curve)return t??new b;const i=this.gameObject.worldQuaternion;return this.curve.getTangentAt(j.clamp01(e),t).applyQuaternion(i)}set closed(e){this._closed=e,this._isDirty=!0}get closed(){return this._closed}_closed=!1;spline=[];set debug(e){e&&!this._builtCurve&&this.buildCurve(),this._debugLine&&(this._debugLine.visible=e)}get curve(){return this._curve}get isDirty(){return this._isDirty}_isDirty=!1;_curve=null;_builtCurve=!1;_debugLine=null;awake(){iS&&(console.log(`[Spline] ${this.name}`,this),this.buildCurve())}update(){this._isDirty&&this.buildCurve(!0),this._debugLine&&this._debugLine.parent!==this.gameObject&&this.gameObject.add(this._debugLine)}buildCurve(e=!1){if(!(this._builtCurve&&!e)){if(this._builtCurve=!0,!this.spline){console.error("[Spline] Can not build curve, no spline data",this.name);return}this._isDirty=!1,this._curve=UI(this.spline,this.closed),this.buildDebugCurve()}}buildDebugCurve(){if(iS&&this.spline&&this._curve){this._debugLine?.removeFromParent(),this._debugLine=null;const e=new Em({color:6684927}),t=this.spline.length*10,i=this._curve.getPoints(t),n=new wn().setFromPoints(i);this._debugLine=new Ia(n,e),this.gameObject?.add(this._debugLine)}}}Gl([Ye()],fa.prototype,"closed",1),Gl([Ye(go)],fa.prototype,"spline",2);function UI(o,e){const t=o.map(s=>new b(-s.position.x,s.position.y,s.position.z));t.length===1&&t.push(t[0]);const i=o.reduce((s,r)=>s+Math.abs(r.tangentOut.x)+Math.abs(r.tangentOut.y)+Math.abs(r.tangentOut.z),0)/o.length,n=j.clamp(j.remap(i,0,.3,0,.5),0,1);return new eP(t,e,"catmullrom",n)}var zI=Object.defineProperty,NI=Object.getOwnPropertyDescriptor,or=(o,e,t,i)=>{for(var n=i>1?void 0:i?NI(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&zI(e,t,n),n};class hn extends E{spline=null;object=void 0;useLookAt=!0;lookAt=null;clamp=!1;get position01(){return this._position01}set position01(e){this._position01=e,this._needsUpdate=!0}reset(){this._position01=0}autoRun=!0;duration=10;pullStrength=1;_position01=0;_needsUpdate=!1;start(){this.object===void 0&&(this.object=this.gameObject),this.updateFromPosition()}onEnable(){window.addEventListener("pointerdown",this.onUserInput,{passive:!0}),this.context.domElement.addEventListener("wheel",this.onUserInput,{passive:!0})}onDisable(){window.removeEventListener("pointerdown",this.onUserInput),this.context.domElement.removeEventListener("wheel",this.onUserInput)}onUserInput=()=>{this.object?.contains(this.context.mainCamera)&&(this._needsUpdate=!1,this._performedUpdates+=999)};update(){this.autoRun&&(this._needsUpdate=!0,this._position01+=this.context.time.deltaTime/this.duration),this._needsUpdate&&(this._needsUpdate=!1,this.updateFromPosition())}updateFromPosition(){if(!this.spline||!this.spline.curve||!this.object)return;this.clamp?this._position01=j.clamp01(this._position01):this._position01=this._position01%1;const e=this._position01>=1?1:this._position01%1,t=this.spline.getPointAt(e);if(this.pullStrength>=1)this.object.worldPosition=t;else if(this._position01!==this._lastPosition01&&(this._performedUpdates=0),this._requiredUpdates=Math.round(100/this.pullStrength),this._performedUpdates<this._requiredUpdates){const i=this.object.worldPosition;this._performedUpdates++;const n=j.clamp01(this.pullStrength),s=this.object.worldPosition=i.lerp(t,n*(this.context.time.deltaTime/.3));this._lastPositionVector.copy(s),this._needsUpdate=!0}if(this.useLookAt)if(this.lookAt)this.object.lookAt(this.lookAt.worldPosition);else{const i=this.spline.getTangentAt(e);this.object.lookAt(t.add(i))}this._lastPosition01=this._position01}_lastPosition01=0;_requiredUpdates=0;_performedUpdates=0;_lastPositionVector=new b}or([Ye(fa)],hn.prototype,"spline",2),or([Ye(M)],hn.prototype,"object",2),or([Ye()],hn.prototype,"useLookAt",2),or([Ye(M)],hn.prototype,"lookAt",2),or([Ye()],hn.prototype,"clamp",2),or([Ye()],hn.prototype,"position01",1),or([Ye()],hn.prototype,"autoRun",2),or([Ye()],hn.prototype,"duration",2);class wo{bb=null;bb_pos=0;__init(e,t){return this.bb_pos=e,this.bb=t,this}static getRootAsSyncedCameraModel(e,t){return(t||new wo).__init(e.readInt32(e.position())+e.position(),e)}static getSizePrefixedRootAsSyncedCameraModel(e,t){return e.setPosition(e.position()+Vb),(t||new wo).__init(e.readInt32(e.position())+e.position(),e)}userId(e){const t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__string(this.bb_pos+t,e):null}guid(e){const t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__string(this.bb_pos+t,e):null}dontSave(){const e=this.bb.__offset(this.bb_pos,8);return e?!!this.bb.readInt8(this.bb_pos+e):!1}pos(e){const t=this.bb.__offset(this.bb_pos,10);return t?(e||new Vr).__init(this.bb_pos+t,this.bb):null}rot(e){const t=this.bb.__offset(this.bb_pos,12);return t?(e||new Vr).__init(this.bb_pos+t,this.bb):null}static startSyncedCameraModel(e){e.startObject(5)}static addUserId(e,t){e.addFieldOffset(0,t,0)}static addGuid(e,t){e.addFieldOffset(1,t,0)}static addDontSave(e,t){e.addFieldInt8(2,+t,0)}static addPos(e,t){e.addFieldStruct(3,t,0)}static addRot(e,t){e.addFieldStruct(4,t,0)}static endSyncedCameraModel(e){return e.endObject()}static finishSyncedCameraModelBuffer(e,t){e.finish(t)}static finishSizePrefixedSyncedCameraModelBuffer(e,t){e.finish(t,void 0,!0)}}var WI=Object.defineProperty,VI=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&WI(e,t,n),n};const tm="SCAM";Eg(tm,wo.getRootAsSyncedCameraModel);const Wi=new Wm;class $I{userId;guid;constructor(e,t){this.guid=t,this.userId=e}send(e,t){if(e){Wi.clear();const i=Wi.createString(this.guid),n=Wi.createString(this.userId);wo.startSyncedCameraModel(Wi),wo.addGuid(Wi,i),wo.addUserId(Wi,n);const s=ee(e),r=Vd(e);wo.addPos(Wi,Vr.createVec3(Wi,s.x,s.y,s.z)),wo.addRot(Wi,Vr.createVec3(Wi,r.x,r.y,r.z));const a=wo.endSyncedCameraModel(Wi);Wi.finish(a,tm),t.sendBinary(Wi.asUint8Array())}}}const nS=class pb extends E{static instances=[];getCameraObject(e){const t=this.userToCamMap[e];return t?this.remoteCams[t].obj:null}cameraPrefab=null;_lastWorldPosition;_lastWorldQuaternion;_model=null;_needsUpdate=!0;_lastUpdateTime=0;remoteCams={};userToCamMap={};_camTimeoutInSeconds=10;_receiveCallback=null;async awake(){this._lastWorldPosition=this.worldPosition.clone(),this._lastWorldQuaternion=this.worldQuaternion.clone(),this.cameraPrefab&&("uri"in this.cameraPrefab&&(this.cameraPrefab=await this.cameraPrefab.instantiate(this.gameObject)),this.cameraPrefab&&"isObject3D"in this.cameraPrefab&&(this.cameraPrefab.visible=!1))}onEnable(){this._receiveCallback=this.context.connection.beginListenBinary(tm,this.onReceivedRemoteCameraInfoBin.bind(this))}onDisable(){this.context.connection.stopListenBinary(tm,this._receiveCallback)}update(){for(const n in this.remoteCams){const s=this.remoteCams[n],r=this.context.time.realtimeSinceStartup-s.lastUpdate;if(!s||r>this._camTimeoutInSeconds){A()&&console.log("Remote cam timeout",n),s?.obj&&S.destroy(s.obj),delete this.remoteCams[n],s&&delete this.userToCamMap[s.userId],pb.instances.push(s),this.context.players.removePlayerView(s.userId,Uo.Browser);continue}}if(this.context.isInXR)return;const e=this.context.mainCamera;if(e===null){this.enabled=!1;return}if(!this.context.connection.isConnected||this.context.connection.connectionId===null)return;this._model===null&&(this._model=new $I(this.context.connection.connectionId,this.context.connection.connectionId+"_camera"));const t=ee(e),i=_e(e);(t.distanceTo(this._lastWorldPosition)>.001||i.angleTo(this._lastWorldQuaternion)>.01)&&(this._needsUpdate=!0),this._lastWorldPosition.copy(t),this._lastWorldQuaternion.copy(i),!((!this._needsUpdate||this.context.time.frameCount%2!==0)&&!(this.context.time.realtimeSinceStartup-this._lastUpdateTime>this._camTimeoutInSeconds*.5))&&(this._lastUpdateTime=this.context.time.realtimeSinceStartup,this._needsUpdate=!1,this._model.send(e,this.context.connection),this.context.isInXR||this.context.players.setPlayerView(this.context.connection.connectionId,e,Uo.Browser))}onReceivedRemoteCameraInfoBin(e){const t=e.guid();if(!t)return;const i=e.userId();if(!i||!this.context.connection.userIsInRoom(i)||!this.cameraPrefab)return;let n=this.remoteCams[t];if(!n)if("isObject3D"in this.cameraPrefab){const l=new Wn;l.context=this.context;const c=S.instantiate(this.cameraPrefab,l);n=this.remoteCams[t]={obj:c,lastUpdate:this.context.time.realtimeSinceStartup,userId:i},n.obj.visible=!0,this.gameObject.add(c),this.userToCamMap[i]=t,pb.instances.push(n);const h=S.getOrAddComponent(c,Le);h.connectionId=i,h.avatar=c}else return;const s=n.obj;this.context.players.setPlayerView(i,s,Uo.Browser),n.lastUpdate=this.context.time.realtimeSinceStartup,pn.markDirty(s);const r=e.pos();r&&Sr(s,r.x(),r.y(),r.z());const a=e.rot();a&&fc(s,a.x(),a.y(),a.z())}};VI([u([M,ne])],nS.prototype,"cameraPrefab");let D0=nS;var HI=Object.defineProperty,GI=Object.getOwnPropertyDescriptor,sr=(o,e,t,i)=>{for(var n=i>1?void 0:i?GI(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&HI(e,t,n),n};const B0="view",F0=w("debugsyncedroom");class Fn extends E{roomName="";urlParameterName="room";joinRandomRoom;requireRoomParameter=!1;autoRejoin=!0;createJoinButton=!0;createViewOnlyButton=!1;get currentRoomName(){return w(B0)||w(this.urlParameterName)}_lastJoinedRoom;set roomPrefix(e){this._roomPrefix=e}get roomPrefix(){return this._roomPrefix}_roomPrefix="";awake(){this.joinRandomRoom===void 0&&this.roomName?.length<=0&&(this.joinRandomRoom=!0),F0&&console.log(`SyncedRoom roomName:${this.roomName}, urlParamName:${this.urlParameterName}, joinRandomRoom:${this.joinRandomRoom}`)}onEnable(){const e=w(B0);if(e&&typeof e=="string"&&e.length>0){console.log("Join as viewer"),this.context.connection.joinRoom(e,!0);return}if(this.tryJoinRoom(),this.createJoinButton){const t=this.createRoomButton();this.context.menu.appendChild(t)}this.createViewOnlyButton&&this.onEnableViewOnlyButton()}onDisable(){this._roomButton?.remove(),this.onDisableViewOnlyButton(),this.roomName&&this.roomName.length>0&&this.context.connection.leaveRoom(this.roomName)}onDestroy(){this.destroyRoomButton()}tryJoinRandomRoom(){this.setRandomRoomUrlParameter(),this.tryJoinRoom()}tryJoinRoom(e=0){e===void 0&&(e=0);let t=!1;if(this.urlParameterName?.length>0){const i=w(this.urlParameterName);if(i&&(typeof i=="string"||typeof i=="number")){t=!0;const n=i_(i.toString());this.roomName=n}else if(this.joinRandomRoom&&(console.debug("No room name found in url, generating random one"),this.setRandomRoomUrlParameter(),e<1))return this.tryJoinRoom(e+1)}else this.joinRandomRoom&&(this.roomName===null||this.roomName===void 0||this.roomName.length<=0)&&(this.roomName=this.generateRoomName());return this.requireRoomParameter&&!t?((F0||A())&&console.warn('[SyncedRoom] Missing required room parameter "'+this.urlParameterName+`" in url - will not connect.
|
|
1427
1427
|
To allow joining a room without a query parameter you can set "requireRoomParameter" to false.`),!1):(this.context.connection.isConnected||this.context.connection.connect(),this._lastJoinedRoom=this.roomName,this._roomPrefix&&(this.roomName=this._roomPrefix+this.roomName),this.roomName.length<=0?(console.warn(`[SyncedRoom] Room name is not set so we can not join a networked room.
|
|
1428
1428
|
Please choose one of the following options to fix this:
|
|
1429
1429
|
A) Set a room name in the SyncedRoom component
|
|
1430
1430
|
B) Set a room name in the URL parameter "?`+this.urlParameterName+`=my_room"
|
|
1431
|
-
C) Set "joinRandomRoom" to true`),!1):(F0&&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(B0,this.context.connection.currentRoomViewId),window.location.origin+window.location.pathname+"?"+t.toString()}return null}setRandomRoomUrlParameter(){const e=dc(),t=this.generateRoomName();w(this.urlParameterName)?e.set(this.urlParameterName,t):e.append(this.urlParameterName,t),Xm(t,e)}generateRoomName(){let e="";for(let t=0;t<6;t++)e+=Math.floor(Math.random()*10).toFixed(0);return e}_roomButton;_roomButtonIconJoin;_roomButtonIconLeave;createRoomButton(){if(this._roomButton)return this._roomButton;const e=document.createElement("button");return this._roomButton=e,e.classList.add("create-room-button"),e.setAttribute("priority","90"),e.onclick=()=>{if(this.context.connection.isInRoom)this.urlParameterName&&uc(this.urlParameterName,null),this.context.connection.leaveRoom(),this._userWantsToBeInARoom=!1;else{if(this.urlParameterName){const t=w(this.urlParameterName);(!t||t===!0)&&(this._lastJoinedRoom?uc(this.urlParameterName,this._lastJoinedRoom):this.setRandomRoomUrlParameter())}this.tryJoinRoom()}},this._roomButtonIconJoin=Pt("group"),this._roomButtonIconLeave=Pt("group_off"),this.updateRoomButtonState(),this.context.connection.beginListen(ie.JoinedRoom,this.updateRoomButtonState),this.context.connection.beginListen(ie.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(ie.JoinedRoom,this.updateRoomButtonState),this.context.connection.stopListen(ie.LeftRoom,this.updateRoomButtonState)}_viewOnlyButton;onEnableViewOnlyButton(){this.context.connection.isConnected?this.onCreateViewOnlyButton():(this.context.connection.stopListen(ie.JoinedRoom,this.onCreateViewOnlyButton),this.context.connection.beginListen(ie.JoinedRoom,this.onCreateViewOnlyButton))}onDisableViewOnlyButton(){this.context.connection.stopListen(ie.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),Oe("View only URL copied to clipboard")):be("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)}}sr([u()],Fn.prototype,"roomName",2),sr([u()],Fn.prototype,"urlParameterName",2),sr([u()],Fn.prototype,"joinRandomRoom",2),sr([u()],Fn.prototype,"requireRoomParameter",2),sr([u()],Fn.prototype,"autoRejoin",2),sr([u()],Fn.prototype,"createJoinButton",2),sr([u()],Fn.prototype,"createViewOnlyButton",2),sr([u()],Fn.prototype,"roomPrefix",1);function qI(){const o=w("testwindowcount")||0;o&&o>0&&XI(o)}function XI(o){if(w("testwindow"))return null;const e=new URL(window.location.href);qm(e.searchParams,ER,1),qm(e.searchParams,"testwindow",1);const t=e.toString(),i=[];window.onbeforeunload=()=>{for(const l of i)l.close()};const n=.05,s=128;let r=0,a=0;for(let l=0;l<o;l++){r*s+s*.01>=window.innerWidth&&(a+=1,r=0);const c=r*(s*(1+n))+window.screenLeft,h=a*(s*(1+n))+window.screenTop+90+60*a;r+=1;const d=window.open(t,"test window "+l,`popup=yes width=${s} height=${s} top=${h} left=${c}`);if(!d){console.warn("Failed to open window");continue}i.push(d),d.onload=()=>{d.onbeforeunload=()=>{for(let p=0;p<i.length;p++){const m=i[p];m!==d&&m.close()}i.length=0}}}return i}class U0 extends E{awake(){qI()}}class z0 extends E{transformsPerFrame=10;interval=0;useFlatbuffers=!0;awake(){if(this.useFlatbuffers)this.context.connection.beginListenBinary(Qc,e=>{});else{this.models=[];for(let e=0;e<this.transformsPerFrame;e++)this.models.push(new QI(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 Wm(1024));const e=this.builder;for(let t=0;t<this.transformsPerFrame;t++){e.clear();const i=hx(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 QI{guid;fast=!1;position;rotation;velocity=void 0;dontSave;isValid(){return this.fast!==void 0||this.position!==void 0||this.rotation!==void 0||this.velocity!==void 0}constructor(e,t){this.guid=e,this.position={x:0,y:0,z:0},this.rotation={x:0,y:0,z:0,w:0},this.update(t,null)}static temp=new b;update(e,t){const i=e.worldPosition;this.position.x=i.x,this.position.y=i.y,this.position.z=i.z;const n=e.worldQuaternion;if(this.rotation.x=n.x,this.rotation.y=n.y,this.rotation.z=n.z,this.rotation.w=n.w,this.fast=!1,t){const s=t.getVelocity();this.velocity===void 0&&(this.velocity={x:0,y:0,z:0}),this.velocity.x=s.x,this.velocity.y=s.y,this.velocity.z=s.z}}}var YI=Object.defineProperty,im=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&YI(e,t,n),n};const ZI=w("debugsignals");class nm{guid}im([u()],nm.prototype,"guid");class $h{signal;reaction}im([u(nm)],$h.prototype,"signal"),im([u(ae)],$h.prototype,"reaction");const oS=class us extends E{static receivers={};static invoke(e){if(us.receivers[e]){const t=us.receivers[e];if(!t)return;for(const i of t)i.invoke(e)}}events;awake(){ZI&&console.log("SignalReceiver awake",this)}onEnable(){if(this.events)for(const e of this.events)us.receivers[e.signal.guid]||(us.receivers[e.signal.guid]=[]),us.receivers[e.signal.guid].push(this)}onDisable(){if(this.events){for(const e of this.events)if(us.receivers[e.signal.guid]){const t=us.receivers[e.signal.guid].indexOf(this);t>=0&&us.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)}}};im([u($h)],oS.prototype,"events");let Hh=oS;var Vi=(o=>(o.Activation="ActivationTrack",o.Animation="AnimationTrack",o.Audio="AudioTrack",o.Control="ControlTrack",o.Marker="MarkerTrack",o.Signal="SignalTrack",o))(Vi||{}),fo=(o=>(o[o.None=0]="None",o[o.Hold=1]="Hold",o[o.Loop=2]="Loop",o[o.PingPong=3]="PingPong",o[o.Continue=4]="Continue",o))(fo||{}),N0=(o=>(o.Signal="SignalEmitter",o))(N0||{});const yo=w("debugtimeline");class ql{director;track;get muted(){return this.track.muted}set muted(e){e!==this.track.muted&&(this.track.muted=e,this.onMuteChanged?.call(this))}*forEachClip(e=!1){if(this.track?.clips)if(e)for(let t=this.track.clips.length-1;t>=0;t--)yield this.track.clips[t];else for(const t of this.track.clips)yield t}getClipTime(e,t){return t.clipIn+(e-t.start)*t.timeScale}getClipTimeNormalized(e,t){return(e-t.start)/t.duration}evaluateWeight(e,t,i,n=!0){if(t<0||t>=i.length)return 0;const s=i[t];if(n||e>=s.start&&e<=s.end){let r=1;if(s.easeInDuration>0){const a=Math.min((e-s.start)/s.easeInDuration,1);r*=a}if(s.easeOutDuration>0){const a=Math.min((s.end-e)/s.easeOutDuration,1);r*=a}return r}return 0}}class KI{clip;rootPositionOffset;rootQuaternionOffset;get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}rootStartPosition;rootEndPosition;rootStartQuaternion;rootEndQuaternion;constructor(e){const t=e.getClip();this.clip=t;const i=e.getRoot(),n=i.name+".position",s=i.name+".quaternion";yo&&console.log(t.name,t.tracks,n);for(const r of t.tracks)if(!(r.times.length<=0)){if(r.name.endsWith(n))this.rootStartPosition=new b().fromArray(r.values,0),this.rootEndPosition=new b().fromArray(r.values,r.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),yo&&console.log(this.rootPositionOffset);else if(r.name.endsWith(s)&&(this.rootStartQuaternion=new N().fromArray(r.values,0),this.rootEndQuaternion=new N().fromArray(r.values,r.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),yo)){const a=new at().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",a)}}}}class Gh extends ql{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&&ox(this._animator.gameObject,this,this.director.enabled&&this.director.weight>0)}createHooks(e,t){if(t.tracks?.length<=0){console.warn("No tracks in AnimationClip",t);return}let i=!1,n=!1;const s=t.tracks.find(r=>r.name.includes(".position")||r.name.includes(".quaternion"))?.name.split(".");if(s){const r=s[s.length-2],a=r+".position",l=r+".quaternion";for(const c of t.tracks)!i&&c.name.endsWith(a)?(i=!0,this.createPositionInterpolant(t,e,c)):!n&&c.name.endsWith(l)&&(n=!0,this.createRotationInterpolant(t,e,c))}if(!i||!n){const r=this.mixer?.getRoot(),a=t.tracks[0],l=a.name.lastIndexOf("."),c=a.name.substring(0,l),h=c.substring(c.lastIndexOf(".")+1),d=r.getObjectByName(h);if(d)if(i){if(!n){const p=t.tracks[0].name.substring(0,l)+".quaternion";yo&&console.warn("Create quaternion track",h,d);const m=new iP(p,[0,t.duration],[0,0,0,1,0,0,0,1]);t.tracks.push(m),this.createRotationInterpolant(t,e,m)}}else{const p=c+".position";yo&&console.warn("Create position track",h,d);const m=new tP(p,[0,t.duration],[0,0,0,0,0,0]);t.tracks.push(m),this.createPositionInterpolant(t,e,m)}}}bind(){if(!this._didBind){this._didBind=!0,yo&&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 KI(e);this._actionOffsets.push(t)}this.target&&(this._animator=S.getComponent(this.target,_t)??null,this._animator&&ox(this._animator.gameObject,this,!0));for(const e of this.models){const t=e.asset,i=t.position,n=t.rotation;i&&i.x!==void 0&&(i.isVector3||(t.position=new b(i.x,i.y,i.z)),n.isQuaternion||(t.rotation=new N(n.x,n.y,n.z,n.w)))}this.ensureTrackOffsets()}}ensureTrackOffsets(){if(this.trackOffset){const e=this.trackOffset.position;e&&(e.isVector3||(this.trackOffset.position=new b(e.x,e.y,e.z)));const t=this.trackOffset.rotation;t&&(t.isQuaternion||(this.trackOffset.rotation=new N(t.x,t.y,t.z,t.w)))}}_useclipOffsets=!0;_totalOffsetPosition=new b;_totalOffsetRotation=new N;_totalOffsetPosition2=new b;_totalOffsetRotation2=new N;_summedPos=new b;_tempPos=new b;_summedRot=new N;_tempRot=new N;_clipRotQuat=new N;evaluate(e){if(this.track.muted||!this.mixer)return;this.bind(),this._totalOffsetPosition.set(0,0,0),this._totalOffsetRotation.set(0,0,0,1),this._totalOffsetPosition2.set(0,0,0),this._totalOffsetRotation2.set(0,0,0,1);let t=0,i=0,n=!1,s=!1,r=0;for(let a=0;a<this.clips.length;a++){const l=this.models[a],c=this.actions[a],h=l.asset;c.weight=0;const d=e>=l.start&&e<=l.end,p=l.preExtrapolationMode,m=l.postExtrapolationMode,g=a<this.clips.length-1?this.models[a+1]:null;let f=d,y=!1;if(!f&&!n&&l.end<e&&m!==fo.None?(!g||g.start>e)&&(f=!0,n=!0):a==0&&!f&&!s&&l.start>e&&p!==fo.None&&(!g||g.start<e)&&(f=!0,y=!0,s=!0),f){let _=this.weight;_*=this.evaluateWeight(e,a,this.models,f),_*=this.director.weight;let v=d;if(y)switch(p){case fo.Hold:break;case fo.Loop:e+=l.start,v=!0;break;default:e+=l.start,v=!0;break}let P=this.getClipTime(e,l),k=0;const O=h.duration;if(y&&p===fo.Hold&&(P=0),v){if(h.loop)for(k+=Math.floor(P/(O+1e-6));P>O;)P-=O}else if(!d&&n)switch(m){case fo.Hold:P=this.getClipTime(l.end,l);break;case fo.Loop:P%=O;break;case fo.PingPong:const L=Math.floor(P/O)%2!==0;P%=O,L&&(P=O-P);break}l.reversed===!0?c.time=c.getClip().duration-P:c.time=P,c.timeScale=0;const j=Math.max(0,_);if(c.weight=j,r+=j,c.clampWhenFinished=!1,c.isRunning()||c.play(),this._useclipOffsets){const L=t==0?this._totalOffsetPosition:this._totalOffsetPosition2,V=t==0?this._totalOffsetRotation:this._totalOffsetRotation2;t<1&&(i=1-_),t+=1;const W=this._summedPos.set(0,0,0),G=this._tempPos.set(0,0,0),X=this._summedRot.identity(),R=this._tempRot.identity(),$=h.rotation;$&&(this._clipRotQuat.identity(),this._clipRotQuat.slerp($,_));const q=this._actionOffsets[a];if(q.hasOffsets)for(let he=0;he<k;he++)q.rootPositionOffset?G.copy(q.rootPositionOffset):G.set(0,0,0),G.applyQuaternion(X),this._clipRotQuat&&G.applyQuaternion(this._clipRotQuat),q.rootQuaternionOffset&&(R.copy(q.rootQuaternionOffset),X.multiply(R)),W.add(G);this._clipRotQuat&&V.multiply(this._clipRotQuat),V.multiply(X),h.position&&W.add(h.position),L.add(W)}}}if(this._useclipOffsets&&(this._totalOffsetPosition.lerp(this._totalOffsetPosition2,i),this._totalOffsetRotation.slerp(this._totalOffsetRotation2,i)),this.__mixerError===void 0&&(yo||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),s=new N;this.ensureTrackOffsets();const r=this.trackOffset?.rotation;i.createInterpolant=()=>{const a=n(),l=a.evaluate.bind(a);return a.evaluate=c=>{const h=l(c);if(s.set(h[0],h[1],h[2],h[3]),s.premultiply(this._totalOffsetRotation),r&&s.premultiply(r),this.director.animationCallbackReceivers)for(const d of this.director.animationCallbackReceivers)d?.onTimelineRotation?.call(d,this.director,this.target,c,s);return h[0]=s.x,h[1]=s.y,h[2]=s.z,h[3]=s.w,h},a}}createPositionInterpolant(e,t,i){const n=i.createInterpolant.bind(i),s=new b;this.ensureTrackOffsets();const r=this.trackOffset?.rotation,a=this.trackOffset?.position;let l;i.createInterpolant=()=>{const c=n(),h=c.evaluate.bind(c);return c.evaluate=d=>{const p=h(d);if(s.set(p[0],p[1],p[2]),t.removeStartOffset&&(l===void 0?(l=null,l=this._actionOffsets.find(m=>m.clip===e)?.rootStartPosition?.clone()):l?.isVector3&&s.sub(l)),s.applyQuaternion(this._totalOffsetRotation),s.add(this._totalOffsetPosition),r&&s.applyQuaternion(r),a&&(s.x-=a.x,s.y+=a.y,s.z+=a.z),this.director.animationCallbackReceivers)for(const m of this.director.animationCallbackReceivers)m?.onTimelinePosition?.call(m,this.director,this.target,d,s);return p[0]=s.x,p[1]=s.y,p[2]=s.z,p},c}}}const JI=w("mutetimeline");class ys extends ql{models=[];listener;audio=[];audioContextTimeOffset=[];lastTime=0;audioSource;_audioLoader=null;getAudioFilePath(e){const t=this.director.sourceId;return Ao(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 nP(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(JI||this.track.muted||this.director.speed<0)return;const t=this.director.context.application.muted,i=this._playableDirectorResumed;this._playableDirectorResumed=!1;const n=t?.1:0;for(let s=0;s<this.models.length;s++){const r=this.models[s],a=this.audio[s],l=r.asset;if((!a||!a.buffer)&&this.isInTimeRange(r,e-1,e+1)&&this.handleAudioLoading(r,a),ji.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,yo&&console.log("Timeline Audio ("+this.track.name+") play with offset "+a.offset+" - "+r.asset.clip),a.play(n),r._didTriggerPlay=!0);else{const h=r.clipIn+(e-r.start)*r.timeScale,d=a.context.currentTime-a._startedAt+a.offset;Math.abs(h-d)>.3&&(a.offset=h,a.stop(),a.play(n))}let c=l.volume;if(this.track.volume!==void 0&&(c*=this.track.volume),t&&(c=0),r.easeInDuration>0){const h=Math.min((e-r.start)/r.easeInDuration,1);c*=h}if(r.easeOutDuration>0){const h=Math.min((r.end-e)/r.easeOutDuration,1);c*=h}a.setVolume(c*this.director.weight)}else r._didTriggerPlay=!1,this.director.isPlaying&&a.isPlaying&&a.stop()}this.lastTime=e}loadAudio(e,t=0,i=0){let n=null;const s=e-i,r=e+t;for(const a of this.models)if(this.isInTimeRange(a,s,r)){const l=this.audio[this.models.indexOf(a)],c=this.handleAudioLoading(a,l);c!==null&&(n===null&&(n=[]),n.push(c))}return n!==null?Promise.all(n):null}isInTimeRange(e,t,i){return t<=e.start&&i>=e.end||t>=e.start&&t<=e.end||i>=e.start&&i<=e.end}static _audioBuffers=new Map;static dispose(){ys._audioBuffers.clear()}handleAudioLoading(e,t){this._audioLoader||(this._audioLoader=new Lm);const i=this.getAudioFilePath(e.asset.clip);if(ys._audioBuffers.get(i)){const s=ys._audioBuffers.get(i);return s.then(r=>{r&&t.setBuffer(r)}),s}yo&&console.warn("LOAD audio track",i,this.director.sourceId);const n=new Promise((s,r)=>{this._audioLoader.load(i,a=>{t.setBuffer(a),s(a)},void 0,a=>{console.error("Error loading audio",a),s(null)})});return ys._audioBuffers.set(i,n),n}}class om extends ql{models=[];needsSorting=!0;*foreachMarker(e=null){this.needsSorting&&this.sort();for(const t of this.models)t&&t.type===e&&(yield t)}onEnable(){this.needsSorting=!0}evaluate(e){this.needsSorting&&this.sort()}sort(){this.needsSorting=!1,this.models.sort((e,t)=>e.time-t.time)}}class qh extends ql{models=[];didTrigger=[];receivers=[];evaluate(e){if(this.track.muted)return;const t=this.director.context.time.deltaTime*1.5;for(let i=0;i<this.models.length;i++){const n=this.models[i],s=this.didTrigger[i],r=n.time-e;let a=!1;if(n.retroActive)a=r<=1e-6;else{const l=Math.abs(r);(l===0||l>=1e-5&&l<t)&&(a=!0)}if(a){if(!s)if(yo&&console.log("Trigger signal",e,n.time,n),this.didTrigger[i]=!0,this.receivers?.length<=0)Hh.invoke(n.asset);else for(const l of this.receivers)l&&l.invoke(n.asset)}else n.emitOnce||(this.didTrigger[i]=!1)}}}class sm extends ql{models=[];timelines=[];resolveSourceObjects(e){for(let t=this.models.length-1;t>=0;t--){const i=this.models[t].asset;if(!i.sourceObject||typeof i.sourceObject!="object"){console.log("no source object, removing model",t,i),this.models.splice(t,1);continue}else{const n=S.getComponent(i.sourceObject,ya);this.timelines.push(n),n&&i.updateDirector&&(n.playOnAwake=!1)}}}_previousActiveModel=null;evaluate(e){this._previousActiveModel=null;for(let t=0;t<this.models.length;t++){const i=this.models[t],n=i.asset;if(e>=i.start&&e<=i.end){this._previousActiveModel=i;const s=this.getClipTime(e,i);if(n.controlActivation){const r=n.sourceObject;r.visible=!0}if(n.updateDirector){const r=this.timelines[t];r&&(r.isPlaying&&r.pause(),r.time=s,r.evaluate())}}else{const s=this._previousActiveModel?.asset;if(n.controlActivation){const r=n.sourceObject;s?.sourceObject!==r&&(r.visible=!1)}}}}}var eL=Object.defineProperty,sS=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&eL(e,t,n),n};const Un=w("debugtimeline"),W0=class mb extends E{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:(Un||Mi())&&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(){Un&&console.log(`[Timeline] Awake '${this.name}'`,this),this.rebuildGraph(),!this.isValid()&&(Un||A())&&(Un?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(){Un&&console.log("[Timeline] OnEnable",this.name,this.playOnAwake);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(){Un&&console.log("[Timeline] OnDisable",this.name),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&&!ji.userInteractionRegistered&&this.waitForAudio;)await To(200)}this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine=this.startCoroutine(this.internalUpdate(),xe.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}get signalTracks(){return this._signalTracks}get markerTracks(){return this._markerTracks}*foreachMarker(e=null){for(const t of this._markerTracks)for(const i of t.foreachMarker(e))yield i}_guidsMap;resolveGuids(e){this._guidsMap=e}_isPlaying=!1;_internalUpdateRoutine;_isPaused=!1;_isStopping=!1;_time=0;_duration=0;_weight=1;_animationTracks=[];_audioTracks=[];_signalTracks=[];_markerTracks=[];_controlTracks=[];_customTracks=[];_tracksArray=[];get _allTracks(){return this._tracksArray.length=0,this._tracksArray.push(this._animationTracks),this._tracksArray.push(this._audioTracks),this._tracksArray.push(this._signalTracks),this._tracksArray.push(this._markerTracks),this._tracksArray.push(this._controlTracks),this._tracksArray.push(this._customTracks),this._tracksArray}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 Vi.Activation:if(!e&&!this._isPlaying)continue;for(let s=0;s<n.outputs.length;s++){const r=n.outputs[s];if(typeof r=="object"){let a=!1;if(n.clips)for(const c of n.clips)c.start<=i&&i<=c.end&&(a=!0);const l=r;l.visible!==void 0&&l.visible!==a&&(l.visible=a,Un&&console.warn(this.name,"set ActivationTrack-"+s,l.name,a,i))}}break}for(const n of this._allTracks)for(const s of n)this._isStopping&&s instanceof Gh||s.evaluate(i)}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=pc(this.playableAsset)),!this.playableAsset||!this.playableAsset.tracks)return;const e=this.findRoot(this.gameObject);for(const t of this.playableAsset.tracks){for(let i=t.outputs.length-1;i>=0;i--){let n=t.outputs[i];if(typeof n=="string"){this._guidsMap&&this._guidsMap[n]&&(n=this._guidsMap[n]);const s=S.findByGuid(n,e);s===null||typeof s!="object"?(t.outputs.splice(i,1),console.warn("Failed to resolve binding",n,t.name,t.type)):(Un&&console.log("Resolved binding",n,"to",s),t.outputs[i]=s)}else if(n===null){if(t.outputs.splice(i,1),mb.createTrackFunctions[t.type])continue;t.type!==Vi.Audio&&t.type!==Vi.Control&&t.type!==Vi.Marker&&t.type!==Vi.Signal&&console.warn("Missing binding",n,t.name,t.type,this.name,this.playableAsset.name)}}if(t.type===Vi.Control&&t.clips)for(let i=0;i<t.clips.length;i++){const n=t.clips[i];let s=n.asset.sourceObject;if(typeof s=="string"){this._guidsMap&&this._guidsMap[s]&&(s=this._guidsMap[s]);const r=S.findByGuid(s,e);r===null||typeof r!="object"?console.warn("Failed to resolve sourceObject binding",s,t.name,n):(Un&&console.log("Resolved binding",s,"to",r),n.asset.sourceObject=r)}}}}findRoot(e){return e.parent?this.findRoot(e.parent):e}updateTimelineDuration(){if(this._duration=0,!(!this.playableAsset||!this.playableAsset.tracks)){for(const e of this.playableAsset.tracks)if(e.muted!==!0){if(e.clips)for(const t of e.clips)t.end>this._duration&&(this._duration=t.end);if(e.markers)for(const t of e.markers)t.time>this._duration&&(this._duration=t.time+.001)}}}setupAndCreateTrackHandlers(){if(this._animationTracks.length=0,this._audioTracks.length=0,this._signalTracks.length=0,!this.playableAsset)return;let e=S.findObjectOfType(Wo,this.context);for(const t of this.playableAsset.tracks){const i=t.type,n=mb.createTrackFunctions[i];if(n!=null){const s=n(this,t);if(typeof s.evaluate=="function"){s.director=this,s.track=t,this._customTracks.push(s);continue}}if(t.type===Vi.Animation){if(!t.clips||t.clips.length<=0){Un&&console.warn("Animation track has no clips",t);continue}for(let s=t.outputs.length-1;s>=0;s--){let r=t.outputs[s];if(r instanceof M){const l=S.getOrAddComponent(r,_t);l&&(r=l)}const a=r?.gameObject?.animations;if(a){const l=new Gh;l.trackOffset=t.trackOffset,l.director=this,l.track=t;for(let c=0;c<t.clips.length;c++){const h=t.clips[c],d=h.asset;if(!d){console.error(`Timeline ${this.name}: clip #${c} on track "${t.name}" has no animation data`);continue}const p=d.clip;let m=p;if((typeof m=="string"||typeof m=="number")&&(m=a.find(f=>f.name===p)),Un&&console.log(d,p,"\u2192",m),!m){console.warn("Could not find animationClip for model",h,t.name,this.name,this.playableAsset?.name,a,r);continue}r instanceof _t&&r.runtimeAnimatorController&&(r.__internalDidAwakeAndStart||r.initializeRuntimeAnimatorController(),r.runtimeAnimatorController.mixer||r.runtimeAnimatorController.bind(r),l.mixer=r.runtimeAnimatorController.mixer),l.mixer||(l.mixer=new Im(r.gameObject),this.context.animations.registerAnimationMixer(l.mixer)),l.clips.push(m),l.mixer.uncacheAction(m),l.createHooks(h.asset,m);const g=l.mixer.clipAction(m);l.actions.push(g),l.models.push(h)}this._animationTracks.push(l)}}}else if(t.type===Vi.Audio){if(!t.clips||t.clips.length<=0)continue;const s=new ys;s.director=this,s.track=t,s.audioSource=t.outputs.find(r=>r instanceof ji),this._audioTracks.push(s),e||(e=this.context.mainCameraComponent?.gameObject.addComponent(Wo)),s.listener=e.listener;for(let r=0;r<t.clips.length;r++){const a=t.clips[r];s.addModel(a)}}else if(t.type===Vi.Marker){if(t.markers){const s=new qh;s.director=this,s.track=t;const r=new om;r.director=this,r.track=t;for(const a of t.markers)a.type===N0.Signal?(s.models.push(a),s.didTrigger.push(!1)):r.models.push(a);if(s!==null&&s.models.length>0){const a=S.getComponent(this.gameObject,Hh);a&&(s.receivers.push(a),this._signalTracks.push(s))}r!==null&&r.models.length>0&&this._markerTracks.push(r)}}else if(t.type===Vi.Signal){const s=new qh;if(s.director=this,s.track=t,t.markers)for(const r of t.markers)s.models.push(r),s.didTrigger.push(!1);for(const r of t.outputs)s.receivers.push(r);this._signalTracks.push(s)}else if(t.type===Vi.Control){const s=new sm;if(s.director=this,s.track=t,t.clips)for(const r of t.clips)s.models.push(r);s.resolveSourceObjects(this.context),this._controlTracks.push(s)}}}setAudioTracksAllowPlaying(e){for(const t of this._audioTracks)t.onAllowAudioChanged(e)}animationCallbackReceivers=[];registerAnimationCallback(e){this.animationCallbackReceivers.push(e)}unregisterAnimationCallback(e){const t=this.animationCallbackReceivers.indexOf(e);t!==-1&&this.animationCallbackReceivers.splice(t,1)}};sS([u()],W0.prototype,"playOnAwake"),sS([u()],W0.prototype,"extrapolationMode");let ya=W0;var tL=Object.defineProperty,rm=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&tL(e,t,n),n};class ba extends E{isGizmo=!1;translationSnap=1;rotationSnapAngle=15;scaleSnap=.25;get control(){return this._control}_control;orbit;onEnable(){if(!(this.isGizmo&&!jc)&&this.context.mainCamera&&(this._control||(this._control=new PP(this.context.mainCamera,this.context.renderer.domElement),this._control.enabled=!0,this._control.getRaycaster().layers.set(2),this._control.size=1,("_root"in this._control?this._control._root:this._control).traverse(e=>{const t=e;if(t.layers.set(2),t){const i=t.material;i&&(i.opacity=.3)}}),this.orbit=S.getComponentInParent(this.context.mainCamera,ge)??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(Co.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(Tn);i&&(i.fastMode=!0,i.requestOwnership())}else{const i=this.gameObject.getComponentInParent(Tn);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=>{this.enabled&&e.keyCode===16&&this.disableSnapping()}}rm([u()],ba.prototype,"isGizmo"),rm([u()],ba.prototype,"translationSnap"),rm([u()],ba.prototype,"rotationSnapAngle"),rm([u()],ba.prototype,"scaleSnap");var iL=Object.defineProperty,nL=Object.getOwnPropertyDescriptor,am=(o,e,t,i)=>{for(var n=i>1?void 0:i?nL(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&iL(e,t,n),n};class V0{texture=null;rect}am([u(Se)],V0.prototype,"texture",2);let Xl=class extends wh{set image(o){this.sprite||(this.sprite=new V0),this.sprite.texture=o,this.onAfterCreated()}get image(){return this.sprite?this.sprite.texture:null}get sprite(){return this._sprite}set sprite(o){this._sprite!==o&&(this._sprite=o,this.onAfterCreated())}_sprite;pixelsPerUnitMultiplier=1;isBuiltinSprite(){const o=this.sprite;switch(o?.texture?.name){case"InputFieldBackground":case"UISprite":case"Background":case"Knob":return!0}return!o?.texture?.name?.length&&o?.texture?.image?.width===32&&o?.texture?.image?.height===32}onBeforeCreate(o){super.onBeforeCreate(o),this.isBuiltinSprite()&&(o.borderRadius=5/this.pixelsPerUnitMultiplier,this.sprite?.texture?.name==="Knob"&&(o.borderRadius=999))}onAfterCreated(){this.__didAwake&&(super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture(this.sprite?.texture))}};am([u(V0)],Xl.prototype,"sprite",1),am([u()],Xl.prototype,"pixelsPerUnitMultiplier",2);class lm extends wh{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))}}am([u(Se)],lm.prototype,"mainTexture",1);var oL=Object.defineProperty,sL=Object.getOwnPropertyDescriptor,$i=(o,e,t,i)=>{for(var n=i>1?void 0:i?sL(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&oL(e,t,n),n};const _a=w("debugbutton");class rr{colorMultiplier;disabledColor;fadeDuration;highlightedColor;normalColor;pressedColor;selectedColor}$i([u()],rr.prototype,"colorMultiplier",2),$i([u(se)],rr.prototype,"disabledColor",2),$i([u()],rr.prototype,"fadeDuration",2),$i([u(se)],rr.prototype,"highlightedColor",2),$i([u(se)],rr.prototype,"normalColor",2),$i([u(se)],rr.prototype,"pressedColor",2),$i([u(se)],rr.prototype,"selectedColor",2);class rL{disabledTrigger;highlightedTrigger;normalTrigger;pressedTrigger;selectedTrigger}class rs extends E{click(){this.onClick?.invoke()}onClick=new ae;_isHovered=0;onPointerEnter(e){const t=e.event.pointerType==="mouse"&&e.button===0;t&&(this._isHovered+=1),_a&&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),_a&&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){_a&&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){_a&&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===Yd.Mouse)&&(_a&&(console.warn("Button Click",this.onClick),Oe("CLICKED button "+this.name+" at "+this.context.time.frameCount)),this.onClick&&this.onClick.listenerCount>0&&(this.onClick.invoke(),e.use(),this.context.accessibility.focus(this),_a))){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(),_a&&console.log(this),this._isInit=!1,this.init()}start(){this._image?.setInteractable(this.interactable),this.gameObject.getComponentInParent(Zc)||this.gameObject.addComponent(Wu)}onEnable(){super.onEnable(),this.context.accessibility.updateElement(this,{role:"button",label:this.gameObject.name+" button",hidden:!1})}onDisable(){super.onDisable(),this.context.accessibility.updateElement(this,{hidden:!0})}onDestroy(){this.context.accessibility.removeElement(this),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,Xl),this._image&&(this.stateSetup(this._image),this.interactable?this._image.setState("normal"):this._image.setState("disabled")))}stateSetup(e){e.setInteractable(this.interactable);const t=this.getFinalColor(e.color,this.colors?.normalColor),i={state:"normal",attributes:{backgroundColor:t,backgroundOpacity:t.alpha}};e.setupState(i);const n=this.getFinalColor(e.color,this.colors?.highlightedColor),s={state:"hovered",attributes:{backgroundColor:n,backgroundOpacity:n.alpha}};e.setupState(s);const r=this.getFinalColor(e.color,this.colors?.pressedColor),a={state:"pressed",attributes:{backgroundColor:r,backgroundOpacity:r.alpha}};e.setupState(a);const l=this.getFinalColor(e.color,this.colors?.selectedColor),c={state:"selected",attributes:{backgroundColor:l,backgroundOpacity:l.alpha}};e.setupState(c);const h=this.getFinalColor(e.color,this.colors?.disabledColor),d={state:"disabled",attributes:{backgroundColor:h,backgroundOpacity:h.alpha}};e.setupState(d)}getFinalColor(e,t){return t?e.clone().multiply(t).convertLinearToSRGB():e.clone().convertLinearToSRGB()}}$i([u(ae)],rs.prototype,"onClick",2),$i([u(rr)],rs.prototype,"colors",2),$i([u()],rs.prototype,"transition",2),$i([u(rL)],rs.prototype,"animationTriggers",2),$i([u(_t)],rs.prototype,"animator",2),$i([u()],rs.prototype,"interactable",1);var aL=Object.defineProperty,cm=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&aL(e,t,n),n};const ar=w("debuginputfield"),Xh=class Q extends E{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 Q.active===this}textComponent;placeholder;onValueChanged;onEndEdit;static active=null;static activeTime=-1;static htmlField=null;static htmlFieldFocused=!1;inputEventFn;_iosEventFn;start(){ar&&console.log(this.name,this)}onEnable(){Q.htmlField||(Q.htmlField=document.createElement("input"),Q.htmlField.style.width="0px",Q.htmlField.style.height="0px",Q.htmlField.style.padding="0px",Q.htmlField.style.border="none",Q.htmlField.style.overflow="hidden",Q.htmlField.style.caretColor="transparent",Q.htmlField.style.outline="none",Q.htmlField.classList.add("ar"),Q.htmlField.onfocus=()=>Q.htmlFieldFocused=!0,Q.htmlField.onblur=()=>Q.htmlFieldFocused=!1,document.body.append(Q.htmlField)),this.inputEventFn||(this.inputEventFn=this.onInput.bind(this)),Q.htmlField.addEventListener("keyup",this.inputEventFn),this.placeholder&&this.textComponent?.text.length&&S.setActive(this.placeholder.gameObject,!1),I.isiOS()&&(this._iosEventFn=this.processInputOniOS.bind(this),window.addEventListener("click",this._iosEventFn))}onDisable(){Q.htmlField?.removeEventListener("keyup",this.inputEventFn),this.onDeselected(),this._iosEventFn&&window.removeEventListener("click",this._iosEventFn)}clear(){Q.active===this&&Q.htmlField?(Q.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){ar&&console.log("CLICK",e,Q.active),Q.activeTime=this.context.time.time,Q.active!==this&&this.startCoroutine(this.activeLoop(),xe.LateUpdate),this.selectInputField()}*activeLoop(){for(this.onSelected();Q.active===this&&!(this.context.input.getPointerClicked(0)&&this.context.time.time-Q.activeTime>.2);)this.setTextFromInputField(),yield;this.onDeselected()}onSelected(){if(Q.active!==this&&(ar&&console.log("Select",this.name,this,Q.htmlField,this.context.isInXR,this.context.arOverlayElement,this.textComponent?.text,Q.htmlField?.value),Q.active?.onDeselected(),Q.active=this,this.placeholder&&S.setActive(this.placeholder.gameObject,!1),Q.htmlField)){if(Q.htmlField.value=this.textComponent?.text||"",ar&&console.log("set input field value",Q.htmlField.value),this.context.isInXR){const e=this.context.arOverlayElement;e&&e.append(Q.htmlField)}this.selectInputField()}}onDeselected(){Q.active===this&&(Q.active=null,ar&&console.log("Deselect",this.name,this),Q.htmlField&&(Q.htmlField.blur(),document.body.append(Q.htmlField)),this.placeholder&&(!this.textComponent||this.textComponent.text.length<=0)&&S.setActive(this.placeholder.gameObject,!0),Q.htmlField&&this.onEndEdit?.invoke(Q.htmlField.value))}update(){Q.active===this&&this.textComponent?.markDirty()}onInput(e){if(Q.active===this){if(ar&&console.log(e.code,e,Q.htmlField?.value,this.textComponent?.text),e.code==="Escape"||e.code==="Enter"){this.onDeselected();return}Q.htmlField&&(this.textComponent&&(this.setTextFromInputField(),this.placeholder&&S.setActive(this.placeholder.gameObject,this.textComponent.text.length<=0)),this.selectInputField())}}setTextFromInputField(){if(this.textComponent&&Q.htmlField){const e=this.textComponent.text,t=Q.htmlField.value,i=this.textComponent.text!==Q.htmlField.value;this.textComponent.text=Q.htmlField.value,i&&(ar&&console.log("[InputField] value changed:",t,e),this.onValueChanged?.invoke(t,e))}}selectInputField(){Q.htmlField&&(ar&&console.log("Focus Inputfield",Q.htmlFieldFocused,Q.htmlField),Q.htmlField.setSelectionRange(Q.htmlField.value.length,Q.htmlField.value.length),I.isiOS()?(Q.htmlField.style.display="block",Q.htmlField.focus({preventScroll:!0})):setTimeout(()=>Q.htmlField?.focus(),1))}processInputOniOS(){const e=this.context.physics.raycast();if(!e.length)return;const t=e[0].object,i=Ff(t);(i?.gameObject===this.gameObject||i?.gameObject.parent===this.gameObject)&&this.selectInputField()}};cm([u(Ht)],Xh.prototype,"textComponent"),cm([u(Ht)],Xh.prototype,"placeholder"),cm([u(ae)],Xh.prototype,"onValueChanged"),cm([u(ae)],Xh.prototype,"onEndEdit");let $0=Xh;var lL=Object.defineProperty,rS=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&lL(e,t,n),n};class Qh extends E{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 OP;t.listenToPointerEvents(this.context.renderer,this.context.mainCamera),this.gameObject.add(t);const i=new kP(e);t.add(i),i.visible=!1;const n=i.material;n.transparent=!0,setTimeout(()=>{i.visible=!0;const s=Vd(this.gameObject).clone();fc(this.gameObject,0,0,0),this.gameObject.updateMatrixWorld();const r=new Yt;r.setFromObject(t),this.setWorldRotation(s.x,s.y,s.z);const a=r.max.x-r.min.x,l=r.max.y-r.min.y;if(this.keepAspect){const h=a/l;a>l?i.scale.set(1/a,1/l/h,1):i.scale.set(1/a*h,1/l,1)}else i.scale.set(1/a,1/l,1);const c=this.gameObject.scale;i.scale.multiply(c)},1)}onDisable(){this._object?.removeFromParent()}}rS([u()],Qh.prototype,"id"),rS([u()],Qh.prototype,"keepAspect");const cL={topLight:{intensity:500,position:[.418,16.199,.3]},room:{position:[-.757,13.219,.717],scale:[31.713,28.305,28.591]},boxes:[{position:[-10.906,2.009,1.846],rotation:-.195,scale:[2.328,7.905,4.651]},{position:[-5.607,-.754,-.758],rotation:.994,scale:[1.97,1.534,3.955]},{position:[6.167,.857,7.803],rotation:.561,scale:[3.927,6.285,3.687]},{position:[-2.017,.018,6.124],rotation:.333,scale:[2.002,4.566,2.064]},{position:[2.291,-.756,-2.621],rotation:-.286,scale:[1.546,1.552,1.496]},{position:[-2.193,-.369,-5.547],rotation:.516,scale:[3.875,3.487,2.986]}],lights:[{intensity:50,position:[-16.116,14.37,8.208],scale:[.1,2.428,2.739]},{intensity:50,position:[-16.109,18.021,-8.207],scale:[.1,2.425,2.751]},{intensity:17,position:[14.904,12.198,-1.832],scale:[.15,4.265,6.331]},{intensity:43,position:[-.462,8.89,14.52],scale:[4.38,5.441,.088]},{intensity:20,position:[3.235,11.486,-12.541],scale:[2.5,2,.1]},{intensity:100,position:[0,20,0],scale:[1,.1,1]}]},hL={topLight:{intensity:400,position:[.5,14,.5]},room:{position:[0,13.2,0],scale:[31.5,28.5,31.5]},boxes:[{position:[-10.906,-1,1.846],rotation:-.195,scale:[2.328,7.905,4.651]},{position:[-5.607,-.754,-.758],rotation:.994,scale:[1.97,1.534,3.955]},{position:[6.167,-.16,7.803],rotation:.561,scale:[3.927,6.285,3.687]},{position:[-2.017,.018,6.124],rotation:.333,scale:[2.002,4.566,2.064]},{position:[2.291,-.756,-2.621],rotation:-.286,scale:[1.546,1.552,1.496]},{position:[-2.193,-.369,-5.547],rotation:.516,scale:[3.875,3.487,2.986]}],lights:[{intensity:80,position:[-14,10,8],scale:[.1,2.5,2.5]},{intensity:80,position:[-14,14,-4],scale:[.1,2.5,2.5]},{intensity:23,position:[14,12,0],scale:[.1,5,5]},{intensity:16,position:[0,9,14],scale:[5,5,.1]},{intensity:80,position:[7,8,-14],scale:[2.5,2.5,.1]},{intensity:80,position:[-7,16,-14],scale:[2.5,2.5,.1]},{intensity:1,position:[0,20,0],scale:[.1,.1,.1]}]};class hm extends Hi{constructor(e){super(),this.position.y=-3.5;const t=new Aa;t.deleteAttribute("uv");const i=new gt({metalness:0,side:Id}),n=new gt({metalness:0}),s=e=="legacy"?cL:hL,r=new Mm(16777215,s.topLight.intensity,28,2);r.position.set(...s.topLight.position),this.add(r);const a=new H(t,i);a.position.set(...s.room.position),a.scale.set(...s.room.scale),this.add(a);for(const l of s.boxes){const c=new H(t,n);c.position.set(...l.position),c.rotation.set(0,l.rotation,0),c.scale.set(...l.scale),this.add(c)}for(const l of s.lights){const c=new H(t,this.createAreaLightMaterial(l.intensity));c.position.set(...l.position),c.scale.set(...l.scale),this.add(c)}}createAreaLightMaterial(e){const t=new Ce;return t.color.setScalar(e),t}}var dL=Object.defineProperty,dm=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&dL(e,t,n),n};const Yh=class HS extends E{target;invertForward=!1;keepUpDirection=!0;copyTargetRotation=!1;static flipYQuat=new N().setFromAxisAngle(new b(0,1,0),Math.PI);onBeforeRender(){let e=this.target;if(e||(e=this.context.mainCamera,A()&&!this.__did_warn&&(this.__did_warn=!0,console.debug(`[LookAt] No target set on ${this.name}, using main camera as target.`))),!e)return;let t=this.copyTargetRotation;(this.context.isInVR||this.context.isInPassThrough)&&(t=!1),gc(this.gameObject,e,this.keepUpDirection,t),this.invertForward&&this.gameObject.quaternion.multiply(HS.flipYQuat)}createBehaviours(e,t,i){if(t.uuid===this.gameObject.uuid){let n=t;if(this.keepUpDirection){const r=rt.createEmptyParent(t);n=r;const a=this.invertForward?-1:1;r.setMatrix(r.getMatrix().multiply(new J().makeRotationZ(Math.PI/2*a))),t.setMatrix(t.getMatrix().multiply(new J().makeRotationZ(-Math.PI/2*a)))}const s=new jt("lookat "+this.name,$t.sceneStartTrigger(),fe.lookAtCameraAction(n,void 0,this.invertForward?bn.back:bn.forward,this.keepUpDirection?bn.up:bn.zero));e.addBehavior(s)}}};dm([u(M)],Yh.prototype,"target"),dm([u()],Yh.prototype,"invertForward"),dm([u()],Yh.prototype,"keepUpDirection"),dm([u()],Yh.prototype,"copyTargetRotation");let H0=Yh;var uL=Object.defineProperty,G0=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&uL(e,t,n),n};class Ql extends E{url;mode=0;clickable=!0;async open(){if(!this.url){console.warn("OpenURL: URL is not set, can't open.",this);return}this._validateUrl();let e=this.url;switch(!e.startsWith("mailto:")&&e.includes("@")&&(e="mailto:"+e),this.mode){case 0:I.isSafari(),globalThis.open(e,"_blank");break;case 1:I.isSafari()&&I.isiOS()?globalThis.open(e,"_top"):globalThis.open(e,"_self");break;case 2:I.isSafari()?globalThis.open(e,"_top"):globalThis.open(e,"_new");break}}start(){this.gameObject.getComponentInParent(Ji)||this.gameObject.addComponent(Ji)}onPointerEnter(e){!e.used&&this.clickable&&this.context.input.setCursor("pointer")}onPointerExit(){this.clickable&&this.context.input.unsetCursor("pointer")}onPointerClick(e){this.clickable&&!e.used&&this.url?.length&&this.open()}_validateUrl(){this.url&&this.url.startsWith("www.")&&(A()&&console.warn("URL is not valid, adding https:// to the start of the URL",this.url),this.url="https://"+this.url)}}G0([u()],Ql.prototype,"url"),G0([u()],Ql.prototype,"mode"),G0([u()],Ql.prototype,"clickable"),Ru(o=>{const e=o.domElement.getAttribute("clickthrough");if(t(e)){const i=o.scene.addComponent(um);Ym(o.domElement,"clickthrough",()=>{const n=o.domElement.getAttribute("clickthrough");i.enabled=t(n)})}function t(i){return i!==null&&i!=="0"&&i!=="false"}});class um extends E{_previousPointerEvents="all";onEnable(){this.context.input.addEventListener("pointerdown",this.onPointerEvent),this.context.input.addEventListener("pointermove",this.onPointerEvent,{queue:100}),window.addEventListener("touchstart",this.onTouchStart,{passive:!0}),window.addEventListener("touchend",this.onTouchEnd,{passive:!0}),this._previousPointerEvents=this.context.domElement.style.pointerEvents}onDisable(){this.context.input.removeEventListener("pointerdown",this.onPointerEvent),this.context.input.removeEventListener("pointermove",this.onPointerEvent),window.removeEventListener("touchstart",this.onTouchStart),window.removeEventListener("touchend",this.onTouchEnd),this.context.domElement.style.pointerEvents=this._previousPointerEvents}onPointerEnter(){}onPointerEvent=e=>{e.pointerId>0||(e.intersections?.length<=0?this.context.domElement.style.pointerEvents="none":this.context.domElement.style.pointerEvents="all")};_touchDidHitAnything=!1;onTouchStart=e=>{const t=e.touches[0];if(!t)return;const i=t.clientX/window.innerWidth*2-1,n=-(t.clientY/window.innerHeight)*2+1;this.context.physics.raycast({screenPoint:new K(i,n)}).length>0&&(this._touchDidHitAnything=!0)};onTouchEnd=e=>{const t=this._touchDidHitAnything;this._touchDidHitAnything=!1,setTimeout(()=>{t&&(this.context.domElement.style.pointerEvents="all")},100)}}var pL=Object.defineProperty,pm=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&pL(e,t,n),n};const mL=w("debugcursor");class va extends E{static NAME="CursorFollow";damping=0;useFullPage=!0;keepDistance=!0;snapToSurface=!1;_distance=-1;updateDistance(e=!1){!e&&this.keepDistance&&this._distance!==-1||(this._distance=this.gameObject.worldPosition.distanceTo(this.context.mainCamera.worldPosition))}awake(){this._distance=-1}onEnable(){this._distance=-1,window.addEventListener("pointermove",this._onPointerMove)}onDisable(){window.removeEventListener("pointermove",this._onPointerMove)}_ndc_x=0;_ndc_y=0;_onPointerMove=e=>{if(!this.useFullPage)return;const t=e.clientX,i=e.clientY,n=this.context.domX,s=this.context.domY,r=this.context.domWidth,a=this.context.domHeight;this._ndc_x=(t-n)/r*2-1,this._ndc_y=-(i-s)/a*2+1};lateUpdate(){this.updateDistance();const e=this.useFullPage?this._ndc_x:this.context.input.mousePositionRC.x,t=this.useFullPage?this._ndc_y:this.context.input.mousePositionRC.y,i=this.context.mainCamera,n=i.worldPosition,s=F(e,t,1).unproject(i);s.sub(n).normalize();const r=F(s).multiplyScalar(this._distance).add(n);let a=r;if(this.damping>0){const l=this.gameObject.worldPosition;l.lerp(r,this.context.time.deltaTime/this.damping),this.gameObject.worldPosition=l,a=l}else this.gameObject.worldPosition=r;if(this.snapToSurface){q0.origin=a,q0.direction=s.multiplyScalar(-1);const l=this.context.physics.raycastFromRay(q0);if(l?.length){const c=l[0];this.damping>0?this.gameObject.worldPosition=a.lerp(c.point,this.context.time.deltaTime/this.damping):this.gameObject.worldPosition=c.point,mL&&B.DrawLine(c.point,c.normal.add(c.point),65280)}}}}pm([u()],va.prototype,"damping"),pm([u()],va.prototype,"useFullPage"),pm([u()],va.prototype,"keepDistance"),pm([u()],va.prototype,"snapToSurface");const q0=new So;var gL=Object.defineProperty,fL=Object.getOwnPropertyDescriptor,Yl=(o,e,t,i)=>{for(var n=i>1?void 0:i?fL(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&gL(e,t,n),n};let bo=class extends E{type="linear";duration=.1;scaleFactor=1.1;hovered=null;idle=null;animation=null;start(){this.idle||(this.idle=Qn.emptyClip()),(!this.hovered||!(this.hovered instanceof ki))&&(this.hovered=Qn.createScaleClip({type:"linear",duration:this.duration||.1,scale:this.gameObject.scale,scaleFactor:this.scaleFactor||1.1})),this.animation??=this.gameObject.addComponent(Ut),this.animation.playAutomatically=!1,this.playIdle()}onEnable(){this.animation&&(this.animation.enabled=!0),this.playIdle()}onDisable(){this.animation&&(this.animation.enabled=!1),this.playIdle()}onPointerEnter(){this.playHover()}onPointerExit(){this.playIdle()}playIdle(){this.idle&&this.animation?.play(this.idle,{exclusive:!0,fadeDuration:.1,loop:!0})}playHover(){this.hovered&&this.animation?.play(this.hovered,{exclusive:!0,fadeDuration:.1,loop:!1,clampWhenFinished:!0})}};Yl([u()],bo.prototype,"type",2),Yl([u()],bo.prototype,"duration",2),Yl([u()],bo.prototype,"scaleFactor",2),Yl([u(ki)],bo.prototype,"hovered",2),Yl([u(ki)],bo.prototype,"idle",2),bo=Yl([ef],bo);var yL=Object.defineProperty,Zl=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&yL(e,t,n),n};const Zh=w("debugscroll");class as extends E{target=null;damping=0;invert=!1;htmlSelector=null;mode="window";changed=new ae;get currentValue(){return this._current_value}_current_value=0;_target_value=0;_appliedValue=-1;_needsUpdate=!1;_firstUpdate=!1;awake(){this._firstUpdate=!0}onEnable(){window.addEventListener("wheel",this.updateCurrentScrollValue,{passive:!0}),this._appliedValue=-1,this._needsUpdate=!0}onDisable(){window.removeEventListener("wheel",this.updateCurrentScrollValue)}lateUpdate(){if(this.updateCurrentScrollValue(),this._target_value>=0&&(this.damping>0&&!this._firstUpdate?(this._current_value=D.lerp(this._current_value,this._target_value,this.context.time.deltaTime/this.damping),Math.abs(this._current_value-this._target_value)<.001&&(this._current_value=this._target_value)):this._current_value=this._target_value),this._needsUpdate||this._current_value!==this._appliedValue){this._appliedValue=this._current_value,this._needsUpdate=!1;let e=!1;if(this.changed.listenerCount>0){const t={type:"change",value:this._current_value,component:this,preventDefault:()=>{t.defaultPrevented=!0},defaultPrevented:!1};this.changed.invoke(t),e=t.defaultPrevented}if(!e){const t=this.invert?1-this._current_value:this._current_value;Array.isArray(this.target)?this.target.forEach(i=>i&&this.applyScroll(i,t)):this.target&&this.applyScroll(this.target,t),Zh&&this.context.time.frame%30===0&&console.debug(`[ScrollFollow] ${this._current_value.toFixed(5)} \u2014 ${(this._target_value*100).toFixed(0)}%, targets [${Array.isArray(this.target)?this.target.length:1}]`)}this._firstUpdate=!1}}_lastSelectorValue=null;_lastSelectorElement=null;updateCurrentScrollValue=()=>{switch(this.mode){case"window":if(this.htmlSelector?.length){if(this.htmlSelector!==this._lastSelectorValue&&(this._lastSelectorElement=document.querySelector(this.htmlSelector),this._lastSelectorValue=this.htmlSelector),this._lastSelectorElement){const e=this._lastSelectorElement.getBoundingClientRect();this._target_value=-e.top/(e.height-window.innerHeight);break}}else if(!(window.document.body.scrollHeight<=window.innerHeight)){const e=window.document.body.scrollHeight-window.innerHeight;this._target_value=window.scrollY/(e||1)}break}(isNaN(this._target_value)||!isFinite(this._target_value))&&(this._target_value=-1)};applyScroll(e,t){if(e)if(e instanceof ya)this.handleTimelineTarget(e,t),e.isPlaying&&e.pause(),e.evaluate();else if(e instanceof _t)e.setFloat("scroll",t);else if(e instanceof Ut)e.time=t*e.duration;else if(e instanceof ji){if(!e.duration)return;e.time=t*e.duration}else if(e instanceof hn)e.position01=t;else if(e instanceof Tt)e.intensity=t;else if(e instanceof M){const i=e;i["needle:scrollbounds"]===void 0&&(i["needle:scrollbounds"]=di(e)||null);const n=i["needle:scrollbounds"];n&&(e.position.y=-n.min.y-t*(n.max.y-n.min.y))}else"scroll"in e&&(typeof e.scroll=="number"?e.scroll=t:typeof e.scroll=="function"&&e.scroll(t))}handleTimelineTarget(e,t){const i=e.duration;let n=aS.get(e);if(!n){n=[],aS.set(e,n);let l=0;for(const c of e.foreachMarker("ScrollMarker")){const h=l++;if(c.element===void 0||c.needsUpdate===!0||c.element&&!c.element?.parentNode){c.needsUpdate=!1;try{if(c.element=lS(h),Zh&&console.debug(`ScrollMarker #${h} (${c.time.toFixed(2)}) found`,c.element),!c.element){(Zh||A())&&console.warn(`No HTML element found for ScrollMarker: ${c.name} (index ${h})`);continue}}catch(d){c.element=null,console.error("ScrollMarker selector is not valid: "+c.name+`
|
|
1432
|
-
`,d)}}c.element&&n.push(c)}n.length<=0&&document.querySelectorAll("[data-timeline-marker]").forEach(c=>{const h=c.getAttribute("data-timeline-marker"),d=parseFloat(h||"NaN");isNaN(d)?(A()||Zh)&&console.warn('[ScrollFollow] data-timeline-marker attribute is not a valid number. Supported are numbers only (e.g. <div data-timeline-marker="0.5">)'):n.push({time:d,element:c})});for(const c of n)c.element&&(c.timeline=new ViewTimeline({subject:c.element,axis:"block"}))}_o.length=0;let s=0;const r=1/60;let a=0;for(let l=0;l<n.length;l++){const c=n[l];if(!c.element)continue;const h=n[l+1],d=h?h.time-r:i;a+=1;const p=c.timeline;if(p){const m=bL(p),g=1-Math.abs(m-.5)*2,f=`marker${l}`;if(m>0&&m<=1){const y=c.time+(d-c.time)*m;_o.push({name:f,time:y,weight:g}),s+=g}else l===0&&m<=0?(_o.push({name:f,time:0,weight:1}),s+=1):l===n.length-1&&m>=1&&(_o.push({name:f,time:i,weight:1}),s+=1)}}if(_o.length<=0&&a<=0)e.time=t*i;else if(_o.length>0){let l=_o[0].time;if(_o.length>1)for(const c of _o){const h=c.weight/Math.max(1e-5,s),d=Math.abs(c.time-l);l+=d*h}this.damping<=0||this._firstUpdate?e.time=l:e.time=
|
|
1431
|
+
C) Set "joinRandomRoom" to true`),!1):(F0&&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(B0,this.context.connection.currentRoomViewId),window.location.origin+window.location.pathname+"?"+t.toString()}return null}setRandomRoomUrlParameter(){const e=dc(),t=this.generateRoomName();w(this.urlParameterName)?e.set(this.urlParameterName,t):e.append(this.urlParameterName,t),Xm(t,e)}generateRoomName(){let e="";for(let t=0;t<6;t++)e+=Math.floor(Math.random()*10).toFixed(0);return e}_roomButton;_roomButtonIconJoin;_roomButtonIconLeave;createRoomButton(){if(this._roomButton)return this._roomButton;const e=document.createElement("button");return this._roomButton=e,e.classList.add("create-room-button"),e.setAttribute("priority","90"),e.onclick=()=>{if(this.context.connection.isInRoom)this.urlParameterName&&uc(this.urlParameterName,null),this.context.connection.leaveRoom(),this._userWantsToBeInARoom=!1;else{if(this.urlParameterName){const t=w(this.urlParameterName);(!t||t===!0)&&(this._lastJoinedRoom?uc(this.urlParameterName,this._lastJoinedRoom):this.setRandomRoomUrlParameter())}this.tryJoinRoom()}},this._roomButtonIconJoin=Pt("group"),this._roomButtonIconLeave=Pt("group_off"),this.updateRoomButtonState(),this.context.connection.beginListen(ie.JoinedRoom,this.updateRoomButtonState),this.context.connection.beginListen(ie.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(ie.JoinedRoom,this.updateRoomButtonState),this.context.connection.stopListen(ie.LeftRoom,this.updateRoomButtonState)}_viewOnlyButton;onEnableViewOnlyButton(){this.context.connection.isConnected?this.onCreateViewOnlyButton():(this.context.connection.stopListen(ie.JoinedRoom,this.onCreateViewOnlyButton),this.context.connection.beginListen(ie.JoinedRoom,this.onCreateViewOnlyButton))}onDisableViewOnlyButton(){this.context.connection.stopListen(ie.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),Oe("View only URL copied to clipboard")):be("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)}}sr([u()],Fn.prototype,"roomName",2),sr([u()],Fn.prototype,"urlParameterName",2),sr([u()],Fn.prototype,"joinRandomRoom",2),sr([u()],Fn.prototype,"requireRoomParameter",2),sr([u()],Fn.prototype,"autoRejoin",2),sr([u()],Fn.prototype,"createJoinButton",2),sr([u()],Fn.prototype,"createViewOnlyButton",2),sr([u()],Fn.prototype,"roomPrefix",1);function qI(){const o=w("testwindowcount")||0;o&&o>0&&XI(o)}function XI(o){if(w("testwindow"))return null;const e=new URL(window.location.href);qm(e.searchParams,ER,1),qm(e.searchParams,"testwindow",1);const t=e.toString(),i=[];window.onbeforeunload=()=>{for(const l of i)l.close()};const n=.05,s=128;let r=0,a=0;for(let l=0;l<o;l++){r*s+s*.01>=window.innerWidth&&(a+=1,r=0);const c=r*(s*(1+n))+window.screenLeft,h=a*(s*(1+n))+window.screenTop+90+60*a;r+=1;const d=window.open(t,"test window "+l,`popup=yes width=${s} height=${s} top=${h} left=${c}`);if(!d){console.warn("Failed to open window");continue}i.push(d),d.onload=()=>{d.onbeforeunload=()=>{for(let p=0;p<i.length;p++){const m=i[p];m!==d&&m.close()}i.length=0}}}return i}class U0 extends E{awake(){qI()}}class z0 extends E{transformsPerFrame=10;interval=0;useFlatbuffers=!0;awake(){if(this.useFlatbuffers)this.context.connection.beginListenBinary(Qc,e=>{});else{this.models=[];for(let e=0;e<this.transformsPerFrame;e++)this.models.push(new QI(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 Wm(1024));const e=this.builder;for(let t=0;t<this.transformsPerFrame;t++){e.clear();const i=hx(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 QI{guid;fast=!1;position;rotation;velocity=void 0;dontSave;isValid(){return this.fast!==void 0||this.position!==void 0||this.rotation!==void 0||this.velocity!==void 0}constructor(e,t){this.guid=e,this.position={x:0,y:0,z:0},this.rotation={x:0,y:0,z:0,w:0},this.update(t,null)}static temp=new b;update(e,t){const i=e.worldPosition;this.position.x=i.x,this.position.y=i.y,this.position.z=i.z;const n=e.worldQuaternion;if(this.rotation.x=n.x,this.rotation.y=n.y,this.rotation.z=n.z,this.rotation.w=n.w,this.fast=!1,t){const s=t.getVelocity();this.velocity===void 0&&(this.velocity={x:0,y:0,z:0}),this.velocity.x=s.x,this.velocity.y=s.y,this.velocity.z=s.z}}}var YI=Object.defineProperty,im=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&YI(e,t,n),n};const ZI=w("debugsignals");class nm{guid}im([u()],nm.prototype,"guid");class $h{signal;reaction}im([u(nm)],$h.prototype,"signal"),im([u(ae)],$h.prototype,"reaction");const oS=class us extends E{static receivers={};static invoke(e){if(us.receivers[e]){const t=us.receivers[e];if(!t)return;for(const i of t)i.invoke(e)}}events;awake(){ZI&&console.log("SignalReceiver awake",this)}onEnable(){if(this.events)for(const e of this.events)us.receivers[e.signal.guid]||(us.receivers[e.signal.guid]=[]),us.receivers[e.signal.guid].push(this)}onDisable(){if(this.events){for(const e of this.events)if(us.receivers[e.signal.guid]){const t=us.receivers[e.signal.guid].indexOf(this);t>=0&&us.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)}}};im([u($h)],oS.prototype,"events");let Hh=oS;var Vi=(o=>(o.Activation="ActivationTrack",o.Animation="AnimationTrack",o.Audio="AudioTrack",o.Control="ControlTrack",o.Marker="MarkerTrack",o.Signal="SignalTrack",o))(Vi||{}),fo=(o=>(o[o.None=0]="None",o[o.Hold=1]="Hold",o[o.Loop=2]="Loop",o[o.PingPong=3]="PingPong",o[o.Continue=4]="Continue",o))(fo||{}),N0=(o=>(o.Signal="SignalEmitter",o))(N0||{});const yo=w("debugtimeline");class ql{director;track;get muted(){return this.track.muted}set muted(e){e!==this.track.muted&&(this.track.muted=e,this.onMuteChanged?.call(this))}*forEachClip(e=!1){if(this.track?.clips)if(e)for(let t=this.track.clips.length-1;t>=0;t--)yield this.track.clips[t];else for(const t of this.track.clips)yield t}getClipTime(e,t){return t.clipIn+(e-t.start)*t.timeScale}getClipTimeNormalized(e,t){return(e-t.start)/t.duration}evaluateWeight(e,t,i,n=!0){if(t<0||t>=i.length)return 0;const s=i[t];if(n||e>=s.start&&e<=s.end){let r=1;if(s.easeInDuration>0){const a=Math.min((e-s.start)/s.easeInDuration,1);r*=a}if(s.easeOutDuration>0){const a=Math.min((s.end-e)/s.easeOutDuration,1);r*=a}return r}return 0}}class KI{clip;rootPositionOffset;rootQuaternionOffset;get hasOffsets(){return this.rootPositionOffset!==void 0||this.rootQuaternionOffset!==void 0}rootStartPosition;rootEndPosition;rootStartQuaternion;rootEndQuaternion;constructor(e){const t=e.getClip();this.clip=t;const i=e.getRoot(),n=i.name+".position",s=i.name+".quaternion";yo&&console.log(t.name,t.tracks,n);for(const r of t.tracks)if(!(r.times.length<=0)){if(r.name.endsWith(n))this.rootStartPosition=new b().fromArray(r.values,0),this.rootEndPosition=new b().fromArray(r.values,r.values.length-3),this.rootPositionOffset=this.rootEndPosition.clone().sub(this.rootStartPosition),yo&&console.log(this.rootPositionOffset);else if(r.name.endsWith(s)&&(this.rootStartQuaternion=new N().fromArray(r.values,0),this.rootEndQuaternion=new N().fromArray(r.values,r.values.length-4),this.rootQuaternionOffset=this.rootEndQuaternion.clone().multiply(this.rootStartQuaternion),yo)){const a=new at().setFromQuaternion(this.rootQuaternionOffset);console.log("ROT",a)}}}}class Gh extends ql{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&&ox(this._animator.gameObject,this,this.director.enabled&&this.director.weight>0)}createHooks(e,t){if(t.tracks?.length<=0){console.warn("No tracks in AnimationClip",t);return}let i=!1,n=!1;const s=t.tracks.find(r=>r.name.includes(".position")||r.name.includes(".quaternion"))?.name.split(".");if(s){const r=s[s.length-2],a=r+".position",l=r+".quaternion";for(const c of t.tracks)!i&&c.name.endsWith(a)?(i=!0,this.createPositionInterpolant(t,e,c)):!n&&c.name.endsWith(l)&&(n=!0,this.createRotationInterpolant(t,e,c))}if(!i||!n){const r=this.mixer?.getRoot(),a=t.tracks[0],l=a.name.lastIndexOf("."),c=a.name.substring(0,l),h=c.substring(c.lastIndexOf(".")+1),d=r.getObjectByName(h);if(d)if(i){if(!n){const p=t.tracks[0].name.substring(0,l)+".quaternion";yo&&console.warn("Create quaternion track",h,d);const m=new iP(p,[0,t.duration],[0,0,0,1,0,0,0,1]);t.tracks.push(m),this.createRotationInterpolant(t,e,m)}}else{const p=c+".position";yo&&console.warn("Create position track",h,d);const m=new tP(p,[0,t.duration],[0,0,0,0,0,0]);t.tracks.push(m),this.createPositionInterpolant(t,e,m)}}}bind(){if(!this._didBind){this._didBind=!0,yo&&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 KI(e);this._actionOffsets.push(t)}this.target&&(this._animator=S.getComponent(this.target,_t)??null,this._animator&&ox(this._animator.gameObject,this,!0));for(const e of this.models){const t=e.asset,i=t.position,n=t.rotation;i&&i.x!==void 0&&(i.isVector3||(t.position=new b(i.x,i.y,i.z)),n.isQuaternion||(t.rotation=new N(n.x,n.y,n.z,n.w)))}this.ensureTrackOffsets()}}ensureTrackOffsets(){if(this.trackOffset){const e=this.trackOffset.position;e&&(e.isVector3||(this.trackOffset.position=new b(e.x,e.y,e.z)));const t=this.trackOffset.rotation;t&&(t.isQuaternion||(this.trackOffset.rotation=new N(t.x,t.y,t.z,t.w)))}}_useclipOffsets=!0;_totalOffsetPosition=new b;_totalOffsetRotation=new N;_totalOffsetPosition2=new b;_totalOffsetRotation2=new N;_summedPos=new b;_tempPos=new b;_summedRot=new N;_tempRot=new N;_clipRotQuat=new N;evaluate(e){if(this.track.muted||!this.mixer)return;this.bind(),this._totalOffsetPosition.set(0,0,0),this._totalOffsetRotation.set(0,0,0,1),this._totalOffsetPosition2.set(0,0,0),this._totalOffsetRotation2.set(0,0,0,1);let t=0,i=0,n=!1,s=!1,r=0;for(let a=0;a<this.clips.length;a++){const l=this.models[a],c=this.actions[a],h=l.asset;c.weight=0;const d=e>=l.start&&e<=l.end,p=l.preExtrapolationMode,m=l.postExtrapolationMode,g=a<this.clips.length-1?this.models[a+1]:null;let f=d,y=!1;if(!f&&!n&&l.end<e&&m!==fo.None?(!g||g.start>e)&&(f=!0,n=!0):a==0&&!f&&!s&&l.start>e&&p!==fo.None&&(!g||g.start<e)&&(f=!0,y=!0,s=!0),f){let _=this.weight;_*=this.evaluateWeight(e,a,this.models,f),_*=this.director.weight;let v=d;if(y)switch(p){case fo.Hold:break;case fo.Loop:e+=l.start,v=!0;break;default:e+=l.start,v=!0;break}let P=this.getClipTime(e,l),k=0;const O=h.duration;if(y&&p===fo.Hold&&(P=0),v){if(h.loop)for(k+=Math.floor(P/(O+1e-6));P>O;)P-=O}else if(!d&&n)switch(m){case fo.Hold:P=this.getClipTime(l.end,l);break;case fo.Loop:P%=O;break;case fo.PingPong:const L=Math.floor(P/O)%2!==0;P%=O,L&&(P=O-P);break}l.reversed===!0?c.time=c.getClip().duration-P:c.time=P,c.timeScale=0;const D=Math.max(0,_);if(c.weight=D,r+=D,c.clampWhenFinished=!1,c.isRunning()||c.play(),this._useclipOffsets){const L=t==0?this._totalOffsetPosition:this._totalOffsetPosition2,V=t==0?this._totalOffsetRotation:this._totalOffsetRotation2;t<1&&(i=1-_),t+=1;const W=this._summedPos.set(0,0,0),G=this._tempPos.set(0,0,0),X=this._summedRot.identity(),R=this._tempRot.identity(),$=h.rotation;$&&(this._clipRotQuat.identity(),this._clipRotQuat.slerp($,_));const q=this._actionOffsets[a];if(q.hasOffsets)for(let he=0;he<k;he++)q.rootPositionOffset?G.copy(q.rootPositionOffset):G.set(0,0,0),G.applyQuaternion(X),this._clipRotQuat&&G.applyQuaternion(this._clipRotQuat),q.rootQuaternionOffset&&(R.copy(q.rootQuaternionOffset),X.multiply(R)),W.add(G);this._clipRotQuat&&V.multiply(this._clipRotQuat),V.multiply(X),h.position&&W.add(h.position),L.add(W)}}}if(this._useclipOffsets&&(this._totalOffsetPosition.lerp(this._totalOffsetPosition2,i),this._totalOffsetRotation.slerp(this._totalOffsetRotation2,i)),this.__mixerError===void 0&&(yo||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),s=new N;this.ensureTrackOffsets();const r=this.trackOffset?.rotation;i.createInterpolant=()=>{const a=n(),l=a.evaluate.bind(a);return a.evaluate=c=>{const h=l(c);if(s.set(h[0],h[1],h[2],h[3]),s.premultiply(this._totalOffsetRotation),r&&s.premultiply(r),this.director.animationCallbackReceivers)for(const d of this.director.animationCallbackReceivers)d?.onTimelineRotation?.call(d,this.director,this.target,c,s);return h[0]=s.x,h[1]=s.y,h[2]=s.z,h[3]=s.w,h},a}}createPositionInterpolant(e,t,i){const n=i.createInterpolant.bind(i),s=new b;this.ensureTrackOffsets();const r=this.trackOffset?.rotation,a=this.trackOffset?.position;let l;i.createInterpolant=()=>{const c=n(),h=c.evaluate.bind(c);return c.evaluate=d=>{const p=h(d);if(s.set(p[0],p[1],p[2]),t.removeStartOffset&&(l===void 0?(l=null,l=this._actionOffsets.find(m=>m.clip===e)?.rootStartPosition?.clone()):l?.isVector3&&s.sub(l)),s.applyQuaternion(this._totalOffsetRotation),s.add(this._totalOffsetPosition),r&&s.applyQuaternion(r),a&&(s.x-=a.x,s.y+=a.y,s.z+=a.z),this.director.animationCallbackReceivers)for(const m of this.director.animationCallbackReceivers)m?.onTimelinePosition?.call(m,this.director,this.target,d,s);return p[0]=s.x,p[1]=s.y,p[2]=s.z,p},c}}}const JI=w("mutetimeline");class ys extends ql{models=[];listener;audio=[];audioContextTimeOffset=[];lastTime=0;audioSource;_audioLoader=null;getAudioFilePath(e){const t=this.director.sourceId;return Ao(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 nP(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(JI||this.track.muted||this.director.speed<0)return;const t=this.director.context.application.muted,i=this._playableDirectorResumed;this._playableDirectorResumed=!1;const n=t?.1:0;for(let s=0;s<this.models.length;s++){const r=this.models[s],a=this.audio[s],l=r.asset;if((!a||!a.buffer)&&this.isInTimeRange(r,e-1,e+1)&&this.handleAudioLoading(r,a),ji.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,yo&&console.log("Timeline Audio ("+this.track.name+") play with offset "+a.offset+" - "+r.asset.clip),a.play(n),r._didTriggerPlay=!0);else{const h=r.clipIn+(e-r.start)*r.timeScale,d=a.context.currentTime-a._startedAt+a.offset;Math.abs(h-d)>.3&&(a.offset=h,a.stop(),a.play(n))}let c=l.volume;if(this.track.volume!==void 0&&(c*=this.track.volume),t&&(c=0),r.easeInDuration>0){const h=Math.min((e-r.start)/r.easeInDuration,1);c*=h}if(r.easeOutDuration>0){const h=Math.min((r.end-e)/r.easeOutDuration,1);c*=h}a.setVolume(c*this.director.weight)}else r._didTriggerPlay=!1,this.director.isPlaying&&a.isPlaying&&a.stop()}this.lastTime=e}loadAudio(e,t=0,i=0){let n=null;const s=e-i,r=e+t;for(const a of this.models)if(this.isInTimeRange(a,s,r)){const l=this.audio[this.models.indexOf(a)],c=this.handleAudioLoading(a,l);c!==null&&(n===null&&(n=[]),n.push(c))}return n!==null?Promise.all(n):null}isInTimeRange(e,t,i){return t<=e.start&&i>=e.end||t>=e.start&&t<=e.end||i>=e.start&&i<=e.end}static _audioBuffers=new Map;static dispose(){ys._audioBuffers.clear()}handleAudioLoading(e,t){this._audioLoader||(this._audioLoader=new Lm);const i=this.getAudioFilePath(e.asset.clip);if(ys._audioBuffers.get(i)){const s=ys._audioBuffers.get(i);return s.then(r=>{r&&t.setBuffer(r)}),s}yo&&console.warn("LOAD audio track",i,this.director.sourceId);const n=new Promise((s,r)=>{this._audioLoader.load(i,a=>{t.setBuffer(a),s(a)},void 0,a=>{console.error("Error loading audio",a),s(null)})});return ys._audioBuffers.set(i,n),n}}class om extends ql{models=[];needsSorting=!0;*foreachMarker(e=null){this.needsSorting&&this.sort();for(const t of this.models)t&&t.type===e&&(yield t)}onEnable(){this.needsSorting=!0}evaluate(e){this.needsSorting&&this.sort()}sort(){this.needsSorting=!1,this.models.sort((e,t)=>e.time-t.time)}}class qh extends ql{models=[];didTrigger=[];receivers=[];evaluate(e){if(this.track.muted)return;const t=this.director.context.time.deltaTime*1.5;for(let i=0;i<this.models.length;i++){const n=this.models[i],s=this.didTrigger[i],r=n.time-e;let a=!1;if(n.retroActive)a=r<=1e-6;else{const l=Math.abs(r);(l===0||l>=1e-5&&l<t)&&(a=!0)}if(a){if(!s)if(yo&&console.log("Trigger signal",e,n.time,n),this.didTrigger[i]=!0,this.receivers?.length<=0)Hh.invoke(n.asset);else for(const l of this.receivers)l&&l.invoke(n.asset)}else n.emitOnce||(this.didTrigger[i]=!1)}}}class sm extends ql{models=[];timelines=[];resolveSourceObjects(e){for(let t=this.models.length-1;t>=0;t--){const i=this.models[t].asset;if(!i.sourceObject||typeof i.sourceObject!="object"){console.log("no source object, removing model",t,i),this.models.splice(t,1);continue}else{const n=S.getComponent(i.sourceObject,ya);this.timelines.push(n),n&&i.updateDirector&&(n.playOnAwake=!1)}}}_previousActiveModel=null;evaluate(e){this._previousActiveModel=null;for(let t=0;t<this.models.length;t++){const i=this.models[t],n=i.asset;if(e>=i.start&&e<=i.end){this._previousActiveModel=i;const s=this.getClipTime(e,i);if(n.controlActivation){const r=n.sourceObject;r.visible=!0}if(n.updateDirector){const r=this.timelines[t];r&&(r.isPlaying&&r.pause(),r.time=s,r.evaluate())}}else{const s=this._previousActiveModel?.asset;if(n.controlActivation){const r=n.sourceObject;s?.sourceObject!==r&&(r.visible=!1)}}}}}var eL=Object.defineProperty,sS=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&eL(e,t,n),n};const Un=w("debugtimeline"),W0=class mb extends E{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:(Un||Mi())&&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(){Un&&console.log(`[Timeline] Awake '${this.name}'`,this),this.rebuildGraph(),!this.isValid()&&(Un||A())&&(Un?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(){Un&&console.log("[Timeline] OnEnable",this.name,this.playOnAwake);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(){Un&&console.log("[Timeline] OnDisable",this.name),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&&!ji.userInteractionRegistered&&this.waitForAudio;)await To(200)}this.invokeStateChangedMethodsOnTracks(),this._internalUpdateRoutine=this.startCoroutine(this.internalUpdate(),xe.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}get signalTracks(){return this._signalTracks}get markerTracks(){return this._markerTracks}*foreachMarker(e=null){for(const t of this._markerTracks)for(const i of t.foreachMarker(e))yield i}_guidsMap;resolveGuids(e){this._guidsMap=e}_isPlaying=!1;_internalUpdateRoutine;_isPaused=!1;_isStopping=!1;_time=0;_duration=0;_weight=1;_animationTracks=[];_audioTracks=[];_signalTracks=[];_markerTracks=[];_controlTracks=[];_customTracks=[];_tracksArray=[];get _allTracks(){return this._tracksArray.length=0,this._tracksArray.push(this._animationTracks),this._tracksArray.push(this._audioTracks),this._tracksArray.push(this._signalTracks),this._tracksArray.push(this._markerTracks),this._tracksArray.push(this._controlTracks),this._tracksArray.push(this._customTracks),this._tracksArray}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 Vi.Activation:if(!e&&!this._isPlaying)continue;for(let s=0;s<n.outputs.length;s++){const r=n.outputs[s];if(typeof r=="object"){let a=!1;if(n.clips)for(const c of n.clips)c.start<=i&&i<=c.end&&(a=!0);const l=r;l.visible!==void 0&&l.visible!==a&&(l.visible=a,Un&&console.warn(this.name,"set ActivationTrack-"+s,l.name,a,i))}}break}for(const n of this._allTracks)for(const s of n)this._isStopping&&s instanceof Gh||s.evaluate(i)}resolveBindings(){if(this._clonedPlayableAsset||(this._clonedPlayableAsset=!0,this.playableAsset=pc(this.playableAsset)),!this.playableAsset||!this.playableAsset.tracks)return;const e=this.findRoot(this.gameObject);for(const t of this.playableAsset.tracks){for(let i=t.outputs.length-1;i>=0;i--){let n=t.outputs[i];if(typeof n=="string"){this._guidsMap&&this._guidsMap[n]&&(n=this._guidsMap[n]);const s=S.findByGuid(n,e);s===null||typeof s!="object"?(t.outputs.splice(i,1),console.warn("Failed to resolve binding",n,t.name,t.type)):(Un&&console.log("Resolved binding",n,"to",s),t.outputs[i]=s)}else if(n===null){if(t.outputs.splice(i,1),mb.createTrackFunctions[t.type])continue;t.type!==Vi.Audio&&t.type!==Vi.Control&&t.type!==Vi.Marker&&t.type!==Vi.Signal&&console.warn("Missing binding",n,t.name,t.type,this.name,this.playableAsset.name)}}if(t.type===Vi.Control&&t.clips)for(let i=0;i<t.clips.length;i++){const n=t.clips[i];let s=n.asset.sourceObject;if(typeof s=="string"){this._guidsMap&&this._guidsMap[s]&&(s=this._guidsMap[s]);const r=S.findByGuid(s,e);r===null||typeof r!="object"?console.warn("Failed to resolve sourceObject binding",s,t.name,n):(Un&&console.log("Resolved binding",s,"to",r),n.asset.sourceObject=r)}}}}findRoot(e){return e.parent?this.findRoot(e.parent):e}updateTimelineDuration(){if(this._duration=0,!(!this.playableAsset||!this.playableAsset.tracks)){for(const e of this.playableAsset.tracks)if(e.muted!==!0){if(e.clips)for(const t of e.clips)t.end>this._duration&&(this._duration=t.end);if(e.markers)for(const t of e.markers)t.time>this._duration&&(this._duration=t.time+.001)}}}setupAndCreateTrackHandlers(){if(this._animationTracks.length=0,this._audioTracks.length=0,this._signalTracks.length=0,!this.playableAsset)return;let e=S.findObjectOfType(Wo,this.context);for(const t of this.playableAsset.tracks){const i=t.type,n=mb.createTrackFunctions[i];if(n!=null){const s=n(this,t);if(typeof s.evaluate=="function"){s.director=this,s.track=t,this._customTracks.push(s);continue}}if(t.type===Vi.Animation){if(!t.clips||t.clips.length<=0){Un&&console.warn("Animation track has no clips",t);continue}for(let s=t.outputs.length-1;s>=0;s--){let r=t.outputs[s];if(r instanceof M){const l=S.getOrAddComponent(r,_t);l&&(r=l)}const a=r?.gameObject?.animations;if(a){const l=new Gh;l.trackOffset=t.trackOffset,l.director=this,l.track=t;for(let c=0;c<t.clips.length;c++){const h=t.clips[c],d=h.asset;if(!d){console.error(`Timeline ${this.name}: clip #${c} on track "${t.name}" has no animation data`);continue}const p=d.clip;let m=p;if((typeof m=="string"||typeof m=="number")&&(m=a.find(f=>f.name===p)),Un&&console.log(d,p,"\u2192",m),!m){console.warn("Could not find animationClip for model",h,t.name,this.name,this.playableAsset?.name,a,r);continue}r instanceof _t&&r.runtimeAnimatorController&&(r.__internalDidAwakeAndStart||r.initializeRuntimeAnimatorController(),r.runtimeAnimatorController.mixer||r.runtimeAnimatorController.bind(r),l.mixer=r.runtimeAnimatorController.mixer),l.mixer||(l.mixer=new Im(r.gameObject),this.context.animations.registerAnimationMixer(l.mixer)),l.clips.push(m),l.mixer.uncacheAction(m),l.createHooks(h.asset,m);const g=l.mixer.clipAction(m);l.actions.push(g),l.models.push(h)}this._animationTracks.push(l)}}}else if(t.type===Vi.Audio){if(!t.clips||t.clips.length<=0)continue;const s=new ys;s.director=this,s.track=t,s.audioSource=t.outputs.find(r=>r instanceof ji),this._audioTracks.push(s),e||(e=this.context.mainCameraComponent?.gameObject.addComponent(Wo)),s.listener=e.listener;for(let r=0;r<t.clips.length;r++){const a=t.clips[r];s.addModel(a)}}else if(t.type===Vi.Marker){if(t.markers){const s=new qh;s.director=this,s.track=t;const r=new om;r.director=this,r.track=t;for(const a of t.markers)a.type===N0.Signal?(s.models.push(a),s.didTrigger.push(!1)):r.models.push(a);if(s!==null&&s.models.length>0){const a=S.getComponent(this.gameObject,Hh);a&&(s.receivers.push(a),this._signalTracks.push(s))}r!==null&&r.models.length>0&&this._markerTracks.push(r)}}else if(t.type===Vi.Signal){const s=new qh;if(s.director=this,s.track=t,t.markers)for(const r of t.markers)s.models.push(r),s.didTrigger.push(!1);for(const r of t.outputs)s.receivers.push(r);this._signalTracks.push(s)}else if(t.type===Vi.Control){const s=new sm;if(s.director=this,s.track=t,t.clips)for(const r of t.clips)s.models.push(r);s.resolveSourceObjects(this.context),this._controlTracks.push(s)}}}setAudioTracksAllowPlaying(e){for(const t of this._audioTracks)t.onAllowAudioChanged(e)}animationCallbackReceivers=[];registerAnimationCallback(e){this.animationCallbackReceivers.push(e)}unregisterAnimationCallback(e){const t=this.animationCallbackReceivers.indexOf(e);t!==-1&&this.animationCallbackReceivers.splice(t,1)}};sS([u()],W0.prototype,"playOnAwake"),sS([u()],W0.prototype,"extrapolationMode");let ya=W0;var tL=Object.defineProperty,rm=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&tL(e,t,n),n};class ba extends E{isGizmo=!1;translationSnap=1;rotationSnapAngle=15;scaleSnap=.25;get control(){return this._control}_control;orbit;onEnable(){if(!(this.isGizmo&&!jc)&&this.context.mainCamera&&(this._control||(this._control=new PP(this.context.mainCamera,this.context.renderer.domElement),this._control.enabled=!0,this._control.getRaycaster().layers.set(2),this._control.size=1,("_root"in this._control?this._control._root:this._control).traverse(e=>{const t=e;if(t.layers.set(2),t){const i=t.material;i&&(i.opacity=.3)}}),this.orbit=S.getComponentInParent(this.context.mainCamera,ge)??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(Co.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(Tn);i&&(i.fastMode=!0,i.requestOwnership())}else{const i=this.gameObject.getComponentInParent(Tn);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=>{this.enabled&&e.keyCode===16&&this.disableSnapping()}}rm([u()],ba.prototype,"isGizmo"),rm([u()],ba.prototype,"translationSnap"),rm([u()],ba.prototype,"rotationSnapAngle"),rm([u()],ba.prototype,"scaleSnap");var iL=Object.defineProperty,nL=Object.getOwnPropertyDescriptor,am=(o,e,t,i)=>{for(var n=i>1?void 0:i?nL(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&iL(e,t,n),n};class V0{texture=null;rect}am([u(Se)],V0.prototype,"texture",2);let Xl=class extends wh{set image(o){this.sprite||(this.sprite=new V0),this.sprite.texture=o,this.onAfterCreated()}get image(){return this.sprite?this.sprite.texture:null}get sprite(){return this._sprite}set sprite(o){this._sprite!==o&&(this._sprite=o,this.onAfterCreated())}_sprite;pixelsPerUnitMultiplier=1;isBuiltinSprite(){const o=this.sprite;switch(o?.texture?.name){case"InputFieldBackground":case"UISprite":case"Background":case"Knob":return!0}return!o?.texture?.name?.length&&o?.texture?.image?.width===32&&o?.texture?.image?.height===32}onBeforeCreate(o){super.onBeforeCreate(o),this.isBuiltinSprite()&&(o.borderRadius=5/this.pixelsPerUnitMultiplier,this.sprite?.texture?.name==="Knob"&&(o.borderRadius=999))}onAfterCreated(){this.__didAwake&&(super.onAfterCreated(),!this.isBuiltinSprite()&&this.setTexture(this.sprite?.texture))}};am([u(V0)],Xl.prototype,"sprite",1),am([u()],Xl.prototype,"pixelsPerUnitMultiplier",2);class lm extends wh{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))}}am([u(Se)],lm.prototype,"mainTexture",1);var oL=Object.defineProperty,sL=Object.getOwnPropertyDescriptor,$i=(o,e,t,i)=>{for(var n=i>1?void 0:i?sL(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&oL(e,t,n),n};const _a=w("debugbutton");class rr{colorMultiplier;disabledColor;fadeDuration;highlightedColor;normalColor;pressedColor;selectedColor}$i([u()],rr.prototype,"colorMultiplier",2),$i([u(se)],rr.prototype,"disabledColor",2),$i([u()],rr.prototype,"fadeDuration",2),$i([u(se)],rr.prototype,"highlightedColor",2),$i([u(se)],rr.prototype,"normalColor",2),$i([u(se)],rr.prototype,"pressedColor",2),$i([u(se)],rr.prototype,"selectedColor",2);class rL{disabledTrigger;highlightedTrigger;normalTrigger;pressedTrigger;selectedTrigger}class rs extends E{click(){this.onClick?.invoke()}onClick=new ae;_isHovered=0;onPointerEnter(e){const t=e.event.pointerType==="mouse"&&e.button===0;t&&(this._isHovered+=1),_a&&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),_a&&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){_a&&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){_a&&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===Yd.Mouse)&&(_a&&(console.warn("Button Click",this.onClick),Oe("CLICKED button "+this.name+" at "+this.context.time.frameCount)),this.onClick&&this.onClick.listenerCount>0&&(this.onClick.invoke(),e.use(),this.context.accessibility.focus(this),_a))){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(),_a&&console.log(this),this._isInit=!1,this.init()}start(){this._image?.setInteractable(this.interactable),this.gameObject.getComponentInParent(Zc)||this.gameObject.addComponent(Wu)}onEnable(){super.onEnable(),this.context.accessibility.updateElement(this,{role:"button",label:this.gameObject.name+" button",hidden:!1})}onDisable(){super.onDisable(),this.context.accessibility.updateElement(this,{hidden:!0})}onDestroy(){this.context.accessibility.removeElement(this),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,Xl),this._image&&(this.stateSetup(this._image),this.interactable?this._image.setState("normal"):this._image.setState("disabled")))}stateSetup(e){e.setInteractable(this.interactable);const t=this.getFinalColor(e.color,this.colors?.normalColor),i={state:"normal",attributes:{backgroundColor:t,backgroundOpacity:t.alpha}};e.setupState(i);const n=this.getFinalColor(e.color,this.colors?.highlightedColor),s={state:"hovered",attributes:{backgroundColor:n,backgroundOpacity:n.alpha}};e.setupState(s);const r=this.getFinalColor(e.color,this.colors?.pressedColor),a={state:"pressed",attributes:{backgroundColor:r,backgroundOpacity:r.alpha}};e.setupState(a);const l=this.getFinalColor(e.color,this.colors?.selectedColor),c={state:"selected",attributes:{backgroundColor:l,backgroundOpacity:l.alpha}};e.setupState(c);const h=this.getFinalColor(e.color,this.colors?.disabledColor),d={state:"disabled",attributes:{backgroundColor:h,backgroundOpacity:h.alpha}};e.setupState(d)}getFinalColor(e,t){return t?e.clone().multiply(t).convertLinearToSRGB():e.clone().convertLinearToSRGB()}}$i([u(ae)],rs.prototype,"onClick",2),$i([u(rr)],rs.prototype,"colors",2),$i([u()],rs.prototype,"transition",2),$i([u(rL)],rs.prototype,"animationTriggers",2),$i([u(_t)],rs.prototype,"animator",2),$i([u()],rs.prototype,"interactable",1);var aL=Object.defineProperty,cm=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&aL(e,t,n),n};const ar=w("debuginputfield"),Xh=class Q extends E{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 Q.active===this}textComponent;placeholder;onValueChanged;onEndEdit;static active=null;static activeTime=-1;static htmlField=null;static htmlFieldFocused=!1;inputEventFn;_iosEventFn;start(){ar&&console.log(this.name,this)}onEnable(){Q.htmlField||(Q.htmlField=document.createElement("input"),Q.htmlField.style.width="0px",Q.htmlField.style.height="0px",Q.htmlField.style.padding="0px",Q.htmlField.style.border="none",Q.htmlField.style.overflow="hidden",Q.htmlField.style.caretColor="transparent",Q.htmlField.style.outline="none",Q.htmlField.classList.add("ar"),Q.htmlField.onfocus=()=>Q.htmlFieldFocused=!0,Q.htmlField.onblur=()=>Q.htmlFieldFocused=!1,document.body.append(Q.htmlField)),this.inputEventFn||(this.inputEventFn=this.onInput.bind(this)),Q.htmlField.addEventListener("keyup",this.inputEventFn),this.placeholder&&this.textComponent?.text.length&&S.setActive(this.placeholder.gameObject,!1),I.isiOS()&&(this._iosEventFn=this.processInputOniOS.bind(this),window.addEventListener("click",this._iosEventFn))}onDisable(){Q.htmlField?.removeEventListener("keyup",this.inputEventFn),this.onDeselected(),this._iosEventFn&&window.removeEventListener("click",this._iosEventFn)}clear(){Q.active===this&&Q.htmlField?(Q.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){ar&&console.log("CLICK",e,Q.active),Q.activeTime=this.context.time.time,Q.active!==this&&this.startCoroutine(this.activeLoop(),xe.LateUpdate),this.selectInputField()}*activeLoop(){for(this.onSelected();Q.active===this&&!(this.context.input.getPointerClicked(0)&&this.context.time.time-Q.activeTime>.2);)this.setTextFromInputField(),yield;this.onDeselected()}onSelected(){if(Q.active!==this&&(ar&&console.log("Select",this.name,this,Q.htmlField,this.context.isInXR,this.context.arOverlayElement,this.textComponent?.text,Q.htmlField?.value),Q.active?.onDeselected(),Q.active=this,this.placeholder&&S.setActive(this.placeholder.gameObject,!1),Q.htmlField)){if(Q.htmlField.value=this.textComponent?.text||"",ar&&console.log("set input field value",Q.htmlField.value),this.context.isInXR){const e=this.context.arOverlayElement;e&&e.append(Q.htmlField)}this.selectInputField()}}onDeselected(){Q.active===this&&(Q.active=null,ar&&console.log("Deselect",this.name,this),Q.htmlField&&(Q.htmlField.blur(),document.body.append(Q.htmlField)),this.placeholder&&(!this.textComponent||this.textComponent.text.length<=0)&&S.setActive(this.placeholder.gameObject,!0),Q.htmlField&&this.onEndEdit?.invoke(Q.htmlField.value))}update(){Q.active===this&&this.textComponent?.markDirty()}onInput(e){if(Q.active===this){if(ar&&console.log(e.code,e,Q.htmlField?.value,this.textComponent?.text),e.code==="Escape"||e.code==="Enter"){this.onDeselected();return}Q.htmlField&&(this.textComponent&&(this.setTextFromInputField(),this.placeholder&&S.setActive(this.placeholder.gameObject,this.textComponent.text.length<=0)),this.selectInputField())}}setTextFromInputField(){if(this.textComponent&&Q.htmlField){const e=this.textComponent.text,t=Q.htmlField.value,i=this.textComponent.text!==Q.htmlField.value;this.textComponent.text=Q.htmlField.value,i&&(ar&&console.log("[InputField] value changed:",t,e),this.onValueChanged?.invoke(t,e))}}selectInputField(){Q.htmlField&&(ar&&console.log("Focus Inputfield",Q.htmlFieldFocused,Q.htmlField),Q.htmlField.setSelectionRange(Q.htmlField.value.length,Q.htmlField.value.length),I.isiOS()?(Q.htmlField.style.display="block",Q.htmlField.focus({preventScroll:!0})):setTimeout(()=>Q.htmlField?.focus(),1))}processInputOniOS(){const e=this.context.physics.raycast();if(!e.length)return;const t=e[0].object,i=Ff(t);(i?.gameObject===this.gameObject||i?.gameObject.parent===this.gameObject)&&this.selectInputField()}};cm([u(Ht)],Xh.prototype,"textComponent"),cm([u(Ht)],Xh.prototype,"placeholder"),cm([u(ae)],Xh.prototype,"onValueChanged"),cm([u(ae)],Xh.prototype,"onEndEdit");let $0=Xh;var lL=Object.defineProperty,rS=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&lL(e,t,n),n};class Qh extends E{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 OP;t.listenToPointerEvents(this.context.renderer,this.context.mainCamera),this.gameObject.add(t);const i=new kP(e);t.add(i),i.visible=!1;const n=i.material;n.transparent=!0,setTimeout(()=>{i.visible=!0;const s=Vd(this.gameObject).clone();fc(this.gameObject,0,0,0),this.gameObject.updateMatrixWorld();const r=new Yt;r.setFromObject(t),this.setWorldRotation(s.x,s.y,s.z);const a=r.max.x-r.min.x,l=r.max.y-r.min.y;if(this.keepAspect){const h=a/l;a>l?i.scale.set(1/a,1/l/h,1):i.scale.set(1/a*h,1/l,1)}else i.scale.set(1/a,1/l,1);const c=this.gameObject.scale;i.scale.multiply(c)},1)}onDisable(){this._object?.removeFromParent()}}rS([u()],Qh.prototype,"id"),rS([u()],Qh.prototype,"keepAspect");const cL={topLight:{intensity:500,position:[.418,16.199,.3]},room:{position:[-.757,13.219,.717],scale:[31.713,28.305,28.591]},boxes:[{position:[-10.906,2.009,1.846],rotation:-.195,scale:[2.328,7.905,4.651]},{position:[-5.607,-.754,-.758],rotation:.994,scale:[1.97,1.534,3.955]},{position:[6.167,.857,7.803],rotation:.561,scale:[3.927,6.285,3.687]},{position:[-2.017,.018,6.124],rotation:.333,scale:[2.002,4.566,2.064]},{position:[2.291,-.756,-2.621],rotation:-.286,scale:[1.546,1.552,1.496]},{position:[-2.193,-.369,-5.547],rotation:.516,scale:[3.875,3.487,2.986]}],lights:[{intensity:50,position:[-16.116,14.37,8.208],scale:[.1,2.428,2.739]},{intensity:50,position:[-16.109,18.021,-8.207],scale:[.1,2.425,2.751]},{intensity:17,position:[14.904,12.198,-1.832],scale:[.15,4.265,6.331]},{intensity:43,position:[-.462,8.89,14.52],scale:[4.38,5.441,.088]},{intensity:20,position:[3.235,11.486,-12.541],scale:[2.5,2,.1]},{intensity:100,position:[0,20,0],scale:[1,.1,1]}]},hL={topLight:{intensity:400,position:[.5,14,.5]},room:{position:[0,13.2,0],scale:[31.5,28.5,31.5]},boxes:[{position:[-10.906,-1,1.846],rotation:-.195,scale:[2.328,7.905,4.651]},{position:[-5.607,-.754,-.758],rotation:.994,scale:[1.97,1.534,3.955]},{position:[6.167,-.16,7.803],rotation:.561,scale:[3.927,6.285,3.687]},{position:[-2.017,.018,6.124],rotation:.333,scale:[2.002,4.566,2.064]},{position:[2.291,-.756,-2.621],rotation:-.286,scale:[1.546,1.552,1.496]},{position:[-2.193,-.369,-5.547],rotation:.516,scale:[3.875,3.487,2.986]}],lights:[{intensity:80,position:[-14,10,8],scale:[.1,2.5,2.5]},{intensity:80,position:[-14,14,-4],scale:[.1,2.5,2.5]},{intensity:23,position:[14,12,0],scale:[.1,5,5]},{intensity:16,position:[0,9,14],scale:[5,5,.1]},{intensity:80,position:[7,8,-14],scale:[2.5,2.5,.1]},{intensity:80,position:[-7,16,-14],scale:[2.5,2.5,.1]},{intensity:1,position:[0,20,0],scale:[.1,.1,.1]}]};class hm extends Hi{constructor(e){super(),this.position.y=-3.5;const t=new Aa;t.deleteAttribute("uv");const i=new gt({metalness:0,side:Id}),n=new gt({metalness:0}),s=e=="legacy"?cL:hL,r=new Mm(16777215,s.topLight.intensity,28,2);r.position.set(...s.topLight.position),this.add(r);const a=new H(t,i);a.position.set(...s.room.position),a.scale.set(...s.room.scale),this.add(a);for(const l of s.boxes){const c=new H(t,n);c.position.set(...l.position),c.rotation.set(0,l.rotation,0),c.scale.set(...l.scale),this.add(c)}for(const l of s.lights){const c=new H(t,this.createAreaLightMaterial(l.intensity));c.position.set(...l.position),c.scale.set(...l.scale),this.add(c)}}createAreaLightMaterial(e){const t=new Ce;return t.color.setScalar(e),t}}var dL=Object.defineProperty,dm=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&dL(e,t,n),n};const Yh=class HS extends E{target;invertForward=!1;keepUpDirection=!0;copyTargetRotation=!1;static flipYQuat=new N().setFromAxisAngle(new b(0,1,0),Math.PI);onBeforeRender(){let e=this.target;if(e||(e=this.context.mainCamera,A()&&!this.__did_warn&&(this.__did_warn=!0,console.debug(`[LookAt] No target set on ${this.name}, using main camera as target.`))),!e)return;let t=this.copyTargetRotation;(this.context.isInVR||this.context.isInPassThrough)&&(t=!1),gc(this.gameObject,e,this.keepUpDirection,t),this.invertForward&&this.gameObject.quaternion.multiply(HS.flipYQuat)}createBehaviours(e,t,i){if(t.uuid===this.gameObject.uuid){let n=t;if(this.keepUpDirection){const r=rt.createEmptyParent(t);n=r;const a=this.invertForward?-1:1;r.setMatrix(r.getMatrix().multiply(new J().makeRotationZ(Math.PI/2*a))),t.setMatrix(t.getMatrix().multiply(new J().makeRotationZ(-Math.PI/2*a)))}const s=new jt("lookat "+this.name,$t.sceneStartTrigger(),fe.lookAtCameraAction(n,void 0,this.invertForward?bn.back:bn.forward,this.keepUpDirection?bn.up:bn.zero));e.addBehavior(s)}}};dm([u(M)],Yh.prototype,"target"),dm([u()],Yh.prototype,"invertForward"),dm([u()],Yh.prototype,"keepUpDirection"),dm([u()],Yh.prototype,"copyTargetRotation");let H0=Yh;var uL=Object.defineProperty,G0=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&uL(e,t,n),n};class Ql extends E{url;mode=0;clickable=!0;async open(){if(!this.url){console.warn("OpenURL: URL is not set, can't open.",this);return}this._validateUrl();let e=this.url;switch(!e.startsWith("mailto:")&&e.includes("@")&&(e="mailto:"+e),this.mode){case 0:I.isSafari(),globalThis.open(e,"_blank");break;case 1:I.isSafari()&&I.isiOS()?globalThis.open(e,"_top"):globalThis.open(e,"_self");break;case 2:I.isSafari()?globalThis.open(e,"_top"):globalThis.open(e,"_new");break}}start(){this.gameObject.getComponentInParent(Ji)||this.gameObject.addComponent(Ji)}onPointerEnter(e){!e.used&&this.clickable&&this.context.input.setCursor("pointer")}onPointerExit(){this.clickable&&this.context.input.unsetCursor("pointer")}onPointerClick(e){this.clickable&&!e.used&&this.url?.length&&this.open()}_validateUrl(){this.url&&this.url.startsWith("www.")&&(A()&&console.warn("URL is not valid, adding https:// to the start of the URL",this.url),this.url="https://"+this.url)}}G0([u()],Ql.prototype,"url"),G0([u()],Ql.prototype,"mode"),G0([u()],Ql.prototype,"clickable"),Ru(o=>{const e=o.domElement.getAttribute("clickthrough");if(t(e)){const i=o.scene.addComponent(um);Ym(o.domElement,"clickthrough",()=>{const n=o.domElement.getAttribute("clickthrough");i.enabled=t(n)})}function t(i){return i!==null&&i!=="0"&&i!=="false"}});class um extends E{_previousPointerEvents="all";onEnable(){this.context.input.addEventListener("pointerdown",this.onPointerEvent),this.context.input.addEventListener("pointermove",this.onPointerEvent,{queue:100}),window.addEventListener("touchstart",this.onTouchStart,{passive:!0}),window.addEventListener("touchend",this.onTouchEnd,{passive:!0}),this._previousPointerEvents=this.context.domElement.style.pointerEvents}onDisable(){this.context.input.removeEventListener("pointerdown",this.onPointerEvent),this.context.input.removeEventListener("pointermove",this.onPointerEvent),window.removeEventListener("touchstart",this.onTouchStart),window.removeEventListener("touchend",this.onTouchEnd),this.context.domElement.style.pointerEvents=this._previousPointerEvents}onPointerEnter(){}onPointerEvent=e=>{e.pointerId>0||(e.intersections?.length<=0?this.context.domElement.style.pointerEvents="none":this.context.domElement.style.pointerEvents="all")};_touchDidHitAnything=!1;onTouchStart=e=>{const t=e.touches[0];if(!t)return;const i=t.clientX/window.innerWidth*2-1,n=-(t.clientY/window.innerHeight)*2+1;this.context.physics.raycast({screenPoint:new K(i,n)}).length>0&&(this._touchDidHitAnything=!0)};onTouchEnd=e=>{const t=this._touchDidHitAnything;this._touchDidHitAnything=!1,setTimeout(()=>{t&&(this.context.domElement.style.pointerEvents="all")},100)}}var pL=Object.defineProperty,pm=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&pL(e,t,n),n};const mL=w("debugcursor");class va extends E{static NAME="CursorFollow";damping=0;useFullPage=!0;keepDistance=!0;snapToSurface=!1;_distance=-1;updateDistance(e=!1){!e&&this.keepDistance&&this._distance!==-1||(this._distance=this.gameObject.worldPosition.distanceTo(this.context.mainCamera.worldPosition))}awake(){this._distance=-1}onEnable(){this._distance=-1,window.addEventListener("pointermove",this._onPointerMove)}onDisable(){window.removeEventListener("pointermove",this._onPointerMove)}_ndc_x=0;_ndc_y=0;_onPointerMove=e=>{if(!this.useFullPage)return;const t=e.clientX,i=e.clientY,n=this.context.domX,s=this.context.domY,r=this.context.domWidth,a=this.context.domHeight;this._ndc_x=(t-n)/r*2-1,this._ndc_y=-(i-s)/a*2+1};lateUpdate(){this.updateDistance();const e=this.useFullPage?this._ndc_x:this.context.input.mousePositionRC.x,t=this.useFullPage?this._ndc_y:this.context.input.mousePositionRC.y,i=this.context.mainCamera,n=i.worldPosition,s=F(e,t,1).unproject(i);s.sub(n).normalize();const r=F(s).multiplyScalar(this._distance).add(n);let a=r;if(this.damping>0){const l=this.gameObject.worldPosition;l.lerp(r,this.context.time.deltaTime/this.damping),this.gameObject.worldPosition=l,a=l}else this.gameObject.worldPosition=r;if(this.snapToSurface){q0.origin=a,q0.direction=s.multiplyScalar(-1);const l=this.context.physics.raycastFromRay(q0);if(l?.length){const c=l[0];this.damping>0?this.gameObject.worldPosition=a.lerp(c.point,this.context.time.deltaTime/this.damping):this.gameObject.worldPosition=c.point,mL&&B.DrawLine(c.point,c.normal.add(c.point),65280)}}}}pm([u()],va.prototype,"damping"),pm([u()],va.prototype,"useFullPage"),pm([u()],va.prototype,"keepDistance"),pm([u()],va.prototype,"snapToSurface");const q0=new So;var gL=Object.defineProperty,fL=Object.getOwnPropertyDescriptor,Yl=(o,e,t,i)=>{for(var n=i>1?void 0:i?fL(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&gL(e,t,n),n};let bo=class extends E{type="linear";duration=.1;scaleFactor=1.1;hovered=null;idle=null;animation=null;start(){this.idle||(this.idle=Qn.emptyClip()),(!this.hovered||!(this.hovered instanceof ki))&&(this.hovered=Qn.createScaleClip({type:"linear",duration:this.duration||.1,scale:this.gameObject.scale,scaleFactor:this.scaleFactor||1.1})),this.animation??=this.gameObject.addComponent(Ut),this.animation.playAutomatically=!1,this.playIdle()}onEnable(){this.animation&&(this.animation.enabled=!0),this.playIdle()}onDisable(){this.animation&&(this.animation.enabled=!1),this.playIdle()}onPointerEnter(){this.playHover()}onPointerExit(){this.playIdle()}playIdle(){this.idle&&this.animation?.play(this.idle,{exclusive:!0,fadeDuration:.1,loop:!0})}playHover(){this.hovered&&this.animation?.play(this.hovered,{exclusive:!0,fadeDuration:.1,loop:!1,clampWhenFinished:!0})}};Yl([u()],bo.prototype,"type",2),Yl([u()],bo.prototype,"duration",2),Yl([u()],bo.prototype,"scaleFactor",2),Yl([u(ki)],bo.prototype,"hovered",2),Yl([u(ki)],bo.prototype,"idle",2),bo=Yl([ef],bo);var yL=Object.defineProperty,Zl=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&yL(e,t,n),n};const Zh=w("debugscroll");class as extends E{target=null;damping=0;invert=!1;htmlSelector=null;mode="window";changed=new ae;get currentValue(){return this._current_value}_current_value=0;_target_value=0;_appliedValue=-1;_needsUpdate=!1;_firstUpdate=!1;awake(){this._firstUpdate=!0}onEnable(){window.addEventListener("wheel",this.updateCurrentScrollValue,{passive:!0}),this._appliedValue=-1,this._needsUpdate=!0}onDisable(){window.removeEventListener("wheel",this.updateCurrentScrollValue)}lateUpdate(){if(this.updateCurrentScrollValue(),this._target_value>=0&&(this.damping>0&&!this._firstUpdate?(this._current_value=j.lerp(this._current_value,this._target_value,this.context.time.deltaTime/this.damping),Math.abs(this._current_value-this._target_value)<.001&&(this._current_value=this._target_value)):this._current_value=this._target_value),this._needsUpdate||this._current_value!==this._appliedValue){this._appliedValue=this._current_value,this._needsUpdate=!1;let e=!1;if(this.changed.listenerCount>0){const t={type:"change",value:this._current_value,component:this,preventDefault:()=>{t.defaultPrevented=!0},defaultPrevented:!1};this.changed.invoke(t),e=t.defaultPrevented}if(!e){const t=this.invert?1-this._current_value:this._current_value;Array.isArray(this.target)?this.target.forEach(i=>i&&this.applyScroll(i,t)):this.target&&this.applyScroll(this.target,t),Zh&&this.context.time.frame%30===0&&console.debug(`[ScrollFollow] ${this._current_value.toFixed(5)} \u2014 ${(this._target_value*100).toFixed(0)}%, targets [${Array.isArray(this.target)?this.target.length:1}]`)}this._firstUpdate=!1}}_lastSelectorValue=null;_lastSelectorElement=null;updateCurrentScrollValue=()=>{switch(this.mode){case"window":if(this.htmlSelector?.length){if(this.htmlSelector!==this._lastSelectorValue&&(this._lastSelectorElement=document.querySelector(this.htmlSelector),this._lastSelectorValue=this.htmlSelector),this._lastSelectorElement){const e=this._lastSelectorElement.getBoundingClientRect();this._target_value=-e.top/(e.height-window.innerHeight);break}}else if(!(window.document.body.scrollHeight<=window.innerHeight)){const e=window.document.body.scrollHeight-window.innerHeight;this._target_value=window.scrollY/(e||1)}break}(isNaN(this._target_value)||!isFinite(this._target_value))&&(this._target_value=-1)};applyScroll(e,t){if(e)if(e instanceof ya)this.handleTimelineTarget(e,t),e.isPlaying&&e.pause(),e.evaluate();else if(e instanceof _t)e.setFloat("scroll",t);else if(e instanceof Ut)e.time=t*e.duration;else if(e instanceof ji){if(!e.duration)return;e.time=t*e.duration}else if(e instanceof hn)e.position01=t;else if(e instanceof Tt)e.intensity=t;else if(e instanceof M){const i=e;i["needle:scrollbounds"]===void 0&&(i["needle:scrollbounds"]=di(e)||null);const n=i["needle:scrollbounds"];n&&(e.position.y=-n.min.y-t*(n.max.y-n.min.y))}else"scroll"in e&&(typeof e.scroll=="number"?e.scroll=t:typeof e.scroll=="function"&&e.scroll(t))}handleTimelineTarget(e,t){const i=e.duration;let n=aS.get(e);if(!n){n=[],aS.set(e,n);let l=0;for(const c of e.foreachMarker("ScrollMarker")){const h=l++;if(c.element===void 0||c.needsUpdate===!0||c.element&&!c.element?.parentNode){c.needsUpdate=!1;try{if(c.element=lS(h),Zh&&console.debug(`ScrollMarker #${h} (${c.time.toFixed(2)}) found`,c.element),!c.element){(Zh||A())&&console.warn(`No HTML element found for ScrollMarker: ${c.name} (index ${h})`);continue}}catch(d){c.element=null,console.error("ScrollMarker selector is not valid: "+c.name+`
|
|
1432
|
+
`,d)}}c.element&&n.push(c)}n.length<=0&&document.querySelectorAll("[data-timeline-marker]").forEach(c=>{const h=c.getAttribute("data-timeline-marker"),d=parseFloat(h||"NaN");isNaN(d)?(A()||Zh)&&console.warn('[ScrollFollow] data-timeline-marker attribute is not a valid number. Supported are numbers only (e.g. <div data-timeline-marker="0.5">)'):n.push({time:d,element:c})});for(const c of n)c.element&&(c.timeline=new ViewTimeline({subject:c.element,axis:"block"}))}_o.length=0;let s=0;const r=1/60;let a=0;for(let l=0;l<n.length;l++){const c=n[l];if(!c.element)continue;const h=n[l+1],d=h?h.time-r:i;a+=1;const p=c.timeline;if(p){const m=bL(p),g=1-Math.abs(m-.5)*2,f=`marker${l}`;if(m>0&&m<=1){const y=c.time+(d-c.time)*m;_o.push({name:f,time:y,weight:g}),s+=g}else l===0&&m<=0?(_o.push({name:f,time:0,weight:1}),s+=1):l===n.length-1&&m>=1&&(_o.push({name:f,time:i,weight:1}),s+=1)}}if(_o.length<=0&&a<=0)e.time=t*i;else if(_o.length>0){let l=_o[0].time;if(_o.length>1)for(const c of _o){const h=c.weight/Math.max(1e-5,s),d=Math.abs(c.time-l);l+=d*h}this.damping<=0||this._firstUpdate?e.time=l:e.time=j.lerp(e.time,l,this.context.time.deltaTime/this.damping),Math.abs(e.time-l)>.001&&(this._needsUpdate=!0),Zh&&this.context.time.frame%30===0&&console.log(`[ScrollFollow ] Timeline ${e.name}: ${l.toFixed(3)}`,_o.map(c=>`[${c.name} ${(c.weight*100).toFixed(0)}%]`).join(", "))}}}Zl([u([E,M])],as.prototype,"target"),Zl([u()],as.prototype,"damping"),Zl([u()],as.prototype,"invert"),Zl([u()],as.prototype,"htmlSelector"),Zl([u()],as.prototype,"mode"),Zl([u(ae)],as.prototype,"changed");const aS=new WeakMap,_o=[],X0=new Array;let Q0=!0;function lS(o){return Q0?(Q0=!1,X0.length=0,document.querySelectorAll("[data-timeline-marker]").forEach((e,t)=>{X0[t]=e}),Q0=!1,lS(o)):X0[o]||null}function bL(o){if(!o.source)return 0;const e=o.currentTime,t=o.duration;let i=1;return(t.unit==="seconds"||t.unit==="percent")&&(i=t.value),e.unit==="seconds"?e.value/i:e.value/100}var cS=Object.defineProperty,_L=Object.getOwnPropertyDescriptor,vL=(o,e,t)=>e in o?cS(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t,mm=(o,e,t,i)=>{for(var n=i>1?void 0:i?_L(e,t):e,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=(i?r(e,t,n):r(n))||n);return i&&n&&cS(e,t,n),n},Y0=(o,e,t)=>vL(o,typeof e!="symbol"?e+"":e,t);const lr=w("debugviewbox"),wL=new se(.5,.5,.5,.5);let st=class extends E{referenceFieldOfView=-1;get mode(){return this._mode}set mode(o){o!==this._mode&&(this._mode=o,o==="once"&&(this._applyCount=0),(lr||this.debug)&&console.debug("[ViewBox] Set mode:",o))}_mode="continuous";debug=!1;onEnable(){(lr||this.debug||A())&&console.debug("[ViewBox] Using camera fov:",this.referenceFieldOfView),st.instances.push(this),this._applyCount=0,this.removeUpdateCallback(),this.context.pre_render_callbacks.push(this.internalUpdate)}onDisable(){(lr||this.debug)&&console.debug("[ViewBox] Disabled");const o=st.instances.indexOf(this);o!==-1&&st.instances.splice(o,1),this._projectedBoxElement?.remove(),this.removeUpdateCallback()}removeUpdateCallback(){const o=this.context.pre_render_callbacks.indexOf(this.internalUpdate);o!==-1&&this.context.pre_render_callbacks.splice(o,1)}_applyCount=0;internalUpdate=()=>{if(this.context.isInXR||this.destroyed||!this.activeAndEnabled)return;if(st.instances[st.instances.length-1]!==this){(lr||this.debug)&&B.DrawWireBox(this.gameObject.worldPosition,this.gameObject.worldScale,wL);return}(lr||this.debug)&&B.DrawWireBox(this.gameObject.worldPosition,this.gameObject.worldScale,14540032,0,!0,this.gameObject.worldQuaternion);const o=this.context.mainCamera;if(!o||!(o instanceof de))return;if((this.referenceFieldOfView===void 0||this.referenceFieldOfView===-1)&&(this.referenceFieldOfView=o.fov,console.debug("[ViewBox] No referenceFieldOfView set, using camera fov:",this.referenceFieldOfView)),this.referenceFieldOfView===void 0||this.referenceFieldOfView<=0){(lr||this.debug)&&console.warn("[ViewBox] No valid referenceFieldOfView set, cannot adjust box size:",this.referenceFieldOfView);return}if(this._applyCount>=1&&this.mode==="once")return;this._applyCount++;const e=this.context.domWidth,t=this.context.domHeight;let i=e,n=t,s=1,r=1;const a=this.context.focusRectSize;a&&(i=a.width,n=a.height,s=e/i,r=t/n),st._tempProjectionMatrix.copy(o.projectionMatrix),st._tempProjectionMatrixInverse.copy(o.projectionMatrixInverse);const l=o.view,c=o.zoom,h=o.aspect,d=o.fov;o.view=null,o.zoom=1,o.fov=this.referenceFieldOfView,o.updateProjectionMatrix();const p=this.gameObject.worldPosition,m=this.gameObject.worldScale,g=o.worldPosition,f=g.distanceTo(p),y=Math.max(m.x,m.y,m.z),_=F(g).sub(p);if(f<y){(this.debug||lr)&&console.warn("[ViewBox] Moving camera out of bounds",f,"<",y);const X=F(_);X.y*=1e-8,X.normalize();const R=y-f,$=g.add(X.multiplyScalar(R));o.worldPosition=$.lerp(g,1-this.context.time.deltaTime)}const v=F(p);o.worldToLocal(v),o.lookAt(p),o.updateMatrixWorld();const P=this.referenceFieldOfView*Math.PI/180,k=2*Math.tan(P/2)*f,O=k*o.aspect,D=this.projectBoxIntoCamera(o,1),L=D.maxX-D.minX,V=D.maxY-D.minY,W=this.fit(L*o.aspect,V,O/s,k/r)/(k*.5),G=F(p);G.project(o),this.context.focusRectSettings.offsetX=G.x,this.context.focusRectSettings.offsetY=G.y,this.context.focusRectSettings.zoom=W,this.context.focusRect||this.context.setCameraFocusRect(this.context.domElement),o.view=l,o.zoom=c,o.aspect=h,o.fov=d,o.projectionMatrix.copy(st._tempProjectionMatrix),o.projectionMatrixInverse.copy(st._tempProjectionMatrixInverse)};fit(o,e,t,i){const n=t/o,s=i/e;return Math.min(n,s)}projectBoxIntoCamera(o,e){const t=.5*e,i=[F(-t,-t,-t),F(t,-t,-t),F(-t,t,-t),F(t,t,-t),F(-t,-t,t),F(t,-t,t),F(-t,t,t),F(t,t,t)];let n=Number.POSITIVE_INFINITY,s=Number.NEGATIVE_INFINITY,r=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY;for(let l=0;l<i.length;l++){const c=i[l];c.applyMatrix4(this.gameObject.matrixWorld),c.project(o),c.x<n&&(n=c.x),c.x>s&&(s=c.x),c.y<r&&(r=c.y),c.y>a&&(a=c.y)}return lr&&(this._projectedBoxElement||(this._projectedBoxElement=document.createElement("div")),this._projectedBoxElement.parentElement!==this.context.domElement&&this.context.domElement.appendChild(this._projectedBoxElement),this._projectedBoxElement.style.position="fixed",this._projectedBoxElement.style.outline="2px dashed rgba(255,0,0,.5)",this._projectedBoxElement.style.left=(n*.5+.5)*this.context.domWidth+"px",this._projectedBoxElement.style.top=(-a*.5+.5)*this.context.domHeight+"px",this._projectedBoxElement.style.width=(s-n)*.5*this.context.domWidth+"px",this._projectedBoxElement.style.height=(a-r)*.5*this.context.domHeight+"px",this._projectedBoxElement.style.pointerEvents="none",this._projectedBoxElement.style.zIndex="1000"),{minX:n,maxX:s,minY:r,maxY:a}}_projectedBoxElement=null};Y0(st,"instances",[]),Y0(st,"_tempProjectionMatrix",new J),Y0(st,"_tempProjectionMatrixInverse",new J),mm([u()],st.prototype,"referenceFieldOfView",2),mm([u()],st.prototype,"mode",1),mm([u()],st.prototype,"debug",2),st=mm([ef],st);var xL=Object.defineProperty,Kl=(o,e,t,i)=>{for(var n=void 0,s=o.length-1,r;s>=0;s--)(r=o[s])&&(n=r(e,t,n)||n);return n&&xL(e,t,n),n};class ls extends E{get activeAndEnabled(){return!0}side="none";controller=!0;hands=!1;controlVisibility=!0;useGripSpace=!1;resetTransformAfterXRSession=!0;_startPosition=new b;_startRotation=new N;_startScale=new b;onEnterXR(e){this._startPosition.copy(this.gameObject.position),this._startRotation.copy(this.gameObject.quaternion),this._startScale.copy(this.gameObject.scale)}onUpdateXR(e){if(!this.enabled)return;const t=e.xr.getController(this.side);if(t){if(t.hand&&!this.hands){this.controlVisibility&&(this.gameObject.visible=!1);return}else if(!this.controller){this.controlVisibility&&(this.gameObject.visible=!1);return}this.controlVisibility&&(this.gameObject.visible=!0),this.useGripSpace||t.targetRayMode==="transient-pointer"?(this.gameObject.worldPosition=t.gripWorldPosition,this.gameObject.worldQuaternion=t.gripWorldQuaternion,this.gameObject.worldScale=F(t.xr.rigScale,t.xr.rigScale,t.xr.rigScale).multiply(this._startScale)):(this.gameObject.worldPosition=t.rayWorldPosition,this.gameObject.worldQuaternion=t.rayWorldQuaternion,this.gameObject.worldScale=F(t.xr.rigScale,t.xr.rigScale,t.xr.rigScale).multiply(this._startScale))}}onLeaveXR(e){this.resetTransformAfterXRSession&&(this.gameObject.position.copy(this._startPosition),this.gameObject.quaternion.copy(this._startRotation),this.gameObject.scale.copy(this._startScale))}}Kl([u()],ls.prototype,"side"),Kl([u()],ls.prototype,"controller"),Kl([u()],ls.prototype,"hands"),Kl([u()],ls.prototype,"controlVisibility"),Kl([u()],ls.prototype,"useGripSpace"),Kl([u()],ls.prototype,"resetTransformAfterXRSession");function hS(o,e){const t=o.xr.getFrame();if(!t)return console.warn("No XRFrame available"),!1;const i=t.session.enabledFeatures;if(i&&!i.some(s=>s==="camera-access"))return console.error(`No camera feed available - please request the 'camera-access' feature before starting WebXR or add the ARCameraBackground component to your scene.
|
|
1433
1433
|
|
|
1434
1434
|
Example to request camera-access in global scope:
|
|
1435
1435
|
NeedleXRSession.onSessionRequestStart(evt => {
|
|
1436
1436
|
evt.init.optionalFeatures = evt.init.optionalFeatures || [];
|
|
1437
1437
|
evt.init.optionalFeatures.push('camera-access');
|
|
1438
1438
|
});
|
|
1439
|
-
`),A()&&_c("No camera feed available - please request the 'camera-access' feature before starting WebXR or add the ARCameraBackground component to your scene"),!1;const n=t.getViewerPose(o.xr.getReferenceSpace());if(n)for(const s of n.views)if("camera"in s&&s.camera){let r=o.xr.getBinding();if(r||(r=new XRWebGLBinding(t.session,o.getContext())),r){let a=null;if("getCameraImage"in r){SL(o,e);const l=o.properties.get(e);if(l)return a=r.getCameraImage(s.camera),l.__webglTexture=a,!0;console.warn("No texture properties found for target texture")}}else console.error(s.camera,o.xr)}else console.error("NO CAMERA IN VIEW");else console.error(o.xr.getReferenceSpace(),t);return!1}const dS=new WeakMap;function SL(o,e){const t=dS.get(e)||new WeakSet;if(t.has(o))return;t.add(o),dS.set(e,t),console.debug("Initialize texture for camera feed");const i=new Ce,n=new vn,s=new Hi;s.add(new H(n,i));const r=new de;i.map=e,o.render(s,r)}function CL(o,e,t,i="image/webp",n){return Z0({context:o,width:e,height:t,mimeType:i,camera:n})}function Z0(o){o||(o={});const{transparent:e=!1}=o;let{mimeType:t,context:i,width:n,height:s,camera:r}=o;if(!i&&(i=pe.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!=xe.EarlyUpdate)return console.warn("Screenshot: defer to access XR frame"),new Promise(
|
|
1439
|
+
`),A()&&_c("No camera feed available - please request the 'camera-access' feature before starting WebXR or add the ARCameraBackground component to your scene"),!1;const n=t.getViewerPose(o.xr.getReferenceSpace());if(n)for(const s of n.views)if("camera"in s&&s.camera){let r=o.xr.getBinding();if(r||(r=new XRWebGLBinding(t.session,o.getContext())),r){let a=null;if("getCameraImage"in r){SL(o,e);const l=o.properties.get(e);if(l)return a=r.getCameraImage(s.camera),l.__webglTexture=a,!0;console.warn("No texture properties found for target texture")}}else console.error(s.camera,o.xr)}else console.error("NO CAMERA IN VIEW");else console.error(o.xr.getReferenceSpace(),t);return!1}const dS=new WeakMap;function SL(o,e){const t=dS.get(e)||new WeakSet;if(t.has(o))return;t.add(o),dS.set(e,t),console.debug("Initialize texture for camera feed");const i=new Ce,n=new vn,s=new Hi;s.add(new H(n,i));const r=new de;i.map=e,o.render(s,r)}function CL(o,e,t,i="image/webp",n){return Z0({context:o,width:e,height:t,mimeType:i,camera:n})}function Z0(o){o||(o={});const{transparent:e=!1}=o;let{mimeType:t,context:i,width:n,height:s,camera:r}=o;if(!i&&(i=pe.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!=xe.EarlyUpdate)return console.warn("Screenshot: defer to access XR frame"),new Promise(D=>{Do(L=>{const V=Z0(o);D(V)},xe.EarlyUpdate,{once:!0})});const c=a.domElement,h=c.width,d=c.height;n||(n=h),s||(s=d);const p=n,m=s;let g=window.devicePixelRatio||1,f=1;i.devicePixelRatio==="auto"||i.devicePixelRatio==="manual"?f=1:f=i.devicePixelRatio/window.devicePixelRatio,g*=f,n/=g,s/=g,n=Math.floor(n),s=Math.floor(s),a.xr.isPresenting&&a.xr.getFrame();const y=a.xr.enabled;a.xr.enabled=!1,a.xr.isPresenting=!1,c.style.width=`${n}px`,c.style.height=`${s}px`;const _=a.getRenderTarget(),v=a.getClearColor(new oe),P=a.getClearAlpha(),k=i.scene.background,O="aspect"in r?r.aspect:null;try{const D=o.render_events!==!1,L=new Array;D&&(el(i.scene,ti,L),L.forEach(R=>{if(R?.onBeforeRender(),R.isInstancingActive&&R.instances)for(let $=0;$<R.instances?.length;$++){const q=R.instances[$];Fo(q.object,!0)}})),e&&(i.scene.background=null,a.setClearColor(0,0)),o.background&&(i.scene.background=null,a.setClearColor(o.background),o.background instanceof se&&a.setClearAlpha(o.background.a)),e&&a.setClearAlpha(0),a.setSize(n,s,!1),"cam"in r&&(r=r.threeCamera),r instanceof de&&(r.aspect=n/s,r.updateProjectionMatrix());const V="type"in o&&o.type==="texture";let W=null;V&&(W=new $n(n,s,{wrapS:Ab,wrapT:Ab,format:1023}),a.setRenderTarget(W));let G=c;if(l?(W&&console.error('Taking XR screenshots with { type: "texture" } is currently not supported.'),G=Jh.compositeWithCameraImage({width:p,height:m,scene:i.scene,camera:r,renderer:a})):i.renderNow(r||null),r instanceof de&&O!=null&&(r.aspect=O,r.updateProjectionMatrix()),D&&L.forEach(R=>R.onAfterRender()),!t&&"download_filename"in o&&o.download_filename)switch(o.download_filename.split(".").pop()?.toLowerCase()){case"png":t="image/png";break;case"jpg":case"jpeg":t="image/jpeg";break;case"webp":t="image/webp";break}if(e&&o.trim===!0){const R=PL(G);R&&(G=R)}if("type"in o){if(o.type==="texture")return W?(o.target&&(o.target.image=W?.texture.image,o.target.needsUpdate=!0),W.texture.offset.set(0,-1),W.texture.needsUpdate=!0,W.texture):(console.error("No target texture found"),null);if(o.type==="blob")return new Promise((R,$)=>{G.toBlob(q=>{R(q)},t)});if(o.type==="share")return new Promise((R,$)=>{G.toBlob(q=>{if(q&&"share"in navigator){let he="file_type"in o&&o.file_type||t;t||(he="image/png");const re=he?.split("/")[1]||"png",me=new File([q],"filename"in o?o.filename||`screenshot.${re}`:`screenshot.${re}`,{type:he});return navigator.share({title:"title"in o?o.title:void 0,text:"text"in o?o.text:void 0,url:"url"in o?o.url:void 0,files:[me]}).catch(te=>{console.warn("User cancelled share",te.message)}).finally(()=>{R({blob:q,shared:!0})})}return{blob:q,shared:!1}},t)})}const X=G.toDataURL(t);if("download_filename"in o&&o.download_filename){let R=o.download_filename;if(I.isMobileDevice()&&typeof window<"u"){const $=R+"_screenshots",q=R.split("."),he=q.pop()?.toLowerCase();let re=0;localStorage.getItem($)&&(re=parseInt(sessionStorage.getItem($)||"0")),re>0&&(R=`${q.join()}-${re}.${he}`),re+=1,sessionStorage.setItem($,re.toString())}uS(X,R)}return X}finally{a.setRenderTarget(_),i.scene.background=k,a.setSize(h,d,!1),a.setClearColor(v,P),O!=null&&r instanceof de&&(r.aspect=O,r.updateProjectionMatrix()),a.xr.enabled=y,a.xr.isPresenting=l,l||i.updateSize(!0)}return null}function PL(o){if(!("document"in globalThis))return null;const e=document.createElement("canvas");e.width=o.width,e.height=o.height;const t=e.getContext("2d");if(!t)return null;t.drawImage(o,0,0);const i=e.width,n=e.height,s=t.getImageData(0,0,i,n).data;let r=n,a=i,l=0,c=0;for(let g=0;g<n;g++)for(let f=0;f<i;f++){const y=(g*i+f)*4;s[y+3]!==0&&(f<a&&(a=f),f>c&&(c=f),g<r&&(r=g),g>l&&(l=g))}const h=c-a+1,d=l-r+1,p=document.createElement("canvas"),m=p.getContext("2d");return m?(p.width=h,p.height=d,m.drawImage(e,a,r,h,d,0,0,h,d),p):null}let Kh=null;function uS(o,e){if(o){if(!o.startsWith("data:image")){console.error("Can not save image: Data url is not an image",o);return}Kh||(Kh=document.createElement("a")),Kh.href=o,Kh.download=e,Kh.click()}}var Jh;(o=>{let e=null,t=null,i=null,n=null,s=null;function r(c){const{renderer:h,width:d,height:p}=c,m=h.xr.enabled,g=h.getRenderTarget(),f=h.autoClear,y=d,_=p,v=d/p;(!i||i.width!==y||i.height!==_)&&(i??=new $n(y,_,{colorSpace:Mo}),i.width=y,i.height=_,i.samples=4,i.texture.repeat.y=-1,i.texture.offset.y=1),(!s||s.width!==y||s.height!==_)&&(s=document.createElement("canvas"),s.width=y,s.height=_,s.style.position="fixed",s.style.top="0px",s.style.right="0px",s.style.width="300px",s.style.height=`${300/v}px`,s.style.zIndex="1000",s.style.pointerEvents="none",s.style.opacity="1.0",s.style.willChange="contents"),e||(e=l({defines:{DECODE_VIDEO_TEXTURE:!0}})),t||(t=l()),n||(n=new Se),h.xr.updateCamera(c.camera),h.xr.enabled=!1,h.autoClear=!1,h.clear(),h.setSize(y,_),h.setRenderTarget(i),hS(c.renderer,n)||console.error("Could not update texture from XR frame");const P=S.findObjectOfType(ed);return P?P.setTexture(n):(e.setTexture(n),h.render(e,c.camera)),h.clearDepth(),h.setSize(y,_),h.render(c.scene,c.camera),h.setRenderTarget(null),t.setTexture(i.texture),h.render(t,c.camera),s.getContext("2d",{alpha:!1}).drawImage(h.domElement,0,0,s.width,s.height),h.setRenderTarget(g),h.xr.enabled=m,h.autoClear=f,s}o.compositeWithCameraImage=r;const a=`
|
|
1440
1440
|
uniform sampler2D t2D;
|
|
1441
1441
|
varying vec2 vUv;
|
|
1442
1442
|
|
|
@@ -1504,7 +1504,7 @@ Please refer to the documentation on <a href="https://fwd.needle.tools/needle-en
|
|
|
1504
1504
|
align-items: center;
|
|
1505
1505
|
`,n.appendChild(s);var r=document.createElementNS("http://www.w3.org/2000/svg","path");r.setAttribute("d","M 12,12 L 28,28 M 28,12 12,28"),r.setAttribute("stroke","#000000"),r.setAttribute("stroke-width","2px"),r.style.cssText=`
|
|
1506
1506
|
/**filter: drop-shadow(0 0px 1.2px rgba(0,0,0,.7));**/
|
|
1507
|
-
`,s.appendChild(r),ad&&console.log("Created fallback close button",s,e)}appendElement(e,t){return t.shadowRoot?t.shadowRoot.appendChild(e):t.appendChild(e)}}const xa=w("debugloading"),ld=w("debugloadingrendering");w("debuglicense");class qL{className;additionalClasses}let cd=0,xS;function nb(o){xa&&console.log(o.progress.loaded.toFixed(0)+"/"+o.progress.total.toFixed(0),o);const e=o.count,t=o.progress.total;t===0||t===void 0?(xS!==o.name&&(cd=0),xS=o.name,cd+=(1-cd)*.001,xa&&be("Loading "+o.name+" did not report total size")):cd=o.progress.loaded/t;const i=o.index/e+cd/e;return
|
|
1507
|
+
`,s.appendChild(r),ad&&console.log("Created fallback close button",s,e)}appendElement(e,t){return t.shadowRoot?t.shadowRoot.appendChild(e):t.appendChild(e)}}const xa=w("debugloading"),ld=w("debugloadingrendering");w("debuglicense");class qL{className;additionalClasses}let cd=0,xS;function nb(o){xa&&console.log(o.progress.loaded.toFixed(0)+"/"+o.progress.total.toFixed(0),o);const e=o.count,t=o.progress.total;t===0||t===void 0?(xS!==o.name&&(cd=0),xS=o.name,cd+=(1-cd)*.001,xa&&be("Loading "+o.name+" did not report total size")):cd=o.progress.loaded/t;const i=o.index/e+cd/e;return j.clamp01(i)}class xd{static LoadingContainerClassName="loading";loadingProgress=0;_element;_progress=0;_allowCustomLoadingElement=!0;_loadingElement;_loadingTextContainer=null;_loadingBar=null;_loadingBarFinishedColor=null;_messageContainer=null;_loadingElementOptions;constructor(e,t){this._element=e,this._loadingElementOptions=t}async onLoadingBegin(e){const t=this._element.shadowRoot||this._element;if(xa&&console.warn("Begin Loading"),!this._loadingElement){for(let i=0;i<t.children.length;i++){const n=t.children[i];if(n.classList.contains(xd.LoadingContainerClassName)){if(!this._allowCustomLoadingElement){xa&&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=nb(e)),!t&&"name"in e&&this.setMessage("loading "+e.name)),this.loadingProgress=i,t&&this.setMessage(t),this.updateDisplay()}onLoadingFinished(){xa&&console.warn("Finished Loading"),ld||(this.loadingProgress=1,this.onDoneLoading())}setMessage(e){this._messageContainer&&(this._messageContainer.innerText=e)}_progressLoop;smoothProgressLoop(){if(this._progressLoop)return;let e=1/12;ld&&(e=1/500,typeof ld=="number"&&(e*=ld)),this._progressLoop=setInterval(()=>{this.loadingProgress>=.95&&!ld&&(e=.9),this._progress=j.lerp(this._progress,this.loadingProgress,e*this.loadingProgress),this.updateDisplay()},e)}onDoneLoading(){if(this._loadingElement){xa&&console.log("Hiding loading element");const e=this._loadingElement;e.animate([{opacity:1},{opacity:0}],{duration:200,easing:"ease-in-out"}).addEventListener("finish",()=>{e.style.display="none",e.remove()})}this._progressLoop&&clearInterval(this._progressLoop),this._progressLoop=null}updateDisplay(){const e=this._progress,t=(e*100).toFixed(0)+"%";this._loadingBar&&(this._loadingBar.style.width=e*100+"%",e>=1&&this._loadingBarFinishedColor&&(this._loadingBar.style.background=this._loadingBarFinishedColor)),this._loadingTextContainer&&(this._loadingTextContainer.textContent=t)}createLoadingElement(e){xa&&!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=Zn();if(!e){this._loadingElement.style.position="absolute",this._loadingElement.style.width="100%",this._loadingElement.style.height="100%",this._loadingElement.style.left="0",this._loadingElement.style.top="0",this._loadingElement.style.overflow="hidden";const g=this._element.getAttribute("loading-background");g?this._loadingElement.style.background=g: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??xd.LoadingContainerClassName;if(this._loadingElement.classList.add(n),this._loadingElementOptions?.additionalClasses)for(const g of this._loadingElementOptions.additionalClasses)this._loadingElement.classList.add(g);const s=document.createElement("div");s.style.cssText=`
|
|
1508
1508
|
position: relative;
|
|
1509
1509
|
display: flex;
|
|
1510
1510
|
flex-direction: column;
|
|
@@ -1617,8 +1617,8 @@ Needle Engine: Begin loading `+t+`
|
|
|
1617
1617
|
`,e),this.onBeforeBeginLoading();const r=[],a={context:this._context,name:"",progress:{},index:0,count:e.length,totalProgress01:this._loadingProgress01},l=new CustomEvent("progress",{detail:a}),c=new Array,h=new AbortController;this._abortController=h;const d={files:e,abortSignal:h.signal,onLoadingProgress:g=>{if(Re&&console.debug("Loading progress: ",g),h.signal.aborted)return;const f=g.index;!c[f]&&g.name&&(c[f]=YL(g.name)),g.name=c[f],s&&this._loadingView?.onLoadingUpdate(g),a.name=g.name,a.progress=g.progress,this._loadingProgress01=nb(g),a.totalProgress01=this._loadingProgress01,this.dispatchEvent(l)},onLoadingFinished:(g,f,y)=>{Re&&console.debug(`Finished loading "${f}" (aborted? ${h.signal.aborted})`),!h.signal.aborted&&y&&r.push({src:f,file:y})}};ZL(this);const p=this.getAttribute("hash");p!=null&&(this._context.hash=p),this._context.alias=i,this._createContextPromise=this._context.create(d);const m=await this._createContextPromise;if(this.applyAttributes(),Re&&console.warn(`--------------
|
|
1618
1618
|
Needle Engine: finished loading `+t+`
|
|
1619
1619
|
`,e,`Aborted? ${h.signal.aborted}`),h.signal.aborted){console.log("Loading finished but aborted...");return}if(this._loadId!==t){console.log("Load id changed during loading process");return}this._loadingProgress01=1,s&&m&&this._loadingView?.onLoadingUpdate(1,"creating scene"),this._didFullyLoad=!0,this.classList.remove("loading"),this.classList.add("loading-finished"),this.dispatchEvent(new CustomEvent("loadfinished",{detail:{context:this._context,src:i,loadedFiles:r}}))}applyAttributes(){if(this._context?.renderer){const n=Bw(this.toneMapping);n!==void 0&&(this._context.renderer.toneMapping=n);const s=this.getAttribute("tone-mapping-exposure");if(s!=null){const r=parseFloat(s);isNaN(r)||(this._context.renderer.toneMappingExposure=r)}}const e=this.getAttribute("background-blurriness");if(e!=null){const n=parseFloat(e);!isNaN(n)&&this._context&&(this._context.scene.backgroundBlurriness=n)}const t=this.getAttribute("environment-intensity");if(t!=null&&this._context){const n=parseFloat(t);!isNaN(n)&&this._context&&(this._context.scene.environmentIntensity=n)}const i=this.getAttribute("background-color");if(this._context?.renderer)if(typeof i=="string"&&i.length>0){const n=se.fromColorRepresentation(i);Re&&console.debug("<needle-engine> background-color changed, str:",i,"\u2192",n),this._context.renderer.setClearColor(n,n.alpha),this.context.scene.background=null}else this.getAttribute("background-image")&&this.setAttribute("background-image",this.getAttribute("background-image"))}onXRSessionStarted=()=>{const e=this.context.xrSessionMode;e==="immersive-ar"?this.onEnterAR(this.context.xrSession):e==="immersive-vr"&&this.onEnterVR(this.context.xrSession),this.context.xrSession?.addEventListener("end",()=>{this.dispatchEvent(new CustomEvent("xr-session-ended",{detail:{session:this.context.xrSession,context:this._context,sessionMode:e}})),e==="immersive-ar"?this.onExitAR(this.context.xrSession):e==="immersive-vr"&&this.onExitVR(this.context.xrSession)})};onReady=()=>this._loadingView?.onLoadingFinished();onError=()=>this._loadingView?.setMessage("Loading failed!");getSourceFiles(){const e=this.getAttribute("src");if(!e)return[];let t;Array.isArray(e)?t=e:e.startsWith("[")&&e.endsWith("]")?t=JSON.parse(e):e.includes(",")?t=e.split(","):t=[e];for(let i=t.length-1;i>=0;i--){const n=t[i];(n==="null"||n==="undefined"||n?.length<=0)&&t.splice(i,1)}return t}checkIfSourceHasChanged(e,t){if(e?.length!==t?.length||e==null&&t!==null||e!==null&&t==null)return!0;if(e!==null&&t!==null){for(let i=0;i<e?.length;i++)if(e[i]!==t[i])return!0}return!1}_previouslyRegisteredMap=new Map;ensureLoadStartIsRegistered(){const e=this.getAttribute("loadstart");e&&this.registerEventFromAttribute("loadstart",e)}registerEventFromAttribute(e,t){const i=this._previouslyRegisteredMap.get(e);if(i&&(this._previouslyRegisteredMap.delete(e),this.removeEventListener(e,i)),typeof t=="string"&&t.length>0)try{const n=(0,eval)(t);typeof n=="function"&&(this._previouslyRegisteredMap.set(e,n),this.addEventListener(e,s=>n?.call(globalThis,this._context,s)))}catch(n){console.error("Error registering event "+e+'="'+t+`" failed with the following error:
|
|
1620
|
-
`,n)}}setPublicKey(){Ss&&Ss.length>0&&this.setAttribute("public-key",Ss)}setVersion(){Ti.length>0&&this.setAttribute("version",Ti)}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(hd),this.classList.remove(dd);const e=this.getAROverlayContainer();Re&&console.warn("onSetupAR:",e),e&&(e.classList.add(hd),e.classList.remove(dd)),this.foreachHtmlElement(t=>this.setupElementsForMode(t,wS))}onSetupVR(){this.classList.remove(hd),this.classList.remove(dd),this.foreachHtmlElement(e=>this.setupElementsForMode(e,CS))}onSetupDesktop(){this.classList.remove(hd),this.classList.add(dd);const e=this.getAROverlayContainer();e&&(e.classList.remove(hd),e.classList.add(dd)),this.foreachHtmlElement(t=>this.setupElementsForMode(t,PS))}setupElementsForMode(e,t,i=null){if(!(e===this._context?.renderer?.domElement||e.id==="VRButton"||e.id==="ARButton"))if(e.classList.contains(t))e.style.visibility="visible",e.style.display==="none"&&(e.style.display="block");else for(const n of XL)e.classList.contains(n)&&(e.style.visibility="hidden",e.style.display="none")}foreachHtmlElement(e){for(let t=0;t<this.children.length;t++){const i=this.children[t];i.style&&e(i)}}onBeforeBeginLoading(){const e=this.getAttribute("dracoDecoderPath");e&&(Re&&console.log("using custom draco decoder path",e),Qw(e));const t=this.getAttribute("dracoDecoderType");t&&(Re&&console.log("using custom draco decoder type",t),Yw(t));const i=this.getAttribute("ktx2DecoderPath");i&&(Re&&console.log("using custom ktx2 decoder path",i),Zw(i))}setAttribute(e,t){super.setAttribute(e,t)}getAttribute(e){return super.getAttribute(e)}addEventListener(e,t,i){return super.addEventListener(e,t,i)}}typeof window<"u"&&!window.customElements.get(SS)&&window.customElements.define(SS,ob);function YL(o){if(o.startsWith("blob:"))return"blob";const e=o.split("/");let t=e[e.length-1];const i=t.indexOf("?");i>0&&(t=t.substring(0,i));const n=t.indexOf("=");n>0&&(t=t.substring(n));const s=t.split(".").pop(),r=s?["glb","gltf","usdz","usd","fbx","obj","mtl"].indexOf(s.toLowerCase()):-1;if(s&&r>=0&&(t=t.substring(0,t.length-s.length-1)),t=decodeURIComponent(t),t.length>3){let a="",l=!1;const c=["(",")","[","]","{","}",":",";",",",".","!","?"];for(let h=0;h<t.length;h++){let d=t[h];(d==="_"||d==="-")&&(d=" "),!(d===" "&&a.length<=0||c.includes(d)||(a.length===0&&(d=d.toUpperCase()),l&&d===" "))&&(l&&(d=d.toUpperCase()),l=!1,a+=d,d===" "&&(l=!0))}return A()&&t!==a&&console.debug('Generated display name: "'+t+'" \u2192 "'+a+'"'),a.trim()}return A()&&console.debug("Loading: use default name",t),t}function ZL(o){Ru(e=>{const t=o.getAttribute("loading-blur");if(t!==null&&t!=="0"&&e.domElement===o){const i=e.lodsManager.manager?.awaitLoading({frames:5,signal:AbortSignal.timeout(1e4),maxPromisesPerObject:1}).catch(r=>{});let n="20px";t.endsWith("px")&&(n=t);const s=170;if(e.scene.background===null){const r=o,a=e.renderer.domElement,l=a.style.filter,c=a.style.overflow;a.style.filter+=`blur(${n})`,r.style.overflow="hidden",i?.then(()=>{const h=a.animate([{filter:"blur(0px)"}],{duration:s,easing:"ease-in"});h.onfinish=()=>{a.style.filter=l,r.style.overflow=c}})}else{const r=document.createElement("div");e.domElement.prepend(r),r.style.cssText="position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 10; pointer-events: none",r.style.backdropFilter=`blur(${n})`,i?.then(()=>{const a=r.animate([{backdropFilter:"blur(0px)",opacity:0}],{duration:s,easing:"ease-in"});a.onfinish=()=>{r.remove()}})}}},{once:!0})}const KL=Object.freeze(Object.defineProperty({__proto__:null,NeedleEngineWebComponent:ob},Symbol.toStringTag,{value:"Module"}));function JL(){Nn.registerWaitForInteraction(()=>{const o=sP.getContext();o.addEventListener("statechange",()=>{setTimeout(()=>{const e=o.state;(e==="suspended"||e==="interrupted")&&o.resume().then(()=>{console.log("AudioContext resumed successfully")}).catch(t=>{console.log("Failed to resume AudioContext: "+t)})},500)})})}setTimeout(JL,1e3);const Ge=w("debugphysics"),sb=w("debugcolliderplacement"),rb=w("debugcollisions"),ej=w("showcolliders"),ym=w("debugraycasts"),Si=Symbol("needle component"),Qt=Symbol("physics body"),OS=Symbol("rigidbody");globalThis.NEEDLE_USE_RAPIER=globalThis.NEEDLE_USE_RAPIER!==void 0?globalThis.NEEDLE_USE_RAPIER:!0,Ge&&console.log("Use Rapier",!0,globalThis.NEEDLE_USE_RAPIER),pe.registerCallback(ue.ContextCreationStart,o=>{Ge&&console.log("Register rapier physics backend"),o.context.physics.engine=new lc(o.context)});class lc{debugRenderColliders=!1;debugRenderRaycasts=!1;removeBody(e){if(Ge&&console.log("REMOVE BODY",e?.name,e[Qt]),!e)return;this.validate();const t=e[Qt];if(e[Qt]=null,t&&this.world){const i=this.objects.findIndex(n=>n===e);if(i>=0){const n=this.bodies[i];if(this.bodies.splice(i,1),this.objects.splice(i,1),n instanceof T.RAPIER_PHYSICS.MODULE.Collider){const s=n;this.world?.removeCollider(s,!0);const r=s.parent();r&&r.numColliders()<=0&&(r[Si]||this.world?.removeRigidBody(r))}else n instanceof T.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,s=n[Qt];s&&this.syncPhysicsBody(n.gameObject,s,t,i)}}updateProperties(e){if(this.validate(),e.isCollider){const t=e,i=t[Qt];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):(Ge&&console.log("Initialize rapier physics engine"),this._hasCreatedWorld?(console.error("Invalid call to create physics world: world is already created"),!0):(this._hasCreatedWorld=!0,T.RAPIER_PHYSICS.MAYBEMODULE==null&&(Ge&&console.trace("Loading rapier physics engine"),await(await T.RAPIER_PHYSICS.load()).init()),Ge&&console.log("Physics engine initialized, creating world..."),this._world=new T.RAPIER_PHYSICS.MODULE.World(this._gravity),this.rapierRay=new T.RAPIER_PHYSICS.MODULE.Ray({x:0,y:0,z:0},{x:0,y:0,z:1}),this.enabled=!0,this._isInitialized=!0,Ge&&console.log("Physics world created"),!0))}validate(){this._isInitialized||Ge&&(this._lastWarnTime=this._lastWarnTime??0,Date.now()-this._lastWarnTime>1e3&&(this._lastWarnTime=Date.now(),console.warn("Physics engine is not initialized")))}rapierRay;raycastVectorsBuffer=new Ei(()=>new b,10);raycast(e,t,i){if(!this._isInitialized)return console.log("Physics engine is not initialized"),null;let n=i?.maxDistance,s=i?.solid;n===void 0&&(n=1/0),s===void 0&&(s=!0);const r=this.getPhysicsRay(this.rapierRay,e,t);if(!r)return null;(this.debugRenderRaycasts||ym)&&B.DrawRay(r.origin,r.dir,255,1);const a=this.world?.castRay(r,n,s,i?.queryFilterFlags,i?.filterGroups,void 0,void 0,l=>{const c=l[Si];return i?.filterPredicate?i.filterPredicate(c):i?.useIgnoreRaycastLayer!==!1?!c?.gameObject.layers.isEnabled(2):!0});if(a){const l=r.pointAt(a.timeOfImpact),c=this.raycastVectorsBuffer.get();return c.set(l.x,l.y,l.z),{point:c,collider:a.collider[Si]}}return null}raycastAndGetNormal(e,t,i){if(!this._isInitialized)return null;let n=i?.maxDistance,s=i?.solid;n===void 0&&(n=1/0),s===void 0&&(s=!0);const r=this.getPhysicsRay(this.rapierRay,e,t);if(!r)return null;(this.debugRenderRaycasts||ym)&&B.DrawRay(r.origin,r.dir,255,1);const a=this.world?.castRayAndGetNormal(r,n,s,i?.queryFilterFlags,i?.filterGroups,void 0,void 0,l=>{const c=l[Si];return i?.filterPredicate?i.filterPredicate(c):i?.useIgnoreRaycastLayer!==!1?!c?.gameObject.layers.isEnabled(2):!0});if(a){const l=r.pointAt(a.timeOfImpact),c=a.normal,h=this.raycastVectorsBuffer.get(),d=this.raycastVectorsBuffer.get();return h.set(l.x,l.y,l.z),d.set(c.x,c.y,c.z),{point:h,normal:d,collider:a.collider[Si]}}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)&&(Ge&&console.warn("Converting screenspace to raycast space",a),this.context?.input.convertScreenspaceToRaycastSpace(a)),a.unproject(n),t=a}const s=t;e.origin.x=s.x,e.origin.y=s.y,e.origin.z=s.z;const r=this.raycastVectorsBuffer.get();if(i)r.set(i.x,i.y,i.z);else{if(!n)return console.error("Can not perform raycast - no camera found"),null;r.set(e.origin.x,e.origin.y,e.origin.z);const a=ee(n);r.sub(a)}return r.normalize(),e.dir.x=r.x,e.dir.y=r.y,e.dir.z=r.z,e}rapierSphere=null;rapierBox=null;rapierColliderArray=[];rapierIdentityRotation={x:0,y:0,z:0,w:1};rapierForwardVector={x:0,y:0,z:1};sphereOverlap(e,t){return this.rapierSphere??=new T.RAPIER_PHYSICS.MODULE.Ball(t),this.rapierSphere.radius=t,(this.debugRenderRaycasts||ym)&&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 T.RAPIER_PHYSICS.MODULE.Cuboid(1,1,1),this.rapierBox.halfExtents.x=t.x*.5,this.rapierBox.halfExtents.y=t.y*.5,this.rapierBox.halfExtents.z=t.z*.5,(this.debugRenderRaycasts||ym)&&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 s=n[Si],r=new G_(s.gameObject,s);return this.rapierColliderArray.push(r),!0},void 0,void 0,void 0,void 0,n=>n.isSensor()?!1:n[Si].gameObject.layers.isEnabled(2)==!1),this.rapierColliderArray):this.rapierColliderArray:this.rapierColliderArray}enabled=!1;get world(){return this._world}_tempPosition=new b;_tempQuaternion=new N;_tempScale=new b;_tempMatrix=new J;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){Ge&&console.warn("Physics are disabled");return}const i=e.gameObject,n=$e(i,this._tempPosition).multiply(t);n.multiplyScalar(.5),n.x<0&&(n.x=Math.abs(n.x)),n.y<0&&(n.y=Math.abs(n.y)),n.z<0&&(n.z=Math.abs(n.z));const s=1e-7;n.x<s&&(n.x=s),n.y<s&&(n.y=s),n.z<s&&(n.z=s);const r=T.RAPIER_PHYSICS.MODULE.ColliderDesc.cuboid(n.x,n.y,n.z);this.createCollider(e,r)}async addSphereCollider(e){if(this._isInitialized||await this.initialize(),!e.activeAndEnabled)return;if(!this.enabled){Ge&&console.warn("Physics are disabled");return}const t=T.RAPIER_PHYSICS.MODULE.ColliderDesc.ball(.5);this.createCollider(e,t),this.updateProperties(e)}async addCapsuleCollider(e,t,i){if(this._isInitialized||await this.initialize(),!e.activeAndEnabled)return;if(!this.enabled){Ge&&console.warn("Physics are disabled");return}const n=e.gameObject.worldScale;n.x=Math.abs(n.x),n.y=Math.abs(n.y);const s=i*n.x;t=Math.max(t,s);const r=D.clamp(t*.5*n.y-i*n.x,0,Number.MAX_SAFE_INTEGER),a=T.RAPIER_PHYSICS.MODULE.ColliderDesc.capsule(r,s);this.createCollider(e,a)}async addMeshCollider(e,t,i,n){let s=t.geometry;if(!s){Ge&&console.warn("Missing mesh geometry",t.name);return}s.index?.array?.length||(console.warn(`Your MeshCollider is missing vertices or indices in the assined mesh "${t.name}". Consider providing an indexed geometry.`),s=EP(s));let r=null;const a=s.getAttribute("position");if(a instanceof wb){const d=a.count;r=new Float32Array(d*3);for(let p=0;p<d;p++){const m=a.getX(p),g=a.getY(p),f=a.getZ(p);r[p*3]=m,r[p*3+1]=g,r[p*3+2]=f}}else r=a.array;if(await this.initialize(),!this.enabled){Ge&&console.warn("Physics are disabled");return}if(!e.activeAndEnabled)return;const l=s.index?.array,c=e.gameObject.worldScale.clone();if(n&&c.multiply(n),Math.abs(c.x-1)>1e-4||Math.abs(c.y-1)>1e-4||Math.abs(c.z-1)>1e-4){const d=`${s.uuid}_${c.x}_${c.y}_${c.z}_${i}`;if(this._meshCache.has(d))Ge&&console.warn("Use cached mesh collider"),r=this._meshCache.get(d);else{(Ge||A())&&console.debug(`[Performance] Your MeshCollider "${e.name}" is scaled: consider applying the scale to the collider mesh instead (${c.x}, ${c.y}, ${c.z})`);const p=new Float32Array(r.length);for(let m=0;m<r.length;m+=3)p[m]=r[m]*c.x,p[m+1]=r[m+1]*c.y,p[m+2]=r[m+2]*c.z;r=p,this._meshCache.set(d,p)}}const h=i?T.RAPIER_PHYSICS.MODULE.ColliderDesc.convexHull(r):T.RAPIER_PHYSICS.MODULE.ColliderDesc.trimesh(r,l);h&&this.createCollider(e,h)}updatePhysicsMaterial(e){if(!e)return;const t=e.sharedMaterial,i=e[Qt];if(i&&t){if(t.bounciness!==void 0&&i.setRestitution(t.bounciness),t.bounceCombine!==void 0)switch(t.bounceCombine){case vt.Average:i.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case vt.Maximum:i.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case vt.Minimum:i.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case vt.Multiply:i.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}if(t.dynamicFriction!==void 0&&i.setFriction(t.dynamicFriction),t.frictionCombine!==void 0)switch(t.frictionCombine){case vt.Average:i.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case vt.Maximum:i.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case vt.Minimum:i.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case vt.Multiply:i.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}}}getBody(e){return e?e[Qt]:null}getComponent(e){return e?e[Si]: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):(Ge&&console.log("Create collider without rigidbody",e.name),i.makeRotationFromQuaternion(_e(e.gameObject)),i.setPosition(ee(e.gameObject))),i.decompose(this._tempPosition,this._tempQuaternion,this._tempScale),this.tryApplyCenter(e,this._tempPosition),t.setTranslation(this._tempPosition.x,this._tempPosition.y,this._tempPosition.z),t.setRotation(this._tempQuaternion),t.setSensor(e.isTrigger);const s=e.sharedMaterial;if(s){if(s.bounciness!==void 0&&t.setRestitution(s.bounciness),s.bounceCombine!==void 0)switch(s.bounceCombine){case vt.Average:t.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case vt.Maximum:t.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case vt.Minimum:t.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case vt.Multiply:t.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}if(s.dynamicFriction!==void 0&&t.setFriction(s.dynamicFriction),s.frictionCombine!==void 0)switch(s.frictionCombine){case vt.Average:t.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case vt.Maximum:t.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case vt.Minimum:t.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case vt.Multiply:t.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}}e.attachedRigidbody?.autoMass===!1&&(t.setDensity(1e-6),t.setMass(1e-6));try{const r=this.world.createCollider(t,n);return r[Si]=e,e[Qt]=r,r.setActiveEvents(T.RAPIER_PHYSICS.MODULE.ActiveEvents.COLLISION_EVENTS),r.setActiveCollisionTypes(T.RAPIER_PHYSICS.MODULE.ActiveCollisionTypes.ALL),this.objects.push(e),this.bodies.push(r),this.updateColliderCollisionGroups(e),Ge&&console.log("Created collider",e.name,r),r}catch(r){return console.error('Error creating collider "'+e.name+`"
|
|
1621
|
-
Error:`,r),null}}updateColliderCollisionGroups(e){const t=e[Qt],i=e.membership;let n=0;if(i==null)n=65535;else for(let a=0;a<i.length;a++){const l=i[a];l>31?console.error(`Rapier only supports 32 layers, layer ${l} is not supported`):n|=1<<Math.floor(l)}const s=e.filter;let r=0;if(s==null)r=65535;else for(let a=0;a<s.length;a++){const l=s[a];l>31?console.error(`Rapier only supports 32 layers, layer ${l} is not supported`):r|=1<<Math.floor(l)}t.setCollisionGroups(n<<16|r)}getRigidbody(e,t){if(!this.world)throw new Error("Physics world not initialized");let i=null;if(e.attachedRigidbody){const n=e.attachedRigidbody;if(i=n[Qt],!i){const s=n.isKinematic&&!sb;Ge&&console.log("Create rigidbody",s);const r=s?T.RAPIER_PHYSICS.MODULE.RigidBodyDesc.kinematicPositionBased():T.RAPIER_PHYSICS.MODULE.RigidBodyDesc.dynamic(),a=ee(e.attachedRigidbody.gameObject);r.setTranslation(a.x,a.y,a.z),r.setRotation(_e(e.attachedRigidbody.gameObject)),r.centerOfMass=new T.RAPIER_PHYSICS.MODULE.Vector3(n.centerOfMass.x,n.centerOfMass.y,n.centerOfMass.z),i=this.world.createRigidBody(r),this.bodies.push(i),this.objects.push(n)}i[Si]=n,n[Qt]=i,this.internalUpdateRigidbodyProperties(n,i),this.getRigidbodyRelativeMatrix(e.gameObject,n.gameObject,t),e[OS]=i}else{const n=T.RAPIER_PHYSICS.MODULE.RigidBodyDesc.kinematicPositionBased(),s=ee(e.gameObject);n.setTranslation(s.x,s.y,s.z),n.setRotation(_e(e.gameObject)),i=this.world.createRigidBody(n),t.identity(),i[Si]=null}return i}internal_getRigidbody(e){return e.isCollider===!0?e[OS]:e[Qt]}internalUpdateColliderProperties(e,t){const i=t.shape;let n=!1;switch(i.type){case T.RAPIER_PHYSICS.MODULE.ShapeType.Ball:{const p=i,m=e,g=e.gameObject,f=$e(g,this._tempPosition),y=Math.abs(m.radius*f.x);n=p.radius!==y,p.radius=y,n&&t.setShape(p);break}case T.RAPIER_PHYSICS.MODULE.ShapeType.Cuboid:const s=i,r=e,a=e.gameObject,l=$e(a,this._tempPosition),c=Math.abs(r.size.x*.5*l.x),h=Math.abs(r.size.y*.5*l.y),d=Math.abs(r.size.z*.5*l.z);n=s.halfExtents.x!==c||s.halfExtents.y!==h||s.halfExtents.z!==d,s.halfExtents.x=c,s.halfExtents.y=h,s.halfExtents.z=d,n&&t.setShape(s);break}if(n){const s=e.attachedRigidbody;s?.autoMass&&this.getBody(s)?.recomputeMassPropertiesFromColliders()}this.updateColliderCollisionGroups(e),e.isTrigger!==t.isSensor()&&t.setSensor(e.isTrigger)}internalUpdateRigidbodyProperties(e,t){if(t.enableCcd(e.collisionDetectionMode!==Bu.Discrete),t.setLinearDamping(e.drag),t.setAngularDamping(e.angularDrag),t.setGravityScale(e.useGravity?e.gravityScale:0,!0),e.dominanceGroup<=127&&e.dominanceGroup>=-127?t.setDominanceGroup(Math.floor(e.dominanceGroup)):t.setDominanceGroup(0),e.autoMass){t.setAdditionalMass(0,!1);for(let i=0;i<t.numColliders();i++)t.collider(i).setDensity(1);t.recomputeMassPropertiesFromColliders()}else{t.setAdditionalMass(e.mass,!1);for(let i=0;i<t.numColliders();i++)t.collider(i).setDensity(1e-7);t.recomputeMassPropertiesFromColliders()}t.setEnabledRotations(!e.lockRotationX,!e.lockRotationY,!e.lockRotationZ,!1),t.setEnabledTranslations(!e.lockPositionX,!e.lockPositionY,!e.lockPositionZ,!1),e.isKinematic?t.setBodyType(T.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicPositionBased,!1):t.setBodyType(T.RAPIER_PHYSICS.MODULE.RigidBodyType.Dynamic,!1)}lines;step(e){if(this.world&&this.enabled){if(this._isUpdatingPhysicsWorld=!0,this.eventQueue||(this.eventQueue=new T.RAPIER_PHYSICS.MODULE.EventQueue(!1)),e===void 0||e<=0){this._isUpdatingPhysicsWorld=!1;return}else if(e!==void 0){const t=D.lerp(this.world.timestep,e,.8);this.world.timestep=t}try{this.world.step(this.eventQueue)}catch(t){console.warn("Error running physics step",{timestep:this.world.timestep},t)}this._isUpdatingPhysicsWorld=!1}}postStep(){this.world&&this.enabled&&(this._isUpdatingPhysicsWorld=!0,this.syncObjects(),this._isUpdatingPhysicsWorld=!1,this.eventQueue&&!this.collisionHandler&&(this.collisionHandler=new tj(this.world,this.eventQueue)),this.collisionHandler&&(this.collisionHandler.handleCollisionEvents(),this.collisionHandler.update()),this.updateDebugRendering(this.world))}updateDebugRendering(e){if(Ge||sb||ej||this.debugRenderColliders===!0){if(!this.lines){const i=new Em({color:7855479,fog:!1}),n=new wn;this.lines=new vb(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 ft(t.vertices,3)),this.lines.geometry.setAttribute("color",new ft(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(!sb)for(let e=0;e<this.bodies.length;e++){const t=this.objects[e],i=this.bodies[e],n=t;if(n?.isCollider===!0&&!n.attachedRigidbody){const l=i.parent();l?this.syncPhysicsBody(t.gameObject,l,!0,!0):this.syncPhysicsBody(t.gameObject,i,!0,!0);continue}const s=i.translation(),r=i.rotation();if(Number.isNaN(s.x)||Number.isNaN(r.x)){!n.__COLLIDER_NAN&&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),c=$e(t.gameObject);l.multiply(c),s.x-=l.x,s.y-=l.y,s.z-=l.z}Sr(t.gameObject,s.x,s.y,s.z),hg(t.gameObject,r.x,r.y,r.z,r.w)}}syncPhysicsBody(e,t,i,n){if(t instanceof T.RAPIER_PHYSICS.MODULE.RigidBody){const s=ee(e,this._tempPosition),r=_e(e,this._tempQuaternion);switch(t.bodyType()){case T.RAPIER_PHYSICS.MODULE.RigidBodyType.Fixed:case T.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicPositionBased:case T.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicVelocityBased:i&&t.setNextKinematicTranslation(s),n&&t.setNextKinematicRotation(r);break;default:i&&t.setTranslation(s,!1),n&&t.setRotation(r,!1);break}}else if(t instanceof T.RAPIER_PHYSICS.MODULE.Collider){e.matrixWorldNeedsUpdate&&e.updateWorldMatrix(!0,!1),e.matrixWorld.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const s=this._tempPosition,r=this._tempQuaternion,a=t[Si];if(this.tryApplyCenter(a,s),i){const l=t.translation();(l.x!==s.x||l.y!==s.y||l.z!==s.z)&&t.setTranslation(s)}if(n){const l=t.rotation();(l.x!==r.x||l.y!==r.y||l.z!==r.z||l.w!==r.w)&&t.setRotation(r)}}}_tempCenterPos=new b;_tempCenterVec=new b;_tempCenterQuaternion=new N;tryApplyCenter(e,t){const i=e.center;i&&e.gameObject&&(i.x!==0||i.y!==0||i.z!==0)&&(this._tempCenterPos.x=i.x,this._tempCenterPos.y=i.y,this._tempCenterPos.z=i.z,$e(e.gameObject,this._tempCenterVec),this._tempCenterPos.multiply(this._tempCenterVec),e.attachedRigidbody?this._tempCenterPos.applyQuaternion(e.gameObject.quaternion):(_e(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=lc._matricesBuffer,n.length=0),e===t){const s=$e(e,this._tempPosition);i.makeScale(s.x,s.y,s.z);for(let r=n.length-1;r>=0;r--)i.multiply(n[r]);return i}return n.push(e.matrix),e.parent&&this.getRigidbodyRelativeMatrix(e.parent,t,i,n),i}static centerConnectionPos={x:0,y:0,z:0};static centerConnectionRot={x:0,y:0,z:0,w:1};addFixedJoint(e,t){if(!this.world){console.error("Physics world not initialized");return}const i=e[Qt],n=t[Qt];this.calculateJointRelativeMatrices(e.gameObject,t.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const s=T.RAPIER_PHYSICS.MODULE.JointData.fixed(lc.centerConnectionPos,lc.centerConnectionRot,this._tempPosition,this._tempQuaternion),r=this.world.createImpulseJoint(s,i,n,!0);Ge&&console.log("ADD FIXED JOINT",r)}addHingeJoint(e,t,i,n){if(!this.world){console.error("Physics world not initialized");return}const s=e[Qt],r=t[Qt];this.calculateJointRelativeMatrices(e.gameObject,t.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const a=T.RAPIER_PHYSICS.MODULE.JointData.revolute(i,this._tempPosition,n),l=this.world.createImpulseJoint(a,s,r,!0);Ge&&console.log("ADD HINGE JOINT",l)}calculateJointRelativeMatrices(e,t,i){e.updateWorldMatrix(!0,!1),t.updateWorldMatrix(!0,!1);const n=e.matrixWorld,s=t.matrixWorld;n.elements[0]=1,n.elements[5]=1,n.elements[10]=1,s.elements[0]=1,s.elements[5]=1,s.elements[10]=1,i.copy(s).premultiply(n.invert()).invert()}}class tj{world;eventQueue;constructor(e,t){this.world=e,this.eventQueue=t}activeCollisions=[];activeCollisionsStay=[];activeTriggers=[];handleCollisionEvents(){this.eventQueue&&this.world&&this.eventQueue.drainCollisionEvents((e,t,i)=>{const n=this.world.getCollider(e),s=this.world.getCollider(t);if(!n||!s)return;const r=n[Si],a=s[Si];rb&&console.log("EVT",r.name,a.name,i,n,s),r&&a&&(i?(this.onCollisionStarted(r,n,a,s),this.onCollisionStarted(a,s,r,n)):(this.onCollisionEnded(r,a),this.onCollisionEnded(a,r)))})}update(){this.onHandleCollisionStay()}onCollisionStarted(e,t,i,n){let s=null;if(e.isTrigger||i.isTrigger)Fr(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)=>{Fr(r,c=>{if(c.destroyed)return;const h=c.onCollisionEnter||c.onCollisionStay||c.onCollisionExit;if(h||rb){if(!s){const d=[],p=a.normal();i instanceof Bs&&i.convex&&(p.x=-p.x,p.y=-p.y,p.z=-p.z);for(let m=0;m<a.numSolverContacts();m++){const g=a.solverContactPoint(m),f=a.contactImpulse(m);if(g){const y=a.contactDist(m),_=a.solverContactFriction(m),v=a.solverContactTangentVelocity(m),P=new $_(g,y,p,f,_,v);d.push(P),rb&&B.DrawDirection(g,p,16711680,3,!0)}}s=new H_(r,i,d)}if(h){const d={collider:e,component:c,collision:s};this.activeCollisions.push(d),c.onCollisionStay&&this.activeCollisionsStay.push(d),c.onCollisionEnter?.call(c,s)}}})})}}onHandleCollisionStay(){for(const e of this.activeCollisionsStay){const t=e.component;if(!t.destroyed&&t.activeAndEnabled&&t.onCollisionStay){if(e.collision.collider.destroyed)continue;const i=e.collision;t.onCollisionStay(i)}}for(const e of this.activeTriggers){const t=e.component;if(!t.destroyed&&t.activeAndEnabled&&t.onTriggerStay){const i=e.otherCollider;if(i.destroyed)continue;t.onTriggerStay(i)}}}onCollisionEnded(e,t){if(!(e.destroyed||t.destroyed)){for(let i=0;i<this.activeCollisions.length;i++){const n=this.activeCollisions[i],s=n.collider;if(s.destroyed||n.collision.collider.destroyed){this.activeCollisions.splice(i,1),i--;continue}if(s===e&&n.collision.collider===t){const r=n.component;if(this.activeCollisions.splice(i,1),i--,r.activeAndEnabled&&r.onCollisionExit){const a=n.collision;r.onCollisionExit(a)}}}for(let i=0;i<this.activeCollisionsStay.length;i++){const n=this.activeCollisionsStay[i],s=n.collider;if(s.destroyed||n.collision.collider.destroyed){this.activeCollisionsStay.splice(i,1),i--;continue}if(s===e&&n.collision.collider===t){const r=n.component;if(this.activeCollisionsStay.splice(i,1),i--,r.activeAndEnabled&&r.onCollisionExit){const a=n.collision;r.onCollisionExit(a)}}}for(let i=0;i<this.activeTriggers.length;i++){const n=this.activeTriggers[i],s=n.collider;if(s.destroyed||n.otherCollider.destroyed){this.activeTriggers.splice(i,1),i--;continue}if(s===e&&n.otherCollider===t){const r=n.component;if(this.activeTriggers.splice(i,1),i--,r.activeAndEnabled&&r.onTriggerExit){const a=n.otherCollider;r.onTriggerExit(a)}}}}}}let ab=0;function kS(o){o?ab++:ab--}function ij(){return ab>0}const nj={binary:!0,animations:!0};async function oj(o){if(!o.context)throw new Error("No context provided to exportAsGLTF");o.scene||(o.scene=o.context.scene);const e={...nj,...o},{context:t}=e,i=new Bb;i.register(a=>new Hx(a)),i.register(a=>new IT(a)),i.register(a=>new qx(a)),dy(i,e.context);const n={binary:e.binary,animations:rj(t,e.scene,[])},s=new sj;console.debug("Exporting GLTF",n),s.onBeforeExport(e),kS(!0);const r=await i.parseAsync(e.scene,n).catch(a=>(console.error(a),null));if(kS(!1),s.onAfterExport(e),!r)throw new Error("Failed to export GLTF");if(e.downloadAs!=null){let a=null;if(r instanceof ArrayBuffer?a=new Blob([r],{type:"application/octet-stream"}):console.error("Can not download GLTF as a blob",r),a){const l=URL.createObjectURL(a),c=document.createElement("a");c.href=l;let h=e.downloadAs;!h.endsWith(".glb")&&!h.endsWith(".gltf")&&(h+=e.binary?".glb":".gltf"),c.download=h,c.click()}}return r}const MS=Symbol("needle:weight");class sj{_undo=[];onBeforeExport(e){e.context.animations.mixers.forEach(t=>{const i=Qn.tryGetActionsFromMixer(t);if(i)for(let n=0;n<i.length;n++){const s=i[n];s[MS]=s.weight,s.weight=0,this._undo.push(()=>{s.weight=s[MS]})}t.update(0)}),e.context.scene.traverse(t=>{if(!by(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 rj(o,e,t){o.animations.mixers.forEach(n=>{const s=Qn.tryGetActionsFromMixer(n);if(s)for(let r=0;r<s.length;r++){const a=s[r].getClip();t.push(a)}}),Array.isArray(e)||(e=[e]);for(const n of e)Qn.tryGetAnimationClipsFromObjectHierarchy(n,t);const i=new Set(t);return Array.from(i)}const ES="needle-button",lb=A();class RS extends HTMLElement{static observedAttributes=["ar","vr","quicklook","qrcode"];constructor(){super(),this.removeEventListener("click",this.#a),this.addEventListener("click",this.#a)}attributeChangedCallback(e,t,i){this.#l()}#t;#n;#o;#e;#i;#r;#s;#l(){if(this.#e?.remove(),this.getAttribute("ar")!=null)this.#i??=new ur,this.#e=this.#i.createARButton(),this.setAttribute("aria-label","Enter augmented reality mode");else if(this.getAttribute("vr")!=null)this.#i??=new ur,this.#e=this.#i.createVRButton(),this.setAttribute("aria-label","Enter virtual reality mode");else if(this.getAttribute("quicklook")!=null)this.#i??=new ur,this.#e=this.#i.createQuicklookButton(),this.setAttribute("aria-label","View in AR with Apple Quick Look");else if(this.getAttribute("qrcode")!=null)this.#r??=new mn,this.#e=this.#r.createQRCode({anchorElement:this}),this.setAttribute("aria-label","Share application with QR code");else{lb?console.warn("No button type specified for <needle-button>. Use either ar, vr or quicklook attribute."):console.debug("No button type specified for <needle-button>. Use either ar, vr or quicklook attribute."),this.setAttribute("aria-label","Needle Button with no specified type");return}this.#t??=this.attachShadow({mode:"open"}),this.#n??=document.createElement("slot"),this.#o??=document.createElement("style"),this.#o.innerHTML=`
|
|
1620
|
+
`,n)}}setPublicKey(){Ss&&Ss.length>0&&this.setAttribute("public-key",Ss)}setVersion(){Ti.length>0&&this.setAttribute("version",Ti)}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(hd),this.classList.remove(dd);const e=this.getAROverlayContainer();Re&&console.warn("onSetupAR:",e),e&&(e.classList.add(hd),e.classList.remove(dd)),this.foreachHtmlElement(t=>this.setupElementsForMode(t,wS))}onSetupVR(){this.classList.remove(hd),this.classList.remove(dd),this.foreachHtmlElement(e=>this.setupElementsForMode(e,CS))}onSetupDesktop(){this.classList.remove(hd),this.classList.add(dd);const e=this.getAROverlayContainer();e&&(e.classList.remove(hd),e.classList.add(dd)),this.foreachHtmlElement(t=>this.setupElementsForMode(t,PS))}setupElementsForMode(e,t,i=null){if(!(e===this._context?.renderer?.domElement||e.id==="VRButton"||e.id==="ARButton"))if(e.classList.contains(t))e.style.visibility="visible",e.style.display==="none"&&(e.style.display="block");else for(const n of XL)e.classList.contains(n)&&(e.style.visibility="hidden",e.style.display="none")}foreachHtmlElement(e){for(let t=0;t<this.children.length;t++){const i=this.children[t];i.style&&e(i)}}onBeforeBeginLoading(){const e=this.getAttribute("dracoDecoderPath");e&&(Re&&console.log("using custom draco decoder path",e),Qw(e));const t=this.getAttribute("dracoDecoderType");t&&(Re&&console.log("using custom draco decoder type",t),Yw(t));const i=this.getAttribute("ktx2DecoderPath");i&&(Re&&console.log("using custom ktx2 decoder path",i),Zw(i))}setAttribute(e,t){super.setAttribute(e,t)}getAttribute(e){return super.getAttribute(e)}addEventListener(e,t,i){return super.addEventListener(e,t,i)}}typeof window<"u"&&!window.customElements.get(SS)&&window.customElements.define(SS,ob);function YL(o){if(o.startsWith("blob:"))return"blob";const e=o.split("/");let t=e[e.length-1];const i=t.indexOf("?");i>0&&(t=t.substring(0,i));const n=t.indexOf("=");n>0&&(t=t.substring(n));const s=t.split(".").pop(),r=s?["glb","gltf","usdz","usd","fbx","obj","mtl"].indexOf(s.toLowerCase()):-1;if(s&&r>=0&&(t=t.substring(0,t.length-s.length-1)),t=decodeURIComponent(t),t.length>3){let a="",l=!1;const c=["(",")","[","]","{","}",":",";",",",".","!","?"];for(let h=0;h<t.length;h++){let d=t[h];(d==="_"||d==="-")&&(d=" "),!(d===" "&&a.length<=0||c.includes(d)||(a.length===0&&(d=d.toUpperCase()),l&&d===" "))&&(l&&(d=d.toUpperCase()),l=!1,a+=d,d===" "&&(l=!0))}return A()&&t!==a&&console.debug('Generated display name: "'+t+'" \u2192 "'+a+'"'),a.trim()}return A()&&console.debug("Loading: use default name",t),t}function ZL(o){Ru(e=>{const t=o.getAttribute("loading-blur");if(t!==null&&t!=="0"&&e.domElement===o){const i=e.lodsManager.manager?.awaitLoading({frames:5,signal:AbortSignal.timeout(1e4),maxPromisesPerObject:1}).catch(r=>{});let n="20px";t.endsWith("px")&&(n=t);const s=170;if(e.scene.background===null){const r=o,a=e.renderer.domElement,l=a.style.filter,c=a.style.overflow;a.style.filter+=`blur(${n})`,r.style.overflow="hidden",i?.then(()=>{const h=a.animate([{filter:"blur(0px)"}],{duration:s,easing:"ease-in"});h.onfinish=()=>{a.style.filter=l,r.style.overflow=c}})}else{const r=document.createElement("div");e.domElement.prepend(r),r.style.cssText="position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 10; pointer-events: none",r.style.backdropFilter=`blur(${n})`,i?.then(()=>{const a=r.animate([{backdropFilter:"blur(0px)",opacity:0}],{duration:s,easing:"ease-in"});a.onfinish=()=>{r.remove()}})}}},{once:!0})}const KL=Object.freeze(Object.defineProperty({__proto__:null,NeedleEngineWebComponent:ob},Symbol.toStringTag,{value:"Module"}));function JL(){Nn.registerWaitForInteraction(()=>{const o=sP.getContext();o.addEventListener("statechange",()=>{setTimeout(()=>{const e=o.state;(e==="suspended"||e==="interrupted")&&o.resume().then(()=>{console.log("AudioContext resumed successfully")}).catch(t=>{console.log("Failed to resume AudioContext: "+t)})},500)})})}setTimeout(JL,1e3);const Ge=w("debugphysics"),sb=w("debugcolliderplacement"),rb=w("debugcollisions"),ej=w("showcolliders"),ym=w("debugraycasts"),Si=Symbol("needle component"),Qt=Symbol("physics body"),OS=Symbol("rigidbody");globalThis.NEEDLE_USE_RAPIER=globalThis.NEEDLE_USE_RAPIER!==void 0?globalThis.NEEDLE_USE_RAPIER:!0,Ge&&console.log("Use Rapier",!0,globalThis.NEEDLE_USE_RAPIER),pe.registerCallback(ue.ContextCreationStart,o=>{Ge&&console.log("Register rapier physics backend"),o.context.physics.engine=new lc(o.context)});class lc{debugRenderColliders=!1;debugRenderRaycasts=!1;removeBody(e){if(Ge&&console.log("REMOVE BODY",e?.name,e[Qt]),!e)return;this.validate();const t=e[Qt];if(e[Qt]=null,t&&this.world){const i=this.objects.findIndex(n=>n===e);if(i>=0){const n=this.bodies[i];if(this.bodies.splice(i,1),this.objects.splice(i,1),n instanceof T.RAPIER_PHYSICS.MODULE.Collider){const s=n;this.world?.removeCollider(s,!0);const r=s.parent();r&&r.numColliders()<=0&&(r[Si]||this.world?.removeRigidBody(r))}else n instanceof T.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,s=n[Qt];s&&this.syncPhysicsBody(n.gameObject,s,t,i)}}updateProperties(e){if(this.validate(),e.isCollider){const t=e,i=t[Qt];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):(Ge&&console.log("Initialize rapier physics engine"),this._hasCreatedWorld?(console.error("Invalid call to create physics world: world is already created"),!0):(this._hasCreatedWorld=!0,T.RAPIER_PHYSICS.MAYBEMODULE==null&&(Ge&&console.trace("Loading rapier physics engine"),await(await T.RAPIER_PHYSICS.load()).init()),Ge&&console.log("Physics engine initialized, creating world..."),this._world=new T.RAPIER_PHYSICS.MODULE.World(this._gravity),this.rapierRay=new T.RAPIER_PHYSICS.MODULE.Ray({x:0,y:0,z:0},{x:0,y:0,z:1}),this.enabled=!0,this._isInitialized=!0,Ge&&console.log("Physics world created"),!0))}validate(){this._isInitialized||Ge&&(this._lastWarnTime=this._lastWarnTime??0,Date.now()-this._lastWarnTime>1e3&&(this._lastWarnTime=Date.now(),console.warn("Physics engine is not initialized")))}rapierRay;raycastVectorsBuffer=new Ei(()=>new b,10);raycast(e,t,i){if(!this._isInitialized)return console.log("Physics engine is not initialized"),null;let n=i?.maxDistance,s=i?.solid;n===void 0&&(n=1/0),s===void 0&&(s=!0);const r=this.getPhysicsRay(this.rapierRay,e,t);if(!r)return null;(this.debugRenderRaycasts||ym)&&B.DrawRay(r.origin,r.dir,255,1);const a=this.world?.castRay(r,n,s,i?.queryFilterFlags,i?.filterGroups,void 0,void 0,l=>{const c=l[Si];return i?.filterPredicate?i.filterPredicate(c):i?.useIgnoreRaycastLayer!==!1?!c?.gameObject.layers.isEnabled(2):!0});if(a){const l=r.pointAt(a.timeOfImpact),c=this.raycastVectorsBuffer.get();return c.set(l.x,l.y,l.z),{point:c,collider:a.collider[Si]}}return null}raycastAndGetNormal(e,t,i){if(!this._isInitialized)return null;let n=i?.maxDistance,s=i?.solid;n===void 0&&(n=1/0),s===void 0&&(s=!0);const r=this.getPhysicsRay(this.rapierRay,e,t);if(!r)return null;(this.debugRenderRaycasts||ym)&&B.DrawRay(r.origin,r.dir,255,1);const a=this.world?.castRayAndGetNormal(r,n,s,i?.queryFilterFlags,i?.filterGroups,void 0,void 0,l=>{const c=l[Si];return i?.filterPredicate?i.filterPredicate(c):i?.useIgnoreRaycastLayer!==!1?!c?.gameObject.layers.isEnabled(2):!0});if(a){const l=r.pointAt(a.timeOfImpact),c=a.normal,h=this.raycastVectorsBuffer.get(),d=this.raycastVectorsBuffer.get();return h.set(l.x,l.y,l.z),d.set(c.x,c.y,c.z),{point:h,normal:d,collider:a.collider[Si]}}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)&&(Ge&&console.warn("Converting screenspace to raycast space",a),this.context?.input.convertScreenspaceToRaycastSpace(a)),a.unproject(n),t=a}const s=t;e.origin.x=s.x,e.origin.y=s.y,e.origin.z=s.z;const r=this.raycastVectorsBuffer.get();if(i)r.set(i.x,i.y,i.z);else{if(!n)return console.error("Can not perform raycast - no camera found"),null;r.set(e.origin.x,e.origin.y,e.origin.z);const a=ee(n);r.sub(a)}return r.normalize(),e.dir.x=r.x,e.dir.y=r.y,e.dir.z=r.z,e}rapierSphere=null;rapierBox=null;rapierColliderArray=[];rapierIdentityRotation={x:0,y:0,z:0,w:1};rapierForwardVector={x:0,y:0,z:1};sphereOverlap(e,t){return this.rapierSphere??=new T.RAPIER_PHYSICS.MODULE.Ball(t),this.rapierSphere.radius=t,(this.debugRenderRaycasts||ym)&&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 T.RAPIER_PHYSICS.MODULE.Cuboid(1,1,1),this.rapierBox.halfExtents.x=t.x*.5,this.rapierBox.halfExtents.y=t.y*.5,this.rapierBox.halfExtents.z=t.z*.5,(this.debugRenderRaycasts||ym)&&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 s=n[Si],r=new G_(s.gameObject,s);return this.rapierColliderArray.push(r),!0},void 0,void 0,void 0,void 0,n=>n.isSensor()?!1:n[Si].gameObject.layers.isEnabled(2)==!1),this.rapierColliderArray):this.rapierColliderArray:this.rapierColliderArray}enabled=!1;get world(){return this._world}_tempPosition=new b;_tempQuaternion=new N;_tempScale=new b;_tempMatrix=new J;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){Ge&&console.warn("Physics are disabled");return}const i=e.gameObject,n=$e(i,this._tempPosition).multiply(t);n.multiplyScalar(.5),n.x<0&&(n.x=Math.abs(n.x)),n.y<0&&(n.y=Math.abs(n.y)),n.z<0&&(n.z=Math.abs(n.z));const s=1e-7;n.x<s&&(n.x=s),n.y<s&&(n.y=s),n.z<s&&(n.z=s);const r=T.RAPIER_PHYSICS.MODULE.ColliderDesc.cuboid(n.x,n.y,n.z);this.createCollider(e,r)}async addSphereCollider(e){if(this._isInitialized||await this.initialize(),!e.activeAndEnabled)return;if(!this.enabled){Ge&&console.warn("Physics are disabled");return}const t=T.RAPIER_PHYSICS.MODULE.ColliderDesc.ball(.5);this.createCollider(e,t),this.updateProperties(e)}async addCapsuleCollider(e,t,i){if(this._isInitialized||await this.initialize(),!e.activeAndEnabled)return;if(!this.enabled){Ge&&console.warn("Physics are disabled");return}const n=e.gameObject.worldScale;n.x=Math.abs(n.x),n.y=Math.abs(n.y);const s=i*n.x;t=Math.max(t,s);const r=j.clamp(t*.5*n.y-i*n.x,0,Number.MAX_SAFE_INTEGER),a=T.RAPIER_PHYSICS.MODULE.ColliderDesc.capsule(r,s);this.createCollider(e,a)}async addMeshCollider(e,t,i,n){let s=t.geometry;if(!s){Ge&&console.warn("Missing mesh geometry",t.name);return}s.index?.array?.length||(console.warn(`Your MeshCollider is missing vertices or indices in the assined mesh "${t.name}". Consider providing an indexed geometry.`),s=EP(s));let r=null;const a=s.getAttribute("position");if(a instanceof wb){const d=a.count;r=new Float32Array(d*3);for(let p=0;p<d;p++){const m=a.getX(p),g=a.getY(p),f=a.getZ(p);r[p*3]=m,r[p*3+1]=g,r[p*3+2]=f}}else r=a.array;if(await this.initialize(),!this.enabled){Ge&&console.warn("Physics are disabled");return}if(!e.activeAndEnabled)return;const l=s.index?.array,c=e.gameObject.worldScale.clone();if(n&&c.multiply(n),Math.abs(c.x-1)>1e-4||Math.abs(c.y-1)>1e-4||Math.abs(c.z-1)>1e-4){const d=`${s.uuid}_${c.x}_${c.y}_${c.z}_${i}`;if(this._meshCache.has(d))Ge&&console.warn("Use cached mesh collider"),r=this._meshCache.get(d);else{(Ge||A())&&console.debug(`[Performance] Your MeshCollider "${e.name}" is scaled: consider applying the scale to the collider mesh instead (${c.x}, ${c.y}, ${c.z})`);const p=new Float32Array(r.length);for(let m=0;m<r.length;m+=3)p[m]=r[m]*c.x,p[m+1]=r[m+1]*c.y,p[m+2]=r[m+2]*c.z;r=p,this._meshCache.set(d,p)}}const h=i?T.RAPIER_PHYSICS.MODULE.ColliderDesc.convexHull(r):T.RAPIER_PHYSICS.MODULE.ColliderDesc.trimesh(r,l);h&&this.createCollider(e,h)}updatePhysicsMaterial(e){if(!e)return;const t=e.sharedMaterial,i=e[Qt];if(i&&t){if(t.bounciness!==void 0&&i.setRestitution(t.bounciness),t.bounceCombine!==void 0)switch(t.bounceCombine){case vt.Average:i.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case vt.Maximum:i.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case vt.Minimum:i.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case vt.Multiply:i.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}if(t.dynamicFriction!==void 0&&i.setFriction(t.dynamicFriction),t.frictionCombine!==void 0)switch(t.frictionCombine){case vt.Average:i.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case vt.Maximum:i.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case vt.Minimum:i.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case vt.Multiply:i.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}}}getBody(e){return e?e[Qt]:null}getComponent(e){return e?e[Si]: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):(Ge&&console.log("Create collider without rigidbody",e.name),i.makeRotationFromQuaternion(_e(e.gameObject)),i.setPosition(ee(e.gameObject))),i.decompose(this._tempPosition,this._tempQuaternion,this._tempScale),this.tryApplyCenter(e,this._tempPosition),t.setTranslation(this._tempPosition.x,this._tempPosition.y,this._tempPosition.z),t.setRotation(this._tempQuaternion),t.setSensor(e.isTrigger);const s=e.sharedMaterial;if(s){if(s.bounciness!==void 0&&t.setRestitution(s.bounciness),s.bounceCombine!==void 0)switch(s.bounceCombine){case vt.Average:t.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case vt.Maximum:t.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case vt.Minimum:t.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case vt.Multiply:t.setRestitutionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}if(s.dynamicFriction!==void 0&&t.setFriction(s.dynamicFriction),s.frictionCombine!==void 0)switch(s.frictionCombine){case vt.Average:t.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Average);break;case vt.Maximum:t.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Max);break;case vt.Minimum:t.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Min);break;case vt.Multiply:t.setFrictionCombineRule(T.RAPIER_PHYSICS.MODULE.CoefficientCombineRule.Multiply);break}}e.attachedRigidbody?.autoMass===!1&&(t.setDensity(1e-6),t.setMass(1e-6));try{const r=this.world.createCollider(t,n);return r[Si]=e,e[Qt]=r,r.setActiveEvents(T.RAPIER_PHYSICS.MODULE.ActiveEvents.COLLISION_EVENTS),r.setActiveCollisionTypes(T.RAPIER_PHYSICS.MODULE.ActiveCollisionTypes.ALL),this.objects.push(e),this.bodies.push(r),this.updateColliderCollisionGroups(e),Ge&&console.log("Created collider",e.name,r),r}catch(r){return console.error('Error creating collider "'+e.name+`"
|
|
1621
|
+
Error:`,r),null}}updateColliderCollisionGroups(e){const t=e[Qt],i=e.membership;let n=0;if(i==null)n=65535;else for(let a=0;a<i.length;a++){const l=i[a];l>31?console.error(`Rapier only supports 32 layers, layer ${l} is not supported`):n|=1<<Math.floor(l)}const s=e.filter;let r=0;if(s==null)r=65535;else for(let a=0;a<s.length;a++){const l=s[a];l>31?console.error(`Rapier only supports 32 layers, layer ${l} is not supported`):r|=1<<Math.floor(l)}t.setCollisionGroups(n<<16|r)}getRigidbody(e,t){if(!this.world)throw new Error("Physics world not initialized");let i=null;if(e.attachedRigidbody){const n=e.attachedRigidbody;if(i=n[Qt],!i){const s=n.isKinematic&&!sb;Ge&&console.log("Create rigidbody",s);const r=s?T.RAPIER_PHYSICS.MODULE.RigidBodyDesc.kinematicPositionBased():T.RAPIER_PHYSICS.MODULE.RigidBodyDesc.dynamic(),a=ee(e.attachedRigidbody.gameObject);r.setTranslation(a.x,a.y,a.z),r.setRotation(_e(e.attachedRigidbody.gameObject)),r.centerOfMass=new T.RAPIER_PHYSICS.MODULE.Vector3(n.centerOfMass.x,n.centerOfMass.y,n.centerOfMass.z),i=this.world.createRigidBody(r),this.bodies.push(i),this.objects.push(n)}i[Si]=n,n[Qt]=i,this.internalUpdateRigidbodyProperties(n,i),this.getRigidbodyRelativeMatrix(e.gameObject,n.gameObject,t),e[OS]=i}else{const n=T.RAPIER_PHYSICS.MODULE.RigidBodyDesc.kinematicPositionBased(),s=ee(e.gameObject);n.setTranslation(s.x,s.y,s.z),n.setRotation(_e(e.gameObject)),i=this.world.createRigidBody(n),t.identity(),i[Si]=null}return i}internal_getRigidbody(e){return e.isCollider===!0?e[OS]:e[Qt]}internalUpdateColliderProperties(e,t){const i=t.shape;let n=!1;switch(i.type){case T.RAPIER_PHYSICS.MODULE.ShapeType.Ball:{const p=i,m=e,g=e.gameObject,f=$e(g,this._tempPosition),y=Math.abs(m.radius*f.x);n=p.radius!==y,p.radius=y,n&&t.setShape(p);break}case T.RAPIER_PHYSICS.MODULE.ShapeType.Cuboid:const s=i,r=e,a=e.gameObject,l=$e(a,this._tempPosition),c=Math.abs(r.size.x*.5*l.x),h=Math.abs(r.size.y*.5*l.y),d=Math.abs(r.size.z*.5*l.z);n=s.halfExtents.x!==c||s.halfExtents.y!==h||s.halfExtents.z!==d,s.halfExtents.x=c,s.halfExtents.y=h,s.halfExtents.z=d,n&&t.setShape(s);break}if(n){const s=e.attachedRigidbody;s?.autoMass&&this.getBody(s)?.recomputeMassPropertiesFromColliders()}this.updateColliderCollisionGroups(e),e.isTrigger!==t.isSensor()&&t.setSensor(e.isTrigger)}internalUpdateRigidbodyProperties(e,t){if(t.enableCcd(e.collisionDetectionMode!==Bu.Discrete),t.setLinearDamping(e.drag),t.setAngularDamping(e.angularDrag),t.setGravityScale(e.useGravity?e.gravityScale:0,!0),e.dominanceGroup<=127&&e.dominanceGroup>=-127?t.setDominanceGroup(Math.floor(e.dominanceGroup)):t.setDominanceGroup(0),e.autoMass){t.setAdditionalMass(0,!1);for(let i=0;i<t.numColliders();i++)t.collider(i).setDensity(1);t.recomputeMassPropertiesFromColliders()}else{t.setAdditionalMass(e.mass,!1);for(let i=0;i<t.numColliders();i++)t.collider(i).setDensity(1e-7);t.recomputeMassPropertiesFromColliders()}t.setEnabledRotations(!e.lockRotationX,!e.lockRotationY,!e.lockRotationZ,!1),t.setEnabledTranslations(!e.lockPositionX,!e.lockPositionY,!e.lockPositionZ,!1),e.isKinematic?t.setBodyType(T.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicPositionBased,!1):t.setBodyType(T.RAPIER_PHYSICS.MODULE.RigidBodyType.Dynamic,!1)}lines;step(e){if(this.world&&this.enabled){if(this._isUpdatingPhysicsWorld=!0,this.eventQueue||(this.eventQueue=new T.RAPIER_PHYSICS.MODULE.EventQueue(!1)),e===void 0||e<=0){this._isUpdatingPhysicsWorld=!1;return}else if(e!==void 0){const t=j.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 tj(this.world,this.eventQueue)),this.collisionHandler&&(this.collisionHandler.handleCollisionEvents(),this.collisionHandler.update()),this.updateDebugRendering(this.world))}updateDebugRendering(e){if(Ge||sb||ej||this.debugRenderColliders===!0){if(!this.lines){const i=new Em({color:7855479,fog:!1}),n=new wn;this.lines=new vb(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 ft(t.vertices,3)),this.lines.geometry.setAttribute("color",new ft(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(!sb)for(let e=0;e<this.bodies.length;e++){const t=this.objects[e],i=this.bodies[e],n=t;if(n?.isCollider===!0&&!n.attachedRigidbody){const l=i.parent();l?this.syncPhysicsBody(t.gameObject,l,!0,!0):this.syncPhysicsBody(t.gameObject,i,!0,!0);continue}const s=i.translation(),r=i.rotation();if(Number.isNaN(s.x)||Number.isNaN(r.x)){!n.__COLLIDER_NAN&&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),c=$e(t.gameObject);l.multiply(c),s.x-=l.x,s.y-=l.y,s.z-=l.z}Sr(t.gameObject,s.x,s.y,s.z),hg(t.gameObject,r.x,r.y,r.z,r.w)}}syncPhysicsBody(e,t,i,n){if(t instanceof T.RAPIER_PHYSICS.MODULE.RigidBody){const s=ee(e,this._tempPosition),r=_e(e,this._tempQuaternion);switch(t.bodyType()){case T.RAPIER_PHYSICS.MODULE.RigidBodyType.Fixed:case T.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicPositionBased:case T.RAPIER_PHYSICS.MODULE.RigidBodyType.KinematicVelocityBased:i&&t.setNextKinematicTranslation(s),n&&t.setNextKinematicRotation(r);break;default:i&&t.setTranslation(s,!1),n&&t.setRotation(r,!1);break}}else if(t instanceof T.RAPIER_PHYSICS.MODULE.Collider){e.matrixWorldNeedsUpdate&&e.updateWorldMatrix(!0,!1),e.matrixWorld.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const s=this._tempPosition,r=this._tempQuaternion,a=t[Si];if(this.tryApplyCenter(a,s),i){const l=t.translation();(l.x!==s.x||l.y!==s.y||l.z!==s.z)&&t.setTranslation(s)}if(n){const l=t.rotation();(l.x!==r.x||l.y!==r.y||l.z!==r.z||l.w!==r.w)&&t.setRotation(r)}}}_tempCenterPos=new b;_tempCenterVec=new b;_tempCenterQuaternion=new N;tryApplyCenter(e,t){const i=e.center;i&&e.gameObject&&(i.x!==0||i.y!==0||i.z!==0)&&(this._tempCenterPos.x=i.x,this._tempCenterPos.y=i.y,this._tempCenterPos.z=i.z,$e(e.gameObject,this._tempCenterVec),this._tempCenterPos.multiply(this._tempCenterVec),e.attachedRigidbody?this._tempCenterPos.applyQuaternion(e.gameObject.quaternion):(_e(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=lc._matricesBuffer,n.length=0),e===t){const s=$e(e,this._tempPosition);i.makeScale(s.x,s.y,s.z);for(let r=n.length-1;r>=0;r--)i.multiply(n[r]);return i}return n.push(e.matrix),e.parent&&this.getRigidbodyRelativeMatrix(e.parent,t,i,n),i}static centerConnectionPos={x:0,y:0,z:0};static centerConnectionRot={x:0,y:0,z:0,w:1};addFixedJoint(e,t){if(!this.world){console.error("Physics world not initialized");return}const i=e[Qt],n=t[Qt];this.calculateJointRelativeMatrices(e.gameObject,t.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const s=T.RAPIER_PHYSICS.MODULE.JointData.fixed(lc.centerConnectionPos,lc.centerConnectionRot,this._tempPosition,this._tempQuaternion),r=this.world.createImpulseJoint(s,i,n,!0);Ge&&console.log("ADD FIXED JOINT",r)}addHingeJoint(e,t,i,n){if(!this.world){console.error("Physics world not initialized");return}const s=e[Qt],r=t[Qt];this.calculateJointRelativeMatrices(e.gameObject,t.gameObject,this._tempMatrix),this._tempMatrix.decompose(this._tempPosition,this._tempQuaternion,this._tempScale);const a=T.RAPIER_PHYSICS.MODULE.JointData.revolute(i,this._tempPosition,n),l=this.world.createImpulseJoint(a,s,r,!0);Ge&&console.log("ADD HINGE JOINT",l)}calculateJointRelativeMatrices(e,t,i){e.updateWorldMatrix(!0,!1),t.updateWorldMatrix(!0,!1);const n=e.matrixWorld,s=t.matrixWorld;n.elements[0]=1,n.elements[5]=1,n.elements[10]=1,s.elements[0]=1,s.elements[5]=1,s.elements[10]=1,i.copy(s).premultiply(n.invert()).invert()}}class tj{world;eventQueue;constructor(e,t){this.world=e,this.eventQueue=t}activeCollisions=[];activeCollisionsStay=[];activeTriggers=[];handleCollisionEvents(){this.eventQueue&&this.world&&this.eventQueue.drainCollisionEvents((e,t,i)=>{const n=this.world.getCollider(e),s=this.world.getCollider(t);if(!n||!s)return;const r=n[Si],a=s[Si];rb&&console.log("EVT",r.name,a.name,i,n,s),r&&a&&(i?(this.onCollisionStarted(r,n,a,s),this.onCollisionStarted(a,s,r,n)):(this.onCollisionEnded(r,a),this.onCollisionEnded(a,r)))})}update(){this.onHandleCollisionStay()}onCollisionStarted(e,t,i,n){let s=null;if(e.isTrigger||i.isTrigger)Fr(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)=>{Fr(r,c=>{if(c.destroyed)return;const h=c.onCollisionEnter||c.onCollisionStay||c.onCollisionExit;if(h||rb){if(!s){const d=[],p=a.normal();i instanceof Bs&&i.convex&&(p.x=-p.x,p.y=-p.y,p.z=-p.z);for(let m=0;m<a.numSolverContacts();m++){const g=a.solverContactPoint(m),f=a.contactImpulse(m);if(g){const y=a.contactDist(m),_=a.solverContactFriction(m),v=a.solverContactTangentVelocity(m),P=new $_(g,y,p,f,_,v);d.push(P),rb&&B.DrawDirection(g,p,16711680,3,!0)}}s=new H_(r,i,d)}if(h){const d={collider:e,component:c,collision:s};this.activeCollisions.push(d),c.onCollisionStay&&this.activeCollisionsStay.push(d),c.onCollisionEnter?.call(c,s)}}})})}}onHandleCollisionStay(){for(const e of this.activeCollisionsStay){const t=e.component;if(!t.destroyed&&t.activeAndEnabled&&t.onCollisionStay){if(e.collision.collider.destroyed)continue;const i=e.collision;t.onCollisionStay(i)}}for(const e of this.activeTriggers){const t=e.component;if(!t.destroyed&&t.activeAndEnabled&&t.onTriggerStay){const i=e.otherCollider;if(i.destroyed)continue;t.onTriggerStay(i)}}}onCollisionEnded(e,t){if(!(e.destroyed||t.destroyed)){for(let i=0;i<this.activeCollisions.length;i++){const n=this.activeCollisions[i],s=n.collider;if(s.destroyed||n.collision.collider.destroyed){this.activeCollisions.splice(i,1),i--;continue}if(s===e&&n.collision.collider===t){const r=n.component;if(this.activeCollisions.splice(i,1),i--,r.activeAndEnabled&&r.onCollisionExit){const a=n.collision;r.onCollisionExit(a)}}}for(let i=0;i<this.activeCollisionsStay.length;i++){const n=this.activeCollisionsStay[i],s=n.collider;if(s.destroyed||n.collision.collider.destroyed){this.activeCollisionsStay.splice(i,1),i--;continue}if(s===e&&n.collision.collider===t){const r=n.component;if(this.activeCollisionsStay.splice(i,1),i--,r.activeAndEnabled&&r.onCollisionExit){const a=n.collision;r.onCollisionExit(a)}}}for(let i=0;i<this.activeTriggers.length;i++){const n=this.activeTriggers[i],s=n.collider;if(s.destroyed||n.otherCollider.destroyed){this.activeTriggers.splice(i,1),i--;continue}if(s===e&&n.otherCollider===t){const r=n.component;if(this.activeTriggers.splice(i,1),i--,r.activeAndEnabled&&r.onTriggerExit){const a=n.otherCollider;r.onTriggerExit(a)}}}}}}let ab=0;function kS(o){o?ab++:ab--}function ij(){return ab>0}const nj={binary:!0,animations:!0};async function oj(o){if(!o.context)throw new Error("No context provided to exportAsGLTF");o.scene||(o.scene=o.context.scene);const e={...nj,...o},{context:t}=e,i=new Bb;i.register(a=>new Hx(a)),i.register(a=>new IT(a)),i.register(a=>new qx(a)),dy(i,e.context);const n={binary:e.binary,animations:rj(t,e.scene,[])},s=new sj;console.debug("Exporting GLTF",n),s.onBeforeExport(e),kS(!0);const r=await i.parseAsync(e.scene,n).catch(a=>(console.error(a),null));if(kS(!1),s.onAfterExport(e),!r)throw new Error("Failed to export GLTF");if(e.downloadAs!=null){let a=null;if(r instanceof ArrayBuffer?a=new Blob([r],{type:"application/octet-stream"}):console.error("Can not download GLTF as a blob",r),a){const l=URL.createObjectURL(a),c=document.createElement("a");c.href=l;let h=e.downloadAs;!h.endsWith(".glb")&&!h.endsWith(".gltf")&&(h+=e.binary?".glb":".gltf"),c.download=h,c.click()}}return r}const MS=Symbol("needle:weight");class sj{_undo=[];onBeforeExport(e){e.context.animations.mixers.forEach(t=>{const i=Qn.tryGetActionsFromMixer(t);if(i)for(let n=0;n<i.length;n++){const s=i[n];s[MS]=s.weight,s.weight=0,this._undo.push(()=>{s.weight=s[MS]})}t.update(0)}),e.context.scene.traverse(t=>{if(!by(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 rj(o,e,t){o.animations.mixers.forEach(n=>{const s=Qn.tryGetActionsFromMixer(n);if(s)for(let r=0;r<s.length;r++){const a=s[r].getClip();t.push(a)}}),Array.isArray(e)||(e=[e]);for(const n of e)Qn.tryGetAnimationClipsFromObjectHierarchy(n,t);const i=new Set(t);return Array.from(i)}const ES="needle-button",lb=A();class RS extends HTMLElement{static observedAttributes=["ar","vr","quicklook","qrcode"];constructor(){super(),this.removeEventListener("click",this.#a),this.addEventListener("click",this.#a)}attributeChangedCallback(e,t,i){this.#l()}#t;#n;#o;#e;#i;#r;#s;#l(){if(this.#e?.remove(),this.getAttribute("ar")!=null)this.#i??=new ur,this.#e=this.#i.createARButton(),this.setAttribute("aria-label","Enter augmented reality mode");else if(this.getAttribute("vr")!=null)this.#i??=new ur,this.#e=this.#i.createVRButton(),this.setAttribute("aria-label","Enter virtual reality mode");else if(this.getAttribute("quicklook")!=null)this.#i??=new ur,this.#e=this.#i.createQuicklookButton(),this.setAttribute("aria-label","View in AR with Apple Quick Look");else if(this.getAttribute("qrcode")!=null)this.#r??=new mn,this.#e=this.#r.createQRCode({anchorElement:this}),this.setAttribute("aria-label","Share application with QR code");else{lb?console.warn("No button type specified for <needle-button>. Use either ar, vr or quicklook attribute."):console.debug("No button type specified for <needle-button>. Use either ar, vr or quicklook attribute."),this.setAttribute("aria-label","Needle Button with no specified type");return}this.#t??=this.attachShadow({mode:"open"}),this.#n??=document.createElement("slot"),this.#o??=document.createElement("style"),this.#o.innerHTML=`
|
|
1622
1622
|
button {
|
|
1623
1623
|
all: unset;
|
|
1624
1624
|
}
|
|
@@ -1651,4 +1651,4 @@ Error:`,r),null}}updateColliderCollisionGroups(e){const t=e[Qt],i=e.membership;l
|
|
|
1651
1651
|
justify-content: center;
|
|
1652
1652
|
gap: .5rem;
|
|
1653
1653
|
}
|
|
1654
|
-
`),this.#n.innerHTML=this.#e.innerHTML,this.#n.style.cssText="display: flex; align-items: center; justify-content: center;",this.#e.innerHTML=this.#n.outerHTML,this.#t.innerHTML=this.#e.outerHTML,this.#t.prepend(this.#o),ku(Sf,{element:this.#t}),this.#s?.disconnect(),this.#s??=new MutationObserver(()=>this.#c()),this.#s.observe(this.#e,{attributes:!0}),lb&&console.log("Needle Button updated",this)}#c(){this.#e&&(this.#e.style.display==="none"?this.style.display="none":this.style.display==="none"&&(this.style.display=""))}#a=e=>{lb&&console.log("Needle Button clicked",{defaultPrevented:e.defaultPrevented,hasButton:!!this.#e}),!e.defaultPrevented&&this.#e&&this.#e.click()}}typeof window<"u"&&!window.customElements.get(ES)&&window.customElements.define(ES,RS);const ud=w("debugavatar");class cb{root;head;leftHand;rigthHand;get isValid(){return this.head!==null&&this.head!==void 0}constructor(e,t,i,n){this.root=e,this.head=t,this.leftHand=i,this.rigthHand=n,this.root?.traverse(s=>s.layers.set(2))}}class TS{avatarRegistryUrl=null;async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let i=null;if(typeof t=="string"){if(i=await this.loadAvatar(e,t),!i){const s=new Wn;i=S.instantiate(Ba(t,e.scene),s)}}else i=t;if(!i)return null;const n=this.findAvatar(i);return n.isValid?(ud&&console.log("[Custom Avatar] valid config",t,ud?n:""),n):(console.warn("[Custom Avatar] config isn't valid",t,ud?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(ud&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){const n=await fetch("./"+t);let s=null;if(n.ok){const r=await n.blob();r&&(s=await r.arrayBuffer())}return s?(await Cn().parseSync(e,s,null,0))?.scene??null:null}const i=new Eo;return Af(i,e),new Promise((n,s)=>{const r=this.avatarRegistryUrl+"/"+t;i.load(r,async a=>{await Cn().createBuiltinComponents(e,r,a,null,void 0),n(a.scene)},a=>{ud&&console.log("[Custom Avatar] "+a.loaded/a.total*100+"% loaded of "+a.total/1024+"kB")},a=>{console.error("[Custom Avatar] Error when loading: "+a),n(null)})})}cacheModel(e,t){}findAvatar(e){const t=e;let i=t;i.children.length==1&&(i=e.children[0]);let n=this.findAvatarPart(i,["head"]);const s=this.findAvatarPart(i,["left","hand"]),r=this.findAvatarPart(i,["right","hand"]);if(!n){n=t;const a=new b;new Yt().setFromObject(n).getSize(a);const l=Math.max(a.x,a.y,a.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+l+" meters! Should be < 0.3m"),l>.3&&n.scale.multiplyScalar(1/l*.3)}return new cb(t,n,s,r)}findAvatarPart(e,t){const i=e.name.toLowerCase();let n=!0;for(const s of t){if(!n)break;i.indexOf(s)===-1&&(n=!1)}if(n)return e;if(e.children)for(const s of e.children){const r=this.findAvatarPart(s,t);if(r)return r}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}}class AS{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(e){}}class IS{}const aj=Object.freeze(Object.defineProperty({__proto__:null,ActionBuilder:fe,ActionCollection:f1,ActionModel:Ci,AlignmentConstraint:Gc,Animation:Ut,AnimationCurve:Ch,AnimationExtension:_p,AnimationTrackHandler:Gh,Animator:_t,AnimatorController:gn,Antialiasing:Eh,Attractor:Wl,AudioExtension:Pa,AudioListener:Wo,AudioSource:ji,AudioTrackHandler:ys,Avatar:Vs,AvatarBlink_Simple:Gr,AvatarEyeLook_Rotation:Gf,AvatarLoader:TS,AvatarMarker:Le,AvatarModel:cb,Avatar_Brain_LookAt:eh,Avatar_MouthShapes:th,Avatar_MustacheShake:$f,Avatar_POI:Hr,AxesHelper:ul,BaseUIComponent:un,BasicIKConstraint:Xf,BehaviorExtension:Hy,BehaviorModel:jt,BloomEffect:$p,BoxCollider:qu,BoxGizmo:sa,BoxHelperComponent:Bt,Button:rs,CallInfo:No,Camera:yi,CameraTargetReachedEvent:Jc,Canvas:Ll,CanvasGroup:Xs,CapsuleCollider:Vo,ChangeMaterialOnClick:Ay,ChangeTransformOnClick:ea,CharacterController:qr,CharacterControllerInput:Ho,ChromaticAberration:Rh,ClickThrough:um,ColorAdjustments:tr,ColorBySpeedModule:zl,ColorOverLifetimeModule:Bp,ContactShadows:nh,ControlTrackHandler:sm,CursorFollow:va,CustomBranding:oa,Deletable:Jf,DeleteBox:gr,DepthOfField:Dn,DeviceFlag:Xu,DocumentExtension:AS,DragControls:Yr,DropListener:Qo,Duplicatable:gy,EffectWrapper:Ah,EmissionModule:is,EmphasizeOnClick:Ol,EnvironmentScene:hm,EventList:ae,EventListEvent:Uu,EventSystem:li,EventTrigger:cp,FieldWithDefault:$x,FixedJoint:c0,Fog:jl,GltfExport:wy,GltfExportBox:_y,Gradient:aa,Graphic:vh,GraphicRaycaster:Wu,GridHelper:Dl,GridLayoutGroup:e0,GroundProjectedEnv:Jn,GroupActionModel:Jr,HideOnStart:fn,HingeJoint:Sh,HorizontalLayoutGroup:Jy,get HoverAnimation(){return bo},Image:Xl,InheritVelocityModule:f0,InputField:$0,InstanceHandle:Ra,InstancingHandler:Oa,Interactable:Kf,Keyframe:wi,LODGroup:Rp,LODModel:Fl,Light:Tt,LimitVelocityOverLifetimeModule:dt,LogStats:Zf,LookAt:H0,LookAtConstraint:Wr,MainModule:Gt,MarkerTrackHandler:om,MaskableGraphic:wh,MeshCollider:Bs,MeshRenderer:ah,MinMaxCurve:Y,MinMaxGradient:la,NeedleMenu:co,NestedGltf:Ul,Networking:p0,NoiseModule:ve,ObjectRaycaster:Ji,OffsetConstraint:ra,OpenURL:Ql,OrbitControls:ge,Outline:Al,Padding:na,ParticleBurst:Dp,ParticleSubEmitter:y0,ParticleSystem:kh,ParticleSystemRenderer:ln,PhysicsExtension:Gy,PixelationEffect:Ih,PlayAnimationOnClick:hh,PlayAudioOnClick:Ns,PlayableDirector:ya,PlayerColor:rc,PointerEventData:vd,PostProcessingHandler:L0,PreliminaryAction:kl,PreliminaryTrigger:dh,RawImage:lm,Rect:S1,RectTransform:Ln,ReflectionProbe:qo,RegisteredAnimationInfo:fr,RemoteSkybox:Yp,Renderer:ti,RendererLightmap:uy,Rigidbody:Ke,RotationBySpeedModule:an,RotationOverLifetimeModule:jn,SceneSwitcher:Je,ScreenCapture:nr,ScreenSpaceAmbientOcclusion:ns,ScreenSpaceAmbientOcclusionN8:Bn,ScrollFollow:as,SeeThrough:ss,SetActiveOnClick:Iy,ShadowCatcher:Uh,ShapeModule:g0,SharpeningEffect:jh,SignalAsset:nm,SignalReceiver:Hh,SignalReceiverEvent:$h,SignalTrackHandler:qh,Size:x1,SizeBySpeedModule:xi,SizeOverLifetimeModule:ca,SkinnedMeshRenderer:py,SmoothFollow:Kp,SpatialGrabRaycaster:Ca,SpatialHtml:Qh,SpatialTrigger:Jp,SpatialTriggerReceiver:mo,SpectatorCamera:em,SphereCollider:pl,SplineContainer:fa,SplineData:go,SplineWalker:hn,Sprite:Zo,SpriteData:El,SpriteRenderer:_i,SpriteSheet:Ml,SubEmitterSystem:Np,SyncedCamera:D0,SyncedRoom:Fn,SyncedTransform:Tn,TapGestureTrigger:jy,TeleportTarget:Cp,TestRunner:U0,TestSimulateUserData:z0,Text:Ht,TextBuilder:Zy,TextExtension:Mp,TextureSheetAnimationModule:qt,TiltShiftEffect:po,ToneMappingEffect:er,TrailModule:Fe,TransformData:Ne,TransformGizmo:ba,TriggerBuilder:$t,TriggerModel:dr,UIRaycastUtils:Bf,UIRootComponent:yh,USDZExporter:uo,USDZText:Il,USDZUIExtension:n0,UsageMarker:oh,VariantAction:Ry,VelocityOverLifetimeModule:He,VerticalLayoutGroup:Ky,VideoPlayer:pt,get ViewBox(){return st},Vignette:pa,VisibilityAction:uh,Voip:Ds,Volume:$l,VolumeParameter:z,VolumeProfile:Wp,WebARCameraBackground:ed,WebARSessionRoot:yn,WebXR:Pp,WebXRImageTracking:id,WebXRImageTrackingModel:cs,WebXRPlaneTracking:hs,WebXRTrackedImage:ac,XRControllerFollow:ls,XRControllerModel:Ko,XRControllerMovement:Bi,XRFlag:tn,XRRig:fm,XRState:ai,__Ignore:IS},Symbol.toStringTag,{value:"Module"})),pd=w("debugmissingcamera");pe.registerCallback(ue.MissingCamera,o=>{pd&&console.warn("Creating missing camera");const e=o.context.scene,t=new de;t.name="Default Fallback Camera",e.add(t);const i=new yi;if(i.sourceId=o.files?.[0]?.src??"unknown",i.fieldOfView=35,o.context.domElement.getAttribute("transparent")!=null)i.clearFlags=$r.Uninitialized;else if(o.context.domElement.getAttribute("background-image")?.length||o.context.lightmaps.tryGetSkybox(i.sourceId))i.clearFlags=$r.Skybox;else{if(i.clearFlags=$r.SolidColor,!o.context.domElement.getAttribute("background-color")){let s="#efefef";typeof window!==void 0&&window.matchMedia("(prefers-color-scheme: dark)").matches&&(s="#1f1f1f"),e.background=new oe(s)}if(!e.environment){const s=new rP(o.context.renderer),r=new hm("neutral");e.environment=s.fromScene(r,.025).texture}}const n=Lr(t,i,!0);return t.position.x=0,t.position.y=1,t.position.z=2,o.context.domElement?.cameraControls!=!1&&LS(o.context,n),n}),pe.registerCallback(ue.ContextCreated,o=>{if(!o.context.mainCamera){pd&&console.log("Will not auto-fit because a default camera exists");return}if(o.context.domElement?.cameraControls==!0){if(m_(o.context.mainCamera)?.isCameraController==!0){pd&&console.log("Will not auto-fit because a camera controller exists");return}LS(o.context)}});function LS(o,e){e=e??o.mainCameraComponent;const t=e?.gameObject;if(pd&&console.log("Creating default camera controls",e?.name),t){const i=Dc(t,ge);i.sourceId=e?.sourceId??"unknown";const n=o.domElement.getAttribute("auto-rotate");i.autoRotate=n!="0"&&n?.toLowerCase()!="false";const s=Number.parseFloat(n||".5");i.autoRotateSpeed=isNaN(s)?.5:s,pd&&console.log("Auto-rotate",i.autoRotate,"speed:",i.autoRotateSpeed);const r=o.domElement.getAttribute("auto-fit");i.autoFit=r!=="0"&&r?.toLowerCase()!="false",i.autoTarget=!0}else console.warn("Missing camera object, can not add orbit controls")}pe.registerCallback(ue.ContextCreated,o=>{const e=o.context.domElement.getAttribute("autoplay");if(e!==void 0&&(e===""||e==="true"||e==="1")&&o.files)for(const t of o.files)S.foreachComponent(t.file.scene,i=>{if(i.enabled!==!1){if(i instanceof Ut&&i.playAutomatically||i instanceof _t||i instanceof ya&&i.playOnAwake===!0)return!0;if(i instanceof Ut)return i.playAutomatically=!0,!0;if(i instanceof ya)return i.playOnAwake=!0,!0}},!0)!==!0&&Qn.autoplayAnimations(t.file)});var hb;(o=>{function e(t,i=!1,n=.75){const s=new fa,r=1-D.clamp(n,0,1);return t.forEach((a,l)=>{const c=new b;l<t.length-1?c.subVectors(t[l+1],a).normalize().multiplyScalar(r):i&&t.length>1&&c.subVectors(t[0],a).normalize().multiplyScalar(r);const h=new go;h.position.copy(a),h.tangentIn.copy(c),h.tangentOut.copy(c),s.addKnot(h)}),s.closed=i,s}o.createFromPoints=e})(hb||(hb={}));class lj extends UP{constructor(){super(new Worker(URL.createObjectURL(new Blob([`import '${new URL("./generateMeshBVH.worker-DiCnZlf3.js",import.meta.url).toString()}';`],{type:"text/javascript"})),{type:"module"})),this.name="GenerateMeshBVHWorker"}runTask(e,t,i={}){return new Promise((n,s)=>{if(t.getAttribute("position").isInterleavedBufferAttribute||t.index&&t.index.isInterleavedBufferAttribute)throw new Error("GenerateMeshBVHWorker: InterleavedBufferAttribute are not supported for the geometry attributes.");e.onerror=c=>{s(new Error(`[GenerateMeshBVHWorker] ${c.message||"Unknown error. Please check the server console. If you're using vite try adding 'three-mesh-bvh' to 'optimizeDeps.exclude' in your vite.config.js"}`))},e.onmessage=c=>{const{data:h}=c;if(h.error)s(new Error(h.error)),e.onmessage=null;else if(h.serialized){const{serialized:d,position:p}=h,m=zP.deserialize(d,t,{setIndex:!1}),g=Object.assign({setBoundingBox:!0},i);if(t.attributes.position.array=p,d.index)if(t.index)t.index.array=d.index;else{const f=new ft(d.index,1,!1);t.setIndex(f)}g.setBoundingBox&&(t.boundingBox=m.getBoundingBox(new Yt)),i.onProgress&&i.onProgress(h.progress),n(m),e.onmessage=null}else i.onProgress&&i.onProgress(h.progress)};const r=t.index?t.index.array:null,a=t.attributes.position.array,l=[a];r&&l.push(r),e.postMessage({index:r,position:a,options:{...i,onProgress:null,includedProgressCallback:!!i.onProgress,groups:[...t.groups]}},l.map(c=>c.buffer).filter(c=>typeof SharedArrayBuffer>"u"||!(c instanceof SharedArrayBuffer)))})}}const cj=Object.freeze(Object.defineProperty({__proto__:null,GenerateMeshBVHWorker:lj},Symbol.toStringTag,{value:"Module"}));export{V_ as $componentName,bk as $physicsKey,fe as ActionBuilder,f1 as ActionCollection,Ci as ActionModel,xw as Addressables,Gc as AlignmentConstraint,rl as AmbientMode,Ut as Animation,Ch as AnimationCurve,_p as AnimationExtension,Gh as AnimationTrackHandler,Qn as AnimationUtils,_t as Animator,As as AnimatorConditionMode,gn as AnimatorController,Lf as AnimatorControllerParameterType,qc as AnimatorStateInfo,Eh as Antialiasing,Nn as Application,Mv as AssetDatabase,ne as AssetReference,Wl as Attractor,Pa as AudioExtension,Wo as AudioListener,ji as AudioSource,ys as AudioTrackHandler,Vs as Avatar,Gr as AvatarBlink_Simple,Gf as AvatarEyeLook_Rotation,TS as AvatarLoader,Le as AvatarMarker,cb as AvatarModel,eh as Avatar_Brain_LookAt,th as Avatar_MouthShapes,$f as Avatar_MustacheShake,Hr as Avatar_POI,cl as Axes,ul as AxesHelper,wc as BUILD_TIME,un as BaseUIComponent,Xf as BasicIKConstraint,Hy as BehaviorExtension,jt as BehaviorModel,zr as BlobStorage,$p as BloomEffect,qu as BoxCollider,sa as BoxGizmo,Bt as BoxHelperComponent,rs as Button,mn as ButtonsFactory,yx as CallDirection,No as CallInfo,yi as Camera,Jc as CameraTargetReachedEvent,Ll as Canvas,Xs as CanvasGroup,Vo as CapsuleCollider,Ay as ChangeMaterialOnClick,ea as ChangeTransformOnClick,qr as CharacterController,Ho as CharacterControllerInput,Rh as ChromaticAberration,Ei as CircularBuffer,$r as ClearFlags,um as ClickThrough,fo as ClipExtrapolation,nn as Collider,H_ as Collision,Bu as CollisionDetectionMode,tr as ColorAdjustments,zl as ColorBySpeedModule,Bp as ColorOverLifetimeModule,IE as Component,E as Component$1,au as ComponentLifecycleEvents,aj as Components,uv as ConnectionEvents,$_ as ContactPoint,nh as ContactShadows,U as Context,bE as ContextArgs,ue as ContextEvent,pe as ContextRegistry,sm as ControlTrackHandler,va as CursorFollow,oa as CustomBranding,Te as CustomShader,Pu as DefaultReflectionMode,Jf as Deletable,gr as DeleteBox,Dn as DepthOfField,Xu as DeviceFlag,I as DeviceUtilities,AS as DocumentExtension,Yr as DragControls,ty as DragMode,Qo as DropListener,gy as Duplicatable,Ah as EffectWrapper,is as EmissionModule,Ol as EmphasizeOnClick,xd as EngineLoadingView,hm as EnvironmentScene,ae as EventList,Uu as EventListEvent,li as EventSystem,cp as EventTrigger,$x as FieldWithDefault,Ea as FileReference,Cw as FileReferenceSerializer,XR as FileSpawnModel,Px as File_Event,c0 as FixedJoint,jl as Fog,xe as FrameEvent,Wa as GENERATOR,S as GameObject,B as Gizmos,wy as GltfExport,_y as GltfExportBox,aa as Gradient,vh as Graphic,Wu as GraphicRaycaster,pr as Graphics,Dl as GridHelper,e0 as GridLayoutGroup,Jn as GroundProjectedEnv,Jr as GroupActionModel,Gd as HideFlags,fn as HideOnStart,Sh as HingeJoint,Jy as HorizontalLayoutGroup,_M as HostData,bo as HoverAnimation,Xl as Image,Ma as ImageReference,Sw as ImageReferenceSerializer,f0 as InheritVelocityModule,J_ as Input,pi as InputEventQueue,Ae as InputEvents,$0 as InputField,Ra as InstanceHandle,Oa as InstancingHandler,pn as InstancingUtil,Vv as InstantiateEvent,Dt as InstantiateIdProvider,Wn as InstantiateOptions,Kf as Interactable,Jh as InternalScreenshotUtils,jk as JoinedRoomResponse,Ck as KeyEventArgs,wi as Keyframe,Rp as LODGroup,Fl as LODModel,Dk as LeftRoomResponse,Tt as Light,Aw as LightData,dt as LimitVelocityOverLifetimeModule,qL as LoadingElementOptions,Zf as LogStats,Ri as LogType,H0 as LookAt,Wr as LookAtConstraint,T as MODULES,Gt as MainModule,om as MarkerTrackHandler,N0 as MarkerType,wh as MaskableGraphic,ms as MaterialPropertyBlock,np as MaterialX,D as Mathf,Bs as MeshCollider,ah as MeshRenderer,Y as MinMaxCurve,la as MinMaxGradient,Ac as NEEDLE_ENGINE_FEATURE_FLAGS,Sc as NEKeyboardEvent,Lo as NEPointerEvent,RS as NeedleButtonElement,ny as NeedleEngineModelLoader,ob as NeedleEngineWebComponent,co as NeedleMenu,Xd as NeedlePatchesKey,Pg as NeedleXRController,Z as NeedleXRSession,gv as NeedleXRSync,xv as NeedleXRUtils,Ul as NestedGltf,mv as NetworkConnection,to as NetworkedStreamEvents,wd as NetworkedStreams,p0 as Networking,Hv as NewInstanceModel,ve as NoiseModule,Ji as ObjectRaycaster,Os as ObjectUtils,ra as OffsetConstraint,Ud as OneEuroFilter,og as OneEuroFilterXYZ,Ql as OpenURL,ge as OrbitControls,Al as Outline,pv as OwnershipEvent,Tg as OwnershipModel,Ss as PUBLIC_KEY,na as Padding,Dp as ParticleBurst,y0 as ParticleSubEmitter,kh as ParticleSystem,Js as ParticleSystemBaseBehaviour,ln as ParticleSystemRenderer,jp as ParticleSystemShapeType,fs as PeerHandle,hv as PeerNetworking,oc as Physics,Gy as PhysicsExtension,vt as PhysicsMaterialCombine,Ih as PixelationEffect,hh as PlayAnimationOnClick,Ns as PlayAudioOnClick,ya as PlayableDirector,rc as PlayerColor,sn as PlayerState,v1 as PlayerStateEvent,Ny as PlayerSync,kw as PlayerView,Mw as PlayerViewManager,vd as PointerEventData,Yd as PointerType,nt as PostProcessingEffect,ut as PostProcessingEffectOrder,L0 as PostProcessingHandler,kl as PreliminaryAction,dh as PreliminaryTrigger,Us as PreviewHelper,Qa as PrimitiveType,le as Progress,Jm as PromiseAllWithErrors,Km as PromiseErrorResult,se as RGBAColor,lc as RapierPhysics,lm as RawImage,ks as RaycastOptions,S1 as Rect,Ln as RectTransform,qo as ReflectionProbe,fr as RegisteredAnimationInfo,Yp as RemoteSkybox,xo as RenderTexture,ux as RenderTextureSerializer,ti as Renderer,Tw as RendererData,uy as RendererLightmap,Ke as Rigidbody,Ze as RigidbodyConstraints,ie as RoomEvents,an as RotationBySpeedModule,jn as RotationOverLifetimeModule,ip as SceneLightSettings,Je as SceneSwitcher,nr as ScreenCapture,ns as ScreenSpaceAmbientOcclusion,Bn as ScreenSpaceAmbientOcclusionN8,as as ScrollFollow,ss as SeeThrough,Pn as SendQueue,rf as SerializationContext,Iy as SetActiveOnClick,Uh as ShadowCatcher,g0 as ShapeModule,G_ as ShapeOverlapResult,jh as SharpeningEffect,nm as SignalAsset,Hh as SignalReceiver,$h as SignalReceiverEvent,qh as SignalTrackHandler,x1 as Size,xi as SizeBySpeedModule,ca as SizeOverLifetimeModule,py as SkinnedMeshRenderer,Kp as SmoothFollow,Ca as SpatialGrabRaycaster,Qh as SpatialHtml,Jp as SpatialTrigger,mo as SpatialTriggerReceiver,em as SpectatorCamera,pl as SphereCollider,Ng as SphereIntersection,fa as SplineContainer,go as SplineData,hb as SplineUtils,hn as SplineWalker,Zo as Sprite,El as SpriteData,_i as SpriteRenderer,Ml as SpriteSheet,UE as StateMachineBehaviour,Wf as StreamEndedEvent,fx as StreamReceivedEvent,Np as SubEmitterSystem,D0 as SyncedCamera,Fn as SyncedRoom,Tn as SyncedTransform,jy as TapGestureTrigger,Cp as TeleportTarget,U0 as TestRunner,z0 as TestSimulateUserData,Ht as Text,Zy as TextBuilder,Mp as TextExtension,qt as TextureSheetAnimationModule,po as TiltShiftEffect,Lw as Time,er as ToneMappingEffect,ql as TrackHandler,Vi as TrackType,Fe as TrailModule,Ne as TransformData,ba as TransformGizmo,$t as TriggerBuilder,dr as TriggerModel,C as TypeStore,Bf as UIRaycastUtils,yh as UIRootComponent,xy as USDDocument,rt as USDObject,Jx as USDWriter,t1 as USDZExporter,uo as USDZExporter$1,Il as USDZText,n0 as USDZUIExtension,px as UriSerializer,oh as UsageMarker,Bk as UserJoinedOrLeftRoomModel,Ti as VERSION,Ry as VariantAction,He as VelocityOverLifetimeModule,Ky as VerticalLayoutGroup,pt as VideoPlayer,st as ViewBox,Uo as ViewDevice,pa as Vignette,uh as VisibilityAction,Ds as Voip,$l as Volume,z as VolumeParameter,Wp as VolumeProfile,ZM as WaitForFrames,Pw as WaitForPromise,mf as WaitForSeconds,ps as Watch,ed as WebARCameraBackground,yn as WebARSessionRoot,Pp as WebXR,ur as WebXRButtonFactory,id as WebXRImageTracking,cs as WebXRImageTrackingModel,hs as WebXRPlaneTracking,ac as WebXRTrackedImage,ls as XRControllerFollow,Ko as XRControllerModel,Bi as XRControllerMovement,tn as XRFlag,fm as XRRig,ai as XRState,no as XRStateFlag,IS as __Ignore,lM as __internalNotifyObjectDestroyed,Io as activeInHierarchyFieldName,Ym as addAttributeChangeCallback,Mn as addComponent,vT as addCustomExtensionPlugin,Lr as addNewComponent,qd as addPatch,fu as apply,AE as applyHMRChanges,aw as applyPrototypeExtensions,$v as beginListenDestroy,qv as beginListenInstantiate,Mg as binaryIdentifierCasts,yE as build_scene_functions,Mr as builtinComponentKeyName,nb as calculateProgress01,yO as clearMessages,iR as colorSerializer,Zv as compareAssociation,zu as componentSerializer,O_ as copyTexture,sx as createMotion,mi as debugNet,Pc as debugOwner,r1 as decompressGpuTexture,pc as deepClone,To as delay,mc as delayForFrames,mu as deserializeObject,Ii as destroy,dw as destroyComponentInstance,Ox as determineMimeTypeFromExtension,ke as disposeObjectResources,io as disposeStream,xc as editorGuidKeyName,Na as enableSpatialConsole,oR as euler,lR as eventListSerializer,oj as exportAsGLTF,hf as findByGuid,tl as findObjectOfType,mw as findObjectsOfType,Wg as findResourceUsers,lx as fitCamera,M_ as fitObjectIntoVolume,Fr as foreachComponent,wu as foreachComponentEnumerator,jO as forward,Fw as generateQRCode,Gv as generateSeed,di as getBoundingBox,m_ as getCameraController,jr as getComponent,Fc as getComponentInChildren,Uc as getComponentInParent,Bc as getComponents,el as getComponentsInChildren,gu as getComponentsInParent,Qx as getFormattedDate,Pt as getIconElement,vf as getIconTexture,Cn as getLoader,Dc as getOrAddComponent,w as getParam,FO as getParentHierarchyPath,QP as getPath,Tk as getPeerOptions,lv as getPeerjsInstance,hM as getResourceUserCount,y_ as getTempColor,hi as getTempQuaternion,F as getTempVector,dc as getUrlParams,k_ as getVisibleInCustomShadowRendering,w_ as getWorldDirection,dg as getWorldEuler,ee as getWorldPosition,_e as getWorldQuaternion,Vd as getWorldRotation,$e as getWorldScale,Kn as hasCommercialLicense,Vc as hasIndieLicense,Fu as hasPointerEventComponent,Zn as hasProLicense,I_ as hideDebugConsole,a1 as imageToCanvas,Ur as instantiate,Ux as invokeLoadedImportPluginHooks,K_ as invokeXRSessionEnd,Z_ as invokeXRSessionStart,gw as isActiveInHierarchy,il as isActiveSelf,tO as isAndroidDevice,P_ as isAnimationAction,vg as isComponent,HP as isDebugMode,ZP as isDesktop,Br as isDestroyed,A as isDevEnvironment,aM as isDisposed,ij as isExporting,W_ as isGLTFModel,Qb as isHostedOnGlitch,If as isHotReloadEnabled,RE as isHotReloading,JP as isIPad,Uw as isIconElement,Mi as isLocalNetwork,nO as isMacOS,KP as isMobileDevice,iO as isMozillaXR,rO as isQuest,Rv as isResourceTrackingEnabled,sO as isSafari,bu as isUsingInstancing,oO as isiOS,eO as isiPad,NL as loadAsset,ly as loadPMREM,ib as loadSync,$d as logHierarchy,kO as lookAtInverse,gc as lookAtObject,MO as lookAtScreenPoint,qP as makeId,t_ as makeIdFromRandomWords,Di as makeNameSafe,fw as markAsInstancedRendered,aO as microphonePermissionsGranted,$P as nameof,Zb as nameofFactory,dx as objectSerializer,Sk as offXRSessionEnd,xk as offXRSessionStart,xE as onAfterRender,wE as onBeforeRender,_E as onClear,vE as onDestroy,Pf as onInitialized,Ru as onStart,$w as onUpdate,Cg as onXRSessionEnd,Qd as onXRSessionStart,_S as parseSync,E_ as placeOnSurface,mg as postprocessFBXMaterials,YE as prefix,Kb as pushState,XP as randomNumber,Eg as registerBinaryType,Eu as registerComponent,hy as registerComponentExtension,cn as registerCustomEffectType,dy as registerExportExtensions,sp as registerExtensions,Jw as registerHotReloadType,_g as registerLoader,Qv as registerPrefabProvider,lw as registerPrototypeExtensions,ef as registerType,n_ as relativePathPrefix,Zm as removeAttributeChangeCallback,cf as removeComponent,wT as removeCustomImportExtensionType,vk as removePatch,Ao as resolveUrl,i_ as sanitizeString,uS as saveImage,CL as screenshot,Z0 as screenshot2,Zg as sendDestroyed,u as serializable,tw as serializeObject,Ye as serializeable,zc as setActive,a_ as setAllowBalloonMessages,pO as setAllowOverlayMessages,Nd as setAutoFitEnabled,sg as setCameraController,bw as setDestroyed,GO as setDevEnvironment,Av as setDisposable,nl as setDontDestroy,qm as setOrAddParamsToUrl,GP as setParam,uc as setParamWithoutReload,Ak as setPeerOptions,rM as setResourceTrackingEnabled,Xm as setState,pg as setVisibleInCustomShadowRendering,ug as setWorldEuler,yt as setWorldPosition,Sr as setWorldPositionXYZ,Sn as setWorldQuaternion,hg as setWorldQuaternionXYZW,C_ as setWorldRotation,fc as setWorldRotationXYZ,za as setWorldScale,_c as showBalloonError,Oe as showBalloonMessage,be as showBalloonWarning,yg as showDebugConsole,OO as slerp,Lc as syncDestroy,zy as syncField,Kg as syncInstantiate,UO as textureToCanvas,o_ as toSourceId,rv as tryCastBinary,Mx as tryDetermineMimetypeFromBinary,kx as tryDetermineMimetypeFromURL,Ba as tryFindObject,av as tryGetGuid,ex as unregisterHotReloadType,Qm as unwatchWrite,g_ as useForAutoFit,kt as validate,Bd as watchWrite};
|
|
1654
|
+
`),this.#n.innerHTML=this.#e.innerHTML,this.#n.style.cssText="display: flex; align-items: center; justify-content: center;",this.#e.innerHTML=this.#n.outerHTML,this.#t.innerHTML=this.#e.outerHTML,this.#t.prepend(this.#o),ku(Sf,{element:this.#t}),this.#s?.disconnect(),this.#s??=new MutationObserver(()=>this.#c()),this.#s.observe(this.#e,{attributes:!0}),lb&&console.log("Needle Button updated",this)}#c(){this.#e&&(this.#e.style.display==="none"?this.style.display="none":this.style.display==="none"&&(this.style.display=""))}#a=e=>{lb&&console.log("Needle Button clicked",{defaultPrevented:e.defaultPrevented,hasButton:!!this.#e}),!e.defaultPrevented&&this.#e&&this.#e.click()}}typeof window<"u"&&!window.customElements.get(ES)&&window.customElements.define(ES,RS);const ud=w("debugavatar");class cb{root;head;leftHand;rigthHand;get isValid(){return this.head!==null&&this.head!==void 0}constructor(e,t,i,n){this.root=e,this.head=t,this.leftHand=i,this.rigthHand=n,this.root?.traverse(s=>s.layers.set(2))}}class TS{avatarRegistryUrl=null;async getOrCreateNewAvatarInstance(e,t){if(!t)return console.error("Can not create avatar: failed to provide id or root object"),null;let i=null;if(typeof t=="string"){if(i=await this.loadAvatar(e,t),!i){const s=new Wn;i=S.instantiate(Ba(t,e.scene),s)}}else i=t;if(!i)return null;const n=this.findAvatar(i);return n.isValid?(ud&&console.log("[Custom Avatar] valid config",t,ud?n:""),n):(console.warn("[Custom Avatar] config isn't valid",t,ud?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(ud&&console.log("[Custom Avatar] "+t+", loading..."),t.endsWith(".glb")||(t+=".glb"),this.avatarRegistryUrl===null){const n=await fetch("./"+t);let s=null;if(n.ok){const r=await n.blob();r&&(s=await r.arrayBuffer())}return s?(await Cn().parseSync(e,s,null,0))?.scene??null:null}const i=new Eo;return Af(i,e),new Promise((n,s)=>{const r=this.avatarRegistryUrl+"/"+t;i.load(r,async a=>{await Cn().createBuiltinComponents(e,r,a,null,void 0),n(a.scene)},a=>{ud&&console.log("[Custom Avatar] "+a.loaded/a.total*100+"% loaded of "+a.total/1024+"kB")},a=>{console.error("[Custom Avatar] Error when loading: "+a),n(null)})})}cacheModel(e,t){}findAvatar(e){const t=e;let i=t;i.children.length==1&&(i=e.children[0]);let n=this.findAvatarPart(i,["head"]);const s=this.findAvatarPart(i,["left","hand"]),r=this.findAvatarPart(i,["right","hand"]);if(!n){n=t;const a=new b;new Yt().setFromObject(n).getSize(a);const l=Math.max(a.x,a.y,a.z);console.warn("[Custom Avatar] Normalizing head scale, it's too big: "+l+" meters! Should be < 0.3m"),l>.3&&n.scale.multiplyScalar(1/l*.3)}return new cb(t,n,s,r)}findAvatarPart(e,t){const i=e.name.toLowerCase();let n=!0;for(const s of t){if(!n)break;i.indexOf(s)===-1&&(n=!1)}if(n)return e;if(e.children)for(const s of e.children){const r=this.findAvatarPart(s,t);if(r)return r}return null}handleCustomAvatarErrors(e){if(!e.ok)throw Error(e.statusText);return e}}class AS{get extensionName(){return"DocumentExtension"}onAfterBuildDocument(e){}}class IS{}const aj=Object.freeze(Object.defineProperty({__proto__:null,ActionBuilder:fe,ActionCollection:f1,ActionModel:Ci,AlignmentConstraint:Gc,Animation:Ut,AnimationCurve:Ch,AnimationExtension:_p,AnimationTrackHandler:Gh,Animator:_t,AnimatorController:gn,Antialiasing:Eh,Attractor:Wl,AudioExtension:Pa,AudioListener:Wo,AudioSource:ji,AudioTrackHandler:ys,Avatar:Vs,AvatarBlink_Simple:Gr,AvatarEyeLook_Rotation:Gf,AvatarLoader:TS,AvatarMarker:Le,AvatarModel:cb,Avatar_Brain_LookAt:eh,Avatar_MouthShapes:th,Avatar_MustacheShake:$f,Avatar_POI:Hr,AxesHelper:ul,BaseUIComponent:un,BasicIKConstraint:Xf,BehaviorExtension:Hy,BehaviorModel:jt,BloomEffect:$p,BoxCollider:qu,BoxGizmo:sa,BoxHelperComponent:Bt,Button:rs,CallInfo:No,Camera:yi,CameraTargetReachedEvent:Jc,Canvas:Ll,CanvasGroup:Xs,CapsuleCollider:Vo,ChangeMaterialOnClick:Ay,ChangeTransformOnClick:ea,CharacterController:qr,CharacterControllerInput:Ho,ChromaticAberration:Rh,ClickThrough:um,ColorAdjustments:tr,ColorBySpeedModule:zl,ColorOverLifetimeModule:Bp,ContactShadows:nh,ControlTrackHandler:sm,CursorFollow:va,CustomBranding:oa,Deletable:Jf,DeleteBox:gr,DepthOfField:Dn,DeviceFlag:Xu,DocumentExtension:AS,DragControls:Yr,DropListener:Qo,Duplicatable:gy,EffectWrapper:Ah,EmissionModule:is,EmphasizeOnClick:Ol,EnvironmentScene:hm,EventList:ae,EventListEvent:Uu,EventSystem:li,EventTrigger:cp,FieldWithDefault:$x,FixedJoint:c0,Fog:jl,GltfExport:wy,GltfExportBox:_y,Gradient:aa,Graphic:vh,GraphicRaycaster:Wu,GridHelper:Dl,GridLayoutGroup:e0,GroundProjectedEnv:Jn,GroupActionModel:Jr,HideOnStart:fn,HingeJoint:Sh,HorizontalLayoutGroup:Jy,get HoverAnimation(){return bo},Image:Xl,InheritVelocityModule:f0,InputField:$0,InstanceHandle:Ra,InstancingHandler:Oa,Interactable:Kf,Keyframe:wi,LODGroup:Rp,LODModel:Fl,Light:Tt,LimitVelocityOverLifetimeModule:dt,LogStats:Zf,LookAt:H0,LookAtConstraint:Wr,MainModule:Gt,MarkerTrackHandler:om,MaskableGraphic:wh,MeshCollider:Bs,MeshRenderer:ah,MinMaxCurve:Y,MinMaxGradient:la,NeedleMenu:co,NestedGltf:Ul,Networking:p0,NoiseModule:ve,ObjectRaycaster:Ji,OffsetConstraint:ra,OpenURL:Ql,OrbitControls:ge,Outline:Al,Padding:na,ParticleBurst:Dp,ParticleSubEmitter:y0,ParticleSystem:kh,ParticleSystemRenderer:ln,PhysicsExtension:Gy,PixelationEffect:Ih,PlayAnimationOnClick:hh,PlayAudioOnClick:Ns,PlayableDirector:ya,PlayerColor:rc,PointerEventData:vd,PostProcessingHandler:L0,PreliminaryAction:kl,PreliminaryTrigger:dh,RawImage:lm,Rect:S1,RectTransform:Ln,ReflectionProbe:qo,RegisteredAnimationInfo:fr,RemoteSkybox:Yp,Renderer:ti,RendererLightmap:uy,Rigidbody:Ke,RotationBySpeedModule:an,RotationOverLifetimeModule:jn,SceneSwitcher:Je,ScreenCapture:nr,ScreenSpaceAmbientOcclusion:ns,ScreenSpaceAmbientOcclusionN8:Bn,ScrollFollow:as,SeeThrough:ss,SetActiveOnClick:Iy,ShadowCatcher:Uh,ShapeModule:g0,SharpeningEffect:jh,SignalAsset:nm,SignalReceiver:Hh,SignalReceiverEvent:$h,SignalTrackHandler:qh,Size:x1,SizeBySpeedModule:xi,SizeOverLifetimeModule:ca,SkinnedMeshRenderer:py,SmoothFollow:Kp,SpatialGrabRaycaster:Ca,SpatialHtml:Qh,SpatialTrigger:Jp,SpatialTriggerReceiver:mo,SpectatorCamera:em,SphereCollider:pl,SplineContainer:fa,SplineData:go,SplineWalker:hn,Sprite:Zo,SpriteData:El,SpriteRenderer:_i,SpriteSheet:Ml,SubEmitterSystem:Np,SyncedCamera:D0,SyncedRoom:Fn,SyncedTransform:Tn,TapGestureTrigger:jy,TeleportTarget:Cp,TestRunner:U0,TestSimulateUserData:z0,Text:Ht,TextBuilder:Zy,TextExtension:Mp,TextureSheetAnimationModule:qt,TiltShiftEffect:po,ToneMappingEffect:er,TrailModule:Fe,TransformData:Ne,TransformGizmo:ba,TriggerBuilder:$t,TriggerModel:dr,UIRaycastUtils:Bf,UIRootComponent:yh,USDZExporter:uo,USDZText:Il,USDZUIExtension:n0,UsageMarker:oh,VariantAction:Ry,VelocityOverLifetimeModule:He,VerticalLayoutGroup:Ky,VideoPlayer:pt,get ViewBox(){return st},Vignette:pa,VisibilityAction:uh,Voip:Ds,Volume:$l,VolumeParameter:z,VolumeProfile:Wp,WebARCameraBackground:ed,WebARSessionRoot:yn,WebXR:Pp,WebXRImageTracking:id,WebXRImageTrackingModel:cs,WebXRPlaneTracking:hs,WebXRTrackedImage:ac,XRControllerFollow:ls,XRControllerModel:Ko,XRControllerMovement:Bi,XRFlag:tn,XRRig:fm,XRState:ai,__Ignore:IS},Symbol.toStringTag,{value:"Module"})),pd=w("debugmissingcamera");pe.registerCallback(ue.MissingCamera,o=>{pd&&console.warn("Creating missing camera");const e=o.context.scene,t=new de;t.name="Default Fallback Camera",e.add(t);const i=new yi;if(i.sourceId=o.files?.[0]?.src??"unknown",i.fieldOfView=35,o.context.domElement.getAttribute("transparent")!=null)i.clearFlags=$r.Uninitialized;else if(o.context.domElement.getAttribute("background-image")?.length||o.context.lightmaps.tryGetSkybox(i.sourceId))i.clearFlags=$r.Skybox;else{if(i.clearFlags=$r.SolidColor,!o.context.domElement.getAttribute("background-color")){let s="#efefef";typeof window!==void 0&&window.matchMedia("(prefers-color-scheme: dark)").matches&&(s="#1f1f1f"),e.background=new oe(s)}if(!e.environment){const s=new rP(o.context.renderer),r=new hm("neutral");e.environment=s.fromScene(r,.025).texture}}const n=Lr(t,i,!0);return t.position.x=0,t.position.y=1,t.position.z=2,o.context.domElement?.cameraControls!=!1&&LS(o.context,n),n}),pe.registerCallback(ue.ContextCreated,o=>{if(!o.context.mainCamera){pd&&console.log("Will not auto-fit because a default camera exists");return}if(o.context.domElement?.cameraControls==!0){if(m_(o.context.mainCamera)?.isCameraController==!0){pd&&console.log("Will not auto-fit because a camera controller exists");return}LS(o.context)}});function LS(o,e){e=e??o.mainCameraComponent;const t=e?.gameObject;if(pd&&console.log("Creating default camera controls",e?.name),t){const i=Dc(t,ge);i.sourceId=e?.sourceId??"unknown";const n=o.domElement.getAttribute("auto-rotate");i.autoRotate=n!="0"&&n?.toLowerCase()!="false";const s=Number.parseFloat(n||".5");i.autoRotateSpeed=isNaN(s)?.5:s,pd&&console.log("Auto-rotate",i.autoRotate,"speed:",i.autoRotateSpeed);const r=o.domElement.getAttribute("auto-fit");i.autoFit=r!=="0"&&r?.toLowerCase()!="false",i.autoTarget=!0}else console.warn("Missing camera object, can not add orbit controls")}pe.registerCallback(ue.ContextCreated,o=>{const e=o.context.domElement.getAttribute("autoplay");if(e!==void 0&&(e===""||e==="true"||e==="1")&&o.files)for(const t of o.files)S.foreachComponent(t.file.scene,i=>{if(i.enabled!==!1){if(i instanceof Ut&&i.playAutomatically||i instanceof _t||i instanceof ya&&i.playOnAwake===!0)return!0;if(i instanceof Ut)return i.playAutomatically=!0,!0;if(i instanceof ya)return i.playOnAwake=!0,!0}},!0)!==!0&&Qn.autoplayAnimations(t.file)});var hb;(o=>{function e(t,i=!1,n=.75){const s=new fa,r=1-j.clamp(n,0,1);return t.forEach((a,l)=>{const c=new b;l<t.length-1?c.subVectors(t[l+1],a).normalize().multiplyScalar(r):i&&t.length>1&&c.subVectors(t[0],a).normalize().multiplyScalar(r);const h=new go;h.position.copy(a),h.tangentIn.copy(c),h.tangentOut.copy(c),s.addKnot(h)}),s.closed=i,s}o.createFromPoints=e})(hb||(hb={}));class lj extends UP{constructor(){super(new Worker(URL.createObjectURL(new Blob([`import '${new URL("./generateMeshBVH.worker-DiCnZlf3.js",import.meta.url).toString()}';`],{type:"text/javascript"})),{type:"module"})),this.name="GenerateMeshBVHWorker"}runTask(e,t,i={}){return new Promise((n,s)=>{if(t.getAttribute("position").isInterleavedBufferAttribute||t.index&&t.index.isInterleavedBufferAttribute)throw new Error("GenerateMeshBVHWorker: InterleavedBufferAttribute are not supported for the geometry attributes.");e.onerror=c=>{s(new Error(`[GenerateMeshBVHWorker] ${c.message||"Unknown error. Please check the server console. If you're using vite try adding 'three-mesh-bvh' to 'optimizeDeps.exclude' in your vite.config.js"}`))},e.onmessage=c=>{const{data:h}=c;if(h.error)s(new Error(h.error)),e.onmessage=null;else if(h.serialized){const{serialized:d,position:p}=h,m=zP.deserialize(d,t,{setIndex:!1}),g=Object.assign({setBoundingBox:!0},i);if(t.attributes.position.array=p,d.index)if(t.index)t.index.array=d.index;else{const f=new ft(d.index,1,!1);t.setIndex(f)}g.setBoundingBox&&(t.boundingBox=m.getBoundingBox(new Yt)),i.onProgress&&i.onProgress(h.progress),n(m),e.onmessage=null}else i.onProgress&&i.onProgress(h.progress)};const r=t.index?t.index.array:null,a=t.attributes.position.array,l=[a];r&&l.push(r),e.postMessage({index:r,position:a,options:{...i,onProgress:null,includedProgressCallback:!!i.onProgress,groups:[...t.groups]}},l.map(c=>c.buffer).filter(c=>typeof SharedArrayBuffer>"u"||!(c instanceof SharedArrayBuffer)))})}}const cj=Object.freeze(Object.defineProperty({__proto__:null,GenerateMeshBVHWorker:lj},Symbol.toStringTag,{value:"Module"}));export{V_ as $componentName,bk as $physicsKey,fe as ActionBuilder,f1 as ActionCollection,Ci as ActionModel,xw as Addressables,Gc as AlignmentConstraint,rl as AmbientMode,Ut as Animation,Ch as AnimationCurve,_p as AnimationExtension,Gh as AnimationTrackHandler,Qn as AnimationUtils,_t as Animator,As as AnimatorConditionMode,gn as AnimatorController,Lf as AnimatorControllerParameterType,qc as AnimatorStateInfo,Eh as Antialiasing,Nn as Application,Mv as AssetDatabase,ne as AssetReference,Wl as Attractor,Pa as AudioExtension,Wo as AudioListener,ji as AudioSource,ys as AudioTrackHandler,Vs as Avatar,Gr as AvatarBlink_Simple,Gf as AvatarEyeLook_Rotation,TS as AvatarLoader,Le as AvatarMarker,cb as AvatarModel,eh as Avatar_Brain_LookAt,th as Avatar_MouthShapes,$f as Avatar_MustacheShake,Hr as Avatar_POI,cl as Axes,ul as AxesHelper,wc as BUILD_TIME,un as BaseUIComponent,Xf as BasicIKConstraint,Hy as BehaviorExtension,jt as BehaviorModel,zr as BlobStorage,$p as BloomEffect,qu as BoxCollider,sa as BoxGizmo,Bt as BoxHelperComponent,rs as Button,mn as ButtonsFactory,yx as CallDirection,No as CallInfo,yi as Camera,Jc as CameraTargetReachedEvent,Ll as Canvas,Xs as CanvasGroup,Vo as CapsuleCollider,Ay as ChangeMaterialOnClick,ea as ChangeTransformOnClick,qr as CharacterController,Ho as CharacterControllerInput,Rh as ChromaticAberration,Ei as CircularBuffer,$r as ClearFlags,um as ClickThrough,fo as ClipExtrapolation,nn as Collider,H_ as Collision,Bu as CollisionDetectionMode,tr as ColorAdjustments,zl as ColorBySpeedModule,Bp as ColorOverLifetimeModule,IE as Component,E as Component$1,au as ComponentLifecycleEvents,aj as Components,uv as ConnectionEvents,$_ as ContactPoint,nh as ContactShadows,U as Context,bE as ContextArgs,ue as ContextEvent,pe as ContextRegistry,sm as ControlTrackHandler,va as CursorFollow,oa as CustomBranding,Te as CustomShader,Pu as DefaultReflectionMode,Jf as Deletable,gr as DeleteBox,Dn as DepthOfField,Xu as DeviceFlag,I as DeviceUtilities,AS as DocumentExtension,Yr as DragControls,ty as DragMode,Qo as DropListener,gy as Duplicatable,Ah as EffectWrapper,is as EmissionModule,Ol as EmphasizeOnClick,xd as EngineLoadingView,hm as EnvironmentScene,ae as EventList,Uu as EventListEvent,li as EventSystem,cp as EventTrigger,$x as FieldWithDefault,Ea as FileReference,Cw as FileReferenceSerializer,XR as FileSpawnModel,Px as File_Event,c0 as FixedJoint,jl as Fog,xe as FrameEvent,Wa as GENERATOR,S as GameObject,B as Gizmos,wy as GltfExport,_y as GltfExportBox,aa as Gradient,vh as Graphic,Wu as GraphicRaycaster,pr as Graphics,Dl as GridHelper,e0 as GridLayoutGroup,Jn as GroundProjectedEnv,Jr as GroupActionModel,Gd as HideFlags,fn as HideOnStart,Sh as HingeJoint,Jy as HorizontalLayoutGroup,_M as HostData,bo as HoverAnimation,Xl as Image,Ma as ImageReference,Sw as ImageReferenceSerializer,f0 as InheritVelocityModule,J_ as Input,pi as InputEventQueue,Ae as InputEvents,$0 as InputField,Ra as InstanceHandle,Oa as InstancingHandler,pn as InstancingUtil,Vv as InstantiateEvent,Dt as InstantiateIdProvider,Wn as InstantiateOptions,Kf as Interactable,Jh as InternalScreenshotUtils,jk as JoinedRoomResponse,Ck as KeyEventArgs,wi as Keyframe,Rp as LODGroup,Fl as LODModel,Dk as LeftRoomResponse,Tt as Light,Aw as LightData,dt as LimitVelocityOverLifetimeModule,qL as LoadingElementOptions,Zf as LogStats,Ri as LogType,H0 as LookAt,Wr as LookAtConstraint,T as MODULES,Gt as MainModule,om as MarkerTrackHandler,N0 as MarkerType,wh as MaskableGraphic,ms as MaterialPropertyBlock,np as MaterialX,j as Mathf,Bs as MeshCollider,ah as MeshRenderer,Y as MinMaxCurve,la as MinMaxGradient,Ac as NEEDLE_ENGINE_FEATURE_FLAGS,Sc as NEKeyboardEvent,Lo as NEPointerEvent,RS as NeedleButtonElement,ny as NeedleEngineModelLoader,ob as NeedleEngineWebComponent,co as NeedleMenu,Xd as NeedlePatchesKey,Pg as NeedleXRController,Z as NeedleXRSession,gv as NeedleXRSync,xv as NeedleXRUtils,Ul as NestedGltf,mv as NetworkConnection,to as NetworkedStreamEvents,wd as NetworkedStreams,p0 as Networking,Hv as NewInstanceModel,ve as NoiseModule,Ji as ObjectRaycaster,Os as ObjectUtils,ra as OffsetConstraint,Ud as OneEuroFilter,og as OneEuroFilterXYZ,Ql as OpenURL,ge as OrbitControls,Al as Outline,pv as OwnershipEvent,Tg as OwnershipModel,Ss as PUBLIC_KEY,na as Padding,Dp as ParticleBurst,y0 as ParticleSubEmitter,kh as ParticleSystem,Js as ParticleSystemBaseBehaviour,ln as ParticleSystemRenderer,jp as ParticleSystemShapeType,fs as PeerHandle,hv as PeerNetworking,oc as Physics,Gy as PhysicsExtension,vt as PhysicsMaterialCombine,Ih as PixelationEffect,hh as PlayAnimationOnClick,Ns as PlayAudioOnClick,ya as PlayableDirector,rc as PlayerColor,sn as PlayerState,v1 as PlayerStateEvent,Ny as PlayerSync,kw as PlayerView,Mw as PlayerViewManager,vd as PointerEventData,Yd as PointerType,nt as PostProcessingEffect,ut as PostProcessingEffectOrder,L0 as PostProcessingHandler,kl as PreliminaryAction,dh as PreliminaryTrigger,Us as PreviewHelper,Qa as PrimitiveType,le as Progress,Jm as PromiseAllWithErrors,Km as PromiseErrorResult,se as RGBAColor,lc as RapierPhysics,lm as RawImage,ks as RaycastOptions,S1 as Rect,Ln as RectTransform,qo as ReflectionProbe,fr as RegisteredAnimationInfo,Yp as RemoteSkybox,xo as RenderTexture,ux as RenderTextureSerializer,ti as Renderer,Tw as RendererData,uy as RendererLightmap,Ke as Rigidbody,Ze as RigidbodyConstraints,ie as RoomEvents,an as RotationBySpeedModule,jn as RotationOverLifetimeModule,ip as SceneLightSettings,Je as SceneSwitcher,nr as ScreenCapture,ns as ScreenSpaceAmbientOcclusion,Bn as ScreenSpaceAmbientOcclusionN8,as as ScrollFollow,ss as SeeThrough,Pn as SendQueue,rf as SerializationContext,Iy as SetActiveOnClick,Uh as ShadowCatcher,g0 as ShapeModule,G_ as ShapeOverlapResult,jh as SharpeningEffect,nm as SignalAsset,Hh as SignalReceiver,$h as SignalReceiverEvent,qh as SignalTrackHandler,x1 as Size,xi as SizeBySpeedModule,ca as SizeOverLifetimeModule,py as SkinnedMeshRenderer,Kp as SmoothFollow,Ca as SpatialGrabRaycaster,Qh as SpatialHtml,Jp as SpatialTrigger,mo as SpatialTriggerReceiver,em as SpectatorCamera,pl as SphereCollider,Ng as SphereIntersection,fa as SplineContainer,go as SplineData,hb as SplineUtils,hn as SplineWalker,Zo as Sprite,El as SpriteData,_i as SpriteRenderer,Ml as SpriteSheet,UE as StateMachineBehaviour,Wf as StreamEndedEvent,fx as StreamReceivedEvent,Np as SubEmitterSystem,D0 as SyncedCamera,Fn as SyncedRoom,Tn as SyncedTransform,jy as TapGestureTrigger,Cp as TeleportTarget,U0 as TestRunner,z0 as TestSimulateUserData,Ht as Text,Zy as TextBuilder,Mp as TextExtension,qt as TextureSheetAnimationModule,po as TiltShiftEffect,Lw as Time,er as ToneMappingEffect,ql as TrackHandler,Vi as TrackType,Fe as TrailModule,Ne as TransformData,ba as TransformGizmo,$t as TriggerBuilder,dr as TriggerModel,C as TypeStore,Bf as UIRaycastUtils,yh as UIRootComponent,xy as USDDocument,rt as USDObject,Jx as USDWriter,t1 as USDZExporter,uo as USDZExporter$1,Il as USDZText,n0 as USDZUIExtension,px as UriSerializer,oh as UsageMarker,Bk as UserJoinedOrLeftRoomModel,Ti as VERSION,Ry as VariantAction,He as VelocityOverLifetimeModule,Ky as VerticalLayoutGroup,pt as VideoPlayer,st as ViewBox,Uo as ViewDevice,pa as Vignette,uh as VisibilityAction,Ds as Voip,$l as Volume,z as VolumeParameter,Wp as VolumeProfile,ZM as WaitForFrames,Pw as WaitForPromise,mf as WaitForSeconds,ps as Watch,ed as WebARCameraBackground,yn as WebARSessionRoot,Pp as WebXR,ur as WebXRButtonFactory,id as WebXRImageTracking,cs as WebXRImageTrackingModel,hs as WebXRPlaneTracking,ac as WebXRTrackedImage,ls as XRControllerFollow,Ko as XRControllerModel,Bi as XRControllerMovement,tn as XRFlag,fm as XRRig,ai as XRState,no as XRStateFlag,IS as __Ignore,lM as __internalNotifyObjectDestroyed,Io as activeInHierarchyFieldName,Ym as addAttributeChangeCallback,Mn as addComponent,vT as addCustomExtensionPlugin,Lr as addNewComponent,qd as addPatch,fu as apply,AE as applyHMRChanges,aw as applyPrototypeExtensions,$v as beginListenDestroy,qv as beginListenInstantiate,Mg as binaryIdentifierCasts,yE as build_scene_functions,Mr as builtinComponentKeyName,nb as calculateProgress01,yO as clearMessages,iR as colorSerializer,Zv as compareAssociation,zu as componentSerializer,O_ as copyTexture,sx as createMotion,mi as debugNet,Pc as debugOwner,r1 as decompressGpuTexture,pc as deepClone,To as delay,mc as delayForFrames,mu as deserializeObject,Ii as destroy,dw as destroyComponentInstance,Ox as determineMimeTypeFromExtension,ke as disposeObjectResources,io as disposeStream,xc as editorGuidKeyName,Na as enableSpatialConsole,oR as euler,lR as eventListSerializer,oj as exportAsGLTF,hf as findByGuid,tl as findObjectOfType,mw as findObjectsOfType,Wg as findResourceUsers,lx as fitCamera,M_ as fitObjectIntoVolume,Fr as foreachComponent,wu as foreachComponentEnumerator,jO as forward,Fw as generateQRCode,Gv as generateSeed,di as getBoundingBox,m_ as getCameraController,jr as getComponent,Fc as getComponentInChildren,Uc as getComponentInParent,Bc as getComponents,el as getComponentsInChildren,gu as getComponentsInParent,Qx as getFormattedDate,Pt as getIconElement,vf as getIconTexture,Cn as getLoader,Dc as getOrAddComponent,w as getParam,FO as getParentHierarchyPath,QP as getPath,Tk as getPeerOptions,lv as getPeerjsInstance,hM as getResourceUserCount,y_ as getTempColor,hi as getTempQuaternion,F as getTempVector,dc as getUrlParams,k_ as getVisibleInCustomShadowRendering,w_ as getWorldDirection,dg as getWorldEuler,ee as getWorldPosition,_e as getWorldQuaternion,Vd as getWorldRotation,$e as getWorldScale,Kn as hasCommercialLicense,Vc as hasIndieLicense,Fu as hasPointerEventComponent,Zn as hasProLicense,I_ as hideDebugConsole,a1 as imageToCanvas,Ur as instantiate,Ux as invokeLoadedImportPluginHooks,K_ as invokeXRSessionEnd,Z_ as invokeXRSessionStart,gw as isActiveInHierarchy,il as isActiveSelf,tO as isAndroidDevice,P_ as isAnimationAction,vg as isComponent,HP as isDebugMode,ZP as isDesktop,Br as isDestroyed,A as isDevEnvironment,aM as isDisposed,ij as isExporting,W_ as isGLTFModel,Qb as isHostedOnGlitch,If as isHotReloadEnabled,RE as isHotReloading,JP as isIPad,Uw as isIconElement,Mi as isLocalNetwork,nO as isMacOS,KP as isMobileDevice,iO as isMozillaXR,rO as isQuest,Rv as isResourceTrackingEnabled,sO as isSafari,bu as isUsingInstancing,oO as isiOS,eO as isiPad,NL as loadAsset,ly as loadPMREM,ib as loadSync,$d as logHierarchy,kO as lookAtInverse,gc as lookAtObject,MO as lookAtScreenPoint,qP as makeId,t_ as makeIdFromRandomWords,Di as makeNameSafe,fw as markAsInstancedRendered,aO as microphonePermissionsGranted,$P as nameof,Zb as nameofFactory,dx as objectSerializer,Sk as offXRSessionEnd,xk as offXRSessionStart,xE as onAfterRender,wE as onBeforeRender,_E as onClear,vE as onDestroy,Pf as onInitialized,Ru as onStart,$w as onUpdate,Cg as onXRSessionEnd,Qd as onXRSessionStart,_S as parseSync,E_ as placeOnSurface,mg as postprocessFBXMaterials,YE as prefix,Kb as pushState,XP as randomNumber,Eg as registerBinaryType,Eu as registerComponent,hy as registerComponentExtension,cn as registerCustomEffectType,dy as registerExportExtensions,sp as registerExtensions,Jw as registerHotReloadType,_g as registerLoader,Qv as registerPrefabProvider,lw as registerPrototypeExtensions,ef as registerType,n_ as relativePathPrefix,Zm as removeAttributeChangeCallback,cf as removeComponent,wT as removeCustomImportExtensionType,vk as removePatch,Ao as resolveUrl,i_ as sanitizeString,uS as saveImage,CL as screenshot,Z0 as screenshot2,Zg as sendDestroyed,u as serializable,tw as serializeObject,Ye as serializeable,zc as setActive,a_ as setAllowBalloonMessages,pO as setAllowOverlayMessages,Nd as setAutoFitEnabled,sg as setCameraController,bw as setDestroyed,GO as setDevEnvironment,Av as setDisposable,nl as setDontDestroy,qm as setOrAddParamsToUrl,GP as setParam,uc as setParamWithoutReload,Ak as setPeerOptions,rM as setResourceTrackingEnabled,Xm as setState,pg as setVisibleInCustomShadowRendering,ug as setWorldEuler,yt as setWorldPosition,Sr as setWorldPositionXYZ,Sn as setWorldQuaternion,hg as setWorldQuaternionXYZW,C_ as setWorldRotation,fc as setWorldRotationXYZ,za as setWorldScale,_c as showBalloonError,Oe as showBalloonMessage,be as showBalloonWarning,yg as showDebugConsole,OO as slerp,Lc as syncDestroy,zy as syncField,Kg as syncInstantiate,UO as textureToCanvas,o_ as toSourceId,rv as tryCastBinary,Mx as tryDetermineMimetypeFromBinary,kx as tryDetermineMimetypeFromURL,Ba as tryFindObject,av as tryGetGuid,ex as unregisterHotReloadType,Qm as unwatchWrite,g_ as useForAutoFit,kt as validate,Bd as watchWrite};
|